public function execute() { $ksStr = $this->getP("ks"); if ($ksStr) { $ksObj = null; try { $ksObj = ks::fromSecureString($ksStr); } catch (Exception $e) { } if ($ksObj) { $partner = PartnerPeer::retrieveByPK($ksObj->partner_id); if (!$partner) { KExternalErrors::dieError(KExternalErrors::PARTNER_NOT_FOUND); } if (!$partner->validateApiAccessControl()) { KExternalErrors::dieError(KExternalErrors::SERVICE_ACCESS_CONTROL_RESTRICTED); } $ksObj->kill(); } KalturaLog::info("Killing session with ks - [{$ksStr}], decoded - [" . base64_decode($ksStr) . "]"); } else { KalturaLog::err('logoutAction called with no KS'); } setcookie('pid', "", 0, "/"); setcookie('subpid', "", 0, "/"); setcookie('kmcks', "", 0, "/"); return sfView::NONE; //redirection to kmc/kmc is done from java script }
public function getLocalThumbFilePath($version, $width, $height, $type, $bgcolor = "ffffff", $crop_provider = null, $quality = 0, $src_x = 0, $src_y = 0, $src_w = 0, $src_h = 0, $vid_sec = -1, $vid_slice = 0, $vid_slices = -1, $density = 0, $stripProfiles = false, $flavorId = null, $fileName = null) { if ($this->getStatus() == entryStatus::DELETED || $this->getModerationStatus() == moderation::MODERATION_STATUS_BLOCK) { KalturaLog::log("rejected live stream entry - not serving thumbnail"); KExternalErrors::dieError(KExternalErrors::ENTRY_DELETED_MODERATED); } $contentPath = myContentStorage::getFSContentRootPath(); $liveEntryExist = false; $liveThumbEntry = null; $liveThumbEntryId = null; $partner = $this->getPartner(); if ($partner) { $liveThumbEntryId = $partner->getLiveThumbEntryId(); } if ($liveThumbEntryId) { $liveThumbEntry = entryPeer::retrieveByPK($liveThumbEntryId); } if ($liveThumbEntry && $liveThumbEntry->getMediaType() == entry::ENTRY_MEDIA_TYPE_IMAGE) { $fileSyncVersion = $partner->getLiveThumbEntryVersion(); $liveEntryKey = $liveThumbEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA, $fileSyncVersion); $contentPath = kFileSyncUtils::getLocalFilePathForKey($liveEntryKey); if ($contentPath) { $msgPath = $contentPath; $liveEntryExist = true; } else { KalturaLog::err('no local file sync for audio entry id'); } } if (!$liveEntryExist) { $msgPath = $contentPath . "content/templates/entry/thumbnail/live_thumb.jpg"; } return myEntryUtils::resizeEntryImage($this, $version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices, $msgPath, $density, $stripProfiles); }
/** * Will forward to the regular swf player according to the widget_id */ public function execute() { // make sure output is not parsed as HTML header("Content-type: application/x-javascript"); $uiconfId = $this->getRequestParameter("uiconfId"); // replace all $_GET with $this->getRequestParameter() // load uiconf from DB. $this->uiconfObj = uiConfPeer::retrieveByPK($uiconfId); if (!$this->uiconfObj) { KExternalErrors::dieError(KExternalErrors::UI_CONF_NOT_FOUND); } @libxml_use_internal_errors(true); $this->uiconfXmlObj = new SimpleXMLElement($this->uiconfObj->getConfFile()); if (!$this->uiconfXmlObj instanceof SimpleXMLElement) { // no xml or invalid XML, so throw exception throw new Exception('uiconf XML is invalid'); } // unsupress the xml errors @libxml_use_internal_errors(false); $this->_initReplacementTokens(); $this->_prepareLibJs(); $this->_prepareJs(); echo $this->jsResult; die; }
/** * Will forward to the uploader swf according to the ui_conf_id */ public function execute() { $ui_conf_id = $this->getRequestParameter("ui_conf_id"); $uiConf = uiConfPeer::retrieveByPK($ui_conf_id); if (!$uiConf) { KExternalErrors::dieError(KExternalErrors::UI_CONF_NOT_FOUND, "UI conf not found"); } $partner_id = $uiConf->getPartnerId(); $subp_id = $uiConf->getSubpId(); $host = requestUtils::getRequestHost(); $ui_conf_swf_url = $uiConf->getSwfUrl(); if (!$ui_conf_swf_url) { KExternalErrors::dieError(KExternalErrors::ILLEGAL_UI_CONF, "SWF URL not found in UI conf"); } if (kString::beginsWith($ui_conf_swf_url, "http")) { $swf_url = $ui_conf_swf_url; // absolute URL } else { $use_cdn = $uiConf->getUseCdn(); $cdn_host = $use_cdn ? myPartnerUtils::getCdnHost($partner_id) : myPartnerUtils::getHost($partner_id); $swf_url = $cdn_host . myPartnerUtils::getUrlForPartner($partner_id, $subp_id) . $ui_conf_swf_url; // relative to the current host } $conf_vars = $uiConf->getConfVars(); if ($conf_vars) { $conf_vars = "&" . $conf_vars; } $params = "host=" . $host . "&uiConfId=" . $ui_conf_id . $conf_vars; KExternalErrors::terminateDispatch(); $this->redirect("{$swf_url}?{$params}"); }
public function buildServeFlavors() { $baseUrl = null; $flavors = $this->buildRtmpFlavorsArray($baseUrl); if (!count($flavors)) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } $this->baseUrl = $baseUrl; return $flavors; }
/** * Will forward to the regular swf player according to the widget_id */ public function execute() { $uiconf_id = $this->getRequestParameter('uiconf_id'); if (!$uiconf_id) { KExternalErrors::dieError(KExternalErrors::MISSING_PARAMETER, 'uiconf_id'); } $uiConf = uiConfPeer::retrieveByPK($uiconf_id); if (!$uiConf) { KExternalErrors::dieError(KExternalErrors::UI_CONF_NOT_FOUND); } $partner_id = $this->getRequestParameter('partner_id', $uiConf->getPartnerId()); if (!$partner_id) { KExternalErrors::dieError(KExternalErrors::MISSING_PARAMETER, 'partner_id'); } $partner_host = myPartnerUtils::getHost($partner_id); $partner_cdnHost = myPartnerUtils::getCdnHost($partner_id); $use_cdn = $uiConf->getUseCdn(); $host = $use_cdn ? $partner_cdnHost : $partner_host; $ui_conf_html5_url = $uiConf->getHtml5Url(); if (kConf::hasMap("optimized_playback")) { $optimizedPlayback = kConf::getMap("optimized_playback"); if (array_key_exists($partner_id, $optimizedPlayback)) { // force a specific kdp for the partner $params = $optimizedPlayback[$partner_id]; if (array_key_exists('html5_url', $params)) { $ui_conf_html5_url = $params['html5_url']; } } } if (kString::beginsWith($ui_conf_html5_url, "http")) { $url = $ui_conf_html5_url; // absolute URL } else { if ($ui_conf_html5_url) { $url = $host . $ui_conf_html5_url; } else { $html5_version = kConf::get('html5_version'); $url = "{$host}/html5/html5lib/{$html5_version}/mwEmbedLoader.php"; } } // append uiconf_id and partner id for optimizing loading of html5 library. append them only for "standard" urls by looking for the mwEmbedLoader.php suffix if (kString::endsWith($url, "mwEmbedLoader.php")) { $url .= "/p/{$partner_id}/uiconf_id/{$uiconf_id}"; $entry_id = $this->getRequestParameter('entry_id'); if ($entry_id) { $url .= "/entry_id/{$entry_id}"; } } requestUtils::sendCachingHeaders(60); header("Pragma:"); kFile::cacheRedirect($url); header("Location:{$url}"); die; }
/** * 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(); }
public function serve() { $baseUrl = null; $flavors = $this->buildRtmpFlavorsArray($baseUrl); if (!count($flavors)) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } $renderer = $this->getRenderer($flavors); $renderer->baseUrl = $baseUrl; return $renderer; }
public function execute() { // Prevent the page fron being embeded in an iframe header('X-Frame-Options: DENY'); // Check if user already logged in and redirect to kmc2 if ($this->getRequest()->getCookie('kmcks')) { $this->redirect('kmc/kmc2'); } if (infraRequestUtils::getProtocol() != infraRequestUtils::PROTOCOL_HTTPS && kConf::get('kmc_secured_login')) { $url = 'https://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; header('Location:' . $url); die; } $this->www_host = kConf::get('www_host'); $https_enabled = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443 ? true : false; $this->securedLogin = kConf::get('kmc_secured_login') || $https_enabled ? true : false; $swfUrl = $this->securedLogin ? 'https://' : 'http://'; $swfUrl .= $this->www_host . myContentStorage::getFSFlashRootPath(); $swfUrl .= '/kmc/login/' . kConf::get('kmc_login_version') . '/login.swf'; $this->swfUrl = $swfUrl; $this->partner_id = $this->getRequestParameter("partner_id"); $this->logoUrl = null; if ($this->partner_id) { $partner = PartnerPeer::retrieveByPK($this->partner_id); if ($partner) { $this->logoUrl = kmcUtils::getWhitelabelData($partner, 'logo_url'); } } $this->beta = $this->getRequestParameter("beta"); //prevent script injections - allow only base64_encode chars , which is used when creating A new hash key $passHashparam = $this->getRequestParameter("setpasshashkey"); if ($passHashparam && !preg_match(self::BASE64_ENCODE_CHARS_REGEX, $passHashparam)) { KExternalErrors::dieError(KExternalErrors::INVALID_HASH); } $this->setPassHashKey = $passHashparam; $this->hashKeyErrorCode = null; $this->displayErrorFromServer = false; if ($this->setPassHashKey) { try { $loginData = UserLoginDataPeer::isHashKeyValid($this->setPassHashKey); $partnerId = $loginData->getConfigPartnerId(); $partner = PartnerPeer::retrieveByPK($partnerId); if ($partner && $partner->getPasswordStructureValidations()) { $this->displayErrorFromServer = true; } } catch (kCoreException $e) { $this->hashKeyErrorCode = $e->getCode(); } } sfView::SUCCESS; }
/** * @param string $url * @param string $urlPrefix * @return string */ public function tokenizeSingleUrl($url, $urlPrefix = null) { if (!$this->ksObject || !$this->ksObject->user) { KExternalErrors::dieError(KExternalErrors::MISSING_PARAMETER, 'ks user'); } $uriRestrict = explode(',', $url); // cannot contain commas, since it's used as the privileges delimiter $uriRestrict = $uriRestrict[0]; $privileges = kSessionBase::PRIVILEGE_DISABLE_ENTITLEMENT_FOR_ENTRY . ':' . $this->entryId; $privileges .= ',' . kSessionBase::PRIVILEGE_VIEW . ':' . $this->entryId; $privileges .= ',' . kSessionBase::PRIVILEGE_URI_RESTRICTION . ':' . $uriRestrict . '*'; $ks = kSessionBase::generateKsV2($this->key, $this->ksObject->user, kSessionBase::SESSION_TYPE_USER, $this->partnerId, $this->window, $privileges, null, null); return $url . '?ks=' . $ks; }
public function execute() { $this->uiconf_id = $this->getRequestParameter('uiconf_id'); if (!$this->uiconf_id) { KExternalErrors::dieError(KExternalErrors::MISSING_PARAMETER, 'uiconf_id'); } $this->uiConf = uiConfPeer::retrieveByPK($this->uiconf_id); if (!$this->uiConf) { KExternalErrors::dieError(KExternalErrors::UI_CONF_NOT_FOUND); } $this->partner_id = $this->getRequestParameter('partner_id', $this->uiConf->getPartnerId()); if (!$this->partner_id) { KExternalErrors::dieError(KExternalErrors::MISSING_PARAMETER, 'partner_id'); } // Single Player parameters $this->entry_id = $this->getRequestParameter('entry_id'); if ($this->entry_id) { $entry = entryPeer::retrieveByPK($this->entry_id); if ($entry) { $this->entry_name = $entry->getName(); $this->entry_description = $entry->getDescription(); $this->entry_thumbnail_url = $entry->getThumbnailUrl(); $flavor_tag = $this->getRequestParameter('flavor_tag', 'iphone'); $flavor_assets = assetPeer::retrieveReadyFlavorsByEntryIdAndTag($this->entry_id, $flavor_tag); $flavor_asset = reset($flavor_assets); /* @var $flavor_asset flavorAsset */ $this->flavor_asset_id = null; if ($flavor_asset) { $this->flavor_asset_id = $flavor_asset->getId(); } } else { $this->entry_id = null; } } $this->delivery_type = $this->getRequestParameter('delivery'); // Playlist Parameters $this->playlist_id = $this->getRequestParameter('playlist_id'); $this->playlist_name = $this->getRequestParameter('playlist_name'); $this->partner_host = myPartnerUtils::getHost($this->partner_id); $this->partner_cdnHost = myPartnerUtils::getCdnHost($this->partner_id); $this->secure_host = kConf::get('cdn_host_https'); }
/** * 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; }
public function execute() { $entry_id = $this->getRequestParameter("entryId"); // 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 $entry = entryPeer::retrieveByPKNoFilter($entry_id); if (!$entry) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } if ($entry->getType() != entryType::LIVE_STREAM || $entry->getStatus() == entryStatus::DELETED) { // because the fiter was turned off - a manual check for deleted entries must be done. die; } $file = $entry->getStreamName(); $streamer = $entry->getStreamUrl(); $this->logMessage("streamclipper: serving entry [{$entry_id}] file[{$file}] streamer[{$streamer}]", "warning"); $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<config>\n\t<file>{$file}</file>\n\t<subscribe>true</subscribe>\n\t<streamer>{$streamer}</streamer>\n\t<type>fcsubscribe</type>\n</config>"; header("Content-Type: text/xml; charset=UTF-8"); echo $xml; die; }
/** * Will forward to the regular swf player according to the widget_id */ public function execute() { $uiconf_id = $this->getRequestParameter('uiconf_id'); if (!$uiconf_id) { KExternalErrors::dieError(KExternalErrors::MISSING_PARAMETER, 'uiconf_id'); } $uiConf = uiConfPeer::retrieveByPK($uiconf_id); if (!$uiConf) { KExternalErrors::dieError(KExternalErrors::UI_CONF_NOT_FOUND); } $partner_id = $this->getRequestParameter('partner_id', $uiConf->getPartnerId()); if (!$partner_id) { KExternalErrors::dieError(KExternalErrors::MISSING_PARAMETER, 'partner_id'); } $partner_host = myPartnerUtils::getHost($partner_id); $partner_cdnHost = myPartnerUtils::getCdnHost($partner_id); $html5_version = kConf::get('html5_version'); $use_cdn = $uiConf->getUseCdn(); $host = $use_cdn ? $partner_cdnHost : $partner_host; $url = $host; $url .= "/html5/html5lib/v{$html5_version}/mwEmbedLoader.php"; $this->redirect($url); }
public function execute() { $this->html5_version = kConf::get('html5_version'); $this->uiconf_id = $this->getRequestParameter('uiconf_id'); if (!$this->uiconf_id) { KExternalErrors::dieError(KExternalErrors::MISSING_PARAMETER, 'uiconf_id'); } $this->uiConf = uiConfPeer::retrieveByPK($this->uiconf_id); if (!$this->uiConf) { KExternalErrors::dieError(KExternalErrors::UI_CONF_NOT_FOUND); } $this->partner_id = $this->getRequestParameter('partner_id', $this->uiConf->getPartnerId()); if (!$this->partner_id) { KExternalErrors::dieError(KExternalErrors::MISSING_PARAMETER, 'partner_id'); } $this->entry_id = $this->getRequestParameter('entry_id'); if (!$this->entry_id) { KExternalErrors::dieError(KExternalErrors::MISSING_PARAMETER, 'entry_id'); } $this->delivery_type = $this->getRequestParameter('delivery'); $this->partner_host = myPartnerUtils::getHost($this->partner_id); $this->partner_cdnHost = myPartnerUtils::getCdnHost($this->partner_id); }
/** * Will forward to the regular swf player according to the widget_id */ public function execute() { 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); $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); if ($width == -1 && $height == -1) { $width = 120; $height = 90; } 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; } } } $bgcolor = $this->getRequestParameter("bgcolor", "ffffff"); $partner = 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 ($upload_token_id) { $upload_token = UploadTokenPeer::retrieveByPK($upload_token_id); if ($upload_token) { $partnerId = $upload_token->getPartnerId(); $partner = PartnerPeer::retrieveByPK($partnerId); 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); kFile::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']; kFile::dumpUrl($remoteUrl); } } } if ($entry_id) { $entry = entryPeer::retrieveByPKNoFilter($entry_id); if (!$entry) { // problem could be due to replication lag kFile::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); } } $partner = $entry->getPartner(); 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, accessControlContextType::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) { $widthRatio = $entry->getWidth() / $rel_width; $src_x = $src_x * $widthRatio; $src_w = $src_w * $widthRatio; } if ($rel_height != -1) { $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"; } kFile::dumpFile($msgPath, null, 0); } if (!$file_sync) { $tempThumbPath = $entry->getLocalThumbFilePath($entry, $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}"); die; } $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($file_sync, $_SERVER['REQUEST_URI']); kFile::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, null, $density, $stripProfiles, $thumbParams); } 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); kFile::dumpUrl($remoteUrl); } } $nocache = strpos($tempThumbPath, "_NOCACHE_") !== false; if ($securyEntryHelper->shouldDisableCache() || kApiCache::hasExtraFields() || !$securyEntryHelper->isKsWidget() && $securyEntryHelper->hasRules()) { $nocache = true; } // notify external proxy, so it'll cache this url if (!$nocache && requestUtils::getHost() == kConf::get("apphome_url") && file_exists($tempThumbPath)) { self::notifyProxy($_SERVER["REQUEST_URI"]); } // cache result if (!$nocache) { $requestKey = $_SERVER["REQUEST_URI"]; $cache = new myCache("thumb", 86400 * 30); // 30 days $cache->put($requestKey, $tempThumbPath); } kFile::dumpFile($tempThumbPath, null, $nocache ? 0 : null); // 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) }
public function execute() { // Disable layout $this->setLayout(false); $this->success = false; $this->type = $this->getRequestParameter('type'); if (!$this->type) { KExternalErrors::dieError(KExternalErrors::MISSING_PARAMETER, 'type'); } $validTypes = array('name', 'email', 'password'); if (!in_array($this->type, $validTypes)) { KExternalErrors::dieError(KExternalErrors::INVALID_SETTING_TYPE); } $ks = $this->getP("kmcks"); if (!$ks) { KExternalErrors::dieError(KExternalErrors::MISSING_PARAMETER, 'ks'); } // Get partner & user info from KS $ksObj = kSessionUtils::crackKs($ks); $partnerId = $ksObj->partner_id; $userId = $ksObj->user; $partner = PartnerPeer::retrieveByPK($partnerId); if (!$partner) { KExternalErrors::dieError(KExternalErrors::PARTNER_NOT_FOUND); } if (!$partner->validateApiAccessControl()) { KExternalErrors::dieError(KExternalErrors::SERVICE_ACCESS_CONTROL_RESTRICTED); } $this->forceKMCHttps = PermissionPeer::isValidForPartner(PermissionName::FEATURE_KMC_ENFORCE_HTTPS, $partnerId); if ($this->forceKMCHttps) { // Prevent the page fron being embeded in an iframe header('X-Frame-Options: SAMEORIGIN'); } if ($this->forceKMCHttps && (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on')) { die; } // Load the current user $dbUser = kuserPeer::getKuserByPartnerAndUid($partnerId, $userId); if (!$dbUser) { KExternalErrors::dieError('INVALID_USER_ID', $userId); } $this->email = $dbUser->getEmail(); $this->fname = $dbUser->getFirstName(); $this->lname = $dbUser->getLastName(); $this->parent_url = $this->clean($_GET['parent']); // Set page title switch ($this->type) { case 'password': $this->pageTitle = 'Change Password'; break; case 'email': $this->pageTitle = 'Change Email Address'; break; case 'name': $this->pageTitle = 'Change Username'; break; } // select which action to do if (isset($_POST['do'])) { switch ($_POST['do']) { case "password": $this->changePassword(); break; case "email": $this->changeEmail(); break; case "name": $this->changeName(); break; } } sfView::SUCCESS; }
/** * Ensure the request for media arrived in a way approved by the partner. * this may include restricting to a specific cdn, enforcing token usage etc.. * Die in case of a breach. * * @param entry $entry * @param asset $asset */ public static function enforceDelivery($entry, $asset = null) { // block inactive partner $partnerId = $entry->getPartnerId(); self::blockInactivePartner($partnerId); // validate serve access control $flavorParamsId = $asset ? $asset->getFlavorParamsId() : null; $secureEntryHelper = new KSecureEntryHelper($entry, null, null, ContextType::SERVE); $secureEntryHelper->validateForServe($flavorParamsId); // enforce delivery $partner = PartnerPeer::retrieveByPK($partnerId); // Note: Partner was already loaded by blockInactivePartner, no need to check for null $restricted = DeliveryProfilePeer::isRequestRestricted($partner); if ($restricted) { KalturaLog::log("DELIVERY_METHOD_NOT_ALLOWED partner [{$partnerId}]"); KExternalErrors::dieError(KExternalErrors::DELIVERY_METHOD_NOT_ALLOWED); } }
/** * Will forward to the regular swf player according to the widget_id */ public function execute() { $entry_id = $this->getRequestParameter("entry_id"); $entry = null; $widget_id = null; $partner_id = null; if ($entry_id) { $entry = entryPeer::retrieveByPK($entry_id); if (!$entry) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } $partner_id = $entry->getPartnerId(); $widget_id = '_' . $partner_id; } $widget_id = $this->getRequestParameter("widget_id", $widget_id); $widget = widgetPeer::retrieveByPK($widget_id); if (!$widget) { KExternalErrors::dieError(KExternalErrors::WIDGET_NOT_FOUND); } $subp_id = $widget->getSubpId(); if (!$subp_id) { $subp_id = 0; } if (!$entry_id) { $entry_id = $widget->getEntryId(); if (!$entry_id) { KExternalErrors::dieError(KExternalErrors::MISSING_PARAMETER, 'entry_id'); } $entry = entryPeer::retrieveByPK($entry_id); if (!$entry) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } } $allowCache = true; $securityType = $widget->getSecurityType(); switch ($securityType) { case widget::WIDGET_SECURITY_TYPE_TIMEHASH: // TODO - I don't know what should be validated here break; case widget::WIDGET_SECURITY_TYPE_MATCH_IP: $allowCache = false; // here we'll attemp to match the ip of the request with that from the customData of the widget $custom_data = $widget->getCustomData(); $valid_country = false; if ($custom_data) { // in this case the custom_data should be of format: // valid_county_1,valid_country_2,...,valid_country_n;falback_entry_id $arr = explode(";", $custom_data); $countries_str = $arr[0]; $fallback_entry_id = isset($arr[1]) ? $arr[1] : null; $fallback_kshow_id = isset($arr[2]) ? $arr[2] : null; $current_country = ""; $valid_country = requestUtils::matchIpCountry($countries_str, $current_country); if (!$valid_country) { KalturaLog::log("Attempting to access widget [{$widget_id}] and entry [{$entry_id}] from country [{$current_country}]. Retrning entry_id: [{$fallback_entry_id}] kshow_id [{$fallback_kshow_id}]"); $entry_id = $fallback_entry_id; } } break; case widget::WIDGET_SECURITY_TYPE_FORCE_KS: $ks_str = $this->getRequestParameter('ks'); try { $ks = kSessionUtils::crackKs($ks_str); } catch (Exception $e) { KExternalErrors::dieError(KExternalErrors::INVALID_KS); } $res = kSessionUtils::validateKSession2(1, $partner_id, 0, $ks_str, $ks); if ($res <= 0) { KExternalErrors::dieError(KExternalErrors::INVALID_KS); } break; default: break; } $requestKey = $_SERVER["REQUEST_URI"]; // check if we cached the redirect url $cache = new myCache("embedIframe", 10 * 60); // 10 minutes $cachedResponse = $cache->get($requestKey); if ($allowCache && $cachedResponse) { header("X-Kaltura: cached-action"); 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"); header("Location:{$cachedResponse}"); die; } $uiconf_id = $this->getRequestParameter('uiconf_id'); if (!$uiconf_id) { $uiconf_id = $widget->getUiConfId(); } if (!$uiconf_id) { KExternalErrors::dieError(KExternalErrors::MISSING_PARAMETER, 'uiconf_id'); } $partner_host = myPartnerUtils::getHost($partner_id); $partner_cdnHost = myPartnerUtils::getCdnHost($partner_id); $uiConf = uiConfPeer::retrieveByPK($uiconf_id); if (!$uiConf) { KExternalErrors::dieError(KExternalErrors::UI_CONF_NOT_FOUND); } $partner_host = myPartnerUtils::getHost($partner_id); $partner_cdnHost = myPartnerUtils::getCdnHost($partner_id); $html5_version = kConf::get('html5_version'); $use_cdn = $uiConf->getUseCdn(); $host = $use_cdn ? $partner_cdnHost : $partner_host; $url = $host; $url .= "/html5/html5lib/v{$html5_version}/mwEmbedFrame.php"; $url .= "/entry_id/{$entry_id}/wid/{$widget_id}/uiconf_id/{$uiconf_id}"; if ($allowCache) { $cache->put($requestKey, $url); } $this->redirect($url); }
public function execute() { sfView::SUCCESS; /** check parameters and verify user is logged-in **/ $this->ks = $this->getP("kmcks"); if (!$this->ks) { // if kmcks from cookie doesn't exist, try ks from REQUEST $this->ks = $this->getP('ks'); } /** if no KS found, redirect to login page **/ if (!$this->ks) { $this->redirect("kmc/kmc"); die; } $ksObj = kSessionUtils::crackKs($this->ks); // Set partnerId from KS $this->partner_id = $ksObj->partner_id; // Check if the KMC can be framed $allowFrame = PermissionPeer::isValidForPartner(PermissionName::FEATURE_KMC_ALLOW_FRAME, $this->partner_id); if (!$allowFrame) { header('X-Frame-Options: DENY'); } // Check for forced HTTPS $force_ssl = PermissionPeer::isValidForPartner(PermissionName::FEATURE_KMC_ENFORCE_HTTPS, $this->partner_id); if ($force_ssl && (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on')) { header("Location: " . infraRequestUtils::PROTOCOL_HTTPS . "://" . $_SERVER['SERVER_NAME'] . $_SERVER["REQUEST_URI"]); die; } /** END - check parameters and verify user is logged-in **/ /** Get array of allowed partners for the current user **/ $allowedPartners = array(); $this->full_name = ""; $currentUser = kuserPeer::getKuserByPartnerAndUid($this->partner_id, $ksObj->user, true); if ($currentUser) { $partners = myPartnerUtils::getPartnersArray($currentUser->getAllowedPartnerIds()); foreach ($partners as $partner) { $allowedPartners[] = array('id' => $partner->getId(), 'name' => $partner->getName()); } $this->full_name = $currentUser->getFullName(); } $this->showChangeAccount = count($allowedPartners) > 1 ? true : false; // Load partner $this->partner = $partner = PartnerPeer::retrieveByPK($this->partner_id); if (!$partner) { KExternalErrors::dieError(KExternalErrors::PARTNER_NOT_FOUND); } if (!$partner->validateApiAccessControl()) { KExternalErrors::dieError(KExternalErrors::SERVICE_ACCESS_CONTROL_RESTRICTED); } kmcUtils::redirectPartnerToCorrectKmc($partner, $this->ks, null, null, null, self::CURRENT_KMC_VERSION); $this->templatePartnerId = $this->partner ? $this->partner->getTemplatePartnerId() : self::SYSTEM_DEFAULT_PARTNER; $ignoreEntrySeoLinks = PermissionPeer::isValidForPartner(PermissionName::FEATURE_IGNORE_ENTRY_SEO_LINKS, $this->partner_id); $useEmbedCodeProtocolHttps = PermissionPeer::isValidForPartner(PermissionName::FEATURE_EMBED_CODE_DEFAULT_PROTOCOL_HTTPS, $this->partner_id); $showFlashStudio = PermissionPeer::isValidForPartner(PermissionName::FEATURE_SHOW_FLASH_STUDIO, $this->partner_id); $showHTMLStudio = PermissionPeer::isValidForPartner(PermissionName::FEATURE_SHOW_HTML_STUDIO, $this->partner_id); $deliveryTypes = $partner->getDeliveryTypes(); $embedCodeTypes = $partner->getEmbedCodeTypes(); $defaultDeliveryType = $partner->getDefaultDeliveryType() ? $partner->getDefaultDeliveryType() : 'http'; $defaultEmbedCodeType = $partner->getDefaultEmbedCodeType() ? $partner->getDefaultEmbedCodeType() : 'auto'; $this->previewEmbedV2 = PermissionPeer::isValidForPartner(PermissionName::FEATURE_PREVIEW_AND_EMBED_V2, $this->partner_id); /** set values for template **/ $this->service_url = requestUtils::getRequestHost(); $this->host = $this->stripProtocol($this->service_url); $this->embed_host = $this->stripProtocol(myPartnerUtils::getHost($this->partner_id)); if (kConf::hasParam('cdn_api_host') && kConf::hasParam('www_host') && $this->host == kConf::get('cdn_api_host')) { $this->host = kConf::get('www_host'); } if ($this->embed_host == kConf::get("www_host") && kConf::hasParam('cdn_api_host')) { $this->embed_host = kConf::get('cdn_api_host'); } $this->embed_host_https = kConf::hasParam('cdn_api_host_https') ? kConf::get('cdn_api_host_https') : kConf::get('www_host'); $this->cdn_url = myPartnerUtils::getCdnHost($this->partner_id); $this->cdn_host = $this->stripProtocol($this->cdn_url); $this->rtmp_host = kConf::get("rtmp_url"); $this->flash_dir = $this->cdn_url . myContentStorage::getFSFlashRootPath(); /** set payingPartner flag **/ $this->payingPartner = 'false'; if ($partner && $partner->getPartnerPackage() != PartnerPackages::PARTNER_PACKAGE_FREE) { $this->payingPartner = 'true'; $ignoreSeoLinks = true; } else { $ignoreSeoLinks = $this->partner->getIgnoreSeoLinks(); } /** get partner languae **/ $language = null; if ($partner->getKMCLanguage()) { $language = $partner->getKMCLanguage(); } $first_login = $partner->getIsFirstLogin(); if ($first_login === true) { $partner->setIsFirstLogin(false); $partner->save(); } /** get logout url **/ $logoutUrl = null; if ($partner->getLogoutUrl()) { $logoutUrl = $partner->getLogoutUrl(); } $this->kmc_swf_version = kConf::get('kmc_version'); $akamaiEdgeServerIpURL = null; if (kConf::hasParam('akamai_edge_server_ip_url')) { $akamaiEdgeServerIpURL = kConf::get('akamai_edge_server_ip_url'); } /** uiconf listing work **/ /** fill $confs with all uiconf objects for all modules **/ $kmcGeneralUiConf = kmcUtils::getAllKMCUiconfs('kmc', $this->kmc_swf_version, self::SYSTEM_DEFAULT_PARTNER); $kmcGeneralTemplateUiConf = kmcUtils::getAllKMCUiconfs('kmc', $this->kmc_swf_version, $this->templatePartnerId); /** for each module, create separated lists of its uiconf, for each need **/ /** kmc general uiconfs **/ $this->kmc_general = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_kmcgeneral", false, $kmcGeneralUiConf); $this->kmc_permissions = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_kmcpermissions", false, $kmcGeneralUiConf); /** P&E players: **/ //$this->content_uiconfs_previewembed = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_previewembed", true, $kmcGeneralUiConf); //$this->content_uiconfs_previewembed_list = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_previewembed_list", true, $kmcGeneralUiConf); $this->content_uiconfs_flavorpreview = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_flavorpreview", false, $kmcGeneralUiConf); /* KCW uiconfs */ $this->content_uiconfs_upload_webcam = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_uploadWebCam", false, $kmcGeneralUiConf); $this->content_uiconfs_upload_import = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_uploadImport", false, $kmcGeneralUiConf); $this->content_uiconds_clipapp_kdp = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_kdpClipApp", false, $kmcGeneralUiConf); $this->content_uiconds_clipapp_kclip = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_kClipClipApp", false, $kmcGeneralUiConf); $this->studioUiConf = kmcUtils::getStudioUiconf(kConf::get("studio_version")); $this->content_uiconfs_studio_v2 = isset($this->studioUiConf) ? array_values($this->studioUiConf) : null; $this->content_uiconf_studio_v2 = is_array($this->content_uiconfs_studio_v2) && reset($this->content_uiconfs_studio_v2) ? reset($this->content_uiconfs_studio_v2) : null; $this->liveAUiConf = kmcUtils::getLiveAUiconf(); $this->content_uiconfs_livea = isset($this->liveAUiConf) ? array_values($this->liveAUiConf) : null; $this->content_uiconf_livea = is_array($this->content_uiconfs_livea) && reset($this->content_uiconfs_livea) ? reset($this->content_uiconfs_livea) : null; $kmcVars = array('kmc_version' => $this->kmc_swf_version, 'kmc_general_uiconf' => $this->kmc_general->getId(), 'kmc_permissions_uiconf' => $this->kmc_permissions->getId(), 'allowed_partners' => $allowedPartners, 'kmc_secured' => (bool) kConf::get("kmc_secured_login"), 'enableLanguageMenu' => true, 'service_url' => $this->service_url, 'host' => $this->host, 'cdn_host' => $this->cdn_host, 'rtmp_host' => $this->rtmp_host, 'embed_host' => $this->embed_host, 'embed_host_https' => $this->embed_host_https, 'flash_dir' => $this->flash_dir, 'getuiconfs_url' => '/index.php/kmc/getuiconfs', 'terms_of_use' => kConf::get('terms_of_use_uri'), 'ks' => $this->ks, 'partner_id' => $this->partner_id, 'first_login' => (bool) $first_login, 'whitelabel' => $this->templatePartnerId, 'ignore_seo_links' => (bool) $ignoreSeoLinks, 'ignore_entry_seo' => (bool) $ignoreEntrySeoLinks, 'embed_code_protocol_https' => (bool) $useEmbedCodeProtocolHttps, 'delivery_types' => $deliveryTypes, 'embed_code_types' => $embedCodeTypes, 'default_delivery_type' => $defaultDeliveryType, 'default_embed_code_type' => $defaultEmbedCodeType, 'kcw_webcam_uiconf' => $this->content_uiconfs_upload_webcam->getId(), 'kcw_import_uiconf' => $this->content_uiconfs_upload_import->getId(), 'default_kdp' => array('id' => $this->content_uiconfs_flavorpreview->getId(), 'height' => $this->content_uiconfs_flavorpreview->getHeight(), 'width' => $this->content_uiconfs_flavorpreview->getWidth(), 'swf_version' => $this->content_uiconfs_flavorpreview->getswfUrlVersion()), 'clipapp' => array('version' => kConf::get("clipapp_version"), 'kdp' => $this->content_uiconds_clipapp_kdp->getId(), 'kclip' => $this->content_uiconds_clipapp_kclip->getId()), 'studio' => array('version' => kConf::get("studio_version"), 'uiConfID' => isset($this->content_uiconf_studio_v2) ? $this->content_uiconf_studio_v2->getId() : '', 'config' => isset($this->content_uiconf_studio_v2) ? $this->content_uiconf_studio_v2->getConfig() : '', 'showFlashStudio' => $showFlashStudio, 'showHTMLStudio' => $showHTMLStudio), 'liveanalytics' => array('version' => kConf::get("liveanalytics_version"), 'player_id' => isset($this->content_uiconf_livea) ? $this->content_uiconf_livea->getId() : '', 'map_zoom_levels' => kConf::hasParam("map_zoom_levels") ? kConf::get("map_zoom_levels") : '', 'map_urls' => kConf::hasParam("cdn_static_hosts") ? array_map(function ($s) { return "{$s}/content/static/maps/v1"; }, kConf::get("cdn_static_hosts")) : ''), 'usagedashboard' => array('version' => kConf::get("usagedashboard_version")), 'disable_analytics' => (bool) kConf::get("kmc_disable_analytics"), 'google_analytics_account' => kConf::get("ga_account"), 'language' => $language, 'logoutUrl' => $logoutUrl, 'allowFrame' => (bool) $allowFrame, 'akamaiEdgeServerIpURL' => $akamaiEdgeServerIpURL, 'logoUrl' => kmcUtils::getWhitelabelData($partner, 'logo_url'), 'supportUrl' => kmcUtils::getWhitelabelData($partner, 'support_url')); $this->kmcVars = $kmcVars; }
public function execute() { requestUtils::handleConditionalGet(); $flavorId = $this->getRequestParameter("flavorId"); $shouldProxy = $this->getRequestParameter("forceproxy", false); $ks = $this->getRequestParameter("ks"); $fileParam = $this->getRequestParameter("file"); $referrer = base64_decode($this->getRequestParameter("referrer")); if (!is_string($referrer)) { // base64_decode can return binary data $referrer = ''; } $flavorAsset = flavorAssetPeer::retrieveById($flavorId); if (is_null($flavorAsset)) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } $entry = entryPeer::retrieveByPK($flavorAsset->getEntryId()); if (is_null($entry)) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } myPartnerUtils::blockInactivePartner($flavorAsset->getPartnerId()); myPartnerUtils::enforceDelivery($flavorAsset->getPartnerId()); //disabled enforce cdn because of rtmp delivery //requestUtils::enforceCdnDelivery($flavorAsset->getPartnerId()); $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); 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); kFile::dumpUrl($remoteUrl, true, true); } $path = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey); $flvWrapper = new myFlvHandler($path); $isFlv = $flvWrapper->isFlv(); $clipFrom = $this->getRequestParameter("clipFrom", 0); // milliseconds $clipTo = $this->getRequestParameter("clipTo", 2147483647); // milliseconds if ($clipTo == 0) { $clipTo = 2147483647; } if (is_dir($path) && $fileParam) { $path .= "/{$fileParam}"; //echo "path($path),file($fileParam)"; kFile::dumpFile($path, null, null); die; } else { if (!$isFlv) { $limit_file_size = 0; if ($clipTo != 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(@filesize($path) * ($clipTo / $duration)); } } kFile::dumpFile($path, null, null, $limit_file_size); die; } } $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; } $seekFrom = $this->getRequestParameter("seekFrom", -1); if ($seekFrom <= 0) { $seekFrom = -1; } $seekFromBytes = $this->getRequestParameter("seekFromBytes", -1); if ($seekFromBytes <= 0) { $seekFromBytes = -1; } $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); } header('Content-Disposition: attachment; filename="video.flv"'); // 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); die; }
public function validateForServe($flavorParamsId) { if (!$this->isFlavorParamsAllowed($flavorParamsId)) { KExternalErrors::dieError(KExternalErrors::ACCESS_CONTROL_RESTRICTED); } if ($this->shouldBlock()) { KExternalErrors::dieError(KExternalErrors::ACCESS_CONTROL_RESTRICTED); } }
private function _prepareJs() { $baseFilePath = $this->_getJsFilesPath(); $somDetectJsPath = $baseFilePath . self::SOM_DETECT_JS_FILENAME; $somJsPath = $baseFilePath . self::SOM_JS_FILENAME; $apiJsPath = $baseFilePath . self::KALTURA_LIB_API_JS_FILENAME; if (!file_exists($somDetectJsPath) || !file_exists($somJsPath) || !file_exists($apiJsPath)) { KExternalErrors::dieError(KExternalErrors::ILLEGAL_UI_CONF, "Required file is missing"); } $somDetectJs = file_get_contents($somDetectJsPath); $somJs = file_get_contents($somJsPath); $apiJs = file_get_contents($apiJsPath); $fullJs = $somDetectJs . PHP_EOL . $somJs . PHP_EOL . $this->jsResult . PHP_EOL . $apiJs; $this->jsResult = $fullJs; }
/** * * Will serve a requested report * @action serveReport * * * @param string $id - the requested id * @return string */ public function serveReportAction($id) { $fileNameRegex = "/^(?<dc>[01]+)_(?<fileName>\\d+_Export_[a-zA-Z0-9]+_[\\w\\-]+.csv)\$/"; // KS verification - we accept either admin session or download privilege of the file $ks = $this->getKs(); if (!$ks || !($ks->isAdmin() || $ks->verifyPrivileges(ks::PRIVILEGE_DOWNLOAD, $id))) { KExternalErrors::dieError(KExternalErrors::ACCESS_CONTROL_RESTRICTED); } if (!preg_match($fileNameRegex, $id, $matches)) { KalturaLog::err("Report Id Format doesn't match the file name format"); throw new KalturaAPIException(KalturaErrors::REPORT_NOT_FOUND, $id); } // Check if the request should be handled by the other DC $curerntDc = kDataCenterMgr::getCurrentDcId(); if ($matches['dc'] == 1 - $curerntDc) { kFileUtils::dumpApiRequest(kDataCenterMgr::getRemoteDcExternalUrlByDcId(1 - $curerntDc)); } // Serve report $filePath = $this->getReportDirectory($this->getPartnerId()) . DIRECTORY_SEPARATOR . $matches['fileName']; return $this->dumpFile($filePath, 'text/csv'); }
protected function validateKs() { if ($this->ksStr) { try { // todo need to check if partner is within a partner group $ks = kSessionUtils::crackKs($this->ksStr); // if entry is "display_in_search=2" validate partner ID from the KS // => meaning it will alwasy pass on partner_id if ($this->entry->getDisplayInSearch() != mySearchUtils::DISPLAY_IN_SEARCH_KALTURA_NETWORK) { $valid = $ks->isValidForPartner($this->entry->getPartnerId()); } else { $valid = $ks->isValidForPartner($ks->partner_id); } if ($valid === ks::EXPIRED) { die("This URL is expired"); } else { if ($valid === ks::INVALID_PARTNER) { if ($this->hasRules()) { // TODO - for now if the entry doesnt have restrictions any way disregard a partner group check die("Invalid session [" . $valid . "]"); } } else { if ($valid !== ks::OK) { die("Invalid session [" . $valid . "]"); } } } if ($ks->partner_id != $this->entry->getPartnerId()) { return; } $this->ks = $ks; } catch (Exception $ex) { KExternalErrors::dieError(KExternalErrors::INVALID_KS_SRT); } } }
public static function dumpUrl($url, $allowRange = true, $passHeaders = false, $additionalHeaders = null) { KalturaLog::debug("URL [{$url}], {$allowRange} [{$allowRange}], {$passHeaders} [{$passHeaders}]"); self::closeDbConnections(); $ch = curl_init(); // set URL and other appropriate options curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_USERAGENT, "curl/7.11.1"); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // in case of private ips (internal to the datacenters) no need to check the certificate validity. // otherwise curling for https://127.0.0.1/ will fail as the certificate is for *.domain.com $urlHost = parse_url($url, PHP_URL_HOST); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, infraRequestUtils::isIpPrivate($urlHost) ? 0 : 2); // prevent loop back of the proxied request by detecting the "X-Kaltura-Proxy header if (isset($_SERVER["HTTP_X_KALTURA_PROXY"])) { KExternalErrors::dieError(KExternalErrors::PROXY_LOOPBACK); } $sendHeaders = array("X-Kaltura-Proxy: dumpUrl"); if ($passHeaders) { $sentHeaders = self::getRequestHeaders(); foreach ($sentHeaders as $header => $value) { $sendHeaders[] = "{$header}: {$value}"; } } elseif ($allowRange && isset($_SERVER['HTTP_RANGE']) && $_SERVER['HTTP_RANGE']) { // get range parameters from HTTP range requst headers list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2); curl_setopt($ch, CURLOPT_RANGE, $range); } if ($additionalHeaders) { foreach ($additionalHeaders as $header => $value) { $sendHeaders[] = "{$header}: {$value}"; } } // when proxying request to other datacenter we may be already in a proxied request (from one of the internal proxy servers) // we need to ensure the original HOST is sent in order to allow restirctions checks $host = isset($_SERVER["HTTP_X_FORWARDED_HOST"]) ? $_SERVER["HTTP_X_FORWARDED_HOST"] : $_SERVER["HTTP_HOST"]; for ($i = 0; $i < count($sendHeaders); $i++) { if (stripos($sendHeaders[$i], "host:") === 0) { array_splice($sendHeaders, $i, 1); break; } } $sendHeaders[] = "Host:{$host}"; curl_setopt($ch, CURLOPT_HTTPHEADER, $sendHeaders); if ($_SERVER['REQUEST_METHOD'] == 'HEAD') { // request was HEAD, proxy only HEAD response curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_NOBODY, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); } else { // Set callback function for body curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'kFileUtils::read_body'); } // Set callback function for headers curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'kFileUtils::read_header'); //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); header("Access-Control-Allow-Origin:*"); // avoid html5 xss issues header("X-Kaltura:dumpUrl"); // grab URL and pass it to the browser $content = curl_exec($ch); KalturaLog::debug("CURL executed [{$content}]"); // close curl resource, and free up system resources curl_close($ch); KExternalErrors::dieGracefully(); }
public function execute() { $this->entryId = $this->getRequestParameter("entryId", null); $this->flavorId = $this->getRequestParameter("flavorId", null); $this->storageId = $this->getRequestParameter("storageId", null); $this->maxBitrate = $this->getRequestParameter("maxBitrate", null); $flavorIdsStr = $this->getRequestParameter("flavorIds", null); if ($flavorIdsStr) { $this->flavorIds = explode(",", $flavorIdsStr); } $this->entry = entryPeer::retrieveByPKNoFilter($this->entryId); if (!$this->entry) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } if (!$this->flavorId) { $flavorParamId = $this->getRequestParameter("flavorParamId", null); if ($flavorParamId) { $flavorAsset = flavorAssetPeer::retrieveByEntryIdAndFlavorParams($entry->getId(), $flavorParamId); if (!$flavorAsset) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } $this->flavorId = $flavorAsset->getId(); } } $this->validateStorageId(); $this->protocol = $this->getRequestParameter("protocol", null); if (!$this->protocol) { $this->protocol = StorageProfile::PLAY_FORMAT_HTTP; } $this->format = $this->getRequestParameter("format"); if (!$this->format) { $this->format = StorageProfile::PLAY_FORMAT_HTTP; } $this->cdnHost = $this->getRequestParameter("cdnHost", null); $partner = $this->entry->getPartner(); if (!$this->cdnHost || $partner->getForceCdnHost()) { $this->cdnHost = myPartnerUtils::getCdnHost($this->entry->getPartnerId(), $this->protocol); } if ($this->maxBitrate && (!is_numeric($this->maxBitrate) || $this->maxBitrate <= 0)) { KExternalErrors::dieError(KExternalErrors::INVALID_MAX_BITRATE); } $ksStr = $this->getRequestParameter("ks"); $base64Referrer = $this->getRequestParameter("referrer"); $referrer = base64_decode($base64Referrer); if (!is_string($referrer)) { $referrer = ""; } // base64_decode can return binary data $securyEntryHelper = new KSecureEntryHelper($this->entry, $ksStr, $referrer); if ($securyEntryHelper->shouldPreview()) { $this->clipTo = $securyEntryHelper->getPreviewLength() * 1000; } else { $securyEntryHelper->validateForPlay($this->entry, $ksStr); } // grab seekFrom parameter and normalize url $this->seekFrom = $this->getRequestParameter("seekFrom", -1); if ($this->seekFrom <= 0) { $this->seekFrom = -1; } if ($this->entry->getStatus() == entryStatus::DELETED) { // because the fiter was turned off - a manual check for deleted entries must be done. die; } $xml = null; switch ($this->format) { case StorageProfile::PLAY_FORMAT_HTTP: $xml = $this->serveHttp(); break; case StorageProfile::PLAY_FORMAT_RTMP: $xml = $this->serveRtmp(); break; case StorageProfile::PLAY_FORMAT_SILVER_LIGHT: $xml = $this->serveSilverLight(); break; case StorageProfile::PLAY_FORMAT_APPLE_HTTP: $xml = $this->serveAppleHttp(); break; case "url": return $this->serveUrl(); break; case "hdnetworksmil": $xml = $this->serveHDNetwork(); break; case "hdnetwork": $duration = $this->entry->getDurationInt(); $mediaUrl = "<media url=\"" . requestUtils::getHost() . str_replace("f4m", "smil", str_replace("hdnetwork", "hdnetworksmil", $_SERVER["REQUEST_URI"])) . "\"/>"; $xml = $this->buildXml(self::PLAY_STREAM_TYPE_RECORDED, array(), 'video/x-flv', $duration, null, $mediaUrl); break; } if ($this->format == StorageProfile::PLAY_FORMAT_APPLE_HTTP) { header("Content-Type: text/plain; charset=UTF-8"); } else { header("Content-Type: text/xml; charset=UTF-8"); header("Content-Disposition: inline; filename=manifest.xml"); } echo $xml; die; }
private function handleFileSyncRedirection(FileSyncKey $syncKey) { list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false); if (is_null($fileSync)) { KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND); } if (!$local) { $remote_url = kDataCenterMgr::getRedirectExternalUrl($fileSync); $this->redirect($remote_url); } }
/** * will create thumbnail according to the entry type * @return the thumbnail path. */ public function getLocalThumbFilePath($version, $width, $height, $type, $bgcolor = "ffffff", $crop_provider = null, $quality = 0, $src_x = 0, $src_y = 0, $src_w = 0, $src_h = 0, $vid_sec = -1, $vid_slice = 0, $vid_slices = -1, $density = 0, $stripProfiles = false, $flavorId = null, $fileName = null) { $contentPath = myContentStorage::getFSContentRootPath(); // if entry type is audio - serve generic thumb: if ($this->getMediaType() == entry::ENTRY_MEDIA_TYPE_AUDIO) { if ($this->getStatus() == entryStatus::DELETED || $this->getModerationStatus() == moderation::MODERATION_STATUS_BLOCK) { KalturaLog::log("rejected audio entry - not serving thumbnail"); KExternalErrors::dieError(KExternalErrors::ENTRY_DELETED_MODERATED); } $audioEntryExist = false; $audioThumbEntry = null; $audioThumbEntryId = null; $partner = $this->getPartner(); if ($partner) { $audioThumbEntryId = $partner->getAudioThumbEntryId(); } if ($audioThumbEntryId) { $audioThumbEntry = entryPeer::retrieveByPK($audioThumbEntryId); } if ($audioThumbEntry && $audioThumbEntry->getMediaType() == entry::ENTRY_MEDIA_TYPE_IMAGE) { $fileSyncVersion = $partner->getAudioThumbEntryVersion(); $audioEntryKey = $audioThumbEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA, $fileSyncVersion); $contentPath = kFileSyncUtils::getLocalFilePathForKey($audioEntryKey); if ($contentPath) { $msgPath = $contentPath; $audioEntryExist = true; } else { KalturaLog::err('no local file sync for entry id'); } } if (!$audioEntryExist) { $msgPath = $contentPath . "content/templates/entry/thumbnail/audio_thumb.jpg"; } return myEntryUtils::resizeEntryImage($this, $version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices, $msgPath, $density, $stripProfiles); } elseif ($this->getMediaType() == entry::ENTRY_MEDIA_TYPE_SHOW) { // roughcut without any thumbnail, probably just created $msgPath = $contentPath . "content/templates/entry/thumbnail/auto_edit.jpg"; return myEntryUtils::resizeEntryImage($this, $version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices, $msgPath, $density, $stripProfiles); } elseif ($this->getType() == entryType::MEDIA_CLIP) { try { return myEntryUtils::resizeEntryImage($this, $version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices); } catch (Exception $ex) { if ($ex->getCode() == kFileSyncException::FILE_DOES_NOT_EXIST_ON_CURRENT_DC) { // get original flavor asset $origFlavorAsset = assetPeer::retrieveOriginalByEntryId($this->getId()); if ($origFlavorAsset) { $syncKey = $origFlavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); list($readyFileSync, $isLocal) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, TRUE, FALSE); if ($readyFileSync) { if ($isLocal) { KalturaLog::err('Trying to redirect to myself - stop here.'); KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC); } //Ready fileSync is on the other DC - dumping kFileUtils::dumpApiRequest(kDataCenterMgr::getRemoteDcExternalUrlByDcId(1 - kDataCenterMgr::getCurrentDcId())); } KalturaLog::err('No ready fileSync found on any DC.'); KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC); } } } } }
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(); }