private function generateKs($partnerId, $additionalData, $privileges) { $partner = $this->getPartner($partnerId); $limitedKs = ''; $result = kSessionUtils::startKSession($partnerId, $partner->getAdminSecret(), '', $limitedKs, self::EXPIRY_SECONDS, kSessionBase::SESSION_TYPE_ADMIN, '', $privileges, null, $additionalData); if ($result < 0) { throw new Exception('Failed to create limited session for partner ' . $partnerId); } return $limitedKs; }
public function execute() { $email = @$_GET['email']; $screenName = @$_GET['screen_name']; $partner_id = $this->getP('partner_id', null); if ($partner_id === null) { header("Location: /index.php/kmc/varlogin"); die; } sfView::SUCCESS; $this->me = PartnerPeer::retrieveByPK($this->getP('partner_id', null)); if (!$this->me || $this->me->getPartnerGroupType() != PartnerGroupType::VAR_GROUP) { die('You are not an wuthorized VAR. If you are a VAR, Please contact us at support@kaltura.com'); } $ks = kSessionUtils::crackKs($this->getP('ks')); $user = $ks->user; $res = kSessionUtils::validateKSession2(kSessionUtils::REQUIED_TICKET_ADMIN, $partner_id, $user, $this->getP('ks'), $ks); if ($res != ks::OK) { header("Location: /index.php/kmc/varlogin"); die; } $c = new Criteria(); $c->addAnd(PartnerPeer::PARTNER_PARENT_ID, $this->me->getId()); // add extra filtering if required //$c->addAnd(PartnerPeer::STATUS, 1); $partners = PartnerPeer::doSelect($c); $this->partners = array(); $partner_id_param_name = 'pid'; $subpid_param_name = 'subpid'; if ($this->me->getKmcVersion() == 1) { $partner_id_param_name = 'partner_id'; $subpid_param_name = 'subp_id'; } $kmc2Query = '?' . $partner_id_param_name . '=' . $this->me->getId() . '&' . $subpid_param_name . '=' . $this->me->getId() * 100 . '&ks=' . $_GET['ks'] . '&email=' . $email . '&screen_name=' . $screenName; $this->varKmcUrl = 'http://' . kConf::get('www_host') . '/index.php/kmc/kmc' . $this->me->getKmcVersion() . $kmc2Query; foreach ($partners as $partner) { $ks = null; kSessionUtils::createKSessionNoValidations($partner->getId(), $partner->getAdminUserId(), $ks, 30 * 86400, 2, "", "*"); $adminUser_email = $partner->getAdminEmail(); $partner_id_param_name = 'pid'; $subpid_param_name = 'subpid'; if ($partner->getKmcVersion() == 1) { $partner_id_param_name = 'partner_id'; $subpid_param_name = 'subp_id'; } $kmc2Query = '?' . $partner_id_param_name . '=' . $partner->getId() . '&' . $subpid_param_name . '=' . $partner->getId() * 100 . '&ks=' . $ks . '&email=' . $adminUser_email . '&screen_name=varAdmin'; //$kmcLink = url_for('index.php/kmc/kmc2'.$kmc2Query); // $kmcLink = 'http://'.kConf::get('www_host').'/index.php/kmc/kmc'.$partner->getKmcVersion().$kmc2Query; $kmcLink = 'http://' . kConf::get('www_host') . "/index.php/kmc/extlogin?ks={$ks}&partner_id=" . $partner->getId(); $this->partners[$partner->getId()] = array('name' => $partner->getPartnerName(), 'kmcLink' => $kmcLink); } }
/** * @return string */ public static function generateKs($partnerId, $tokenPrefix) { $partner = PartnerPeer::retrieveByPK($partnerId); $userSecret = $partner->getSecret(); //actionslimit:1 $privileges = kSessionBase::PRIVILEGE_SET_ROLE . ":" . self::EXTERNAL_INTEGRATION_SERVICES_ROLE_NAME; $privileges .= "," . kSessionBase::PRIVILEGE_ACTIONS_LIMIT . ":1"; $dcParams = kDataCenterMgr::getCurrentDc(); $token = $dcParams["secret"]; $additionalData = md5($tokenPrefix . $token); $ks = ""; $creationSucces = kSessionUtils::startKSession($partnerId, $userSecret, "", $ks, self::THREE_DAYS_IN_SECONDS, KalturaSessionType::USER, "", $privileges, null, $additionalData); if ($creationSucces >= 0) { return $ks; } return false; }
public function execute() { $this->ks = $this->getP("ks"); $this->partner_id = $this->getP("partner_id"); if (!$this->ks) { $ks = null; $this->partner_id = 0; kSessionUtils::createKSessionNoValidations($this->partner_id, 0, $ks, 8640000, true, "", ""); $this->ks = $ks; } $this->subp_id = $this->getP("subp_id"); $this->uid = $this->getP("uid"); $this->screen_name = $this->getP("screen_name"); $this->email = $this->getP("email"); $this->beta = $this->getRequestParameter("beta"); sfView::SUCCESS; }
public function execute() { $ksStr = $this->getP("ks"); if ($ksStr) { kSessionUtils::killKSession($ksStr); KalturaLog::debug("Killing session with ks - [{$ksStr}], decoded - [" . base64_decode($ksStr) . "]"); } else { KalturaLog::err('logoutAction called with no KS'); } setcookie('pid', "", 0, "/"); setcookie('subpid', "", 0, "/"); setcookie('uid', "", 0, "/"); setcookie('kmcks', "", 0, "/"); setcookie('screen_name', "", 0, "/"); setcookie('email', "", 0, "/"); return sfView::NONE; //redirection to kmc/kmc is done from java script }
public function executeImpl($partner_id, $subp_id, $puser_id, $partner_prefix, $puser_kuser) { // make sure the secret fits the one in the partner's table $ks_str = ""; $expiry = $this->getP("expiry", 86400); $widget_id = $this->getPM("widget_id"); $widget = widgetPeer::retrieveByPK($widget_id); if (!$widget) { $this->addError(APIErrors::INVALID_WIDGET_ID, $widget_id); return; } $partner_id = $widget->getPartnerId(); $partner = PartnerPeer::retrieveByPK($partner_id); // TODO - see how to decide if the partner has a URL to redirect to // according to the partner's policy and the widget's policy - define the privileges of the ks // TODO - decide !! - for now only view - any kshow $privileges = "view:*,widget:1"; if ($widget->getSecurityType() == widget::WIDGET_SECURITY_TYPE_FORCE_KS) { if (!$this->ks) { // the one from the defPartnerservices2Action $this->addException(APIErrors::MISSING_KS); } $ks_str = $this->getP("ks"); $widget_partner_id = $widget->getPartnerId(); $res = kSessionUtils::validateKSession2(1, $widget_partner_id, $puser_id, $ks_str, $this->ks); if (0 >= $res) { // chaned this to be an exception rather than an error $this->addException(APIErrors::INVALID_KS, $ks_str, $res, ks::getErrorStr($res)); } } else { // the session will be for NON admins and privileges of view only $puser_id = 0; $result = kSessionUtils::createKSessionNoValidations($partner_id, $puser_id, $ks_str, $expiry, false, "", $privileges); } if ($result >= 0) { $this->addMsg("ks", $ks_str); $this->addMsg("partner_id", $partner_id); $this->addMsg("subp_id", $widget->getSubpId()); $this->addMsg("uid", "0"); } else { // TODO - see that there is a good error for when the invalid login count exceed s the max $this->addError(APIErrors::START_WIDGET_SESSION_ERROR, $widget_id); } }
public function executeImpl($partner_id, $subp_id, $puser_id, $partner_prefix, $puser_kuser) { // make sure the secret fits the one in the partner's table $ks = ""; $expiry = $this->getP("expiry", 86400); $admin = $this->getP("admin", false); $privileges = $this->getP("privileges", null); $result = kSessionUtils::startKSession($partner_id, $this->getPM("secret"), $puser_id, $ks, $expiry, $admin, "", $privileges); if ($result >= 0) { $this->addMsg("ks", $ks); $this->addMsg("partner_id", $partner_id); $this->addMsg("subp_id", $subp_id); $this->addMsg("uid", $puser_id); } else { // TODO - see that there is a good error for when the invalid login count exceed s the max $this->addError(APIErrors::START_SESSION_ERROR, $partner_id); $this->addDebug("error", $result); } }
private static function validateKs($ks_str) { if (!$ks_str) { return null; } // 1. crack the ks - $ks = kSessionUtils::crackKs($ks_str); // 2. extract partner_id $ks_partner_id = $ks->partner_id; $partner_id = $ks_partner_id; // use the user from the ks if not explicity set $puser_id = $ks->user; // 4. validate ticket per service for the ticket's partner $ticket_type = 2; $ks_puser_id = $ks->user; $res = kSessionUtils::validateKSession2($ticket_type, $ks_partner_id, $ks_puser_id, $ks_str, $ks); if (0 >= $res) { // chaned this to be an exception rather than an error return null; } return $partner_id; }
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; }
/** * Tests UserService->disableLoginAction() */ public function testDisableLoginAction() { // check that login can be disabled $this->startSession(KalturaSessionType::ADMIN, null); $newUser1 = $this->createUser(true, false, __FUNCTION__); $addedUser1 = $this->addUser($newUser1); $loginUser = $this->createUser(true, false, __FUNCTION__); $newClient = $this->getClient(null); $ks = $newClient->user->loginByLoginId($newUser1->email, $newUser1->password); $this->assertNotNull($ks); $ks = kSessionUtils::crackKs($ks); $this->assertNotNull($ks); $this->assertEquals($addedUser1->partnerId, $ks->partner_id); $disabledUser = $this->client->user->disableLogin($newUser1->id); $this->assertType('KalturaUser', $disabledUser); $this->assertEquals($newUser1->id, $disabledUser->id); $exceptionThrown = false; try { $newClient->user->loginByLoginId($newUser1->email, $newUser1->password); } catch (Exception $e) { $exceptionThrown = $e; } $this->checkException($exceptionThrown, 'USER_NOT_FOUND'); // check failure to disable already disabled user $exceptionThrown = false; try { $this->client->user->disableLogin($newUser1->id); } catch (Exception $e) { $exceptionThrown = $e; } $this->checkException($exceptionThrown, 'USER_LOGIN_ALREADY_DISABLED'); }
public static function initKsPartnerUser($ksString, $requestedPartnerId = null, $requestedPuserId = null) { if (!$ksString) { kCurrentContext::$ks = null; kCurrentContext::$ks_partner_id = null; kCurrentContext::$ks_uid = null; kCurrentContext::$master_partner_id = null; kCurrentContext::$partner_id = $requestedPartnerId; kCurrentContext::$uid = $requestedPuserId; kCurrentContext::$is_admin_session = false; } else { try { $ksObj = kSessionUtils::crackKs($ksString); } catch (Exception $ex) { if (strpos($ex->getMessage(), "INVALID_STR") !== null) { //TODO: throw different type of error throw new KalturaAPIException(APIErrors::INVALID_KS, $ksString, ks::INVALID_STR, ks::getErrorStr(ks::INVALID_STR)); } else { throw $ex; } } kCurrentContext::$ks = $ksString; kCurrentContext::$ks_object = $ksObj; kCurrentContext::$ks_partner_id = $ksObj->partner_id; kCurrentContext::$ks_uid = $ksObj->user; kCurrentContext::$master_partner_id = $ksObj->master_partner_id ? $ksObj->master_partner_id : kCurrentContext::$ks_partner_id; kCurrentContext::$is_admin_session = $ksObj->isAdmin(); kCurrentContext::$partner_id = $requestedPartnerId; kCurrentContext::$uid = $requestedPuserId; } // set partner ID for logger if (kCurrentContext::$partner_id) { $GLOBALS["partnerId"] = kCurrentContext::$partner_id; } else { if (kCurrentContext::$ks_partner_id) { $GLOBALS["partnerId"] = kCurrentContext::$ks_partner_id; } } self::$ksPartnerUserInitialized = true; }
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; }
private static function createNotificationData($notification_type, $obj, $extra_notification_data = null) { $params = array(); $param_names = null; switch ($notification_type) { case kNotificationJobData::NOTIFICATION_TYPE_ENTRY_ADD: $param_names = array("name", "tags", "search_text", "media_type", "length_in_msecs", "permissions", "thumbnail_url", "kshow_id", "roughcut_id", "group_id", "partner_data", "status", "width", "height", "data_url", "download_url", "download_size", "media_date"); break; case kNotificationJobData::NOTIFICATION_TYPE_ENTRY_UPDATE: $param_names = array("name", "tags", "search_text", "media_type", "length_in_msecs", "permissions", "thumbnail_url", "kshow_id", "group_id", "partner_data", "status", "width", "height", "data_url", "download_url", "download_size", "media_date", "moderation_status"); break; case kNotificationJobData::NOTIFICATION_TYPE_ENTRY_UPDATE_PERMISSIONS: $param_names = array("permissions"); break; case kNotificationJobData::NOTIFICATION_TYPE_ENTRY_DELETE: $param_names = null; break; case kNotificationJobData::NOTIFICATION_TYPE_ENTRY_BLOCK: $param_names = null; break; case kNotificationJobData::NOTIFICATION_TYPE_ENTRY_UPDATE_THUMBNAIL: $param_names = array("thumbnail_url", "kshow_id"); break; case kNotificationJobData::NOTIFICATION_TYPE_ENTRY_REPORT: $param_names = array("objectId", "comments", "reportCode"); break; case kNotificationJobData::NOTIFICATION_TYPE_ENTRY_UPDATE_MODERATION: $param_names = array("moderation_status", "moderation_count"); break; case kNotificationJobData::NOTIFICATION_TYPE_KSHOW_ADD: //$param_names = array ( "name" , "description" , "searchText" , "permissions" ,"groupId"); $param_names = array("name", "description", "tags", "search_text", "permissions", "group_id", "partner_data", "show_entry_id"); break; case kNotificationJobData::NOTIFICATION_TYPE_KSHOW_DELETE: $param_names = null; break; case kNotificationJobData::NOTIFICATION_TYPE_KSHOW_UPDATE_INFO: //$param_names = array ( "name" , "description" , "searchText" ,"groupId" ); $param_names = array("name", "description", "tags", "search_text", "group_id", "partner_data"); break; case kNotificationJobData::NOTIFICATION_TYPE_KSHOW_UPDATE_PERMISSIONS: $param_names = array("permissions"); break; case kNotificationJobData::NOTIFICATION_TYPE_KSHOW_RANK: $param_names = array("rank", "votes"); break; case kNotificationJobData::NOTIFICATION_TYPE_KSHOW_BLOCK: $param_namesmes = null; break; case kNotificationJobData::NOTIFICATION_TYPE_USER_BANNED: $param_names = array("screen_name", "email"); break; case kNotificationJobData::NOTIFICATION_TYPE_BATCH_JOB_STARTED: case kNotificationJobData::NOTIFICATION_TYPE_BATCH_JOB_SUCCEEDED: case kNotificationJobData::NOTIFICATION_TYPE_BATCH_JOB_FAILED: case kNotificationJobData::NOTIFICATION_TYPE_BATCH_JOB_SIMILAR_EXISTS: $param_names = array("id", "job_sub_type", "abort", "message", "description", "updates_count", "created_at", "updated_at"); break; } if ($param_names == null) { return ""; } foreach ($param_names as $name) { $method_name = "get" . $name; $method_name = str_replace("_", "", $method_name); // this is to support underscores in the names rather than camelback $res = call_user_func(array($obj, $method_name)); $params[$name] = $res; } if ($extra_notification_data) { if (is_array($extra_notification_data)) { foreach ($extra_notification_data as $extra_params_name => $extra_params_value) { $params[$extra_params_name] = $extra_params_value; } } else { $params["extra_notification_data"] = $extra_notification_data; } } try { $ksObj = kSessionUtils::crackKs(kCurrentContext::$ks); if ($ksObj) { $params['ks_data'] = $ksObj->additional_data; } } catch (Exception $ex) { KalturaLog::log('could not crack KS [' . kCurrentContext::$ks . '] for adding to notification param'); } return serialize($params); }
public static function userLoginByKs($ks, $requestedPartnerId, $useOwnerIfNoUser = false) { $ksObj = kSessionUtils::crackKs($ks); $ksUserId = $ksObj->user; $ksPartnerId = $ksObj->partner_id; $kuser = null; if ((is_null($ksUserId) || $ksUserId === '') && $useOwnerIfNoUser) { KalturaLog::log('No user id on KS, trying to login as the account owner'); $partner = PartnerPeer::retrieveByPK($ksPartnerId); if (!$partner) { throw new kUserException('Invalid partner id [' . $ksPartnerId . ']', kUserException::INVALID_PARTNER); } $ksUserId = $partner->getAccountOwnerKuserId(); $kuser = kuserPeer::retrieveByPK($ksUserId); } if (!$kuser) { $kuser = kuserPeer::getKuserByPartnerAndUid($ksPartnerId, $ksUserId, true); } if (!$kuser) { throw new kUserException('User with id [' . $ksUserId . '] was not found for partner with id [' . $ksPartnerId . ']', kUserException::USER_NOT_FOUND); } return self::userLogin($kuser->getLoginData(), null, $requestedPartnerId, false); // don't validate password }
/** * @action getAdminSession * @param int $partnerId * @param string $userId * @return string */ public function getAdminSessionAction($partnerId, $userId = null) { $dbPartner = PartnerPeer::retrieveByPK($partnerId); if (!$dbPartner) { throw new KalturaAPIException(KalturaErrors::UNKNOWN_PARTNER_ID, $partnerId); } if (!$userId) { $userId = $dbPartner->getAdminUserId(); } $kuser = kuserPeer::getKuserByPartnerAndUid($partnerId, $userId); if (!$kuser) { throw new KalturaAPIException(KalturaErrors::INVALID_USER_ID, $userId); } if (!$kuser->getIsAdmin()) { throw new KalturaAPIException(KalturaErrors::USER_NOT_ADMIN, $userId); } $ks = ""; kSessionUtils::createKSessionNoValidations($dbPartner->getId(), $userId, $ks, 86400, 2, "", "*"); return $ks; }
/** * Get an admin session using admin email and password (Used for login to the KMC application) * * @action login * @param string $email * @param string $password * @param int $partnerId * @return string * * @throws KalturaErrors::ADMIN_KUSER_NOT_FOUND * @thrown KalturaErrors::INVALID_PARTNER_ID * @thrown KalturaErrors::LOGIN_RETRIES_EXCEEDED * @thrown KalturaErrors::LOGIN_BLOCKED * @thrown KalturaErrors::PASSWORD_EXPIRED * @thrown KalturaErrors::INVALID_PARTNER_ID * @thrown KalturaErrors::INTERNAL_SERVERL_ERROR */ public function loginAction($email, $password, $partnerId = null) { try { $ks = parent::loginImpl(null, $email, $password, $partnerId); $tempKs = kSessionUtils::crackKs($ks); if (!$tempKs->isAdmin()) { throw new KalturaAPIException(KalturaErrors::ADMIN_KUSER_NOT_FOUND); } return $ks; } catch (KalturaAPIException $e) { $this->throwTranslatedException($e); } }
public function getDownloadUrlWithExpiry($expiry, $useCdn = false, $forceProxy = false, $preview = null) { $ksStr = ""; $partnerId = $this->getPartnerId(); if ($this->isKsNeededForDownload() || $preview) { $partner = PartnerPeer::retrieveByPK($partnerId); $secret = $partner->getSecret(); $privilege = ks::PRIVILEGE_DOWNLOAD . ":" . $this->getEntryId(); $privilege .= "," . kSessionBase::PRIVILEGE_DISABLE_ENTITLEMENT_FOR_ENTRY . ":" . $this->getEntryId(); $privilege .= "," . kSessionBase::PRIVILEGE_VIEW . ":" . $this->getEntryId(); $privilege .= "," . kSessionBase::PRIVILEGE_DOWNLOAD_ASSET . ":" . $this->getId(); if ($preview) { $privilege .= "," . kSessionBase::PRIVILEGE_PREVIEW . ":" . $preview; } $result = kSessionUtils::startKSession($partnerId, $secret, null, $ksStr, $expiry, false, "", $privilege); if ($result < 0) { throw new Exception("Failed to generate session for asset [" . $this->getId() . "] of type " . $this->getType()); } } $finalPath = $this->getFinalDownloadUrlPathWithoutKs(); if ($ksStr) { $finalPath .= "/ks/" . $ksStr; } if ($forceProxy) { $finalPath .= "/relocate/" . $this->getEntryId() . "." . $this->getFileExt(); } // Gonen May 12 2010 - removing CDN URLs. see ticket 5135 in internal mantis // in order to avoid conflicts with access_control (geo-location restriction), we always return the requestHost (www_host from kConf) // and not the CDN host relevant for the partner. // Tan-Tan January 27 2011 - in some places we do need the cdn, I added a paramter useCdn to force it. if ($useCdn) { // TODO in that case we should use the serve flavor and the url manager in order to support secured and signed urls $downloadUrl = myPartnerUtils::getCdnHost($partnerId) . $finalPath; } else { $downloadUrl = requestUtils::getRequestHost() . $finalPath; } return $downloadUrl; }
/** * Start a session for Kaltura's flash widgets * * @action startWidgetSession * @param string $widgetId * @param int $expiry * * @throws APIErrors::INVALID_WIDGET_ID * @throws APIErrors::MISSING_KS * @throws APIErrors::INVALID_KS * @throws APIErrors::START_WIDGET_SESSION_ERROR * @return KalturaStartWidgetSessionResponse */ function startWidgetSession($widgetId, $expiry = 86400) { // make sure the secret fits the one in the partner's table $ksStr = ""; $widget = widgetPeer::retrieveByPK($widgetId); if (!$widget) { throw new KalturaAPIException(APIErrors::INVALID_WIDGET_ID, $widgetId); } $partnerId = $widget->getPartnerId(); //$partner = PartnerPeer::retrieveByPK( $partner_id ); // TODO - see how to decide if the partner has a URL to redirect to // according to the partner's policy and the widget's policy - define the privileges of the ks // TODO - decide !! - for now only view - any kshow $privileges = "view:*,widget:1"; if (PermissionPeer::isValidForPartner(PermissionName::FEATURE_ENTITLEMENT, $partnerId) && !$widget->getEnforceEntitlement() && $widget->getEntryId()) { $privileges .= ',' . kSessionBase::PRIVILEGE_DISABLE_ENTITLEMENT_FOR_ENTRY . ':' . $widget->getEntryId(); } if (PermissionPeer::isValidForPartner(PermissionName::FEATURE_ENTITLEMENT, $partnerId) && !is_null($widget->getPrivacyContext()) && $widget->getPrivacyContext() != '') { $privileges .= ',' . kSessionBase::PRIVILEGE_PRIVACY_CONTEXT . ':' . $widget->getPrivacyContext(); } $userId = 0; /*if ( $widget->getSecurityType() == widget::WIDGET_SECURITY_TYPE_FORCE_KS ) { $user = $this->getKuser(); if ( ! $this->getKS() )// the one from the base class throw new KalturaAPIException ( APIErrors::MISSING_KS ); $widget_partner_id = $widget->getPartnerId(); $res = kSessionUtils::validateKSession2 ( 1 ,$widget_partner_id , $user->getId() , $ks_str , $this->ks ); if ( 0 >= $res ) { // chaned this to be an exception rather than an error throw new KalturaAPIException ( APIErrors::INVALID_KS , $ks_str , $res , ks::getErrorStr( $res )); } } else {*/ // the session will be for NON admins and privileges of view only $result = kSessionUtils::createKSessionNoValidations($partnerId, $userId, $ksStr, $expiry, false, "", $privileges); //} if ($result >= 0) { $response = new KalturaStartWidgetSessionResponse(); $response->partnerId = $partnerId; $response->ks = $ksStr; $response->userId = $userId; return $response; } else { // TODO - see that there is a good error for when the invalid login count exceed s the max throw new KalturaAPIException(APIErrors::START_WIDGET_SESSION_ERROR, $widgetId); } }
/** * Code to be run after persisting the object * @param PropelPDO $con */ public function postSave(PropelPDO $con = null) { // update plugin permissions in the database if (is_array($this->setEnabledPlugins)) { foreach ($this->setEnabledPlugins as $pluginName => $enabled) { if ($enabled) { PermissionPeer::enablePlugin($pluginName, $this->getId()); } else { PermissionPeer::disablePlugin($pluginName, $this->getId()); } } } // update special services permissions in the database if (is_array($this->setEnabledServices)) { foreach ($this->setEnabledServices as $permissionName => $enabled) { if ($enabled) { PermissionPeer::enableForPartner($permissionName, PermissionType::SPECIAL_FEATURE, $this->getId()); } else { PermissionPeer::disableForPartner($permissionName, $this->getId()); } } } $this->setEnabledPlugins = array(); $this->setEnabledServices = array(); $ksObj = kSessionUtils::crackKs(kCurrentContext::$ks); $currentKuser = null; if (is_object($ksObj)) { $currentKuser = kuserPeer::getKuserByEmail($ksObj->user, -2); } if ($currentKuser) { $allowedPartners = $currentKuser->getAllowedPartners(); if (isset($allowedPartners) && !empty($allowedPartners)) { $partnersArray = array_map('trim', explode(',', $allowedPartners)); if (!in_array($this->getId(), $partnersArray)) { $currentKuser->setAllowedPartners($allowedPartners . ',' . $this->getId()); } } else { $currentKuser->setAllowedPartners($this->getId()); } $currentKuser->save(); } }
private static function errorIfKsNotValid() { // if no ks in current context - no need to check anything if (!self::$ksString) { return; } $ksObj = null; $res = kSessionUtils::validateKSessionNoTicket(self::$ksPartnerId, self::$ksUserId, self::$ksString, $ksObj); if (0 >= $res) { switch ($res) { case ks::INVALID_STR: KalturaLog::err('Invalid KS [' . self::$ksString . ']'); break; case ks::INVALID_PARTNER: KalturaLog::err('Wrong partner [' . self::$ksPartnerId . '] actual partner [' . $ksObj->partner_id . ']'); break; case ks::INVALID_USER: KalturaLog::err('Wrong user [' . self::$ksUserId . '] actual user [' . $ksObj->user . ']'); break; case ks::EXPIRED: KalturaLog::err('KS Expired [' . date('Y-m-d H:i:s', $ksObj->valid_until) . ']'); break; case ks::LOGOUT: KalturaLog::err('KS already logged out'); break; case ks::EXCEEDED_ACTIONS_LIMIT: KalturaLog::err('KS exceeded number of actions limit'); break; case ks::EXCEEDED_RESTRICTED_IP: KalturaLog::err('IP does not match KS restriction'); break; } throw new kCoreException("Invalid KS", kCoreException::INVALID_KS, ks::getErrorStr($res)); } }
private static function createUrl($partner_id, $file_name) { $ksStr = ""; $partner = PartnerPeer::retrieveByPK($partner_id); $secret = $partner->getSecret(); $privilege = ks::PRIVILEGE_DOWNLOAD . ":" . $file_name; $maxExpiry = 86400; $expiry = $partner->getKsMaxExpiryInSeconds(); if (!$expiry || $expiry > $maxExpiry) { $expiry = $maxExpiry; } $result = kSessionUtils::startKSession($partner_id, $secret, null, $ksStr, $expiry, false, "", $privilege); if ($result < 0) { throw new Exception("Failed to generate session for asset [" . $this->getId() . "] of type " . $this->getType()); } //url is built with DC url in order to be directed to the same DC of the saved file $url = kDataCenterMgr::getCurrentDcUrl() . "/api_v3/index.php/service/report/action/serve/ks/{$ksStr}/id/{$file_name}/report.csv"; return $url; }
/** * Retrieve partner secret and admin secret * * @action getSecrets * @param int $partnerId * @param string $adminEmail * @param string $cmsPassword * @return KalturaPartner * * * @throws APIErrors::ADMIN_KUSER_NOT_FOUND */ public function getSecretsAction($partnerId, $adminEmail, $cmsPassword) { KalturaResponseCacher::disableCache(); $adminKuser = null; try { $adminKuser = UserLoginDataPeer::userLoginByEmail($adminEmail, $cmsPassword, $partnerId); } catch (kUserException $e) { throw new KalturaAPIException(APIErrors::ADMIN_KUSER_NOT_FOUND, "The data you entered is invalid"); } if (!$adminKuser || !$adminKuser->getIsAdmin()) { throw new KalturaAPIException(APIErrors::ADMIN_KUSER_NOT_FOUND, "The data you entered is invalid"); } KalturaLog::log("Admin Kuser found, going to validate password", KalturaLog::INFO); // user logged in - need to re-init kPermissionManager in order to determine current user's permissions $ks = null; kSessionUtils::createKSessionNoValidations($partnerId, $adminKuser->getPuserId(), $ks, 86400, $adminKuser->getIsAdmin(), "", '*'); kCurrentContext::initKsPartnerUser($ks); kPermissionManager::init(); $dbPartner = PartnerPeer::retrieveByPK($partnerId); $partner = new KalturaPartner(); $partner->fromPartner($dbPartner); $partner->cmsPassword = $cmsPassword; return $partner; }
public function getDownloadUrlWithExpiry($expiry, $useCdn = false) { $ksStr = ""; $partnerId = $this->getPartnerId(); $partner = PartnerPeer::retrieveByPK($partnerId); $secret = $partner->getSecret(); $privilege = ks::PRIVILEGE_DOWNLOAD . ":" . $this->getEntryId(); $result = kSessionUtils::startKSession($partnerId, $secret, null, $ksStr, $expiry, false, "", $privilege); if ($result < 0) { throw new Exception("Failed to generate session for flavor asset [" . $this->getId() . "]"); } $finalPath = myPartnerUtils::getUrlForPartner($this->getPartnerId(), $this->getPartnerId() * 100) . "/download" . "/entry_id/" . $this->getEntryId() . "/flavor/" . $this->getId() . "/ks/" . $ksStr; // Gonen May 12 2010 - removing CDN URLs. see ticket 5135 in internal mantis // in order to avoid conflicts with access_control (geo-location restriction), we always return the requestHost (www_host from kConf) // and not the CDN host relevant for the partner. // Tan-Tan January 27 2011 - in some places we do need the cdn, I added a paramter useCdn to force it. if ($useCdn) { $downloadUrl = myPartnerUtils::getCdnHost($partnerId) . $finalPath; } else { $downloadUrl = requestUtils::getRequestHost() . $finalPath; } return $downloadUrl; }
/** * Will forward to the regular swf player according to the widget_id */ public function execute() { $uv_cookie = @$_COOKIE['uv']; if (strlen($uv_cookie) != 35) { $uv_cookie = "uv_" . md5(uniqid(rand(), true)); } setrawcookie('uv', $uv_cookie, time() + 3600 * 24 * 365, '/'); // check if this is a request for the kdp without a wrapper // in case of an application loading the kdp (e.g. kmc) $nowrapper = $this->getRequestParameter("nowrapper", false); // allow caching if either the cache start time (cache_st) parameter // wasn't specified or if it is past the specified time $cache_st = $this->getRequestParameter("cache_st"); $allowCache = !$cache_st || $cache_st < time(); $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"; // if there is no wrapper the loader is responsible for setting extra params to the kdp $noncached_params = ""; if (!$nowrapper) { $noncached_params = $externalInterfaceDisabled . "&referer=" . urlencode($referer); } $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? "https" : "http"; $requestKey = $protocol . $_SERVER["REQUEST_URI"]; // check if we cached the redirect url $cache = new myCache("kwidget", 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}" . $noncached_params); die; } // check if we cached the patched swf with flashvars $cache_swfdata = new myCache("kwidgetswf", 10 * 60); // 10 minutes $cachedResponse = $cache_swfdata->get($requestKey); if ($allowCache && $cachedResponse) { header("X-Kaltura:cached-action"); requestUtils::sendCdnHeaders("swf", strlen($cachedResponse), 60 * 10); echo $cachedResponse; die; } $widget_id = $this->getRequestParameter("wid"); $show_version = $this->getRequestParameter("v"); $debug_kdp = $this->getRequestParameter("debug_kdp", false); $widget = widgetPeer::retrieveByPK($widget_id); if (!$widget) { die; } // because of the routing rule - the entry_id & kmedia_type WILL exist. be sure to ignore them if smaller than 0 $kshow_id = $widget->getKshowId(); $entry_id = $widget->getEntryId(); $gallery_widget = !$kshow_id && !$entry_id; if (!$entry_id) { $entry_id = -1; } if ($widget->getSecurityType() != widget::WIDGET_SECURITY_TYPE_TIMEHASH) { // try eid - if failed entry_id $eid = $this->getRequestParameter("eid", $this->getRequestParameter("entry_id")); // try kid - if failed kshow_id $kid = $this->getRequestParameter("kid", $this->getRequestParameter("kshow_id")); if ($eid != null) { $entry_id = $eid; } elseif ($kid != null) { $kshow_id = $kid; } } if ($widget->getSecurityType() == 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("kwidgetAction: 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; $kshow_id = $fallback_kshow_id; } } } elseif ($widget->getSecurityType() == widget::WIDGET_SECURITY_TYPE_FORCE_KS) { } $kmedia_type = -1; // support either uiconf_id or ui_conf_id $uiconf_id = $this->getRequestParameter("uiconf_id"); if (!$uiconf_id) { $uiconf_id = $this->getRequestParameter("ui_conf_id"); } if ($uiconf_id) { $widget_type = $uiconf_id; $uiconf_id_str = "&uiconf_id={$uiconf_id}"; } else { $widget_type = $widget->getUiConfId(); $uiconf_id_str = ""; } if (empty($widget_type)) { $widget_type = 3; } $kdata = $widget->getCustomData(); $partner_host = myPartnerUtils::getHost($widget->getPartnerId()); $partner_cdnHost = myPartnerUtils::getCdnHost($widget->getPartnerId()); $host = $partner_host; if ($widget_type == 10) { $swf_url = $host . "/swf/weplay.swf"; } else { $swf_url = $host . "/swf/kplayer.swf"; } $partner_id = $widget->getPartnerId(); $subp_id = $widget->getSubpId(); if (!$subp_id) { $subp_id = 0; } $uiConf = uiConfPeer::retrieveByPK($widget_type); // new ui_confs which are deleted should stop the script // the check for >100000 is for supporting very old mediawiki and such players if (!$uiConf && $widget_type > 100000) { die; } if ($uiConf) { $ui_conf_swf_url = $uiConf->getSwfUrl(); if (kString::beginsWith($ui_conf_swf_url, "http")) { $swf_url = $ui_conf_swf_url; // absolute URL } else { $use_cdn = $uiConf->getUseCdn(); $host = $use_cdn ? $partner_cdnHost : $partner_host; $swf_url = $host . myPartnerUtils::getUrlForPartner($partner_id, $subp_id) . $ui_conf_swf_url; } if ($debug_kdp) { $swf_url = str_replace("/kdp/", "/kdp_debug/", $swf_url); } } if ($show_version < 0) { $show_version = null; } $ip = requestUtils::getRemoteAddress(); // to convert back, use long2ip // the widget log should change to reflect the new data, but for now - i used $widget_id instead of the widgget_type // WidgetLog::createWidgetLog( $referer , $ip , $kshow_id , $entry_id , $kmedia_type , $widget_id ); if ($entry_id == -1) { $entry_id = null; } $kdp3 = false; $base_wrapper_swf = myContentStorage::getFSFlashRootPath() . "/kdpwrapper/" . kConf::get('kdp_wrapper_version') . "/kdpwrapper.swf"; $widgetIdStr = "widget_id={$widget_id}"; $partnerIdStr = "partner_id={$partner_id}&subp_id={$subp_id}"; if ($uiConf) { $ks_flashvars = ""; $conf_vars = $uiConf->getConfVars(); if ($conf_vars) { $conf_vars = "&" . $conf_vars; } $wrapper_swf = $base_wrapper_swf; $partner = PartnerPeer::retrieveByPK($partner_id); if ($partner) { $partner_type = $partner->getType(); } if (version_compare($uiConf->getSwfUrlVersion(), "3.0", ">=")) { $kdp3 = true; // further in the code, $wrapper_swf is being used and not $base_wrapper_swf $wrapper_swf = $base_wrapper_swf = myContentStorage::getFSFlashRootPath() . '/kdp3wrapper/' . kConf::get('kdp3_wrapper_version') . '/kdp3wrapper.swf'; $widgetIdStr = "widgetId={$widget_id}"; $uiconf_id_str = "&uiConfId={$uiconf_id}"; $partnerIdStr = "partnerId={$partner_id}&subpId={$subp_id}"; } // if we are loaded without a wrapper (directly in flex) // 1. dont create the ks - keep url the same for caching // 2. dont patch the uiconf - patching is done only to wrapper anyway if ($nowrapper) { $dynamic_date = $widgetIdStr . "&host=" . str_replace("http://", "", str_replace("https://", "", $partner_host)) . "&cdnHost=" . str_replace("http://", "", str_replace("https://", "", $partner_cdnHost)) . $uiconf_id_str . $conf_vars; $url = "{$swf_url}?{$dynamic_date}"; } else { // if kdp version >= 2.5 if (version_compare($uiConf->getSwfUrlVersion(), "2.5", ">=")) { // create an anonymous session $ks = ""; $result = kSessionUtils::createKSessionNoValidations($partner_id, 0, $ks, 86400, false, "", "view:*"); $ks_flashvars = "&{$partnerIdStr}&uid=0&ts=" . microtime(true); if ($widget->getSecurityType() != widget::WIDGET_SECURITY_TYPE_FORCE_KS) { $ks_flashvars = "&ks={$ks}" . $ks_flashvars; } // patch kdpwrapper with getwidget and getuiconf $root = myContentStorage::getFSContentRootPath(); $confFile_mtime = $uiConf->getUpdatedAt(null); $new_swf_path = "widget_{$widget_id}_{$widget_type}_{$confFile_mtime}_" . md5($base_wrapper_swf . $swf_url) . ".swf"; $md5 = md5($new_swf_path); $new_swf_path = "content/cacheswf/" . substr($md5, 0, 2) . "/" . substr($md5, 2, 2) . "/" . $new_swf_path; $cached_swf = "{$root}/{$new_swf_path}"; if (!file_exists($cached_swf) || filemtime($cached_swf) < $confFile_mtime) { kFile::fullMkdir($cached_swf); require_once SF_ROOT_DIR . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . "api_v3" . DIRECTORY_SEPARATOR . "bootstrap.php"; $dispatcher = KalturaDispatcher::getInstance(); try { $widget_result = $dispatcher->dispatch("widget", "get", array("ks" => $ks, "id" => $widget_id)); $ui_conf_result = $dispatcher->dispatch("uiConf", "get", array("ks" => $ks, "id" => $widget_type)); } catch (Exception $ex) { die; } $serializer = new KalturaXmlSerializer(false); $serializer->serialize($widget_result); $widget_xml = $serializer->getSerializedData(); $serializer = new KalturaXmlSerializer(false); $serializer->serialize($ui_conf_result); $ui_conf_xml = $serializer->getSerializedData(); $patcher = new kPatchSwf($root . $base_wrapper_swf); $result = "<xml><result>{$widget_xml}</result><result>{$ui_conf_xml}</result></xml>"; $patcher->patch($result, $cached_swf); } if (file_exists($cached_swf)) { $wrapper_swf = $new_swf_path; } } $kdp_version_2 = strpos($swf_url, "kdp/v2.") > 0; if ($partner_host == "http://www.kaltura.com" && !$kdp_version_2 && !$kdp3) { $partner_host = 1; // otherwise the kdp will try going to cdnwww.kaltura.com } $track_wrapper = ''; if (kConf::get('track_kdpwrapper') && kConf::get('kdpwrapper_track_url')) { $track_wrapper = "&wrapper_tracker_url=" . urlencode(kConf::get('kdpwrapper_track_url') . "?activation_key=" . kConf::get('kaltura_activation_key') . "&package_version=" . kConf::get('kaltura_version')); } $dynamic_date = $widgetIdStr . $track_wrapper . "&kdpUrl=" . urlencode($swf_url) . "&host=" . str_replace("http://", "", str_replace("https://", "", $partner_host)) . "&cdnHost=" . str_replace("http://", "", str_replace("https://", "", $partner_cdnHost)) . ($show_version ? "&entryVersion={$show_version}" : "") . ($kshow_id ? "&kshowId={$kshow_id}" : "") . ($entry_id ? "&entryId={$entry_id}" : "") . $uiconf_id_str . $ks_flashvars . ($cache_st ? "&clientTag=cache_st:{$cache_st}" : "") . $conf_vars; // for now changed back to $host since kdp version prior to 1.0.15 didnt support loading by external domain kdpwrapper $url = $host . myPartnerUtils::getUrlForPartner($partner_id, $subp_id) . "/{$wrapper_swf}?{$dynamic_date}"; // patch wrapper with flashvars and dump to browser if (version_compare($uiConf->getSwfUrlVersion(), "2.6.6", ">=")) { $patcher = new kPatchSwf($root . $wrapper_swf, "KALTURA_FLASHVARS_DATA"); ob_start(); $patcher->patch($dynamic_date . "&referer=" . urlencode($referer)); $wrapper_data = ob_get_contents(); ob_end_clean(); requestUtils::sendCdnHeaders("swf", strlen($wrapper_data), $allowCache ? 60 * 10 : 0); echo $wrapper_data; if ($allowCache) { $cache_swfdata->put($requestKey, $wrapper_data); } die; } } } else { $dynamic_date = "kshowId={$kshow_id}" . "&host=" . requestUtils::getRequestHostId() . ($show_version ? "&entryVersion={$show_version}" : "") . ($entry_id ? "&entryId={$entry_id}" : "") . ($entry_id ? "&KmediaType={$kmedia_type}" : ""); $dynamic_date .= "&isWidget={$widget_type}&referer=" . urlencode($referer); $dynamic_date .= "&kdata={$kdata}"; $url = "{$swf_url}?{$dynamic_date}"; } // if referer has a query string an IE bug will prevent out flashvars to propagate // when nowrapper is true we cant use /swfparams either as there isnt a kdpwrapper if (!$nowrapper && $uiConf && version_compare($uiConf->getSwfUrlVersion(), "2.6.6", ">=")) { // apart from the /swfparam/ format, add .swf suffix to the end of the stream in case // a corporate firewall looks at the file suffix $pos = strpos($url, "?"); $url = substr($url, 0, $pos) . "/swfparams/" . urlencode(substr($url, $pos + 1)) . ".swf"; } if ($allowCache) { $cache->put($requestKey, $url); } if (strpos($url, "/swfparams/") > 0) { $url = substr($url, 0, -4) . urlencode($noncached_params) . ".swf"; } else { $url .= $noncached_params; } $this->redirect($url); }
public function execute() { sfView::SUCCESS; /** check parameters and verify user is logged-in **/ $this->partner_id = $this->getP("pid"); $this->subp_id = $this->getP("subpid", (int) $this->partner_id * 100); $this->uid = $this->getP("uid"); $this->ks = $this->getP("kmcks"); if (!$this->ks) { // if kmcks from cookie doesn't exist, try ks from REQUEST $this->ks = $this->getP('ks'); } $this->screen_name = $this->getP("screen_name"); $this->email = $this->getP("email"); /** if no KS found, redirect to login page **/ if (!$this->ks) { $this->redirect("kmc/kmc"); die; } $ksObj = kSessionUtils::crackKs($this->ks); /** END - check parameters and verify user is logged-in **/ /** Get array of allowed partners for the current user **/ $this->allowedPartners = array(); $currentUser = kuserPeer::getKuserByPartnerAndUid($this->partner_id, $ksObj->user, true); if ($currentUser) { $partners = myPartnerUtils::getPartnersArray($currentUser->getAllowedPartnerIds()); foreach ($partners as $partner) { $this->allowedPartners[] = array('id' => $partner->getId(), 'name' => $partner->getName()); } $this->full_name = $currentUser->getFullName(); } /** load partner from DB, and set templatePartnerId **/ $this->partner = $partner = null; $this->templatePartnerId = self::SYSTEM_DEFAULT_PARTNER; $this->ignoreSeoLinks = false; $this->ignoreEntrySeoLinks = false; $this->useEmbedCodeProtocolHttps = false; $this->v2Flavors = false; if ($this->partner_id !== NULL) { $this->partner = $partner = PartnerPeer::retrieveByPK($this->partner_id); kmcUtils::redirectPartnerToCorrectKmc($partner, $this->ks, $this->uid, $this->screen_name, $this->email, self::CURRENT_KMC_VERSION); $this->templatePartnerId = $this->partner ? $this->partner->getTemplatePartnerId() : self::SYSTEM_DEFAULT_PARTNER; $this->ignoreSeoLinks = $this->partner->getIgnoreSeoLinks(); $this->ignoreEntrySeoLinks = PermissionPeer::isValidForPartner(PermissionName::FEATURE_IGNORE_ENTRY_SEO_LINKS, $this->partner_id); $this->useEmbedCodeProtocolHttps = PermissionPeer::isValidForPartner(PermissionName::FEATURE_EMBED_CODE_DEFAULT_PROTOCOL_HTTPS, $this->partner_id); $this->v2Flavors = PermissionPeer::isValidForPartner(PermissionName::FEATURE_V2_FLAVORS, $this->partner_id); } /** END - load partner from DB, and set templatePartnerId **/ /** set default flags **/ $this->payingPartner = 'false'; $this->kdp508_players = array(); $this->first_login = false; /** END - set default flags **/ /** set values for template **/ $this->service_url = myPartnerUtils::getHost($this->partner_id); $this->host = $this->stripProtocol($this->service_url); $this->embed_host = $this->host; if (kConf::hasParam('cdn_api_host') && kConf::hasParam('www_host') && $this->host == kConf::get('cdn_api_host')) { $this->host = kConf::get('www_host'); } $this->cdn_url = myPartnerUtils::getCdnHost($this->partner_id); $this->cdn_host = $this->stripProtocol($this->cdn_url); $this->rtmp_host = myPartnerUtils::getRtmpUrl($this->partner_id); $this->flash_dir = $this->cdn_url . myContentStorage::getFSFlashRootPath(); // Decide if to hide akamai delivery type $this->hideAkamaiHDNetwork = $partner->getDisableAkamaiHDNetwork(); /** set payingPartner flag **/ if ($partner && $partner->getPartnerPackage() != PartnerPackages::PARTNER_PACKAGE_FREE) { $this->payingPartner = 'true'; } /** END - set payingPartner flag **/ /** get partner languae **/ $this->language = null; if ($partner->getKMCLanguage()) { $this->language = $partner->getKMCLanguage(); } /** END - get partner languae **/ /** set first_login flag **/ $this->first_login = $partner->getIsFirstLogin(); if ($this->first_login === true) { $partner->setIsFirstLogin(false); $partner->save(); } /** END - set first_login flag **/ /** get logout url **/ $this->logoutUrl = null; if ($partner->getLogoutUrl()) { $this->logoutUrl = $partner->getLogoutUrl(); } /** END - get logout url**/ /** partner-specific: change KDP version for partners working with auto-moderaion **/ // set content kdp version according to partner id $moderated_partners = array(31079, 28575, 32774); $this->content_kdp_version = 'v2.7.0'; if (in_array($this->partner_id, $moderated_partners)) { $this->content_kdp_version = 'v2.1.2.29057'; } /** END - partner-specific: change KDP version for partners working with auto-moderaion **/ $this->kmc_swf_version = kConf::get('kmc_version'); /** uiconf listing work **/ /** fill $this->confs with all uiconf objects for all modules **/ $kmcGeneralUiConf = kmcUtils::getAllKMCUiconfs('kmc', $this->kmc_swf_version, self::SYSTEM_DEFAULT_PARTNER); $kmcGeneralTemplateUiConf = kmcUtils::getAllKMCUiconfs('kmc', $this->kmc_swf_version, $this->templatePartnerId); /** for each module, create separated lists of its uiconf, for each need **/ /** kmc general uiconfs **/ $this->kmc_general = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_kmcgeneral", false, $kmcGeneralUiConf); $this->kmc_permissions = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_kmcpermissions", false, $kmcGeneralUiConf); /** P&E players: **/ //$this->content_uiconfs_previewembed = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_previewembed", true, $kmcGeneralUiConf); //$this->content_uiconfs_previewembed_list = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_previewembed_list", true, $kmcGeneralUiConf); $this->content_uiconfs_flavorpreview = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_flavorpreview", false, $kmcGeneralUiConf); /* KCW uiconfs */ $this->content_uiconfs_upload_webcam = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_uploadWebCam", false, $kmcGeneralUiConf); $this->content_uiconfs_upload_import = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_uploadImport", false, $kmcGeneralUiConf); $this->content_uiconds_clipapp_kdp = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_kdpClipApp", false, $kmcGeneralUiConf); $this->content_uiconds_clipapp_kclip = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_kClipClipApp", false, $kmcGeneralUiConf); /** content KCW,KSE,KAE **/ //$this->content_uiconfs_upload = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_upload", false, $kmcGeneralUiConf); //$this->simple_editor = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_simpleedit", false, $kmcGeneralUiConf); //$this->advanced_editor = kmcUtils::find_confs_by_usage_tag($kmcGeneralTemplateUiConf, "kmc_advanceedit", false, $kmcGeneralUiConf); /** END - uiconf listing work **/ /** get templateXmlUrl for whitelabeled partners **/ //$this->appstudio_templatesXmlUrl = $this->getAppStudioTemplatePath(); }
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); // 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); } myPartnerUtils::blockInactivePartner($entry->getPartnerId()); // 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. die; } 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); kFile::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 = flavorAssetPeer::retrieveBestEditByEntryId($entry->getId()); } elseif (!is_null($flavor)) { $flavorAsset = flavorAssetPeer::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 = flavorAssetPeer::retrieveByEntryIdAndFlavorParams($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 = flavorAssetPeer::retrieveOriginalByEntryId($entry->getId()); } else { $flavorAsset = flavorAssetPeer::retrieveBestPlayByEntryId($entry->getId()); } if (!$flavorAsset) { $flavorAssets = flavorAssetPeer::retreiveReadyByEntryIdAndTag($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); } $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}"); die; } 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}"); die; } // 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); 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"); die; } $ks = kSessionUtils::crackKs($ks_str); if (!$ks) { $this->logMessage("flvclipper - invalid ks [{$ks_str}]"); die; } $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}]"); die; } } 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}"); die; } 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}"); die; } } } // 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); die; } // mp4 if (!$isFlv) { kFile::dumpFile($path); } $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}"); } return sfView::SUCCESS; }
/** * 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); }
private function validateTicketSetPartner($partner_id, $subp_id, $puser_id, $ks_str) { if ($ks_str) { // 1. crack the ks - $ks = kSessionUtils::crackKs($ks_str); // 2. extract partner_id $ks_partner_id = $ks->partner_id; $master_partner_id = $ks->master_partner_id; if (!$master_partner_id) { $master_partner_id = $ks_partner_id; } if (!$partner_id) { $partner_id = $ks_partner_id; } // use the user from the ks if not explicity set if (!$puser_id) { $puser_id = $ks->user; } kCurrentContext::$ks = $ks_str; kCurrentContext::$partner_id = $partner_id; kCurrentContext::$ks_partner_id = $ks_partner_id; kCurrentContext::$master_partner_id = $master_partner_id; kCurrentContext::$uid = $puser_id; kCurrentContext::$ks_uid = $ks->user; // 3. retrieve partner $ks_partner = PartnerPeer::retrieveByPK($ks_partner_id); // the service_confgi is assumed to be the one of the operating_partner == ks_partner if (!$ks_partner) { $this->addException(APIErrors::UNKNOWN_PARTNER_ID, $ks_partner_id); } $this->setServiceConfigFromPartner($ks_partner); if ($ks_partner && !$ks_partner->getStatus()) { $this->addException(APIErrors::SERVICE_FORBIDDEN_PARTNER_DELETED); } // 4. validate ticket per service for the ticket's partner $ticket_type = $this->ticketType2(); if ($ticket_type == kSessionUtils::REQUIED_TICKET_NOT_ACCESSIBLE) { // partner cannot access this service $this->addException(APIErrors::SERVICE_FORBIDDEN); } if ($this->force_ticket_check && $ticket_type != kSessionUtils::REQUIED_TICKET_NONE) { // TODO - which user is this ? from the ks ? from the puser_id ? $ks_puser_id = $ks->user; //$ks = null; $res = kSessionUtils::validateKSession2($ticket_type, $ks_partner_id, $ks_puser_id, $ks_str, $ks); if (0 >= $res) { // chaned this to be an exception rather than an error $this->addException(APIErrors::INVALID_KS, $ks_str, $res, ks::getErrorStr($res)); } $this->ks = $ks; } elseif ($ticket_type == kSessionUtils::REQUIED_TICKET_NONE && $ks_str) { $ks_puser_id = $ks->user; $res = kSessionUtils::validateKSession2($ticket_type, $ks_partner_id, $ks_puser_id, $ks_str, $ks); if ($res > 0) { $this->ks = $ks; } } // 5. see partner is allowed to access the desired partner (if himself - easy, else - should appear in the partnerGroup) $allow_access = myPartnerUtils::allowPartnerAccessPartner($ks_partner_id, $this->partnerGroup2(), $partner_id); if (!$allow_access) { $this->addException(APIErrors::PARTNER_ACCESS_FORBIDDEN, $ks_partner_id, $partner_id); } // 6. set the partner to be the desired partner and the operating_partner to be the one from the ks $this->partner = PartnerPeer::retrieveByPK($partner_id); $this->operating_partner = $ks_partner; // the config is that of the ks_partner NOT of the partner // $this->setServiceConfigFromPartner( $ks_partner ); - was already set above to extract the ks // TODO - should change service_config to be the one of the partner_id ?? // 7. if ok - return the partner_id to be used from this point onwards return array($partner_id, $subp_id, $puser_id, true); // allow private_partner_data } else { // no ks_str // 1. extract partner by partner_id + // 2. retrieve partner $this->partner = PartnerPeer::retrieveByPK($partner_id); if (!$this->partner) { $this->partner = null; // go to the default config $this->setServiceConfigFromPartner(null); if ($this->requirePartner2()) { $this->addException(APIErrors::UNKNOWN_PARTNER_ID, $partner_id); } } if ($this->partner && !$this->partner->getStatus()) { $this->addException(APIErrors::SERVICE_FORBIDDEN_PARTNER_DELETED); } kCurrentContext::$ks = null; kCurrentContext::$partner_id = $partner_id; kCurrentContext::$ks_partner_id = null; kCurrentContext::$uid = $puser_id; kCurrentContext::$ks_uid = null; // 3. make sure the service can be accessed with no ticket $this->setServiceConfigFromPartner($this->partner); $ticket_type = $this->ticketType2(); if ($ticket_type == kSessionUtils::REQUIED_TICKET_NOT_ACCESSIBLE) { // partner cannot access this service $this->addException(APIErrors::SERVICE_FORBIDDEN); } if ($this->force_ticket_check && $ticket_type != kSessionUtils::REQUIED_TICKET_NONE) { // NEW: 2008-12-28 // Instead of throwing an exception, see if the service allows KN. // If so - a relativly week partner access if ($this->kalturaNetwork2()) { // if the service supports KN - continue without private data return array($partner_id, $subp_id, $puser_id, false); // DONT allow private_partner_data } // chaned this to be an exception rather than an error $this->addException(APIErrors::MISSING_KS); } // 4. set the partner & operating_partner to be the one-and-only partner of this session $this->operating_partner = $this->partner; return array($partner_id, $subp_id, $puser_id, true); // allow private_partner_data } }
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); } } }
/** * * Gets KS for PS2 * @param string $secret * @param string $userId * @param KalturaSessionType $type * @param string $partnerId * @param int $expiry * @param unknown_type $privileges */ public static function getKs($secret, $userId = "", $type = 0, $partnerId = null, $expiry = 86400, $privileges = null) { $ks = ''; $result = kSessionUtils::startKSession($partnerId, $secret, $userId, $ks, $expiry, $type, "", $privileges); if ($result >= 0) { return $ks; } else { throw new Exception("Error starting admin session for: Partner: {$partnerId}, with Secret: {$secret} \n"); } }