Exemplo n.º 1
0
 public function doFromObject($dbObject, KalturaDetachedResponseProfile $responseProfile = null)
 {
     parent::doFromObject($dbObject, $responseProfile);
     $dbEntry = entryPeer::retrieveByPK($dbObject->getEntryId());
     if (!kEntitlementUtils::isEntitledForEditEntry($dbEntry)) {
         /**
          * @var kQuiz $kQuiz
          */
         $kQuiz = QuizPlugin::validateAndGetQuiz($dbEntry);
         $dbUserEntry = UserEntryPeer::retrieveByPK($this->quizUserEntryId);
         if ($dbUserEntry && $dbUserEntry->getStatus() == QuizPlugin::getCoreValue('UserEntryStatus', QuizUserEntryStatus::QUIZ_SUBMITTED)) {
             if (!$kQuiz->getShowCorrectAfterSubmission()) {
                 $this->isCorrect = KalturaNullableBoolean::NULL_VALUE;
                 $this->correctAnswerKeys = null;
                 $this->explanation = null;
             }
         } else {
             if (!$kQuiz->getShowResultOnAnswer()) {
                 $this->isCorrect = KalturaNullableBoolean::NULL_VALUE;
             }
             if (!$kQuiz->getShowCorrectKeyOnAnswer()) {
                 $this->correctAnswerKeys = null;
                 $this->explanation = null;
             }
         }
     }
 }
Exemplo n.º 2
0
 public function validateForInsert($propertiesToSkip = array())
 {
     parent::validateForInsert($propertiesToSkip);
     $dbEntry = entryPeer::retrieveByPK($this->entryId);
     QuizPlugin::validateAndGetQuiz($dbEntry);
     if (!kEntitlementUtils::isEntitledForEditEntry($dbEntry)) {
         throw new KalturaAPIException(KalturaErrors::INVALID_USER_ID);
     }
 }
Exemplo n.º 3
0
 public function validateForResponseProfile()
 {
     if (kEntitlementUtils::getEntitlementEnforcement()) {
         if (PermissionPeer::isValidForPartner(PermissionName::FEATURE_ENABLE_RESPONSE_PROFILE_USER_CACHE, kCurrentContext::getCurrentPartnerId())) {
             KalturaResponseProfileCacher::useUserCache();
             return;
         }
         throw new KalturaAPIException(KalturaErrors::CANNOT_LIST_RELATED_ENTITLED_WHEN_ENTITLEMENT_IS_ENABLE, get_class($this));
     }
 }
Exemplo n.º 4
0
 /**
  * Creates default criteria filter
  */
 public static function setDefaultCriteriaFilter()
 {
     if (self::$s_criteria_filter == null) {
         self::$s_criteria_filter = new criteriaFilter();
     }
     $c = KalturaCriteria::create(self::OM_CLASS);
     if (kEntitlementUtils::getEntitlementEnforcement()) {
         $privacyContexts = kEntitlementUtils::getKsPrivacyContextArray();
         $c->addAnd(self::PRIVACY_CONTEXT, $privacyContexts, Criteria::IN);
     }
     $c->addAnd(self::INSTANCE_COUNT, 0, Criteria::GREATER_THAN);
     self::$s_criteria_filter->setFilter($c);
 }
Exemplo n.º 5
0
 /**
  * if user is entitled for this action will update quizData on entry
  * @param entry $dbEntry
  * @param KalturaQuiz $quiz
  * @param int $currentVersion
  * @param kQuiz|null $newQuiz
  * @return KalturaQuiz
  * @throws KalturaAPIException
  */
 private function validateAndUpdateQuizData(entry $dbEntry, KalturaQuiz $quiz, $currentVersion = 0, kQuiz $newQuiz = null)
 {
     if (!kEntitlementUtils::isEntitledForEditEntry($dbEntry)) {
         KalturaLog::debug('Update quiz allowed only with admin KS or entry owner or co-editor');
         throw new KalturaAPIException(KalturaErrors::INVALID_USER_ID);
     }
     $quizData = $quiz->toObject($newQuiz);
     $quizData->setVersion($currentVersion + 1);
     QuizPlugin::setQuizData($dbEntry, $quizData);
     $dbEntry->setIsTrimDisabled(true);
     $dbEntry->save();
     $quiz->fromObject($quizData);
     return $quiz;
 }
Exemplo n.º 6
0
 public function getListResponse(KalturaFilterPager $pager, KalturaDetachedResponseProfile $responseProfile = null)
 {
     if (kEntitlementUtils::getEntitlementEnforcement() && (is_null($this->objectIdIn) && is_null($this->objectIdEqual))) {
         throw new KalturaAPIException(MetadataErrors::MUST_FILTER_ON_OBJECT_ID);
     }
     if (!$this->metadataObjectTypeEqual) {
         throw new KalturaAPIException(MetadataErrors::MUST_FILTER_ON_OBJECT_TYPE);
     }
     if ($this->metadataObjectTypeEqual == MetadataObjectType::CATEGORY) {
         if ($this->objectIdEqual) {
             $categoryIds = array($this->objectIdEqual);
         } else {
             if ($this->objectIdIn) {
                 $categoryIds = explode(',', $this->objectIdIn);
             }
         }
         if ($categoryIds) {
             $categories = categoryPeer::retrieveByPKs($categoryIds);
             if (!count($categories)) {
                 KalturaLog::debug("No categories found");
                 $response = new KalturaMetadataListResponse();
                 $response->objects = new KalturaMetadataArray();
                 $response->totalCount = 0;
                 return $response;
             }
             $categoryIds = array();
             foreach ($categories as $category) {
                 $categoryIds[] = $category->getId();
             }
             $this->objectIdEqual = null;
             $this->objectIdIn = implode(',', $categoryIds);
         }
     }
     $metadataFilter = $this->toObject();
     $c = KalturaCriteria::create(MetadataPeer::OM_CLASS);
     $metadataFilter->attachToCriteria($c);
     $pager->attachToCriteria($c);
     $list = MetadataPeer::doSelect($c);
     $response = new KalturaMetadataListResponse();
     $response->objects = KalturaMetadataArray::fromDbArray($list, $responseProfile);
     if ($c instanceof SphinxMetadataCriteria) {
         $response->totalCount = $c->getRecordsCount();
     } elseif ($pager->pageIndex == 1 && count($response->objects) < $pager->pageSize) {
         $response->totalCount = count($response->objects);
     } else {
         $pager->detachFromCriteria($c);
         $response->totalCount = MetadataPeer::doCount($c);
     }
     return $response;
 }
 private static function getObjectSpecificCacheKey(IBaseObject $object, $responseProfileKey)
 {
     $userRoles = kPermissionManager::getCurrentRoleIds();
     sort($userRoles);
     $objectType = get_class($object);
     $objectId = $object->getPrimaryKey();
     $partnerId = $object->getPartnerId();
     $profileKey = $responseProfileKey;
     $protocol = infraRequestUtils::getProtocol();
     $ksType = kCurrentContext::getCurrentSessionType();
     $userRoles = implode('-', $userRoles);
     $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
     $entitlement = (int) kEntitlementUtils::getEntitlementEnforcement();
     return "obj_rp{$profileKey}_p{$partnerId}_o{$objectType}_i{$objectId}_h{$protocol}_k{$ksType}_u{$userRoles}_w{$host}_e{$entitlement}";
 }
Exemplo n.º 8
0
 /**
  * Delivering the status of a live stream (on-air/offline) if it is possible
  * 
  * @action isLive
  * @param string $id ID of the live stream
  * @param KalturaPlaybackProtocol $protocol protocol of the stream to test.
  * @return bool
  * 
  * @throws KalturaErrors::LIVE_STREAM_STATUS_CANNOT_BE_DETERMINED
  * @throws KalturaErrors::INVALID_ENTRY_ID
  */
 public function isLiveAction($id, $protocol)
 {
     if (!kCurrentContext::$ks) {
         kEntitlementUtils::initEntitlementEnforcement(null, false);
         $liveStreamEntry = kCurrentContext::initPartnerByEntryId($id);
         if (!$liveStreamEntry || $liveStreamEntry->getStatus() == entryStatus::DELETED) {
             throw new KalturaAPIException(KalturaErrors::INVALID_ENTRY_ID, $id);
         }
         // enforce entitlement
         $this->setPartnerFilters(kCurrentContext::getCurrentPartnerId());
     } else {
         $liveStreamEntry = entryPeer::retrieveByPK($id);
     }
     if (!$liveStreamEntry || $liveStreamEntry->getType() != entryType::LIVE_STREAM) {
         throw new KalturaAPIException(KalturaErrors::INVALID_ENTRY_ID, $id);
     }
     if (!in_array($liveStreamEntry->getSource(), LiveEntry::$kalturaLiveSourceTypes)) {
         KalturaResponseCacher::setConditionalCacheExpiry(self::ISLIVE_ACTION_NON_KALTURA_LIVE_CONDITIONAL_CACHE_EXPIRY);
     }
     /* @var $liveStreamEntry LiveStreamEntry */
     if (in_array($liveStreamEntry->getSource(), array(KalturaSourceType::LIVE_STREAM, KalturaSourceType::LIVE_STREAM_ONTEXTDATA_CAPTIONS))) {
         return $this->responseHandlingIsLive($liveStreamEntry->hasMediaServer());
     }
     $dpda = new DeliveryProfileDynamicAttributes();
     $dpda->setEntryId($id);
     $dpda->setFormat($protocol);
     switch ($protocol) {
         case KalturaPlaybackProtocol::HLS:
         case KalturaPlaybackProtocol::APPLE_HTTP:
             $url = $liveStreamEntry->getHlsStreamUrl();
             foreach (array(KalturaPlaybackProtocol::HLS, KalturaPlaybackProtocol::APPLE_HTTP) as $hlsProtocol) {
                 $config = $liveStreamEntry->getLiveStreamConfigurationByProtocol($hlsProtocol, requestUtils::getProtocol());
                 if ($config) {
                     $url = $config->getUrl();
                     $protocol = $hlsProtocol;
                     break;
                 }
             }
             KalturaLog::info('Determining status of live stream URL [' . $url . ']');
             $urlManager = DeliveryProfilePeer::getLiveDeliveryProfileByHostName(parse_url($url, PHP_URL_HOST), $dpda);
             if ($urlManager) {
                 return $this->responseHandlingIsLive($urlManager->isLive($url));
             }
             break;
         case KalturaPlaybackProtocol::HDS:
         case KalturaPlaybackProtocol::AKAMAI_HDS:
             $config = $liveStreamEntry->getLiveStreamConfigurationByProtocol($protocol, requestUtils::getProtocol());
             if ($config) {
                 $url = $config->getUrl();
                 KalturaLog::info('Determining status of live stream URL [' . $url . ']');
                 $urlManager = DeliveryProfilePeer::getLiveDeliveryProfileByHostName(parse_url($url, PHP_URL_HOST), $dpda);
                 if ($urlManager) {
                     return $this->responseHandlingIsLive($urlManager->isLive($url));
                 }
             }
             break;
     }
     throw new KalturaAPIException(KalturaErrors::LIVE_STREAM_STATUS_CANNOT_BE_DETERMINED, $protocol);
 }
 public function __construct($feedId, $feedProcessingKey = null, $ks = null)
 {
     $this->feedProcessingKey = $feedProcessingKey;
     myDbHelper::$use_alternative_con = myDbHelper::DB_HELPER_CONN_PROPEL3;
     $microTimeStart = microtime(true);
     KalturaLog::info("syndicationFeedRenderer- initialize ");
     $this->syndicationFeedDb = $syndicationFeedDB = syndicationFeedPeer::retrieveByPK($feedId);
     if (!$syndicationFeedDB) {
         throw new Exception("Feed Id not found");
     }
     kCurrentContext::initKsPartnerUser($ks, $syndicationFeedDB->getPartnerId(), '');
     kPermissionManager::init();
     kEntitlementUtils::initEntitlementEnforcement($syndicationFeedDB->getPartnerId(), $syndicationFeedDB->getEnforceEntitlement());
     if (!is_null($syndicationFeedDB->getPrivacyContext()) && $syndicationFeedDB->getPrivacyContext() != '') {
         kEntitlementUtils::setPrivacyContextSearch($syndicationFeedDB->getPrivacyContext());
     }
     $tmpSyndicationFeed = KalturaSyndicationFeedFactory::getInstanceByType($syndicationFeedDB->getType());
     $tmpSyndicationFeed->fromObject($syndicationFeedDB);
     $this->syndicationFeed = $tmpSyndicationFeed;
     // add partner to default criteria
     myPartnerUtils::addPartnerToCriteria('category', $this->syndicationFeed->partnerId, true);
     myPartnerUtils::addPartnerToCriteria('asset', $this->syndicationFeed->partnerId, true);
     myPartnerUtils::resetPartnerFilter('entry');
     $this->baseCriteria = clone entryPeer::getDefaultCriteriaFilter();
     $startDateCriterion = $this->baseCriteria->getNewCriterion(entryPeer::START_DATE, time(), Criteria::LESS_EQUAL);
     $startDateCriterion->addOr($this->baseCriteria->getNewCriterion(entryPeer::START_DATE, null));
     $this->baseCriteria->addAnd($startDateCriterion);
     $endDateCriterion = $this->baseCriteria->getNewCriterion(entryPeer::END_DATE, time(), Criteria::GREATER_EQUAL);
     $endDateCriterion->addOr($this->baseCriteria->getNewCriterion(entryPeer::END_DATE, null));
     $this->baseCriteria->addAnd($endDateCriterion);
     $this->baseCriteria->addAnd(entryPeer::PARTNER_ID, $this->syndicationFeed->partnerId);
     $this->baseCriteria->addAnd(entryPeer::STATUS, entryStatus::READY);
     $this->baseCriteria->addAnd(entryPeer::TYPE, array(entryType::MEDIA_CLIP, entryType::MIX), Criteria::IN);
     $this->baseCriteria->addAnd(entryPeer::MODERATION_STATUS, array(entry::ENTRY_MODERATION_STATUS_REJECTED, entry::ENTRY_MODERATION_STATUS_PENDING_MODERATION), Criteria::NOT_IN);
     if ($this->syndicationFeed->playlistId) {
         $this->entryFilters = myPlaylistUtils::getPlaylistFiltersById($this->syndicationFeed->playlistId);
         foreach ($this->entryFilters as $entryFilter) {
             $entryFilter->setPartnerSearchScope(baseObjectFilter::MATCH_KALTURA_NETWORK_AND_PRIVATE);
             // partner scope already attached
         }
         $playlist = entryPeer::retrieveByPK($this->syndicationFeed->playlistId);
         if ($playlist) {
             if ($playlist->getMediaType() != entry::ENTRY_MEDIA_TYPE_XML) {
                 $this->staticPlaylist = true;
                 $this->staticPlaylistEntriesIdsOrder = explode(',', $playlist->getDataContent());
             }
         }
     } else {
         $this->entryFilters = array();
     }
     $microTimeEnd = microtime(true);
     KalturaLog::info("syndicationFeedRenderer- initialization done [" . ($microTimeEnd - $microTimeStart) . "]");
 }
Exemplo n.º 10
0
 /**
  * Index CategoryUser by userid and category id
  * 
  * @action index
  * @param string $userId
  * @param int $categoryId
  * @param bool $shouldUpdate
  * @throws KalturaErrors::INVALID_CATEGORY_USER_ID
  * @return int
  */
 public function indexAction($userId, $categoryId, $shouldUpdate = true)
 {
     if (kEntitlementUtils::getEntitlementEnforcement()) {
         throw new KalturaAPIException(KalturaErrors::CANNOT_INDEX_OBJECT_WHEN_ENTITLEMENT_IS_ENABLE);
     }
     $partnerId = kCurrentContext::$partner_id ? kCurrentContext::$partner_id : kCurrentContext::$ks_partner_id;
     $kuser = kuserPeer::getActiveKuserByPartnerAndUid($partnerId, $userId);
     if (!$kuser) {
         throw new KalturaAPIException(KalturaErrors::INVALID_USER_ID);
     }
     $dbCategoryKuser = categoryKuserPeer::retrievePermittedKuserInCategory($categoryId, $kuser->getId(), null, false);
     if (!$dbCategoryKuser) {
         throw new KalturaAPIException(KalturaErrors::INVALID_CATEGORY_USER_ID);
     }
     if (!$shouldUpdate) {
         $dbCategoryKuser->setUpdatedAt(time());
         $dbCategoryKuser->save();
         return $dbCategoryKuser->getId();
     }
     $dbCategoryKuser->reSetCategoryFullIds();
     $dbCategoryKuser->reSetScreenName();
     $dbCategoryKuser->save();
     return $dbCategoryKuser->getId();
 }
Exemplo n.º 11
0
 /**
  * Search caption asset items by filter, pager and free text
  *
  * @action searchEntries
  * @param KalturaBaseEntryFilter $entryFilter
  * @param KalturaCaptionAssetItemFilter $captionAssetItemFilter
  * @param KalturaFilterPager $captionAssetItemPager
  * @return KalturaBaseEntryListResponse
  */
 public function searchEntriesAction(KalturaBaseEntryFilter $entryFilter = null, KalturaCaptionAssetItemFilter $captionAssetItemFilter = null, KalturaFilterPager $captionAssetItemPager = null)
 {
     if (!$captionAssetItemPager) {
         $captionAssetItemPager = new KalturaFilterPager();
     }
     if (!$captionAssetItemFilter) {
         $captionAssetItemFilter = new KalturaCaptionAssetItemFilter();
     }
     $captionAssetItemFilter->validatePropertyNotNull(array("contentLike", "contentMultiLikeOr", "contentMultiLikeAnd"));
     $captionAssetItemCoreFilter = new CaptionAssetItemFilter();
     $captionAssetItemFilter->toObject($captionAssetItemCoreFilter);
     $entryIdChunks = array(NULL);
     if ($entryFilter || kEntitlementUtils::getEntitlementEnforcement()) {
         $entryCoreFilter = new entryFilter();
         if ($entryFilter) {
             $entryFilter->toObject($entryCoreFilter);
         }
         $entryCoreFilter->setPartnerSearchScope($this->getPartnerId());
         $this->addEntryAdvancedSearchFilter($captionAssetItemFilter, $entryCoreFilter);
         $entryCriteria = KalturaCriteria::create(entryPeer::OM_CLASS);
         $entryCoreFilter->attachToCriteria($entryCriteria);
         $entryCriteria->setLimit(self::MAX_NUMBER_OF_ENTRIES);
         $entryCriteria->applyFilters();
         $entryIds = $entryCriteria->getFetchedIds();
         if (!$entryIds || !count($entryIds)) {
             $entryIds = array('NOT_EXIST');
         }
         $entryIdChunks = array_chunk($entryIds, self::SIZE_OF_ENTRIES_CHUNK);
     }
     $entries = array();
     $counter = 0;
     $shouldSortCaptionFiltering = $entryFilter->orderBy ? true : false;
     $captionAssetItemCriteria = KalturaCriteria::create(CaptionAssetItemPeer::OM_CLASS);
     $captionAssetItemCoreFilter->attachToCriteria($captionAssetItemCriteria);
     $captionAssetItemCriteria->setGroupByColumn('str_entry_id');
     $captionAssetItemCriteria->setSelectColumn('str_entry_id');
     foreach ($entryIdChunks as $chunk) {
         $currCriteria = clone $captionAssetItemCriteria;
         if ($chunk) {
             $currCriteria->add(CaptionAssetItemPeer::ENTRY_ID, $chunk, KalturaCriteria::IN);
         } else {
             $captionAssetItemPager->attachToCriteria($currCriteria);
         }
         $currCriteria->applyFilters();
         $currEntries = $currCriteria->getFetchedIds();
         //sorting this chunk according to results of first sphinx query
         if ($shouldSortCaptionFiltering) {
             $currEntries = array_intersect($entryIds, $currEntries);
         }
         $entries = array_merge($entries, $currEntries);
         $counter += $currCriteria->getRecordsCount();
     }
     $inputPageSize = $captionAssetItemPager->pageSize;
     $inputPageIndex = $captionAssetItemPager->pageIndex;
     //page index & size validation - no negative values & size not too big
     $pageSize = max(min($inputPageSize, baseObjectFilter::getMaxInValues()), 0);
     $pageIndex = max($captionAssetItemPager::MIN_PAGE_INDEX, $inputPageIndex) - 1;
     $firstIndex = $pageSize * $pageIndex;
     $entries = array_slice($entries, $firstIndex, $pageSize);
     $dbList = entryPeer::retrieveByPKs($entries);
     if ($shouldSortCaptionFiltering) {
         //results ids mapping
         $entriesMapping = array();
         foreach ($dbList as $item) {
             $entriesMapping[$item->getId()] = $item;
         }
         $dbList = array();
         foreach ($entries as $entryId) {
             if (isset($entriesMapping[$entryId])) {
                 $dbList[] = $entriesMapping[$entryId];
             }
         }
     }
     $list = KalturaBaseEntryArray::fromDbArray($dbList, $this->getResponseProfile());
     $response = new KalturaBaseEntryListResponse();
     $response->objects = $list;
     $response->totalCount = $counter;
     return $response;
 }
Exemplo n.º 12
0
 /**
  * Return all categories kuser is entitled to view the content.
  * (User may call category->get to view a category - but not to view its content)
  * 
  * @param int $kuserId
  * @param int $limit
  * @return array<category>
  */
 public static function retrieveEntitledAndNonIndexedByKuser($kuserId, $limit)
 {
     $partnerId = kCurrentContext::$partner_id ? kCurrentContext::$partner_id : kCurrentContext::$ks_partner_id;
     $partner = PartnerPeer::retrieveByPK($partnerId);
     $categoryGroupSize = kConf::get('max_number_of_memebrs_to_be_indexed_on_entry');
     if ($partner && $partner->getCategoryGroupSize()) {
         $categoryGroupSize = $partner->getCategoryGroupSize();
     }
     $c = KalturaCriteria::create(categoryPeer::OM_CLASS);
     $filteredCategoriesIds = entryPeer::getFilterdCategoriesIds();
     if (count($filteredCategoriesIds)) {
         $c->addAnd(categoryPeer::ID, $filteredCategoriesIds, Criteria::IN);
     }
     $membersCountCrit = $c->getNewCriterion(categoryPeer::MEMBERS_COUNT, $categoryGroupSize, Criteria::GREATER_THAN);
     $membersCountCrit->addOr($c->getNewCriterion(categoryPeer::ENTRIES_COUNT, kConf::get('category_entries_count_limit_to_be_indexed'), Criteria::GREATER_THAN));
     $c->addAnd($membersCountCrit);
     $c->setLimit($limit);
     $c->addDescendingOrderByColumn(categoryPeer::UPDATED_AT);
     //all fields needed from default criteria
     //here we cannot use the default criteria, as we need to get all categories user is entitled to view the content.
     //not deleted or purged
     $c->add(self::STATUS, array(CategoryStatus::DELETED, CategoryStatus::PURGED), Criteria::NOT_IN);
     $c->add(self::PARTNER_ID, $partnerId, Criteria::EQUAL);
     //add privacy context
     $privacyContextCrit = $c->getNewCriterion(self::PRIVACY_CONTEXTS, kEntitlementUtils::getKsPrivacyContext(), KalturaCriteria::IN_LIKE);
     $privacyContextCrit->addTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY);
     $c->addAnd($privacyContextCrit);
     //set privacy by ks and type
     $crit = $c->getNewCriterion(self::PRIVACY, kEntitlementUtils::getPrivacyForKs($partnerId), Criteria::IN);
     $crit->addTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY);
     //user is entitled to view all cantent that belong to categoires he is a membr of
     $kuser = null;
     $ksString = kCurrentContext::$ks ? kCurrentContext::$ks : '';
     if ($ksString != '') {
         $kuser = kCurrentContext::getCurrentKsKuser();
     }
     if ($kuser) {
         // get the groups that the user belongs to in case she is not associated to the category directly
         $kgroupIds = KuserKgroupPeer::retrieveKgroupIdsByKuserId($kuser->getId());
         $kgroupIds[] = $kuser->getId();
         $membersCrit = $c->getNewCriterion(self::MEMBERS, $kgroupIds, KalturaCriteria::IN_LIKE);
         $membersCrit->addTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY);
         $crit->addOr($membersCrit);
     }
     $c->addAnd($crit);
     $c->applyFilters();
     $categoryIds = $c->getFetchedIds();
     return $categoryIds;
 }
Exemplo n.º 13
0
 /**
  * To validate if user is entitled to the category � all needed is to select from the db.
  * 
  * @throws KalturaErrors::ENTRY_CATEGORY_FIELD_IS_DEPRECATED
  */
 public function validateCategories()
 {
     $partnerId = kCurrentContext::$ks_partner_id ? kCurrentContext::$ks_partner_id : kCurrentContext::$partner_id;
     if (implode(',', kEntitlementUtils::getKsPrivacyContext()) != kEntitlementUtils::DEFAULT_CONTEXT . $partnerId && ($this->categoriesIds != null || $this->categories != null)) {
         throw new KalturaAPIException(KalturaErrors::ENTRY_CATEGORY_FIELD_IS_DEPRECATED);
     }
     if ($this->categoriesIds != null) {
         $catsNames = array();
         $cats = explode(",", $this->categoriesIds);
         foreach ($cats as $cat) {
             $catName = categoryPeer::retrieveByPK($cat);
             if (is_null($catName)) {
                 throw new KalturaAPIException(KalturaErrors::CATEGORY_NOT_FOUND, $cat);
             }
         }
     }
     if ($this->categories != null) {
         $catsNames = array();
         $cats = explode(",", $this->categories);
         foreach ($cats as $cat) {
             $catName = categoryPeer::getByFullNameExactMatch($cat);
             if (is_null($catName)) {
                 KalturaCriterion::disableTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY);
                 $catName = categoryPeer::getByFullNameExactMatch($cat);
                 if ($catName) {
                     throw new KalturaAPIException(KalturaErrors::CATEGORY_NOT_PERMITTED, $cat);
                 }
                 KalturaCriterion::restoreTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY);
             }
         }
     }
 }
 /**
  * Serve XML rendition of the Kaltura Live Transcoding Profile usable by the Wowza transcoding add-on
  * 
  * @action serve
  * @param string $streamName the id of the live entry with it's stream suffix
  * @param string $hostname the media server host name
  * @return file
  * 
  * @throws KalturaErrors::ENTRY_ID_NOT_FOUND
  * @throws WowzaErrors::INVALID_STREAM_NAME
  */
 public function serveAction($streamName, $hostname = null)
 {
     $matches = null;
     if (!preg_match('/^(\\d_.{8})_(\\d+)$/', $streamName, $matches)) {
         throw new KalturaAPIException(WowzaErrors::INVALID_STREAM_NAME, $streamName);
     }
     $entryId = $matches[1];
     $suffix = $matches[2];
     $entry = null;
     if (!kCurrentContext::$ks) {
         kEntitlementUtils::initEntitlementEnforcement(null, false);
         $entry = kCurrentContext::initPartnerByEntryId($entryId);
         if (!$entry || $entry->getStatus() == entryStatus::DELETED) {
             throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId);
         }
         // enforce entitlement
         $this->setPartnerFilters(kCurrentContext::getCurrentPartnerId());
     } else {
         $entry = entryPeer::retrieveByPK($entryId);
     }
     if (!$entry || $entry->getType() != KalturaEntryType::LIVE_STREAM || !in_array($entry->getSource(), array(KalturaSourceType::LIVE_STREAM, KalturaSourceType::LIVE_STREAM_ONTEXTDATA_CAPTIONS))) {
         throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId);
     }
     $mediaServer = null;
     if ($hostname) {
         $mediaServer = MediaServerPeer::retrieveByHostname($hostname);
     }
     $conversionProfileId = $entry->getConversionProfileId();
     $liveParams = assetParamsPeer::retrieveByProfile($conversionProfileId);
     $liveParamsInput = null;
     $disableIngested = true;
     foreach ($liveParams as $liveParamsItem) {
         /* @var $liveParamsItem liveParams */
         if ($liveParamsItem->getStreamSuffix() == $suffix) {
             $liveParamsInput = $liveParamsItem;
             if (!$liveParamsInput->hasTag(assetParams::TAG_SOURCE)) {
                 $liveParams = array($liveParamsInput);
                 $disableIngested = false;
             }
             break;
         }
     }
     $ignoreLiveParamsIds = array();
     if ($disableIngested) {
         $conversionProfileAssetParams = flavorParamsConversionProfilePeer::retrieveByConversionProfile($conversionProfileId);
         foreach ($conversionProfileAssetParams as $conversionProfileAssetParamsItem) {
             /* @var $conversionProfileAssetParamsItem flavorParamsConversionProfile */
             if ($conversionProfileAssetParamsItem->getOrigin() == assetParamsOrigin::INGEST) {
                 $ignoreLiveParamsIds[] = $conversionProfileAssetParamsItem->getFlavorParamsId();
             }
         }
     }
     // translate the $liveParams to XML according to doc: http://www.wowza.com/forums/content.php?304#configTemplate
     $root = new SimpleXMLElement('<Root/>');
     $transcode = $root->addChild('Transcode');
     $encodes = $transcode->addChild('Encodes');
     $groups = array();
     foreach ($liveParams as $liveParamsItem) {
         /* @var $liveParamsItem liveParams */
         if (!$liveParamsItem->hasTag(assetParams::TAG_SOURCE) && in_array($liveParamsItem->getId(), $ignoreLiveParamsIds)) {
             continue;
         }
         $this->appendLiveParams($entry, $mediaServer, $encodes, $liveParamsItem);
         $tags = $liveParamsItem->getTagsArray();
         $tags[] = 'all';
         foreach ($tags as $tag) {
             if (!isset($groups[$tag])) {
                 $groups[$tag] = array();
             }
             $systemName = $liveParamsItem->getSystemName() ? $liveParamsItem->getSystemName() : $liveParamsItem->getId();
             $groups[$tag][] = $systemName;
         }
     }
     $decode = $transcode->addChild('Decode');
     $video = $decode->addChild('Video');
     $video->addChild('Deinterlace', 'false');
     $streamNameGroups = $transcode->addChild('StreamNameGroups');
     foreach ($groups as $groupName => $groupMembers) {
         $streamNameGroup = $streamNameGroups->addChild('StreamNameGroup');
         $streamNameGroup->addChild('Name', $groupName);
         $streamNameGroup->addChild('StreamName', '${SourceStreamName}_' . $groupName);
         $members = $streamNameGroup->addChild('Members');
         foreach ($groupMembers as $groupMember) {
             $member = $members->addChild('Member');
             $member->addChild('EncodeName', $groupMember);
         }
     }
     $properties = $transcode->addChild('Properties');
     $dom = new DOMDocument("1.0");
     $dom->preserveWhiteSpace = false;
     $dom->formatOutput = true;
     $dom->loadXML($root->asXML());
     return new kRendererString($dom->saveXML(), 'text/xml');
 }
 /**
  * Will forward to the regular swf player according to the widget_id 
  */
 public function execute()
 {
     $entryId = $this->getRequestParameter("entry_id");
     $flavorId = $this->getRequestParameter("flavor");
     $fileName = $this->getRequestParameter("file_name");
     $fileName = basename($fileName);
     $ksStr = $this->getRequestParameter("ks");
     $referrer = $this->getRequestParameter("referrer");
     $referrer = base64_decode($referrer);
     if (!is_string($referrer)) {
         // base64_decode can return binary data
         $referrer = "";
     }
     $entry = null;
     if ($ksStr) {
         try {
             kCurrentContext::initKsPartnerUser($ksStr);
         } catch (Exception $ex) {
             KExternalErrors::dieError(KExternalErrors::INVALID_KS);
         }
     } else {
         $entry = kCurrentContext::initPartnerByEntryId($entryId);
         if (!$entry) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     kEntitlementUtils::initEntitlementEnforcement();
     if (!$entry) {
         $entry = entryPeer::retrieveByPK($entryId);
         if (!$entry) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     } else {
         if (!kEntitlementUtils::isEntryEntitled($entry)) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     myPartnerUtils::blockInactivePartner($entry->getPartnerId());
     $securyEntryHelper = new KSecureEntryHelper($entry, $ksStr, $referrer, accessControlContextType::DOWNLOAD);
     $securyEntryHelper->validateForDownload($entry, $ksStr);
     $flavorAsset = null;
     if ($flavorId) {
         // get flavor asset
         $flavorAsset = assetPeer::retrieveById($flavorId);
         if (is_null($flavorAsset) || $flavorAsset->getStatus() != flavorAsset::FLAVOR_ASSET_STATUS_READY) {
             KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
         }
         // the request flavor should belong to the requested entry
         if ($flavorAsset->getEntryId() != $entryId) {
             KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
         }
     } else {
         $flavorAsset = assetPeer::retrieveBestPlayByEntryId($entry->getId());
     }
     // Gonen 26-04-2010: in case entry has no flavor with 'mbr' tag - we return the source
     if (!$flavorAsset && ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_VIDEO || $entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_AUDIO)) {
         $flavorAsset = assetPeer::retrieveOriginalByEntryId($entryId);
     }
     if ($flavorAsset) {
         $syncKey = $this->getSyncKeyAndForFlavorAsset($entry, $flavorAsset);
     } else {
         $syncKey = $this->getBestSyncKeyForEntry($entry);
     }
     if (is_null($syncKey)) {
         KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND);
     }
     $this->handleFileSyncRedirection($syncKey);
     $filePath = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey);
     $wamsAssetId = kFileSyncUtils::getWamsAssetIdForKey($syncKey);
     $wamsURL = kFileSyncUtils::getWamsURLForKey($syncKey);
     list($fileBaseName, $fileExt) = $this->getFileName($entry, $flavorAsset);
     if (!$fileName) {
         $fileName = $fileBaseName;
     }
     if ($fileExt && !is_dir($filePath)) {
         $fileName = $fileName . '.' . $fileExt;
     }
     //enable downloading file_name which inside the flavor asset directory
     if (is_dir($filePath)) {
         $filePath = $filePath . DIRECTORY_SEPARATOR . $fileName;
     }
     $this->dumpFile($filePath, $fileName, $wamsAssetId, $wamsURL);
     die;
     // no view
 }
 /**
  * List metadata objects by filter and pager
  * 
  * @action list
  * @param KalturaMetadataFilter $filter
  * @param KalturaFilterPager $pager
  * @return KalturaMetadataListResponse
  */
 function listAction(KalturaMetadataFilter $filter = null, KalturaFilterPager $pager = null)
 {
     if (!$filter) {
         $filter = new KalturaMetadataFilter();
     }
     if (kEntitlementUtils::getEntitlementEnforcement() && (is_null($filter->objectIdIn) && is_null($filter->objectIdEqual))) {
         throw new KalturaAPIException(MetadataErrors::MUST_FILTER_ON_OBJECT_ID);
     }
     $entryIds = null;
     if ($filter->metadataObjectTypeEqual == MetadataObjectType::ENTRY) {
         if ($filter->objectIdEqual) {
             $entryIds = array($filter->objectIdEqual);
         } else {
             if ($filter->objectIdIn) {
                 $entryIds = explode(',', $filter->objectIdIn);
             }
         }
     }
     if (is_null($entryIds)) {
         myPartnerUtils::addPartnerToCriteria(new MetadataPeer(), $this->getPartnerId(), $this->private_partner_data, $this->partnerGroup());
     } else {
         $entryIds = entryPeer::filterEntriesByPartnerOrKalturaNetwork($entryIds, $this->getPartnerId());
         $filter->objectIdEqual = null;
         $filter->objectIdIn = implode(',', $entryIds);
     }
     $metadataFilter = new MetadataFilter();
     $filter->toObject($metadataFilter);
     $c = new Criteria();
     $metadataFilter->attachToCriteria($c);
     if ($entryIds === array()) {
         $c->addAnd(MetadataPeer::OBJECT_ID, array(), Criteria::IN);
     }
     $count = MetadataPeer::doCount($c);
     if (!$pager) {
         $pager = new KalturaFilterPager();
     }
     $pager->attachToCriteria($c);
     $list = MetadataPeer::doSelect($c);
     $response = new KalturaMetadataListResponse();
     $response->objects = KalturaMetadataArray::fromDbArray($list);
     $response->totalCount = $count;
     return $response;
 }
Exemplo n.º 17
0
 /**
  * @param string $captionAssetId
  * @throws KalturaAPIException
  * @return CaptionAsset
  */
 protected function validateForDownload($captionAssetId)
 {
     $captionAsset = null;
     if (!kCurrentContext::$ks) {
         $captionAsset = kCurrentContext::initPartnerByAssetId($captionAssetId);
         if (!$captionAsset || $captionAsset->getStatus() == asset::ASSET_STATUS_DELETED) {
             throw new KalturaAPIException(KalturaCaptionErrors::CAPTION_ASSET_ID_NOT_FOUND, $captionAssetId);
         }
         // enforce entitlement
         $this->setPartnerFilters(kCurrentContext::getCurrentPartnerId());
         kEntitlementUtils::initEntitlementEnforcement();
     } else {
         $captionAsset = assetPeer::retrieveById($captionAssetId);
     }
     if (!$captionAsset || !$captionAsset instanceof CaptionAsset) {
         throw new KalturaAPIException(KalturaCaptionErrors::CAPTION_ASSET_ID_NOT_FOUND, $captionAssetId);
     }
     if (kCurrentContext::$ks_object && kCurrentContext::$ks_object->verifyPrivileges(CaptionPlugin::KS_PRIVILEGE_CAPTION, $captionAsset->getEntryId())) {
         return $captionAsset;
     }
     $entry = entryPeer::retrieveByPK($captionAsset->getEntryId());
     if (!$entry) {
         //we will throw caption asset not found, as the user is not entitled, and should not know that the entry exists.
         throw new KalturaAPIException(KalturaCaptionErrors::CAPTION_ASSET_ID_NOT_FOUND, $captionAssetId);
     }
     $securyEntryHelper = new KSecureEntryHelper($entry, kCurrentContext::$ks, null, ContextType::DOWNLOAD);
     $securyEntryHelper->validateForDownload();
     return $captionAsset;
 }
Exemplo n.º 18
0
 /**
  * validate category fields
  * 1. category that inherit memebers cannot set values to inherited fields.
  * 2. validate the owner id exists as kuser
  * 
  * @param category $sourceObject
  */
 private function validateCategory(category $sourceObject = null)
 {
     if ($this->privacyContext != null && kEntitlementUtils::getEntitlementEnforcement()) {
         throw new KalturaAPIException(KalturaErrors::CANNOT_UPDATE_CATEGORY_PRIVACY_CONTEXT);
     }
     if (!$this->privacyContext && (!$sourceObject || !$sourceObject->getPrivacyContexts())) {
         $isInheritedPrivacyContext = true;
         if ($this->parentId != null) {
             $parentCategory = categoryPeer::retrieveByPK($this->parentId);
             if (!$parentCategory) {
                 throw new KalturaAPIException(KalturaErrors::CATEGORY_NOT_FOUND, $this->parentId);
             }
             if ($parentCategory->getPrivacyContexts() == '') {
                 $isInheritedPrivacyContext = false;
             }
         } else {
             $isInheritedPrivacyContext = false;
         }
         if (!$isInheritedPrivacyContext) {
             if ($this->appearInList != KalturaAppearInListType::PARTNER_ONLY && !$this->isNull('appearInList')) {
                 throw new KalturaAPIException(KalturaErrors::CANNOT_SET_APPEAR_IN_LIST_FIELD_WITH_NO_PRIVACY_CONTEXT);
             }
             if ($this->inheritanceType != KalturaInheritanceType::MANUAL && !$this->isNull('inheritanceType')) {
                 throw new KalturaAPIException(KalturaErrors::CANNOT_SET_INHERITANCE_TYPE_FIELD_WITH_NO_PRIVACY_CONTEXT);
             }
             if ($this->privacy != KalturaPrivacyType::ALL && !$this->isNull('privacy')) {
                 throw new KalturaAPIException(KalturaErrors::CANNOT_SET_PRIVACY_FIELD_WITH_NO_PRIVACY_CONTEXT);
             }
             if (!$this->isNull('owner')) {
                 throw new KalturaAPIException(KalturaErrors::CANNOT_SET_OWNER_FIELD_WITH_NO_PRIVACY_CONTEXT);
             }
             if ($this->userJoinPolicy != KalturaUserJoinPolicyType::NOT_ALLOWED && !$this->isNull('userJoinPolicy')) {
                 throw new KalturaAPIException(KalturaErrors::CANNOT_SET_USER_JOIN_POLICY_FIELD_WITH_NO_PRIVACY_CONTEXT);
             }
             if ($this->contributionPolicy != KalturaContributionPolicyType::ALL && !$this->isNull('contributionPolicy')) {
                 throw new KalturaAPIException(KalturaErrors::CANNOT_SET_CONTIRUBUTION_POLICY_FIELD_WITH_NO_PRIVACY_CONTEXT);
             }
             if ($this->defaultPermissionLevel != KalturaCategoryUserPermissionLevel::MEMBER && !$this->isNull('defaultPermissionLevel')) {
                 throw new KalturaAPIException(KalturaErrors::CANNOT_SET_DEFAULT_PERMISSION_LEVEL_FIELD_WITH_NO_PRIVACY_CONTEXT);
             }
         }
     }
     if ($this->inheritanceType != KalturaInheritanceType::MANUAL && $this->inheritanceType != null || $this->inheritanceType == null && $sourceObject && $sourceObject->getInheritanceType() != KalturaInheritanceType::MANUAL) {
         if ($this->owner != null) {
             if (!$sourceObject) {
                 throw new KalturaAPIException(KalturaErrors::CANNOT_SET_OWNER_WHEN_CATEGORY_INHERIT_MEMBERS);
             } elseif ($this->owner != $sourceObject->getKuserId()) {
                 throw new KalturaAPIException(KalturaErrors::CANNOT_SET_OWNER_WHEN_CATEGORY_INHERIT_MEMBERS);
             }
         }
         if ($this->userJoinPolicy != null) {
             if (!$sourceObject) {
                 throw new KalturaAPIException(KalturaErrors::CANNOT_SET_USER_JOIN_POLICY_WHEN_CATEGORY_INHERIT_MEMBERS);
             } elseif ($this->userJoinPolicy != $sourceObject->getUserJoinPolicy()) {
                 throw new KalturaAPIException(KalturaErrors::CANNOT_SET_USER_JOIN_POLICY_WHEN_CATEGORY_INHERIT_MEMBERS);
             }
         }
         if ($this->defaultPermissionLevel != null) {
             if (!$sourceObject) {
                 throw new KalturaAPIException(KalturaErrors::CANNOT_SET_DEFAULT_PERMISSION_LEVEL_WHEN_CATEGORY_INHERIT_MEMBERS);
             } elseif ($this->defaultPermissionLevel != $sourceObject->getDefaultPermissionLevel()) {
                 throw new KalturaAPIException(KalturaErrors::CANNOT_SET_DEFAULT_PERMISSION_LEVEL_WHEN_CATEGORY_INHERIT_MEMBERS);
             }
         }
     }
     if (!is_null($sourceObject)) {
         $partnerId = kCurrentContext::$partner_id ? kCurrentContext::$partner_id : kCurrentContext::$ks_partner_id;
         $partner = PartnerPeer::retrieveByPK($partnerId);
         if (!$partner || $partner->getFeaturesStatusByType(IndexObjectType::LOCK_CATEGORY)) {
             throw new KalturaAPIException(KalturaErrors::CATEGORIES_LOCKED);
         }
     }
     if ($this->owner && $this->owner != '' && !$this->owner instanceof KalturaNullField) {
         if (!preg_match(kuser::PUSER_ID_REGEXP, $this->owner)) {
             throw new KalturaAPIException(KalturaErrors::CANNOT_SET_OWNER_FIELD_WITH_USER_ID, $this->owner);
         }
         $partnerId = kCurrentContext::$partner_id ? kCurrentContext::$partner_id : kCurrentContext::$ks_partner_id;
         kuserPeer::createKuserForPartner($partnerId, $this->owner);
     }
 }
Exemplo n.º 19
0
 public function dispatch($service, $action, $params = array())
 {
     $start = microtime(true);
     // prevent impersonate to partner zero
     $p = isset($params["p"]) && $params["p"] ? $params["p"] : null;
     if (!$p) {
         $p = isset($params["partnerId"]) && $params["partnerId"] ? $params["partnerId"] : null;
     }
     $GLOBALS["partnerId"] = $p;
     // set for logger
     $userId = "";
     $ksStr = isset($params["ks"]) ? $params["ks"] : null;
     if (!$service) {
         throw new KalturaAPIException(KalturaErrors::SERVICE_NOT_SPECIFIED);
     }
     //strtolower on service - map is indexed according to lower-case service IDs
     $service = strtolower($service);
     $serviceActionItem = KalturaServicesMap::retrieveServiceActionItem($service, $action);
     $action = strtolower($action);
     if (!isset($serviceActionItem->actionMap[$action])) {
         KalturaLog::crit("Action does not exist!");
         throw new KalturaAPIException(KalturaErrors::ACTION_DOES_NOT_EXISTS, $action, $service);
     }
     try {
         $actionReflector = new KalturaActionReflector($service, $action, $serviceActionItem->actionMap[$action]);
     } catch (Exception $e) {
         throw new Exception("Could not create action reflector for service [{$service}], action [{$action}]. Received error: " . $e->getMessage());
     }
     $actionParams = $actionReflector->getActionParams();
     $actionInfo = $actionReflector->getActionInfo();
     // services.ct - check if partner is allowed to access service ...
     kCurrentContext::$host = isset($_SERVER["HOSTNAME"]) ? $_SERVER["HOSTNAME"] : gethostname();
     kCurrentContext::$user_ip = requestUtils::getRemoteAddress();
     kCurrentContext::$ps_vesion = "ps3";
     kCurrentContext::$service = $serviceActionItem->serviceInfo->serviceName;
     kCurrentContext::$action = $action;
     kCurrentContext::$client_lang = isset($params['clientTag']) ? $params['clientTag'] : null;
     kCurrentContext::initKsPartnerUser($ksStr, $p, $userId);
     // validate it's ok to access this service
     $deserializer = new KalturaRequestDeserializer($params);
     $this->arguments = $deserializer->buildActionArguments($actionParams);
     KalturaLog::debug("Dispatching service [" . $service . "], action [" . $action . "], reqIndex [" . kCurrentContext::$multiRequest_index . "] with params " . print_r($this->arguments, true));
     $responseProfile = $deserializer->getResponseProfile();
     if ($responseProfile) {
         KalturaLog::debug("Response profile: " . print_r($responseProfile, true));
     }
     kPermissionManager::init(kConf::get('enable_cache'));
     kEntitlementUtils::initEntitlementEnforcement();
     $disableTags = $actionInfo->disableTags;
     if ($disableTags && is_array($disableTags) && count($disableTags)) {
         foreach ($disableTags as $disableTag) {
             KalturaCriterion::disableTag($disableTag);
         }
     }
     if ($actionInfo->validateUserObjectClass && $actionInfo->validateUserIdParamName && isset($actionParams[$actionInfo->validateUserIdParamName])) {
         //			// TODO maybe if missing should throw something, maybe a bone?
         //			if(!isset($actionParams[$actionInfo->validateUserIdParamName]))
         //				throw new KalturaAPIException(KalturaErrors::MISSING_MANDATORY_PARAMETER, $actionInfo->validateUserIdParamName);
         KalturaLog::debug("validateUserIdParamName: " . $actionInfo->validateUserIdParamName);
         $objectId = $params[$actionInfo->validateUserIdParamName];
         $this->validateUser($actionInfo->validateUserObjectClass, $objectId, $actionInfo->validateUserPrivilege, $actionInfo->validateOptions);
     }
     // initialize the service before invoking the action on it
     // action reflector will init the service to maintain the pluginable action transparency
     $actionReflector->initService($responseProfile);
     $invokeStart = microtime(true);
     KalturaLog::debug("Invoke start");
     try {
         $res = $actionReflector->invoke($this->arguments);
     } catch (KalturaAPIException $e) {
         if ($actionInfo->returnType != 'file') {
             throw $e;
         }
         KalturaResponseCacher::adjustApiCacheForException($e);
         $res = new kRendererDieError($e->getCode(), $e->getMessage());
     }
     kEventsManager::flushEvents();
     KalturaLog::debug("Invoke took - " . (microtime(true) - $invokeStart) . " seconds");
     KalturaLog::debug("Dispatch took - " . (microtime(true) - $start) . " seconds, memory: " . memory_get_peak_usage(true));
     return $res;
 }
Exemplo n.º 20
0
 public function execute()
 {
     requestUtils::handleConditionalGet();
     $entry_id = $this->getRequestParameter("entry_id");
     $ks_str = $this->getRequestParameter("ks");
     $base64_referrer = $this->getRequestParameter("referrer");
     $referrer = base64_decode($base64_referrer);
     if (!is_string($referrer)) {
         // base64_decode can return binary data
         $referrer = "";
     }
     $clip_from = $this->getRequestParameter("clip_from", 0);
     // milliseconds
     $clip_to = $this->getRequestParameter("clip_to", 2147483647);
     // milliseconds
     if ($clip_to == 0) {
         $clip_to = 2147483647;
     }
     $request = $_SERVER["REQUEST_URI"];
     // remove dynamic fields from the url so we'll request a single url from the cdn
     $request = str_replace("/referrer/{$base64_referrer}", "", $request);
     $request = str_replace("/ks/{$ks_str}", "", $request);
     $entry = null;
     if ($ks_str) {
         try {
             kCurrentContext::initKsPartnerUser($ks_str);
         } catch (Exception $ex) {
             KExternalErrors::dieError(KExternalErrors::INVALID_KS);
         }
     } else {
         $entry = kCurrentContext::initPartnerByEntryId($entry_id);
         if (!$entry) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     kEntitlementUtils::initEntitlementEnforcement();
     // workaround the filter which hides all the deleted entries -
     // now that deleted entries are part of xmls (they simply point to the 'deleted' templates), we should allow them here
     if (!$entry) {
         $entry = entryPeer::retrieveByPKNoFilter($entry_id);
     } else {
         if (!kEntitlementUtils::isEntryEntitled($entry)) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     if (!$entry) {
         KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
     }
     KalturaMonitorClient::initApiMonitor(false, 'keditorservices.flvclipper', $entry->getPartnerId());
     myPartnerUtils::blockInactivePartner($entry->getPartnerId());
     if (PermissionPeer::isValidForPartner(PermissionName::FEATURE_BLOCK_FLVCLIPPER_ACTION, $entry->getPartnerId())) {
         KExternalErrors::dieError(KExternalErrors::ACTION_BLOCKED);
     }
     // set the memory size to be able to serve big files in a single chunk
     ini_set("memory_limit", "64M");
     // set the execution time to be able to serve big files in a single chunk
     ini_set("max_execution_time", 240);
     if ($entry->getType() == entryType::MIX && $entry->getStatus() == entryStatus::DELETED) {
         // because the fiter was turned off - a manual check for deleted entries must be done.
         KExternalErrors::dieGracefully();
     } else {
         if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_IMAGE) {
             $version = $this->getRequestParameter("version", null);
             $width = $this->getRequestParameter("width", -1);
             $height = $this->getRequestParameter("height", -1);
             $crop_provider = $this->getRequestParameter("crop_provider", null);
             $bgcolor = $this->getRequestParameter("bgcolor", "ffffff");
             $type = $this->getRequestParameter("type", 1);
             $quality = $this->getRequestParameter("quality", 0);
             $src_x = $this->getRequestParameter("src_x", 0);
             $src_y = $this->getRequestParameter("src_y", 0);
             $src_w = $this->getRequestParameter("src_w", 0);
             $src_h = $this->getRequestParameter("src_h", 0);
             $vid_sec = $this->getRequestParameter("vid_sec", -1);
             $vid_slice = $this->getRequestParameter("vid_slice", -1);
             $vid_slices = $this->getRequestParameter("vid_slices", -1);
             if ($width == -1 && $height == -1) {
                 $width = 640;
                 $height = 480;
             } else {
                 if ($width == -1) {
                     // if only either width or height is missing reset them to zero, and convertImage will handle them
                     $width = 0;
                 } else {
                     if ($height == -1) {
                         $height = 0;
                     }
                 }
             }
             $tempThumbPath = myEntryUtils::resizeEntryImage($entry, $version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices);
             kFileUtils::dumpFile($tempThumbPath, null, strpos($tempThumbPath, "_NOCACHE_") === false ? null : 0);
         }
     }
     $audio_only = $this->getRequestParameter("audio_only");
     // milliseconds
     $flavor = $this->getRequestParameter("flavor", 1);
     //
     $flavor_param_id = $this->getRequestParameter("flavor_param_id", null);
     //
     $streamer = $this->getRequestParameter("streamer");
     //
     if (substr($streamer, 0, 4) == "rtmp") {
         // the fms may add .mp4 to the end of the url
         $streamer = "rtmp";
     }
     // grab seek_from_bytes parameter and normalize url
     $seek_from_bytes = $this->getRequestParameter("seek_from_bytes", -1);
     $request = str_replace("/seek_from_bytes/{$seek_from_bytes}", "", $request);
     if ($seek_from_bytes <= 0) {
         $seek_from_bytes = -1;
     }
     // grab seek_from parameter and normalize url
     $seek_from = $this->getRequestParameter("seek_from", -1);
     $request = str_replace("/seek_from/{$seek_from}", "", $request);
     if ($seek_from <= 0) {
         $seek_from = -1;
     }
     $this->dump_from_byte = 0;
     // reset accurate seek from timestamp
     $seek_from_timestamp = -1;
     // backward compatibility
     if ($flavor === "0") {
         // for edit version
         $flavor = "edit";
     }
     if ($flavor === "1" || $flavor === 1) {
         // for play version
         $flavor = null;
     }
     // when flavor is null, we will get a default flavor
     if ($flavor == "edit") {
         $flavorAsset = assetPeer::retrieveBestEditByEntryId($entry->getId());
     } elseif (!is_null($flavor)) {
         $flavorAsset = assetPeer::retrieveById($flavor);
         // when specific asset was request, we don't validate its tags
         if ($flavorAsset && ($flavorAsset->getEntryId() != $entry->getId() || $flavorAsset->getStatus() != flavorAsset::FLAVOR_ASSET_STATUS_READY)) {
             $flavorAsset = null;
         }
         // we will throw an error later
     } elseif (is_null($flavor) && !is_null($flavor_param_id)) {
         $flavorAsset = assetPeer::retrieveByEntryIdAndParams($entry->getId(), $flavor_param_id);
         if ($flavorAsset && $flavorAsset->getStatus() != flavorAsset::FLAVOR_ASSET_STATUS_READY) {
             $flavorAsset = null;
         }
         // we will throw an error later
     } else {
         if ($entry->getSource() == entry::ENTRY_MEDIA_SOURCE_WEBCAM) {
             $flavorAsset = assetPeer::retrieveOriginalByEntryId($entry->getId());
         } else {
             $flavorAsset = assetPeer::retrieveBestPlayByEntryId($entry->getId());
         }
         if (!$flavorAsset) {
             $flavorAssets = assetPeer::retrieveReadyFlavorsByEntryIdAndTag($entry->getId(), flavorParams::TAG_WEB);
             if (count($flavorAssets) > 0) {
                 $flavorAsset = $flavorAssets[0];
             }
         }
     }
     if (is_null($flavorAsset)) {
         KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
     }
     $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     if (kFileSyncUtils::file_exists($syncKey, false)) {
         $path = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey);
     } else {
         list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false);
         if (is_null($fileSync)) {
             KalturaLog::log("Error - no FileSync for flavor [" . $flavorAsset->getId() . "]");
             KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND);
         }
         if ($fileSync->getFileType() == FileSync::FILE_SYNC_FILE_TYPE_URL) {
             $urlManager = DeliveryProfilePeer::getRemoteDeliveryByStorageId(DeliveryProfileDynamicAttributes::init($fileSync->getDc(), $flavorAsset->getEntryId()), null, $flavorAsset);
             if (!$urlManager) {
                 KalturaLog::log("Error - failed to find an HTTP delivery for storage profile [" . $fileSync->getDc() . "]");
                 KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND);
             }
             $url = rtrim($urlManager->getUrl(), '/') . '/' . ltrim($urlManager->getFileSyncUrl($fileSync), '/');
             header('location: ' . $url);
             die;
         }
         $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync);
         $this->redirect($remoteUrl);
     }
     $flv_wrapper = new myFlvHandler($path);
     $isFlv = $flv_wrapper->isFlv();
     // scrubbing is not allowed within mp4 files
     if (!$isFlv) {
         $seek_from = $seek_from_bytes = -1;
     }
     if ($seek_from !== -1 && $seek_from !== 0) {
         if ($audio_only === '0') {
             // audio_only was explicitly set to 0 - don't attempt to make further automatic investigations
         } elseif ($flv_wrapper->getFirstVideoTimestamp() < 0) {
             $audio_only = true;
         }
         list($bytes, $duration, $first_tag_byte, $to_byte) = $flv_wrapper->clip(0, -1, $audio_only);
         list($bytes, $duration, $from_byte, $to_byte, $seek_from_timestamp) = $flv_wrapper->clip($seek_from, -1, $audio_only);
         $seek_from_bytes = myFlvHandler::FLV_HEADER_SIZE + $flv_wrapper->getMetadataSize($audio_only) + $from_byte - $first_tag_byte;
     }
     // the direct path without a cdn is "http://s3kaltura.s3.amazonaws.com".$entry->getDataPath();
     $extStorageUrl = $entry->getExtStorageUrl();
     if ($extStorageUrl && substr_count($extStorageUrl, 's3kaltura')) {
         // if for some reason we didnt set our accurate $seek_from_timestamp reset it to the requested seek_from
         if ($seek_from_timestamp == -1) {
             $seek_from_timestamp = $seek_from;
         }
         $request_host = parse_url($extStorageUrl, PHP_URL_HOST);
         $akamai_url = str_replace($request_host, "cdns3akmi.kaltura.com", $extStorageUrl);
         $akamai_url .= $seek_from_bytes == -1 ? "" : "?aktimeoffset=" . floor($seek_from_timestamp / 1000);
         header("Location: {$akamai_url}");
         KExternalErrors::dieGracefully();
     } elseif ($extStorageUrl) {
         // if for some reason we didnt set our accurate $seek_from_timestamp reset it to the requested seek_from
         if ($seek_from_timestamp == -1) {
             $seek_from_timestamp = $seek_from;
         }
         $extStorageUrl .= $seek_from_bytes == -1 ? "" : "?aktimeoffset=" . floor($seek_from_timestamp / 1000);
         header("Location: {$extStorageUrl}");
         KExternalErrors::dieGracefully();
     }
     // use headers to detect cdn
     $cdn_name = "";
     $via_header = @$_SERVER["HTTP_VIA"];
     if (strpos($via_header, "llnw.net") !== false) {
         $cdn_name = "limelight";
     } else {
         if (strpos($via_header, "akamai") !== false) {
             $cdn_name = "akamai";
         } else {
             if (strpos($via_header, "Level3") !== false) {
                 $cdn_name = "level3";
             }
         }
     }
     // setting file extension - first trying frrom flavor asset
     $ext = $flavorAsset->getFileExt();
     // if failed, set extension according to file type (isFlv)
     if (!$ext) {
         $ext = $isFlv ? "flv" : "mp4";
     }
     $flv_extension = $streamer == "rtmp" ? "?" : "/a.{$ext}?novar=0";
     // dont check for rtmp / and for an already redirect url
     if ($streamer != "rtmp" && strpos($request, $flv_extension) === false) {
         // check security using ks
         $securyEntryHelper = new KSecureEntryHelper($entry, $ks_str, $referrer, ContextType::PLAY);
         if ($securyEntryHelper->shouldPreview()) {
             $this->checkForPreview($securyEntryHelper, $clip_to);
         } else {
             $securyEntryHelper->validateForPlay($entry, $ks_str);
         }
     } else {
         // if needs security check using cdn authentication mechanism
         // for now assume this is a cdn request and don't check for security
     }
     // use limelight mediavault if either security policy requires it or if we're trying to seek within the video
     if ($entry->getSecurityPolicy() || $seek_from_bytes !== -1) {
         // we have three options:
         // arrived through limelight mediavault url - the url is secured
         // arrived directly through limelight (not secured through mediavault) - enforce ks and redirect to mediavault url
         // didnt use limelight - enforce ks
         // the cdns are configured to authenticate request for /s/....
         // check if we're already in a redirected secure link using the "/s/" prefix
         $secure_request = substr($request, 0, 3) == "/s/";
         if ($secure_request && ($cdn_name == "limelight" || $cdn_name == "level3")) {
             // request was validated by cdn let it through
         } else {
             // extract ks
             $ks_str = $this->getRequestParameter("ks", "");
             if ($entry->getSecurityPolicy()) {
                 if (!$ks_str) {
                     $this->logMessage("flvclipper - no KS");
                     KExternalErrors::dieGracefully();
                 }
                 $ks = kSessionUtils::crackKs($ks_str);
                 if (!$ks) {
                     $this->logMessage("flvclipper - invalid ks [{$ks_str}]");
                     KExternalErrors::dieGracefully();
                 }
                 $matched_privs = $ks->verifyPrivileges("sview", $entry_id);
                 $this->logMessage("flvclipper - verifyPrivileges name [sview], priv [{$entry_id}] [{$matched_privs}]");
                 if (!$matched_privs) {
                     $this->logMessage("flvclipper - doesnt not match required privlieges [{$ks_str}]");
                     KExternalErrors::dieGracefully();
                 }
             }
             if ($cdn_name == "limelight") {
                 $ll_url = requestUtils::getCdnHost() . "/s{$request}" . $flv_extension;
                 $secret = kConf::get("limelight_madiavault_password");
                 $expire = "&e=" . (time() + 120);
                 $ll_url .= $expire;
                 $fs = $seek_from_bytes == -1 ? "" : "&fs={$seek_from_bytes}";
                 $ll_url .= "&h=" . md5("{$secret}{$ll_url}") . $fs;
                 //header("Location: $ll_url");
                 $this->redirect($ll_url);
             } else {
                 if ($cdn_name == "level3") {
                     $level3_url = $request . $flv_extension;
                     if ($entry->getSecurityPolicy()) {
                         $level3_url = "/s{$level3_url}";
                         // set expire time in GMT hence the date("Z") offset
                         $expire = "&nva=" . strftime("%Y%m%d%H%M%S", time() - date("Z") + 30);
                         $level3_url .= $expire;
                         $secret = kConf::get("level3_authentication_key");
                         $hash = "0" . substr(self::hmac('sha1', $secret, $level3_url), 0, 20);
                         $level3_url .= "&h={$hash}";
                     }
                     $level3_url .= $seek_from_bytes == -1 ? "" : "&start={$seek_from_bytes}";
                     header("Location: {$level3_url}");
                     KExternalErrors::dieGracefully();
                 } else {
                     if ($cdn_name == "akamai") {
                         $akamai_url = $request . $flv_extension;
                         // if for some reason we didnt set our accurate $seek_from_timestamp reset it to the requested seek_from
                         if ($seek_from_timestamp == -1) {
                             $seek_from_timestamp = $seek_from;
                         }
                         $akamai_url .= $seek_from_bytes == -1 ? "" : "&aktimeoffset=" . floor($seek_from_timestamp / 1000);
                         header("Location: {$akamai_url}");
                         KExternalErrors::dieGracefully();
                     }
                 }
             }
             // a seek request without a supporting cdn - we need to send the answer from our server
             if ($seek_from_bytes !== -1 && $via_header === null) {
                 $this->dump_from_byte = $seek_from_bytes;
             }
         }
     }
     // always add the file suffix to the request (needed for scrubbing by some cdns,
     // and also breaks without extension on some corporate antivirus).
     // we add the the novar paramter since a leaving a trailing "?" will be trimmed
     // and then the /seek_from request will result in another url which level3
     // will try to refetch from the origin
     // note that for streamer we dont add the file extension
     if ($streamer != "rtmp" && strpos($request, $flv_extension) === false) {
         // a seek request without a supporting cdn - we need to send the answer from our server
         if ($seek_from_bytes !== -1 && $via_header === null) {
             $request .= "/seek_from_bytes/{$seek_from_bytes}";
         }
         requestUtils::sendCdnHeaders("flv", 0);
         header("Location: {$request}" . $flv_extension);
         KExternalErrors::dieGracefully();
     }
     // mp4
     if (!$isFlv) {
         $limit_file_size = 0;
         if ($clip_to != 2147483647) {
             $mediaInfo = mediaInfoPeer::retrieveByFlavorAssetId($flavorAsset->getId());
             if ($mediaInfo && ($mediaInfo->getVideoDuration() || $mediaInfo->getAudioDuration() || $mediaInfo->getContainerDuration())) {
                 $duration = $mediaInfo->getVideoDuration() ? $mediaInfo->getVideoDuration() : ($mediaInfo->getAudioDuration() ? $mediaInfo->getAudioDuration() : $mediaInfo->getContainerDuration());
                 $limit_file_size = floor(@kFile::fileSize($path) * ($clip_to / $duration) * 1.2);
             }
         }
         KalturaLog::info("serving file [{$path}] entry id [{$entry_id}] limit file size [{$limit_file_size}] clip_to [{$clip_to}]");
         kFileUtils::dumpFile($path, null, null, $limit_file_size);
     }
     $this->logMessage("flvclipperAction: serving file [{$path}] entry_id [{$entry_id}] clip_from [{$clip_from}] clip_to [{$clip_to}]", "warning");
     if ($audio_only === '0') {
         // audio_only was explicitly set to 0 - don't attempt to make further automatic investigations
     } elseif ($flv_wrapper->getFirstVideoTimestamp() < 0) {
         $audio_only = true;
     }
     //$start = microtime(true);
     list($bytes, $duration, $from_byte, $to_byte, $from_ts, $cuepoint_pos) = myFlvStaticHandler::clip($path, $clip_from, $clip_to, $audio_only);
     $metadata_size = $flv_wrapper->getMetadataSize($audio_only);
     $this->from_byte = $from_byte;
     $this->to_byte = $to_byte;
     //$end1 = microtime(true);
     //$this->logMessage( "flvclipperAction: serving file [$path] entry_id [$entry_id] bytes [$bytes] duration [$duration] [$from_byte]->[$to_byte]" , "warning" );
     //$this->logMessage( "flvclipperAction: serving file [$path] t1 [" . ( $end1-$start) . "]");
     $data_offset = $metadata_size + myFlvHandler::getHeaderSize();
     // if we're returning a partial file adjust the total size:
     // substract the metadata and bytes which are not delivered
     if ($this->dump_from_byte >= $data_offset && !$audio_only) {
         $bytes -= $metadata_size + max(0, $this->dump_from_byte - $data_offset);
     }
     $this->total_length = $data_offset + $bytes;
     //echo " $bytes , $duration ,$from_byte , $to_byte, $cuepoint_pos\n"; die;
     $this->cuepoint_time = 0;
     $this->cuepoint_pos = 0;
     if ($streamer == "chunked" && $clip_to != 2147483647) {
         $this->cuepoint_time = $clip_to - 1;
         $this->cuepoint_pos = $cuepoint_pos;
         $this->total_length += myFlvHandler::CUEPOINT_TAG_SIZE;
     }
     //$this->logMessage( "flvclipperAction: serving file [$path] entry_id [$entry_id] bytes with header & md [" . $this->total_length . "] bytes [$bytes] duration [$duration] [$from_byte]->[$to_byte]" , "warning" );
     $this->flv_wrapper = $flv_wrapper;
     $this->audio_only = $audio_only;
     try {
         Propel::close();
     } catch (Exception $e) {
         $this->logMessage("flvclipperAction: error closing db {$e}");
     }
     KExternalErrors::terminateDispatch();
     return sfView::SUCCESS;
 }
Exemplo n.º 21
0
 /**
  * Index metadata by id, will also index the related object
  *
  * @action index
  * @param string $id
  * @param bool $shouldUpdate
  * @return int
  */
 function indexAction($id, $shouldUpdate)
 {
     if (kEntitlementUtils::getEntitlementEnforcement()) {
         throw new KalturaAPIException(KalturaErrors::CANNOT_INDEX_OBJECT_WHEN_ENTITLEMENT_IS_ENABLE);
     }
     $dbMetadata = MetadataPeer::retrieveByPK($id);
     if (!$dbMetadata) {
         throw new KalturaAPIException(MetadataErrors::METADATA_NOT_FOUND, $id);
     }
     $dbMetadata->indexToSearchIndex();
     $relatedObject = kMetadataManager::getObjectFromPeer($dbMetadata);
     if ($relatedObject && $relatedObject instanceof IIndexable) {
         $relatedObject->indexToSearchIndex();
     }
     return $dbMetadata->getId();
 }
Exemplo n.º 22
0
 /**
  * Override in order to filter objects returned from doSelect.
  *
  * @param      array $selectResults The array of objects to filter.
  * @param	   Criteria $criteria
  */
 public static function filterSelectResults(&$selectResults, Criteria $criteria)
 {
     if (empty($selectResults)) {
         return;
     }
     $partnerId = kCurrentContext::getCurrentPartnerId();
     $partner = PartnerPeer::retrieveByPK($partnerId);
     if ($partner && $partner->getShouldApplyAccessControlOnEntryMetadata() && !kCurrentContext::$is_admin_session) {
         if (is_null(self::$accessControlScope)) {
             self::$accessControlScope = new accessControlScope();
             self::$accessControlScope->setContexts(array(ContextType::METADATA));
         }
         $selectResults = array_filter($selectResults, array('entryPeer', 'filterByAccessControl'));
         if ($criteria instanceof KalturaCriteria) {
             $criteria->setRecordsCount(count($selectResults));
         }
     }
     $removedRecordsCount = 0;
     if (!kEntitlementUtils::getEntitlementEnforcement() && !is_null(kCurrentContext::$ks) || !self::$filerResults || !kEntitlementUtils::getInitialized()) {
         // if initEntitlement hasn't run - skip filters.
         return parent::filterSelectResults($selectResults, $criteria);
     }
     if (is_null(kCurrentContext::$ks) && count($selectResults)) {
         $entry = $selectResults[0];
         $partner = $entry->getPartner();
         if (!$partner) {
             throw new kCoreException('entry partner not found');
         }
         if (!$partner->getDefaultEntitlementEnforcement() || !PermissionPeer::isValidForPartner(PermissionName::FEATURE_ENTITLEMENT, $partner->getId())) {
             return parent::filterSelectResults($selectResults, $criteria);
         }
     }
     foreach ($selectResults as $key => $entry) {
         if (!kEntitlementUtils::isEntryEntitled($entry)) {
             unset($selectResults[$key]);
             $removedRecordsCount++;
         }
     }
     if ($criteria instanceof KalturaCriteria) {
         $recordsCount = $criteria->getRecordsCount();
         $criteria->setRecordsCount($recordsCount - $removedRecordsCount);
     }
     self::$filerResults = false;
     parent::filterSelectResults($selectResults, $criteria);
 }
 public static function syncEntriesCategories(entry $entry, $isCategoriesModified)
 {
     self::$skipEntrySave = true;
     if ($entry->getNewCategories() != null && $entry->getNewCategories() !== "") {
         $newCats = explode(entry::ENTRY_CATEGORY_SEPARATOR, $entry->getNewCategories());
     } else {
         $newCats = array();
     }
     if (!$isCategoriesModified) {
         if ($entry->getNewCategoriesIds() != null && $entry->getNewCategoriesIds() !== "") {
             $newCatsIds = explode(entry::ENTRY_CATEGORY_SEPARATOR, $entry->getNewCategoriesIds());
         } else {
             $newCatsIds = array();
         }
         KalturaCriterion::disableTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY);
         $dbCategories = categoryPeer::retrieveByPKs($newCatsIds);
         KalturaCriterion::restoreTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY);
         foreach ($dbCategories as $dbCategory) {
             //skip categoy with privacy contexts.
             if ($dbCategory->getPrivacyContexts() != null && $dbCategory->getPrivacyContexts() != '') {
                 continue;
             }
             $newCats[] = $dbCategory->getFullName();
         }
     }
     $newCats = array_unique($newCats);
     $allIds = array();
     $allCats = array();
     $allIdsWithParents = array();
     $addedCats = array();
     $removedCats = array();
     $remainingCats = array();
     $oldCats = array();
     $oldCatsIds = array();
     $dbOldCategoriesEntry = categoryEntryPeer::selectByEntryId($entry->getId());
     foreach ($dbOldCategoriesEntry as $dbOldCategoryEntry) {
         $oldCatsIds[] = $dbOldCategoryEntry->getCategoryId();
     }
     $oldCategoris = categoryPeer::retrieveByPKsNoFilter($oldCatsIds);
     foreach ($oldCategoris as $category) {
         if ($category->getPrivacyContexts() != '' && $category->getPrivacyContexts() != null) {
             continue;
         }
         $oldCats[] = $category->getFullName();
     }
     foreach ($oldCats as $cat) {
         if (array_search($cat, $newCats) === false) {
             $removedCats[] = $cat;
         }
     }
     foreach ($newCats as $cat) {
         if (array_search($cat, $oldCats) === false) {
             $addedCats[] = $cat;
         } else {
             $remainingCats[] = $cat;
         }
     }
     foreach ($remainingCats as $cat) {
         KalturaCriterion::disableTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY);
         $category = categoryPeer::getByFullNameExactMatch($cat);
         KalturaCriterion::restoreTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY);
         if ($category) {
             if ($category->getPrivacyContext() == '' || $category->getPrivacyContext() == null) {
                 $allCats[] = $category->getFullName();
                 $allIds[] = $category->getId();
             }
             $allIdsWithParents[] = $category->getId();
             $allIdsWithParents = array_merge($allIdsWithParents, $category->getAllParentsIds());
         }
     }
     $alreadyAddedCatIds = $allIdsWithParents;
     foreach ($addedCats as $cat) {
         $category = categoryPeer::getByFullNameExactMatch($cat);
         if (!$category) {
             KalturaCriterion::disableTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY);
             $unentitedCategory = categoryPeer::getByFullNameExactMatch($cat);
             KalturaCriterion::restoreTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY);
             if (!$unentitedCategory) {
                 $category = category::createByPartnerAndFullName($entry->getPartnerId(), $cat);
                 //it is possible to add on an entry a few new categories on the same new parent -
                 //and we need to sync sphinx once we add so the category will not be duplicated
                 kEventsManager::flushEvents();
             }
         } else {
             $categoryKuser = categoryKuserPeer::retrieveByCategoryIdAndActiveKuserId($category->getId(), kCurrentContext::$ks_kuser_id);
             if (kEntitlementUtils::getEntitlementEnforcement() && $category->getContributionPolicy() != ContributionPolicyType::ALL && (!$categoryKuser || $categoryKuser->getPermissionLevel() == CategoryKuserPermissionLevel::MEMBER)) {
                 //user is not entitled to add entry to this category
                 $category = null;
             }
         }
         if (!$category) {
             continue;
         }
         //when use caetgoryEntry->add categoryEntry object was alreay created - and no need to create it.
         //when using baseEntry->categories = 'my category' will need to add the new category.
         $categoryEntry = categoryEntryPeer::retrieveByCategoryIdAndEntryId($category->getId(), $entry->getId());
         if (!$categoryEntry) {
             $categoryEntry = new categoryEntry();
             $categoryEntry->setEntryId($entry->getId());
             $categoryEntry->setCategoryId($category->getId());
             $categoryEntry->setEntryCategoriesAddedIds($alreadyAddedCatIds);
             $categoryEntry->setPartnerId($entry->getPartnerId());
             $categoryEntry->setStatus(CategoryEntryStatus::ACTIVE);
             $categoryEntry->save();
         }
         if ($category->getPrivacyContext() == '' || $category->getPrivacyContext() == null) {
             // only categories with no context should be set on entry->categories and entry->categoriesIds
             $allCats[] = $category->getFullName();
             $allIds[] = $category->getId();
         }
         $alreadyAddedCatIds[] = $category->getId();
         $alreadyAddedCatIds = array_merge($alreadyAddedCatIds, $category->getAllParentsIds());
     }
     $alreadyRemovedCatIds = $allIdsWithParents;
     foreach ($removedCats as $cat) {
         $category = categoryPeer::getByFullNameExactMatch($cat);
         if ($category) {
             $categoryEntryToDelete = categoryEntryPeer::retrieveByCategoryIdAndEntryId($category->getId(), $entry->getId());
             if ($categoryEntryToDelete) {
                 $categoryKuser = categoryKuserPeer::retrieveByCategoryIdAndActiveKuserId($categoryEntryToDelete->getCategoryId(), kCurrentContext::$ks_kuser_id);
                 if ($category->getPrivacyContexts() && (!$categoryKuser || $categoryKuser->getPermissionLevel() == CategoryKuserPermissionLevel::MEMBER)) {
                     //not entiteld to delete - should be set back on the entry.
                     $allCats[] = $category->getFullName();
                     $allIds[] = $category->getId();
                 } else {
                     $categoryEntryToDelete->setEntryCategoriesRemovedIds($alreadyRemovedCatIds);
                     $categoryEntryToDelete->setStatus(CategoryEntryStatus::DELETED);
                     $categoryEntryToDelete->save();
                 }
             }
             $alreadyRemovedCatIds[] = $category->getId();
             $alreadyRemovedCatIds = array_merge($alreadyRemovedCatIds, $category->getAllParentsIds());
         } else {
             //category was not found - it could be that user is not entitled to remove it
             KalturaCriterion::disableTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY);
             $category = categoryPeer::getByFullNameExactMatch($cat);
             KalturaCriterion::restoreTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY);
             if ($category) {
                 $allCats[] = $category->getFullName();
                 $allIds[] = $category->getId();
             }
         }
     }
     self::$skipEntrySave = false;
     $entry->parentSetCategories(implode(",", $allCats));
     $entry->parentSetCategoriesIds(implode(',', $allIds));
 }
Exemplo n.º 24
0
 /**
  * activate CategoryEntry when it is pending moderation
  * 
  * @action reject
  * @param string $entryId
  * @param int $categoryId
  * @throws KalturaErrors::INVALID_ENTRY_ID
  * @throws KalturaErrors::CATEGORY_NOT_FOUND
  * @throws KalturaErrors::ENTRY_IS_NOT_ASSIGNED_TO_CATEGORY
  * @throws KalturaErrors::CANNOT_ACTIVATE_CATEGORY_ENTRY
  */
 function rejectAction($entryId, $categoryId)
 {
     $entry = entryPeer::retrieveByPK($entryId);
     if (!$entry) {
         throw new KalturaAPIException(KalturaErrors::INVALID_ENTRY_ID, $entryId);
     }
     $category = categoryPeer::retrieveByPK($categoryId);
     if (!$category) {
         throw new KalturaAPIException(KalturaErrors::CATEGORY_NOT_FOUND, $categoryId);
     }
     $dbCategoryEntry = categoryEntryPeer::retrieveByCategoryIdAndEntryId($categoryId, $entryId);
     if (!$dbCategoryEntry) {
         throw new KalturaAPIException(KalturaErrors::ENTRY_IS_NOT_ASSIGNED_TO_CATEGORY);
     }
     //validate user is entiteld to reject entry from category
     if (kEntitlementUtils::getEntitlementEnforcement()) {
         $categoryKuser = categoryKuserPeer::retrievePermittedKuserInCategory($categoryId, kCurrentContext::getCurrentKsKuserId());
         if (!$categoryKuser || $categoryKuser->getPermissionLevel() != CategoryKuserPermissionLevel::MANAGER && $categoryKuser->getPermissionLevel() != CategoryKuserPermissionLevel::MODERATOR) {
             throw new KalturaAPIException(KalturaErrors::CANNOT_REJECT_CATEGORY_ENTRY);
         }
     }
     if ($dbCategoryEntry->getStatus() != CategoryEntryStatus::PENDING) {
         throw new KalturaAPIException(KalturaErrors::CANNOT_REJECT_CATEGORY_ENTRY_SINCE_IT_IS_NOT_PENDING);
     }
     $dbCategoryEntry->setStatus(CategoryEntryStatus::REJECTED);
     $dbCategoryEntry->save();
 }
 /**
  * Serves attachment by its id
  *  
  * @action serve
  * @param string $attachmentAssetId
  * @return file
  *  
  * @throws KalturaAttachmentErrors::ATTACHMENT_ASSET_ID_NOT_FOUND
  */
 public function serveAction($attachmentAssetId)
 {
     $attachmentAsset = null;
     if (!kCurrentContext::$ks) {
         $attachmentAsset = kCurrentContext::initPartnerByAssetId($attachmentAssetId);
         if (!$attachmentAsset || $attachmentAsset->getStatus() == asset::ASSET_STATUS_DELETED) {
             throw new KalturaAPIException(KalturaAttachmentErrors::ATTACHMENT_ASSET_ID_NOT_FOUND, $attachmentAssetId);
         }
         // enforce entitlement
         kEntitlementUtils::initEntitlementEnforcement();
     } else {
         $attachmentAsset = assetPeer::retrieveById($attachmentAssetId);
     }
     if (!$attachmentAsset || !$attachmentAsset instanceof AttachmentAsset) {
         throw new KalturaAPIException(KalturaAttachmentErrors::ATTACHMENT_ASSET_ID_NOT_FOUND, $attachmentAssetId);
     }
     $entry = entryPeer::retrieveByPK($attachmentAsset->getEntryId());
     if (!$entry) {
         //we will throw attachment asset not found, as the user is not entitled, and should not know that the entry exists.
         throw new KalturaAPIException(KalturaAttachmentErrors::ATTACHMENT_ASSET_ID_NOT_FOUND, $attachmentAssetId);
     }
     $securyEntryHelper = new KSecureEntryHelper($entry, kCurrentContext::$ks, null, accessControlContextType::DOWNLOAD);
     $securyEntryHelper->validateForDownload();
     $ext = $attachmentAsset->getFileExt();
     if (is_null($ext)) {
         $ext = 'txt';
     }
     $fileName = $attachmentAsset->getFilename();
     if (!$fileName) {
         $fileName = $attachmentAsset->getEntryId() . "_" . $attachmentAsset->getId() . ".{$ext}";
     }
     return $this->serveAsset($attachmentAsset, $fileName);
 }
Exemplo n.º 26
0
 protected function initEntry()
 {
     $this->entryId = $this->getRequestParameter("entryId", null);
     // look for a valid token
     $expiry = $this->getRequestParameter("expiry");
     if ($expiry && $expiry <= time()) {
         KExternalErrors::dieError(KExternalErrors::EXPIRED_TOKEN);
     }
     $urlToken = $this->getRequestParameter("kt");
     if ($urlToken) {
         if ($_SERVER["REQUEST_METHOD"] != "GET" || !self::validateKalturaToken($_SERVER["REQUEST_URI"], $urlToken)) {
             KExternalErrors::dieError(KExternalErrors::INVALID_TOKEN);
         }
     }
     // initalize the context
     $ksStr = $this->getRequestParameter("ks");
     if ($ksStr && !$urlToken) {
         try {
             kCurrentContext::initKsPartnerUser($ksStr);
         } catch (Exception $ex) {
             KExternalErrors::dieError(KExternalErrors::INVALID_KS);
         }
     } else {
         $this->entry = kCurrentContext::initPartnerByEntryId($this->entryId);
         if (!$this->entry || $this->entry->getStatus() == entryStatus::DELETED) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     // no need for any further check if a token was used
     if ($urlToken) {
         return;
     }
     // enforce entitlement
     kEntitlementUtils::initEntitlementEnforcement();
     if (!$this->entry) {
         $this->entry = entryPeer::retrieveByPKNoFilter($this->entryId);
         if (!$this->entry || $this->entry->getStatus() == entryStatus::DELETED) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     } else {
         if (!kEntitlementUtils::isEntryEntitled($this->entry)) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     myPartnerUtils::blockInactivePartner($this->entry->getPartnerId());
     // enforce access control
     $base64Referrer = $this->getRequestParameter("referrer");
     $hashes = $this->getRequestParameter("hashes");
     $keyValueHashes = array();
     if ($hashes) {
         $hashes = urldecode($hashes);
         $hashes = explode(",", $hashes);
         foreach ($hashes as $keyValueHashString) {
             list($key, $value) = explode('=', $keyValueHashString);
             $keyValueHashes[$key] = $value;
         }
     }
     // replace space in the base64 string with + as space is invalid in base64 strings and caused
     // by symfony calling str_parse to replace + with spaces.
     // this happens only with params passed in the url path and not the query strings. specifically the ~ char at
     // a columns divided by 3 causes this issue (e.g. http://www.xyzw.com/~xxx)
     //replace also any - with + and _ with /
     $referrer = base64_decode(str_replace(array('-', '_', ' '), array('+', '/', '+'), $base64Referrer));
     if (!is_string($referrer)) {
         $referrer = "";
     }
     // base64_decode can return binary data
     $this->secureEntryHelper = new KSecureEntryHelper($this->entry, $ksStr, $referrer, ContextType::PLAY, $keyValueHashes);
     if ($this->secureEntryHelper->shouldPreview()) {
         $previewLengthInMsecs = $this->secureEntryHelper->getPreviewLength() * 1000;
         $entryLengthInMsecs = $this->entry->getLengthInMsecs();
         if ($previewLengthInMsecs < $entryLengthInMsecs) {
             $this->deliveryAttributes->setClipTo($previewLengthInMsecs);
         }
     } else {
         $this->secureEntryHelper->validateForPlay();
     }
     if (PermissionPeer::isValidForPartner(PermissionName::FEATURE_ENTITLEMENT, $this->entry->getPartnerId()) || $this->secureEntryHelper->hasRules()) {
         $this->forceUrlTokenization = true;
     }
 }
Exemplo n.º 27
0
 public function validateForResponseProfile()
 {
     if (PermissionPeer::isValidForPartner(PermissionName::FEATURE_ENABLE_RESPONSE_PROFILE_USER_CACHE, kCurrentContext::getCurrentPartnerId())) {
         return;
     }
     if (kEntitlementUtils::getEntitlementEnforcement()) {
         throw new KalturaAPIException(KalturaErrors::CANNOT_LIST_RELATED_ENTITLED_WHEN_ENTITLEMENT_IS_ENABLE, get_class($this));
     }
     if (!kCurrentContext::$is_admin_session && !$this->idEqual && !$this->idIn && !$this->referenceIdEqual && !$this->redirectFromEntryId && !$this->referenceIdIn && !$this->parentEntryIdEqual) {
         if (kCurrentContext::$ks_object->privileges === ks::PATTERN_WILDCARD) {
             return;
         }
         if (kCurrentContext::$ks_object->getPrivilegeValue(ks::PRIVILEGE_LIST) === ks::PATTERN_WILDCARD) {
             return;
         }
         throw new KalturaAPIException(KalturaErrors::USER_KS_CANNOT_LIST_RELATED_ENTRIES, get_class($this));
     }
 }
 public function execute($add_extra_debug_data = true)
 {
     date_default_timezone_set(kConf::get("date_default_timezone"));
     // TODO - remove for production - use some configuration to determine
     kConfigTable::$should_use_cache = false;
     $start_impl = $end_impl = 0;
     $nocache = false;
     if ($this->getP("nocache")) {
         $nocache = true;
         $this->logMessage("Not using cache!");
         objectWrapperBase::useCache(false);
     }
     $add_benchmarks = $this->getP("add_benchmarks", false);
     // while testing our system - will match each service agains its description
     // $this->matchInDescription();
     $this->msg = array();
     $this->error = array();
     $this->debug = array();
     $start_time = microtime(true);
     $start = microtime(true);
     $this->benchmarkStart("beforeImpl");
     $this->response_type = $this->getP("format", self::DEFAULT_FORMAT);
     //
     /*
     		$should_debug = $this->getP ( "should_debug" , true );
     		if ( $should_debug == "false" ) $this->should_debug  = false;
     */
     if ($this->should_debug && $add_extra_debug_data) {
         $this->benchmarkStart("signature");
         $sig_type = $this->getP("sigtype", self::SIG_TYPE_POST);
         $signature_params = self::getParamsFromSigType($sig_type);
         $signatura_valid = self::validateSignature($signature_params);
         $this->benchmarkEnd("signature");
         $this->addDebug("sigtype", $sig_type);
         $this->addDebug("validateSignature", $signatura_valid);
         $this->addDebug("signature", self::signature($signature_params));
         //			$this->addDebug( "rawsignature" , self::signature( $signature_params , false ) );
     }
     $partner_id = $this->getP("partner_id");
     if (!$partner_id) {
         $partner_id = $this->getP("partnerId");
     }
     $subp_id = $this->getP("subp_id");
     if (!$subp_id) {
         $subp_id = $this->getP("subpId");
     }
     $puser_id = $this->getP("uid");
     $ks_str = $this->getP("ks");
     if ($ks_str == "{ks}") {
         $ks_str = "";
     }
     // if the client DIDN'T replace the dynamic ks - ignore it
     // the $execution_cache_key can be used by services to cache the results depending on the inpu parameters
     // if the $execution_cache_key is not null, the rendere will search for the result of the rendering depending on the $execution_cache_key
     // if it doesn't find it - it will create it (per format) and store it for next time
     $execution_cache_key = null;
     // moved the renderer here to see if has the $execution_cache_key and if so - skip the implementation
     $renderer = new kalturaWebserviceRenderer($this->response_context);
     $private_partner_data = false;
     try {
         try {
             $arr = list($partner_id, $subp_id, $uid, $private_partner_data) = $this->validateTicketSetPartner($partner_id, $subp_id, $puser_id, $ks_str);
         } catch (Exception $ex) {
             KalturaLog::log('validateTicketSetPartner failed - not caching response');
             defPartnerservices2baseAction::disableCache();
             throw $ex;
         }
         // if PS2 permission validation is enabled for the current partner, only the actions defined in kConf's parameter "ps2_actions_not_blocked_by_permissions" will be allowed
         $currentPartner = $this->getPartner();
         if ($currentPartner && $currentPartner->getEnabledService(PermissionName::FEATURE_PS2_PERMISSIONS_VALIDATION)) {
             if (!in_array(strtolower(get_class($this)), kConf::get('ps2_actions_not_blocked_by_permissions'))) {
                 KalturaLog::log('PS2 action ' . get_class($this) . ' is being blocked for partner ' . $currentPartner->getId() . ' defined with FEATURE_PS2_PERMISSIONS_VALIDATION enabled');
                 $this->addException(APIErrors::SERVICE_FORBIDDEN, get_class($this));
             }
         }
         $this->private_partner_data = $private_partner_data;
         //print_r ( $arr );
         // TODO - validate the matchIp is ok with the user's IP
         $this->validateIp();
         // most services should not attempt to cache the results - for them this will return null
         $execution_cache_key = $this->getExecutionCacheKeyWrapper($partner_id, $subp_id, $puser_id);
         // if the key is not null - it will be used in the renderer for using the cotent from the cache
         if ($nocache) {
             $renderer->deleteCacheKey($execution_cache_key, $this->response_type);
         } else {
             $renderer->setCacheKey($execution_cache_key);
         }
         if (!$renderer->hasContentForCacheKey($this->response_type)) {
             $this->benchmarkStart("applyPartnerFilters");
             //init entitlement before set the default criteire by myPartnerUtils::applyPartnerFilters
             kEntitlementUtils::initEntitlementEnforcement();
             // apply filters for Criteria so there will be no chance of exposure of date from other partners !
             // TODO - add the parameter for allowing kaltura network
             myPartnerUtils::applyPartnerFilters($partner_id, $private_partner_data, $this->partnerGroup2(), $this->kalturaNetwork2());
             $this->benchmarkEnd("applyPartnerFilters");
             $this->benchmarkStart("puserKuser");
             list($partner_id, $subp_id, $puser_id, $partner_prefix) = $this->preparePartnerPuserDetails($partner_id, $subp_id, $puser_id);
             $puser_kuser = $this->getPuserKuser($partner_id, $subp_id, $puser_id);
             $this->benchmarkEnd("puserKuser");
             $this->benchmarkEnd("beforeImpl");
             // ----------------------------- impl --------------------------
             $start_impl = microtime(true);
             $result = $this->executeImpl($partner_id, $subp_id, $puser_id, $partner_prefix, $puser_kuser);
             $end_impl = microtime(true);
             kEventsManager::flushEvents();
         } else {
             /// the renderer claims to have the desired result ! just flow down the code ... ;)
         }
         // ----------------------------- impl --------------------------
     } catch (APIException $api_ex) {
         $message = $api_ex->getMessage();
         if ($this->should_debug && $message) {
             $this->addError(APIErrors::SERVERL_ERROR, "[{$message}]");
         } elseif ($api_ex->api_code) {
             call_user_func_array(array(&$this, 'addError'), $api_ex->extra_data);
             //				$this->addError ( $api_ex->api_code ,$api_ex->extra_data );
         }
     } catch (PropelException $pex) {
         KalturaLog::alert($pex->getMessage());
         $this->addError(APIErrors::INTERNAL_DATABASE_ERROR);
     } catch (Exception $ex) {
         $this->addError(APIErrors::INTERNAL_SERVERL_ERROR, $ex->getMessage());
         KalturaLog::err($ex->getMessage());
     }
     $execute_impl_end_time = microtime(true);
     // render according to the format_type
     $res = array();
     $this->addMsg("serverTime", time());
     $res['result'] = $this->msg;
     $res['error'] = $this->error;
     if ($this->should_debug) {
         // this specific debug line should be used
         $this->addDebug("execute_impl_time", $end_impl - $start_impl);
         $this->addDebug("execute_time", $execute_impl_end_time - $start_time);
         // will be used as a place holder and will be replaced after the rendering.
         if ($add_extra_debug_data) {
             $this->addDebug("total_time", self::__TOTAL_TIME__);
         }
         if ($add_benchmarks && count($this->benchmarks) > 0) {
             $this->addDebug("host", @$_ENV["HOSTNAME"]);
             $this->addDebug("benchmarks", $this->getBenchmarks());
         }
         $res['debug'] = $this->debug;
     }
     // ignore all the errors and debug - the first msg is the only html used
     if ($this->response_type == kalturaWebserviceRenderer::RESPONSE_TYPE_HTML) {
         $res = "<html>";
         foreach ($this->msg as $html_bit) {
             $res .= $html_bit;
         }
         $res .= "</html>";
     }
     if ($this->response_type == kalturaWebserviceRenderer::RESPONSE_TYPE_MRSS) {
         // in case of mRss - render only the result not the errors ot the debug
         list($response, $content_type) = $renderer->renderDataInRequestedFormat($res['result'], $this->response_type, true, self::$escape_text);
     } else {
         list($response, $content_type) = $renderer->renderDataInRequestedFormat($res, $this->response_type, true, self::$escape_text);
     }
     $end_time = microtime(true);
     if (is_string($response)) {
         $this->logMessage("Rendereing took: [" . ($end_time - $start_time) . "] seconds. Response size [" . strlen($response) . "]", SF_LOG_WARNING);
         $this->logMessage($response, SF_LOG_WARNING);
     } else {
         $this->logMessage("Rendereing took: [" . ($end_time - $start_time) . "]");
     }
     if ($this->should_debug && $add_extra_debug_data) {
         // fix the total time including the render time
         $str_time = (string) ($end_time - $start_time);
         if ($this->response_type == kalturaWebserviceRenderer::RESPONSE_TYPE_PHP) {
             // replcate the placehoder with the real execution time
             // this is a nasty hack - we replace the serialized PHP value - the length of the placeholder is 14 characters
             // the length of the str_time can be less - replace the whole string phrase
             $replace_string = 's:' . strlen($str_time) . ':"' . $str_time;
             $response = str_replace('s:14:"' . self::__TOTAL_TIME__, $replace_string, $response);
         } elseif ($this->response_type == kalturaWebserviceRenderer::RESPONSE_TYPE_PHP_ARRAY || $this->response_type == kalturaWebserviceRenderer::RESPONSE_TYPE_PHP_OBJECT) {
             // the $response is not a string - we can't just replace it
             $res["debug"]["total_time"] = $str_time;
         } elseif ($this->response_type == kalturaWebserviceRenderer::RESPONSE_TYPE_MRSS) {
             // do nothing to the result
         } else {
             $response = str_replace(self::__TOTAL_TIME__, $str_time, $response);
         }
     }
     header("Access-Control-Allow-Origin:*");
     // avoid html5 xss issues
     $this->setContentType($content_type);
     // while testing our system - will match each service agains its description
     // $this->matchOutDescription();
     return $response;
 }
Exemplo n.º 29
0
 public function getPrivacyByContexts()
 {
     return implode(' ', kEntitlementUtils::getPrivacyContextForEntry($this));
 }
 /**
  * Index an entry by id.
  * 
  * @action index
  * @param string $id
  * @param bool $shouldUpdate
  * @return int entry int id
  */
 function indexAction($id, $shouldUpdate = true)
 {
     if (kEntitlementUtils::getEntitlementEnforcement()) {
         throw new KalturaAPIException(KalturaErrors::CANNOT_INDEX_OBJECT_WHEN_ENTITLEMENT_IS_ENABLE);
     }
     $entryDb = entryPeer::retrieveByPK($id);
     if (!$entryDb) {
         throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $id);
     }
     if (!$shouldUpdate) {
         $entryDb->indexToSearchIndex();
         return $entryDb->getIntId();
     }
     return myEntryUtils::index($entryDb);
 }