public function initService($serviceId, $serviceName, $actionName) { parent::initService($serviceId, $serviceName, $actionName); $this->applyPartnerFilterForClass('CuePoint'); // when session is not admin, allow access to user entries only if (!$this->getKs() || !$this->getKs()->isAdmin()) { KalturaCriterion::enableTag(KalturaCriterion::TAG_USER_SESSION); CuePointPeer::setUserContentOnly(true); } if (!CuePointPlugin::isAllowedPartner($this->getPartnerId())) { throw new KalturaAPIException(KalturaErrors::FEATURE_FORBIDDEN, CuePointPlugin::PLUGIN_NAME); } if (!$this->getPartner()->getEnabledService(PermissionName::FEATURE_KALTURA_LIVE_STREAM)) { throw new KalturaAPIException(KalturaErrors::FEATURE_FORBIDDEN, 'Kaltura Live Streams'); } }
public function initService($serviceId, $serviceName, $actionName) { $ks = kCurrentContext::$ks_object ? kCurrentContext::$ks_object : null; if ($actionName == 'search' && (!$ks || !$ks->isAdmin() && !$ks->verifyPrivileges(ks::PRIVILEGE_LIST, ks::PRIVILEGE_WILDCARD))) { KalturaCriterion::enableTag(KalturaCriterion::TAG_WIDGET_SESSION); entryPeer::setUserContentOnly(true); } parent::initService($serviceId, $serviceName, $actionName); if ($actionName != 'parse') { $this->applyPartnerFilterForClass('asset'); $this->applyPartnerFilterForClass('CaptionAssetItem'); } if (!CaptionSearchPlugin::isAllowedPartner($this->getPartnerId())) { throw new KalturaAPIException(KalturaErrors::FEATURE_FORBIDDEN, CaptionSearchPlugin::PLUGIN_NAME); } }
public function initService($serviceId, $serviceName, $actionName) { parent::initService($serviceId, $serviceName, $actionName); // Play-Server and Media-Server list entries of all partners // This is not too expensive as the requests are cached conditionally and performed on sphinx $allowedSystemPartners = array(Partner::MEDIA_SERVER_PARTNER_ID, Partner::PLAY_SERVER_PARTNER_ID); if (in_array($this->getPartnerId(), $allowedSystemPartners) && $actionName == 'list') { myPartnerUtils::resetPartnerFilter('entry'); } else { $this->applyPartnerFilterForClass('CuePoint'); } // when session is not admin, allow access to user entries only if (!$this->getKs() || !$this->getKs()->isAdmin()) { KalturaCriterion::enableTag(KalturaCriterion::TAG_USER_SESSION); CuePointPeer::setUserContentOnly(true); } if (!CuePointPlugin::isAllowedPartner($this->getPartnerId())) { throw new KalturaAPIException(KalturaErrors::FEATURE_FORBIDDEN, CuePointPlugin::PLUGIN_NAME); } }
public static function retrieveByPK($pk, PropelPDO $con = null) { KalturaCriterion::disableTags(array(KalturaCriterion::TAG_USER_SESSION)); $res = parent::retrieveByPK($pk, $con); KalturaCriterion::restoreTags(array(KalturaCriterion::TAG_USER_SESSION)); return $res; }
public function execute() { //entitlement should be disabled to serveFlavor action as we do not get ks on this action. KalturaCriterion::disableTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY); requestUtils::handleConditionalGet(); $flavorId = $this->getRequestParameter("flavorId"); $shouldProxy = $this->getRequestParameter("forceproxy", false); $fileName = $this->getRequestParameter("fileName"); $fileParam = $this->getRequestParameter("file"); $fileParam = basename($fileParam); $pathOnly = $this->getRequestParameter("pathOnly", false); $referrer = base64_decode($this->getRequestParameter("referrer")); if (!is_string($referrer)) { // base64_decode can return binary data $referrer = ''; } $flavorAsset = assetPeer::retrieveById($flavorId); if (is_null($flavorAsset)) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } $entryId = $this->getRequestParameter("entryId"); if (!is_null($entryId) && $flavorAsset->getEntryId() != $entryId) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } if ($fileName) { header("Content-Disposition: attachment; filename=\"{$fileName}\""); header("Content-Type: application/force-download"); header("Content-Description: File Transfer"); } $clipTo = null; $entry = $flavorAsset->getentry(); if (!$entry) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } KalturaMonitorClient::initApiMonitor(false, 'extwidget.serveFlavor', $flavorAsset->getPartnerId()); myPartnerUtils::enforceDelivery($entry, $flavorAsset); $version = $this->getRequestParameter("v"); if (!$version) { $version = $flavorAsset->getVersion(); } $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, $version); if ($pathOnly && kIpAddressUtils::isInternalIp($_SERVER['REMOTE_ADDR'])) { $path = null; list($file_sync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, false, false); if ($file_sync) { $parent_file_sync = kFileSyncUtils::resolve($file_sync); $path = $parent_file_sync->getFullPath(); if ($fileParam && is_dir($path)) { $path .= "/{$fileParam}"; } } $renderer = new kRendererString('{"sequences":[{"clips":[{"type":"source","path":"' . $path . '"}]}]}', 'application/json'); if ($path) { $this->storeCache($renderer, $flavorAsset->getPartnerId()); } $renderer->output(); KExternalErrors::dieGracefully(); } if (kConf::hasParam('serve_flavor_allowed_partners') && !in_array($flavorAsset->getPartnerId(), kConf::get('serve_flavor_allowed_partners'))) { KExternalErrors::dieError(KExternalErrors::ACTION_BLOCKED); } if (!kFileSyncUtils::file_exists($syncKey, false)) { list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false); if (is_null($fileSync)) { KalturaLog::log("Error - no FileSync for flavor [" . $flavorAsset->getId() . "]"); KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND); } // always dump remote urls so they will be cached by the cdn transparently $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync); kFileUtils::dumpUrl($remoteUrl); } $path = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey); $isFlv = false; if (!$shouldProxy) { $flvWrapper = new myFlvHandler($path); $isFlv = $flvWrapper->isFlv(); } $clipFrom = $this->getRequestParameter("clipFrom", 0); // milliseconds if (is_null($clipTo)) { $clipTo = $this->getRequestParameter("clipTo", self::NO_CLIP_TO); } // milliseconds if ($clipTo == 0) { $clipTo = self::NO_CLIP_TO; } if (!is_numeric($clipTo) || $clipTo < 0) { KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'clipTo must be a positive number'); } $seekFrom = $this->getRequestParameter("seekFrom", -1); if ($seekFrom <= 0) { $seekFrom = -1; } $seekFromBytes = $this->getRequestParameter("seekFromBytes", -1); if ($seekFromBytes <= 0) { $seekFromBytes = -1; } if ($fileParam && is_dir($path)) { $path .= "/{$fileParam}"; kFileUtils::dumpFile($path, null, null); KExternalErrors::dieGracefully(); } else { if (!$isFlv || $clipTo == self::NO_CLIP_TO && $seekFrom < 0 && $seekFromBytes < 0) { $limit_file_size = 0; if ($clipTo != self::NO_CLIP_TO) { if (strtolower($flavorAsset->getFileExt()) == 'mp4' && PermissionPeer::isValidForPartner(PermissionName::FEATURE_ACCURATE_SERVE_CLIPPING, $flavorAsset->getPartnerId())) { $contentPath = myContentStorage::getFSContentRootPath(); $tempClipName = $version . '_' . $clipTo . '.mp4'; $tempClipPath = $contentPath . myContentStorage::getGeneralEntityPath("entry/tempclip", $flavorAsset->getIntId(), $flavorAsset->getId(), $tempClipName); if (!file_exists($tempClipPath)) { kFile::fullMkdir($tempClipPath); $clipToSec = round($clipTo / 1000, 3); $cmdLine = kConf::get("bin_path_ffmpeg") . " -i {$path} -vcodec copy -acodec copy -f mp4 -t {$clipToSec} -y {$tempClipPath} 2>&1"; KalturaLog::log("Executing {$cmdLine}"); $output = array(); $return_value = ""; exec($cmdLine, $output, $return_value); KalturaLog::log("ffmpeg returned {$return_value}, output:" . implode("\n", $output)); } if (file_exists($tempClipPath)) { KalturaLog::log("Dumping {$tempClipPath}"); kFileUtils::dumpFile($tempClipPath); } else { KalturaLog::err('Failed to clip the file using ffmpeg, falling back to rough clipping'); } } $mediaInfo = mediaInfoPeer::retrieveByFlavorAssetId($flavorAsset->getId()); if ($mediaInfo && ($mediaInfo->getVideoDuration() || $mediaInfo->getAudioDuration() || $mediaInfo->getContainerDuration())) { $duration = $mediaInfo->getVideoDuration() ? $mediaInfo->getVideoDuration() : ($mediaInfo->getAudioDuration() ? $mediaInfo->getAudioDuration() : $mediaInfo->getContainerDuration()); $limit_file_size = floor(@kFile::fileSize($path) * ($clipTo / $duration) * 1.2); } } $renderer = kFileUtils::getDumpFileRenderer($path, null, null, $limit_file_size); if (!$fileName) { $this->storeCache($renderer, $flavorAsset->getPartnerId()); } $renderer->output(); KExternalErrors::dieGracefully(); } } $audioOnly = $this->getRequestParameter("audioOnly"); // milliseconds if ($audioOnly === '0') { // audioOnly was explicitly set to 0 - don't attempt to make further automatic investigations } elseif ($flvWrapper->getFirstVideoTimestamp() < 0) { $audioOnly = true; } $bytes = 0; if ($seekFrom !== -1 && $seekFrom !== 0) { list($bytes, $duration, $firstTagByte, $toByte) = $flvWrapper->clip(0, -1, $audioOnly); list($bytes, $duration, $fromByte, $toByte, $seekFromTimestamp) = $flvWrapper->clip($seekFrom, -1, $audioOnly); $seekFromBytes = myFlvHandler::FLV_HEADER_SIZE + $flvWrapper->getMetadataSize($audioOnly) + $fromByte - $firstTagByte; } else { list($bytes, $duration, $fromByte, $toByte, $fromTs, $cuepointPos) = myFlvStaticHandler::clip($path, $clipFrom, $clipTo, $audioOnly); } $metadataSize = $flvWrapper->getMetadataSize($audioOnly); $dataOffset = $metadataSize + myFlvHandler::getHeaderSize(); $totalLength = $dataOffset + $bytes; list($bytes, $duration, $fromByte, $toByte, $fromTs, $cuepointPos) = myFlvStaticHandler::clip($path, $clipFrom, $clipTo, $audioOnly); list($rangeFrom, $rangeTo, $rangeLength) = requestUtils::handleRangeRequest($totalLength); if ($totalLength < 1000) { // (actually $total_length is probably 13 or 143 - header + empty metadata tag) probably a bad flv maybe only the header - dont cache requestUtils::sendCdnHeaders("flv", $rangeLength, 0); } else { requestUtils::sendCdnHeaders("flv", $rangeLength); } // dont inject cuepoint into the stream $cuepointTime = 0; $cuepointPos = 0; try { Propel::close(); } catch (Exception $e) { $this->logMessage("serveFlavor: error closing db {$e}"); } header("Content-Type: video/x-flv"); $flvWrapper->dump(self::CHUNK_SIZE, $fromByte, $toByte, $audioOnly, $seekFromBytes, $rangeFrom, $rangeTo, $cuepointTime, $cuepointPos); KExternalErrors::dieGracefully(); }
public static function executeDynamicPlaylist($partner_id, $xml, $filter = null, $detailed = true, $pager = null) { list($total_results, $list_of_filters) = self::getPlaylistFilterListStruct($xml); $entry_filters = array(); if (!$list_of_filters) { return null; } // TODO - for now we assume that there are more or equal filters in the XML than the ones from the request $filterLimit = null; if ($filter && $filter->getLimit() > 0) { $filterLimit = $filter->getLimit(); // Get the max results from the limit of the first filter $total_results = min($total_results, $filterLimit); // Clear this limit so it won't overcloud the limits of $entry_filter_xml rules $filter->setLimit(null); } $numFiltersInList = count($list_of_filters); for ($i = 0; $i < $numFiltersInList; $i++) { $entry_filter_xml = $list_of_filters[$i]; /* @var $entry_filter_xml SimpleXMLElement */ // in general this service can fetch entries from kaltura networks. // for each filter we should decide if thie assumption is true... $allow_partner_only = true; self::replaceContextTokens($entry_filter_xml); // compile all the filters - only then execute them if not yet reached the total_results // TODO - optimize - maybe create them only when needed. - For now it's safer to compile all even if not needed. $entry_filter = new entryFilter(); // add the desired prefix "_" because the XML is not expected to have it while the entryFilter class expects it $entry_filter->fillObjectFromXml($entry_filter_xml, "_"); // make sure there is alway a limit for each filter - if not an explicit one - the system limit should be used if ($entry_filter->getLimit() == null || $entry_filter->getLimit() < 1) { $entry_filter->setLimit(self::TOTAL_RESULTS); } // merge the current_filter with the correcponding extra_filter // allow the extra_filter to override properties of the current filter if ($filter) { if ($filterLimit && $i == $numFiltersInList - 1) { // Hack (in order to preserve old behavior): // If the filter contained a limit, we'll add it to the last XML filter on the list // in order to make sure the number of requested ($limit) entries will be supplied. // This handles requests of a $limit which is higher than the total sum of inner XML filter limits. $filter->setLimit($filterLimit); } $entry_filter->fillObjectFromObject($filter, myBaseObject::CLONE_FIELD_POLICY_THIS, myBaseObject::CLONE_POLICY_PREFER_NEW, null, null, false); $entry_filter->setPartnerSearchScope(baseObjectFilter::MATCH_KALTURA_NETWORK_AND_PRIVATE); } self::updateEntryFilter($entry_filter, $partner_id, true); $entry_filters[] = $entry_filter; } if ($pager) { $startOffset = $pager->calcOffset(); $pageSize = $pager->calcPageSize(); if ($startOffset > $total_results) { return array(); } $total_results = min($total_results, $startOffset + $pageSize); } $entry_ids_list = array(); foreach ($entry_filters as $entry_filter) { $current_limit = max(0, $total_results - count($entry_ids_list)); // if the current_limit is < 0 - set it to be 0 // no need to fetch any more results if ($current_limit <= 0) { break; } $c = KalturaCriteria::create(entryPeer::OM_CLASS); // don't fetch the same entries twice - filter out all the entries that were already fetched if ($entry_ids_list) { $c->add(entryPeer::ID, $entry_ids_list, Criteria::NOT_IN); } $filter_limit = $entry_filter->getLimit(); if ($filter_limit > $current_limit) { // set a smaller limit incase the filter's limit is to high $entry_filter->setLimit($current_limit); } // read the _eq_display_in_search field but ignore it because it's part of a more complex criterion $display_in_search = $entry_filter->get("_eq_display_in_search"); if ($display_in_search >= 2) { $entry_filter->set("_eq_display_in_search", null); } $entry_filter->attachToCriteria($c); // add some hard-coded criteria $c->addAnd(entryPeer::TYPE, array(entryType::MEDIA_CLIP, entryType::MIX, entryType::LIVE_STREAM), Criteria::IN); // search only for clips or roughcuts $c->addAnd(entryPeer::STATUS, entryStatus::READY); // search only for READY entries $c->addAnd(entryPeer::DISPLAY_IN_SEARCH, mySearchUtils::DISPLAY_IN_SEARCH_SYSTEM, Criteria::NOT_EQUAL); if ($display_in_search >= 2) { // We don't allow searching in the KalturaNEtwork anymore (mainly for performance reasons) // allow only assets for the partner $c->addAnd(entryPeer::PARTNER_ID, $partner_id); // /* $crit = $c->getNewCriterion ( entryPeer::PARTNER_ID , $partner_id ); $crit->addOr ( $c->getNewCriterion ( entryPeer::DISPLAY_IN_SEARCH , $display_in_search ) ); $c->addAnd ( $crit ); */ } if (!self::$isAdminKs) { self::addSchedulingToCriteria($c); } self::addModerationToCriteria($c); $c = entryPeer::prepareEntitlementCriteriaAndFilters($c); $entry_ids_list_for_filter = $c->getFetchedIds(); // update total count and merge current result with the global list $entry_ids_list = array_merge($entry_ids_list, $entry_ids_list_for_filter); } if ($pager) { // Keep the paged entries only $entry_ids_list = array_slice($entry_ids_list, $startOffset, $pageSize); } // Disable entitlement, which was already applied in entryPeer::prepareEntitlementCriteriaAndFilters() // otherwise we will hit the 150 entries limit from SphinxCriterion KalturaCriterion::disableTag(KalturaCriterion::TAG_ENTITLEMENT_ENTRY); $db_entry_list = entryPeer::retrieveByPKs($entry_ids_list); KalturaCriterion::restoreTag(KalturaCriterion::TAG_ENTITLEMENT_ENTRY); // Map the entries to their IDs $entry_map = array(); foreach ($db_entry_list as $entry) { $entry_map[$entry->getId()] = $entry; } // Build entry_list according to the playlist order $entry_list = array(); foreach ($entry_ids_list as $entryId) { $entry_list[] = $entry_map[$entryId]; } return $entry_list; }
public function handleMultiRequest() { // arrange the parameters by request index $commonParams = array(); $listOfRequests = array(); $dependencies = array(); $allDependencies = array(); $pastResults = array(); foreach ($this->params as $paramName => $paramValue) { $explodedName = explode(':', $paramName, 2); if (count($explodedName) <= 1 || !is_numeric($explodedName[0])) { $commonParams[$paramName] = $paramValue; continue; } $requestIndex = (int) $explodedName[0]; $paramName = $explodedName[1]; if (!array_key_exists($requestIndex, $listOfRequests)) { $listOfRequests[$requestIndex] = array(); } $listOfRequests[$requestIndex][$paramName] = $paramValue; $matches = array(); if (preg_match('/\\{([0-9]*)\\:result\\:?(.*)?\\}/', $paramValue, $matches)) { $pastResultsIndex = $matches[0]; $resultIndex = $matches[1]; $resultKey = $matches[2]; if (!isset($dependencies[$requestIndex][$pastResultsIndex])) { $dependencies[$resultIndex][$pastResultsIndex] = $resultKey; } $allDependencies[$pastResultsIndex] = true; } } // process the requests $results = array(); for ($i = 1; isset($listOfRequests[$i]); $i++) { $currentParams = $listOfRequests[$i]; if (!isset($currentParams["service"]) || !isset($currentParams["action"])) { break; } kCurrentContext::$multiRequest_index = $i; $currentService = $currentParams["service"]; $currentAction = $currentParams["action"]; // copy derived common params to current params if (isset($commonParams['clientTag']) && !isset($currentParams['clientTag'])) { $currentParams['clientTag'] = $commonParams['clientTag']; } if (isset($commonParams['ks']) && !isset($currentParams['ks'])) { $currentParams['ks'] = $commonParams['ks']; } if (isset($commonParams['partnerId']) && !isset($currentParams['partnerId'])) { $currentParams['partnerId'] = $commonParams['partnerId']; } // check if we need to replace params with prev results foreach ($currentParams as $key => &$val) { if (isset($pastResults[$val])) { $val = $pastResults[$val]; } else { if (isset($allDependencies[$val])) { $val = null; } } } // cached parameters should be different when the request is part of a multirequest // as part of multirequest - the cached data is a serialized php object // when not part of multirequest - the cached data is the actual response $currentParams['multirequest'] = true; unset($currentParams['format']); $cache = new KalturaResponseCacher($currentParams); $success = true; $errorCode = null; $this->onRequestStart($currentService, $currentAction, $currentParams, $i, true); $cachedResult = $cache->checkCache('X-Kaltura-Part-Of-MultiRequest'); if ($cachedResult) { $currentResult = unserialize($cachedResult); } else { if ($i != 1) { kMemoryManager::clearMemory(); KalturaCriterion::clearTags(); } try { $currentResult = $this->dispatcher->dispatch($currentService, $currentAction, $currentParams); } catch (Exception $ex) { $success = false; $errorCode = $ex->getCode(); $currentResult = $this->getExceptionObject($ex, $currentService, $currentAction); } $cache->storeCache($currentResult, "", true); } $this->onRequestEnd($success, $errorCode, $i); if (isset($dependencies[$i])) { foreach ($dependencies[$i] as $currentDependency => $dependencyName) { if (strlen(trim($dependencyName)) > 0) { $resultPathArray = explode(":", $dependencyName); } else { $resultPathArray = array(); } $currValue = $this->getValueFromObject($currentResult, $resultPathArray); $pastResults[$currentDependency] = $currValue; } } $results[$i] = $this->serializer->serialize($currentResult); // in case a serve action is included in a multirequest, return only the result of the serve action // in order to avoid serializing the kRendererBase object and returning the internal server paths to the client if ($currentResult instanceof kRendererBase) { return $currentResult; } } return $results; }
public function addOr(Criterion $criterion) { $currentField = $this->getTable() . '.' . $this->getColumn(); $addedField = $this->getTable() . '.' . $this->getColumn(); KalturaLog::debug("Add OR criterion field [{$addedField}] to current field [{$currentField}]"); // Validate that the added criterion and the current criterios are both attributes or both matches if ($this->criteria->hasSphinxFieldName($addedField)) { $currentSphinxField = $this->criteria->getSphinxFieldName($currentField); $addedSphinxField = $this->criteria->getSphinxFieldName($addedField); if ($currentSphinxField != $addedSphinxField) { KalturaLog::debug("Current sphinx field [{$currentSphinxField}] and added sphinx field [{$addedField}]"); $currentType = $this->criteria->getSphinxFieldType($currentSphinxField); $addedType = $this->criteria->getSphinxFieldType($addedField); if ($currentType != $addedType) { KalturaLog::debug("Current type [{$currentType}] and added type [{$addedType}]"); if ($currentType == IIndexable::FIELD_TYPE_STRING || $addedType == IIndexable::FIELD_TYPE_STRING) { throw new kCoreException("Cannot mix OR operator on attributes and matches", kCoreException::INVALID_QUERY); } } } } if ($criterion instanceof SphinxCriterion) { $criterion->setSelfMatchOperator(self::SPHINX_OR); } return parent::addOr($criterion); }
protected function doGetListResponse(KalturaFilterPager $pager) { myDbHelper::$use_alternative_con = myDbHelper::DB_HELPER_CONN_PROPEL3; $disableWidgetSessionFilters = false; if ($this && ($this->idEqual != null || $this->idIn != null || $this->referenceIdEqual != null || $this->redirectFromEntryId != null || $this->referenceIdIn != null || $this->parentEntryIdEqual != null)) { $disableWidgetSessionFilters = true; } $c = $this->prepareEntriesCriteriaFilter($pager); if ($disableWidgetSessionFilters) { KalturaCriterion::disableTag(KalturaCriterion::TAG_WIDGET_SESSION); } $list = entryPeer::doSelect($c); $totalCount = $c->getRecordsCount(); if ($disableWidgetSessionFilters) { KalturaCriterion::restoreTag(KalturaCriterion::TAG_WIDGET_SESSION); } myDbHelper::$use_alternative_con = null; return array($list, $totalCount); }
/** * Append an OR Criterion onto this Criterion's list. * @return Criterion */ public function addOr(Criterion $criterion) { $this->hasOr = true; return parent::addOr($criterion); }
private static function getCategoriesByIds($categoriesIds) { $c = KalturaCriteria::create(categoryPeer::OM_CLASS); KalturaCriterion::disableTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY); $c->add(categoryPeer::ID, $categoriesIds, Criteria::IN); KalturaCriterion::restoreTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY); $c->dontCount(); KalturaCriterion::disableTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY); $categories = categoryPeer::doSelect($c); KalturaCriterion::restoreTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY); return $categories; }
public static function executeDynamicPlaylist($partner_id, $xml, $extra_filters = null, $detailed = true) { list($total_results, $list_of_filters) = self::getPlaylistFilterListStruct($xml); $entry_filters = array(); if (!$list_of_filters) { return null; } // TODO - for now we assume that there are more or equal filters in the XML than the ones from the request $i = 1; // the extra_filter is 1-based foreach ($list_of_filters as $entry_filter_xml) { // in general this service can fetch entries from kaltura networks. // for each filter we should decide if thie assumption is true... $allow_partner_only = true; // compile all the filters - only then execute them if not yet reached the total_results // TODO - optimize - maybe create them only when needed. - For now it's safer to compile all even if not needed. $entry_filter = new entryFilter(); // add the desired prefix "_" because the XML is not expected to have it while the entryFilter class expects it $entry_filter->fillObjectFromXml($entry_filter_xml, "_"); // make sure there is alway a limit for each filter - if not an explicit one - the system limit should be used if ($entry_filter->getLimit() == null || $entry_filter->getLimit() < 1) { $entry_filter->setLimit(self::TOTAL_RESULTS); } $extra_filter = @$extra_filters[$i]; // merge the current_filter with the correcponding extra_filter // allow the extra_filter to override properties of the current filter if ($extra_filter) { $entry_filter->fillObjectFromObject($extra_filter, myBaseObject::CLONE_FIELD_POLICY_THIS, myBaseObject::CLONE_POLICY_PREFER_NEW, null, null, false); $entry_filter->setPartnerSearchScope(baseObjectFilter::MATCH_KALTURA_NETWORK_AND_PRIVATE); } self::updateEntryFilter($entry_filter, $partner_id, true); $entry_filters[] = $entry_filter; $i++; } $number_of_entries = 0; $entry_list = array(); $i = 1; foreach ($entry_filters as $entry_filter) { $current_limit = max(0, $total_results - $number_of_entries); // if the current_limit is < 0 - set it to be 0 $exclude_id_list = self::getIds($entry_list); $c = KalturaCriteria::create(entryPeer::OM_CLASS); // don't fetch the same entries twice - filter out all the entries that were already fetched if ($exclude_id_list) { $c->add(entryPeer::ID, $exclude_id_list, Criteria::NOT_IN); } // no need to fetch any more results if ($current_limit <= 0) { break; } $filter_limit = $entry_filter->getLimit(); if ($filter_limit > $current_limit) { // set a smaller limit incase the filter's limit is to high $entry_filter->setLimit($current_limit); } // read the _eq_display_in_search field but ignore it because it's part of a more complex criterion $display_in_search = $entry_filter->get("_eq_display_in_search"); if ($display_in_search >= 2) { $entry_filter->set("_eq_display_in_search", null); } $entry_filter->attachToCriteria($c); // add some hard-coded criteria $c->addAnd(entryPeer::TYPE, array(entryType::MEDIA_CLIP, entryType::MIX, entryType::LIVE_STREAM), Criteria::IN); // search only for clips or roughcuts $c->addAnd(entryPeer::STATUS, entryStatus::READY); // search only for READY entries $c->addAnd(entryPeer::DISPLAY_IN_SEARCH, mySearchUtils::DISPLAY_IN_SEARCH_SYSTEM, Criteria::NOT_EQUAL); if ($display_in_search >= 2) { // We don't allow searching in the KalturaNEtwork anymore (mainly for performance reasons) // allow only assets for the partner $c->addAnd(entryPeer::PARTNER_ID, $partner_id); // /* $crit = $c->getNewCriterion ( entryPeer::PARTNER_ID , $partner_id ); $crit->addOr ( $c->getNewCriterion ( entryPeer::DISPLAY_IN_SEARCH , $display_in_search ) ); $c->addAnd ( $crit ); */ } if (!self::$isAdminKs) { self::addSchedulingToCriteria($c); } self::addModerationToCriteria($c); KalturaCriterion::disableTag(KalturaCriterion::TAG_WIDGET_SESSION); if ($detailed) { $entry_list_for_filter = entryPeer::doSelectJoinkuser($c); } else { $entry_list_for_filter = entryPeer::doSelect($c); } // maybe join with kuser to add some data about the contributor KalturaCriterion::restoreTag(KalturaCriterion::TAG_WIDGET_SESSION); // update total count and merge current result with the global list $number_of_entries += count($entry_list_for_filter); $entry_list = array_merge($entry_list, $entry_list_for_filter); } return $entry_list; }
public static function getPrivacyContextForEntry(entry $entry) { $privacyContexts = array(); $entryPrivacy = null; $categories = array(); if (count($entry->getAllCategoriesIds(true))) { $c = KalturaCriteria::create(categoryPeer::OM_CLASS); KalturaCriterion::disableTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY); $c->add(categoryPeer::ID, $entry->getAllCategoriesIds(true), Criteria::IN); KalturaCriterion::restoreTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY); KalturaCriterion::disableTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY); $categories = categoryPeer::doSelect($c); KalturaCriterion::restoreTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY); foreach ($categories as $category) { $categoryPrivacy = $category->getPrivacy(); $categoryPrivacyContexts = $category->getPrivacyContexts(); if (!$categoryPrivacyContexts) { $categoryPrivacyContexts = self::DEFAULT_CONTEXT . $entry->getPartnerId(); } $categoryPrivacyContexts = explode(',', $categoryPrivacyContexts); foreach ($categoryPrivacyContexts as $categoryPrivacyContext) { if (trim($categoryPrivacyContext) == '') { $categoryPrivacyContext = self::DEFAULT_CONTEXT . $entry->getPartnerId(); } if (!isset($privacyContexts[$categoryPrivacyContext]) || $privacyContexts[$categoryPrivacyContext] > $categoryPrivacy) { $privacyContexts[trim($categoryPrivacyContext)] = $categoryPrivacy; } } } } //Entry That doesn't assinged to any category is public. if (!count($categories)) { $privacyContexts[self::DEFAULT_CONTEXT . $entry->getPartnerId()] = PrivacyType::ALL; } $entryPrivacyContexts = array(); foreach ($privacyContexts as $categoryPrivacyContext => $Privacy) { $entryPrivacyContexts[] = $categoryPrivacyContext . '_' . $Privacy; } KalturaLog::debug('Privacy by context: ' . print_r($entryPrivacyContexts, true)); return $entryPrivacyContexts; }
public static function initPartnerByAssetId($assetId) { KalturaCriterion::disableTags(array(KalturaCriterion::TAG_ENTITLEMENT_ENTRY, KalturaCriterion::TAG_WIDGET_SESSION)); $asset = assetPeer::retrieveByIdNoFilter($assetId); KalturaCriterion::restoreTags(array(KalturaCriterion::TAG_ENTITLEMENT_ENTRY, KalturaCriterion::TAG_WIDGET_SESSION)); if (!$asset) { return null; } kCurrentContext::$ks = null; kCurrentContext::$ks_object = null; kCurrentContext::$ks_hash = null; kCurrentContext::$ks_partner_id = $asset->getPartnerId(); kCurrentContext::$ks_uid = null; kCurrentContext::$master_partner_id = null; kCurrentContext::$partner_id = $asset->getPartnerId(); kCurrentContext::$uid = null; kCurrentContext::$is_admin_session = false; return $asset; }
public function execute() { //entitlement should be disabled to serveFlavor action as we do not get ks on this action. KalturaCriterion::disableTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY); requestUtils::handleConditionalGet(); $flavorId = $this->getRequestParameter("flavorId"); $shouldProxy = $this->getRequestParameter("forceproxy", false); $ks = $this->getRequestParameter("ks"); $fileParam = $this->getRequestParameter("file"); $fileParam = basename($fileParam); $referrer = base64_decode($this->getRequestParameter("referrer")); if (!is_string($referrer)) { // base64_decode can return binary data $referrer = ''; } $flavorAsset = assetPeer::retrieveById($flavorId); if (is_null($flavorAsset)) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } $entryId = $this->getRequestParameter("entryId"); if (!is_null($entryId) && $flavorAsset->getEntryId() != $entryId) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } $clipTo = null; // $securyEntryHelper = new KSecureEntryHelper($entry, $ks, $referrer, accessControlContextType::PLAY); // if ($securyEntryHelper->shouldPreview()) // { // $clipTo = $securyEntryHelper->getPreviewLength() * 1000; // } // else // { // $securyEntryHelper->validateForPlay($entry, $ks); // } myPartnerUtils::blockInactivePartner($flavorAsset->getPartnerId()); myPartnerUtils::enforceDelivery($flavorAsset->getPartnerId()); //disabled enforce cdn because of rtmp delivery //requestUtils::enforceCdnDelivery($flavorAsset->getPartnerId()); $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); if (!kFileSyncUtils::file_exists($syncKey, false)) { list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false); if (is_null($fileSync)) { KalturaLog::log("Error - no FileSync for flavor [" . $flavorAsset->getId() . "]"); KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND); } // always dump remote urls so they will be cached by the cdn transparently //$remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync); $remoteUrl = $fileSync->getWamsUrl(); if (!is_null($remoteUrl)) { header('Location: ' . $remoteUrl); die; } else { $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync); } kFile::dumpUrl($remoteUrl); } $path = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey); $isFlv = false; if (!$shouldProxy) { $flvWrapper = new myFlvHandler($path); $isFlv = $flvWrapper->isFlv(); } $clipFrom = $this->getRequestParameter("clipFrom", 0); // milliseconds if (is_null($clipTo)) { $clipTo = $this->getRequestParameter("clipTo", 2147483647); } // milliseconds if ($clipTo == 0) { $clipTo = 2147483647; } if ($fileParam && is_dir($path)) { $path .= "/{$fileParam}"; kFile::dumpFile($path, null, null); die; } else { if (!$isFlv) { $limit_file_size = 0; if ($clipTo != 2147483647) { $mediaInfo = mediaInfoPeer::retrieveByFlavorAssetId($flavorAsset->getId()); if ($mediaInfo && ($mediaInfo->getVideoDuration() || $mediaInfo->getAudioDuration() || $mediaInfo->getContainerDuration())) { $duration = $mediaInfo->getVideoDuration() ? $mediaInfo->getVideoDuration() : ($mediaInfo->getAudioDuration() ? $mediaInfo->getAudioDuration() : $mediaInfo->getContainerDuration()); $limit_file_size = floor(@kFile::fileSize($path) * ($clipTo / $duration)); } } kFile::dumpFile($path, null, null, $limit_file_size); die; } } $audioOnly = $this->getRequestParameter("audioOnly"); // milliseconds if ($audioOnly === '0') { // audioOnly was explicitly set to 0 - don't attempt to make further automatic investigations } elseif ($flvWrapper->getFirstVideoTimestamp() < 0) { $audioOnly = true; } $seekFrom = $this->getRequestParameter("seekFrom", -1); if ($seekFrom <= 0) { $seekFrom = -1; } $seekFromBytes = $this->getRequestParameter("seekFromBytes", -1); if ($seekFromBytes <= 0) { $seekFromBytes = -1; } $bytes = 0; if ($seekFrom !== -1 && $seekFrom !== 0) { list($bytes, $duration, $firstTagByte, $toByte) = $flvWrapper->clip(0, -1, $audioOnly); list($bytes, $duration, $fromByte, $toByte, $seekFromTimestamp) = $flvWrapper->clip($seekFrom, -1, $audioOnly); $seekFromBytes = myFlvHandler::FLV_HEADER_SIZE + $flvWrapper->getMetadataSize($audioOnly) + $fromByte - $firstTagByte; } else { list($bytes, $duration, $fromByte, $toByte, $fromTs, $cuepointPos) = myFlvStaticHandler::clip($path, $clipFrom, $clipTo, $audioOnly); } $metadataSize = $flvWrapper->getMetadataSize($audioOnly); $dataOffset = $metadataSize + myFlvHandler::getHeaderSize(); $totalLength = $dataOffset + $bytes; list($bytes, $duration, $fromByte, $toByte, $fromTs, $cuepointPos) = myFlvStaticHandler::clip($path, $clipFrom, $clipTo, $audioOnly); list($rangeFrom, $rangeTo, $rangeLength) = requestUtils::handleRangeRequest($totalLength); if ($totalLength < 1000) { // (actually $total_length is probably 13 or 143 - header + empty metadata tag) probably a bad flv maybe only the header - dont cache requestUtils::sendCdnHeaders("flv", $rangeLength, 0); } else { requestUtils::sendCdnHeaders("flv", $rangeLength); } header('Content-Disposition: attachment; filename="video.flv"'); // dont inject cuepoint into the stream $cuepointTime = 0; $cuepointPos = 0; try { Propel::close(); } catch (Exception $e) { $this->logMessage("serveFlavor: error closing db {$e}"); } header("Content-Type: video/x-flv"); $flvWrapper->dump(self::CHUNK_SIZE, $fromByte, $toByte, $audioOnly, $seekFromBytes, $rangeFrom, $rangeTo, $cuepointTime, $cuepointPos); die; }
public function handleMultiRequest() { $listOfRequests = array(); $results = array(); $found = true; $i = 1; while ($found) { $currentService = isset($this->params[$i . ":service"]) ? $this->params[$i . ":service"] : null; $currentAction = isset($this->params[$i . ":action"]) ? $this->params[$i . ":action"] : null; $found = $currentAction && $currentService; if ($found) { $listOfRequests[$i]["service"] = $currentService; $listOfRequests[$i]["action"] = $currentAction; // find all the parameters for this request foreach ($this->params as $key => $val) { // the key "1:myparam" mean that we should input value of this key to request "1", for param "myparam" $keyArray = explode(":", $key); if ($keyArray[0] == $i) { array_shift($keyArray); // remove the request number $requestKey = implode(":", $keyArray); /* remarked by Dor - 13/10/2010 * There is no need to remove service and action from the params in case of multirequest * while they are needed in KalturaResponseCacher if (in_array($requestKey, array("service", "action"))) // don't add service name and action name to the params continue; */ $listOfRequests[$i]["params"][$requestKey] = $val; // store the param } } // clientTag param might be used in KalturaResponseCacher if (isset($this->params['clientTag']) && !isset($listOfRequests[$i]["params"]['clientTag'])) { $listOfRequests[$i]["params"]['clientTag'] = $this->params['clientTag']; } // if ks is not set for a specific request, copy the ks from the top params $currentKs = isset($listOfRequests[$i]["params"]["ks"]) ? $listOfRequests[$i]["params"]["ks"] : null; if (!$currentKs) { $mainKs = isset($this->params["ks"]) ? $this->params["ks"] : null; if ($mainKs) { $listOfRequests[$i]["params"]["ks"] = $mainKs; } } $currentPartner = isset($listOfRequests[$i]["params"]["partnerId"]) ? $listOfRequests[$i]["params"]["partnerId"] : null; if (!$currentPartner) { $mainPartner = isset($this->params["partnerId"]) ? $this->params["partnerId"] : null; if ($mainPartner) { $listOfRequests[$i]["params"]["partnerId"] = $mainPartner; } } $i++; } else { // will break the loop } } $i = 1; foreach ($listOfRequests as $currentRequest) { kCurrentContext::$multiRequest_index = $i; $currentService = $currentRequest["service"]; $currentAction = $currentRequest["action"]; $currentParams = $currentRequest["params"]; // check if we need to replace params with prev results foreach ($currentParams as $key => &$val) { $matches = array(); // keywords: multirequest, result, depend, pass // figuring out if requested params should be extracted from previous result // example: if you want to use KalturaPlaylist->playlistContent result from the first request // in your second request, the second request will contain the following value: // {1:result:playlistContent} if (preg_match('/\\{([0-9]*)\\:result\\:?(.*)?\\}/', $val, $matches)) { $resultIndex = $matches[1]; $resultKey = $matches[2]; if (count($results) >= $resultIndex) { if (strlen(trim($resultKey)) > 0) { $resultPathArray = explode(":", $resultKey); } else { $resultPathArray = array(); } $val = $this->getValueFromObject($results[$resultIndex], $resultPathArray); } } } // cached parameters should be different when the request is part of a multirequest // as part of multirequest - the cached data is a serialized php object // when not part of multirequest - the cached data is the actual response $currentParams['multirequest'] = true; unset($currentParams['format']); $cache = new KalturaResponseCacher($currentParams); if (!isset($currentParams['ks']) && kCurrentContext::$ks) { $cache->setKS(kCurrentContext::$ks); } $success = true; $errorCode = null; $this->onRequestStart($currentService, $currentAction, $currentParams, $i, true); $cachedResult = $cache->checkCache('X-Kaltura-Part-Of-MultiRequest'); if ($cachedResult) { $currentResult = unserialize($cachedResult); } else { if ($i != 1) { kMemoryManager::clearMemory(); KalturaCriterion::clearTags(); } try { $currentResult = $this->dispatcher->dispatch($currentService, $currentAction, $currentParams); } catch (Exception $ex) { $success = false; $errorCode = $ex->getCode(); $currentResult = $this->getExceptionObject($ex); } $cache->storeCache($currentResult, "", true); } $this->onRequestEnd($success, $errorCode, $i); $results[$i] = $currentResult; $i++; } return $results; }
public function handleMultiRequest() { // arrange the parameters by request index $commonParams = array(); $listOfRequests = array(); $requestStartIndex = 1; $requestEndIndex = 1; foreach ($this->params as $paramName => $paramValue) { if (is_numeric($paramName)) { $paramName = intval($paramName); $requestStartIndex = min($requestStartIndex, $paramName); $requestEndIndex = max($requestEndIndex, $paramName); $listOfRequests[$paramName] = $paramValue; continue; } $explodedName = explode(':', $paramName, 2); if (count($explodedName) <= 1 || !is_numeric($explodedName[0])) { $commonParams[$paramName] = $paramValue; continue; } $requestIndex = (int) $explodedName[0]; $requestStartIndex = min($requestStartIndex, $requestIndex); $requestEndIndex = max($requestEndIndex, $requestIndex); $paramName = $explodedName[1]; if (!array_key_exists($requestIndex, $listOfRequests)) { $listOfRequests[$requestIndex] = array(); } $listOfRequests[$requestIndex][$paramName] = $paramValue; } $multiRequestResultsPaths = $this->getMultiRequestResultsPaths($listOfRequests); // process the requests $results = array(); kCurrentContext::$multiRequest_index = 0; for ($i = $requestStartIndex; $i <= $requestEndIndex; $i++) { $currentParams = $listOfRequests[$i]; if (!isset($currentParams["service"]) || !isset($currentParams["action"])) { break; } kCurrentContext::$multiRequest_index++; $currentService = $currentParams["service"]; $currentAction = $currentParams["action"]; // copy derived common params to current params if (isset($commonParams['clientTag']) && !isset($currentParams['clientTag'])) { $currentParams['clientTag'] = $commonParams['clientTag']; } if (isset($commonParams['ks']) && !isset($currentParams['ks'])) { $currentParams['ks'] = $commonParams['ks']; } if (isset($commonParams['partnerId']) && !isset($currentParams['partnerId'])) { $currentParams['partnerId'] = $commonParams['partnerId']; } // cached parameters should be different when the request is part of a multirequest // as part of multirequest - the cached data is a serialized php object // when not part of multirequest - the cached data is the actual response $currentParams['multirequest'] = true; unset($currentParams['format']); $cache = new KalturaResponseCacher($currentParams); $success = true; $errorCode = null; $this->onRequestStart($currentService, $currentAction, $currentParams, kCurrentContext::$multiRequest_index, true); $cachedResult = $cache->checkCache('X-Kaltura-Part-Of-MultiRequest'); if ($cachedResult) { $currentResult = unserialize($cachedResult); } else { if (kCurrentContext::$multiRequest_index != 1) { kMemoryManager::clearMemory(); KalturaCriterion::clearTags(); } try { $currentResult = $this->dispatcher->dispatch($currentService, $currentAction, $currentParams); } catch (Exception $ex) { $success = false; $errorCode = $ex->getCode(); $currentResult = $this->getExceptionObject($ex, $currentService, $currentAction); } $cache->storeCache($currentResult, "", true); } $this->onRequestEnd($success, $errorCode, kCurrentContext::$multiRequest_index); for ($nextMultiRequestIndex = $i + 1; $nextMultiRequestIndex <= count($listOfRequests); $nextMultiRequestIndex++) { if (isset($multiRequestResultsPaths[$nextMultiRequestIndex])) { $listOfRequests[$nextMultiRequestIndex] = $this->replaceMultiRequestResults(kCurrentContext::$multiRequest_index, $multiRequestResultsPaths[$nextMultiRequestIndex], $listOfRequests[$nextMultiRequestIndex], $currentResult); } } $results[kCurrentContext::$multiRequest_index] = $this->serializer->serialize($currentResult); // in case a serve action is included in a multirequest, return only the result of the serve action // in order to avoid serializing the kRendererBase object and returning the internal server paths to the client if ($currentResult instanceof kRendererBase) { return $currentResult; } } return $results; }
protected function listEntriesByFilter(KalturaBaseEntryFilter $filter = null, KalturaFilterPager $pager = null) { myDbHelper::$use_alternative_con = myDbHelper::DB_HELPER_CONN_PROPEL3; $disableWidgetSessionFilters = false; if ($filter && ($filter->idEqual != null || $filter->idIn != null || $filter->referenceIdEqual != null || $filter->referenceIdIn != null)) { $disableWidgetSessionFilters = true; } if (!$pager) { $pager = new KalturaFilterPager(); } $c = $this->prepareEntriesCriteriaFilter($filter, $pager); if ($disableWidgetSessionFilters) { KalturaCriterion::disableTag(KalturaCriterion::TAG_WIDGET_SESSION); } $list = entryPeer::doSelect($c); $totalCount = $c->getRecordsCount(); if ($disableWidgetSessionFilters) { KalturaCriterion::restoreTag(KalturaCriterion::TAG_WIDGET_SESSION); } return array($list, $totalCount); }
public static function clearTags() { self::$enabledTags = array('TAG_PARTNER_SESSION' => 0); }
/** * Get web playable Flavor Assets for Entry * * @action getWebPlayableByEntryId * @param string $entryId * @return KalturaFlavorAssetArray */ public function getWebPlayableByEntryIdAction($entryId) { // entry could be "display_in_search = 2" - in that case we want to pull it although KN is off in services.ct for this action $c = KalturaCriteria::create(entryPeer::OM_CLASS); $c->addAnd(entryPeer::ID, $entryId); $criterionPartnerOrKn = $c->getNewCriterion(entryPeer::PARTNER_ID, $this->getPartnerId()); $criterionPartnerOrKn->addOr($c->getNewCriterion(entryPeer::DISPLAY_IN_SEARCH, mySearchUtils::DISPLAY_IN_SEARCH_KALTURA_NETWORK)); $c->addAnd($criterionPartnerOrKn); // there could only be one entry because the query is by primary key. // so using doSelectOne is safe. KalturaCriterion::disableTag(KalturaCriterion::TAG_WIDGET_SESSION); $dbEntry = entryPeer::doSelectOne($c); KalturaCriterion::restoreTag(KalturaCriterion::TAG_WIDGET_SESSION); if (!$dbEntry) { throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId); } $flavorAssetsDb = assetPeer::retrieveReadyWebByEntryId($entryId); if (count($flavorAssetsDb) == 0) { throw new KalturaAPIException(KalturaErrors::NO_FLAVORS_FOUND); } $flavorAssets = KalturaFlavorAssetArray::fromDbArray($flavorAssetsDb); return $flavorAssets; }
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)); }
public function reSetDirectSubCategoriesCount() { $partnerId = kCurrentContext::$partner_id ? kCurrentContext::$partner_id : kCurrentContext::$ks_partner_id; $c = KalturaCriteria::create(categoryPeer::OM_CLASS); $c->add(categoryPeer::STATUS, array(CategoryStatus::DELETED, CategoryStatus::PURGED), Criteria::NOT_IN); $c->add(categoryPeer::PARENT_ID, $this->getId(), Criteria::EQUAL); KalturaCriterion::disableTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY); $c->applyFilters(); KalturaCriterion::restoreTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY); $this->setDirectSubCategoriesCount($c->getRecordsCount()); }
/** * Get category by full name using exact match (returns null or category object) * * @param $fullName * @param $ignoreCategoryId * @param $partnerId * @return category */ public static function getByFullNameExactMatch($fullName, $ignoreCategoryId = null, $partnerId = null) { $fullName = self::getParsedFullName($fullName); if (trim($fullName) == '') { return null; } $c = KalturaCriteria::create(categoryPeer::OM_CLASS); $c->add(categoryPeer::FULL_NAME, $fullName); if ($ignoreCategoryId) { $c->add(categoryPeer::ID, $ignoreCategoryId, Criteria::NOT_EQUAL); } $tagDisabled = false; if (!is_null($partnerId)) { $tagDisabled = true; KalturaCriterion::disableTag(KalturaCriterion::TAG_PARTNER_SESSION); $c->add(categoryPeer::PARTNER_ID, $partnerId); } $ret = categoryPeer::doSelectOne($c); if ($tagDisabled) { KalturaCriterion::restoreTag(KalturaCriterion::TAG_PARTNER_SESSION); } return $ret; }
public function addIndexCategoryInheritedTreeJob($fullIdsStartsWithCategoryId) { $featureStatusToRemoveIndex = new kFeatureStatus(); $featureStatusToRemoveIndex->setType(IndexObjectType::CATEGORY); $featureStatusesToRemove = array(); $featureStatusesToRemove[] = $featureStatusToRemoveIndex; $filter = new categoryFilter(); $filter->setFullIdsStartsWith($fullIdsStartsWithCategoryId); $filter->setInheritanceTypeEqual(InheritanceType::INHERIT); $c = KalturaCriteria::create(categoryPeer::OM_CLASS); $filter->attachToCriteria($c); KalturaCriterion::disableTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY); $categories = categoryPeer::doSelect($c); KalturaCriterion::restoreTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY); if (count($categories)) { kJobsManager::addIndexJob($this->getPartnerId(), IndexObjectType::CATEGORY, $filter, true, $featureStatusesToRemove); } }
/** * 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); } } } }
private static function applyEntitlementCriteria(Criteria &$c) { $skipApplyFilters = false; if (kEntitlementUtils::getEntitlementEnforcement() && KalturaCriterion::isTagEnable(KalturaCriterion::TAG_ENTITLEMENT_ENTRY) && self::$kuserBlongToMoreThanMaxCategoriesForSearch && !$c->getOffset()) { KalturaCriterion::disableTag(KalturaCriterion::TAG_ENTITLEMENT_ENTRY); $entitlementCrit = clone $c; $entitlementCrit->applyFilters(); KalturaCriterion::restoreTag(KalturaCriterion::TAG_ENTITLEMENT_ENTRY); if ($entitlementCrit->getRecordsCount() < $entitlementCrit->getLimit()) { $c = $entitlementCrit; $c->setRecordsCount($entitlementCrit->getRecordsCount()); $skipApplyFilters = true; self::$filerResults = true; } else { self::$filerResults = false; //TODO add header that not full search } } return $skipApplyFilters; }
/** * List base entries by filter according to reference id * * @action listByReferenceId * @param string $refId Entry Reference ID * @param KalturaFilterPager $pager Pager * @throws KalturaErrors::MISSING_MANDATORY_PARAMETER */ function listByReferenceId($refId, KalturaFilterPager $pager = null) { if (!$refId) { //if refId wasn't provided return an error of missing parameter throw new KalturaAPIException(KalturaErrors::MISSING_MANDATORY_PARAMETER, $refId); } if (!$pager) { $pager = new KalturaFilterPager(); } $entryFilter = new entryFilter(); $entryFilter->setPartnerSearchScope(baseObjectFilter::MATCH_KALTURA_NETWORK_AND_PRIVATE); //setting reference ID $entryFilter->set('_eq_reference_id', $refId); $c = KalturaCriteria::create(entryPeer::OM_CLASS); $pager->attachToCriteria($c); $entryFilter->attachToCriteria($c); $c->add(entryPeer::DISPLAY_IN_SEARCH, mySearchUtils::DISPLAY_IN_SEARCH_SYSTEM, Criteria::NOT_EQUAL); KalturaCriterion::disableTag(KalturaCriterion::TAG_WIDGET_SESSION); $list = entryPeer::doSelect($c); KalturaCriterion::restoreTag(KalturaCriterion::TAG_WIDGET_SESSION); $totalCount = $c->getRecordsCount(); $newList = KalturaBaseEntryArray::fromEntryArray($list, false); $response = new KalturaBaseEntryListResponse(); $response->objects = $newList; $response->totalCount = $totalCount; return $response; }
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; }
public function getEntitledKusers() { $entitledKusersPublish = explode(',', $this->getEntitledKusersPublish()); $entitledKusersEdit = explode(',', $this->getEntitledKusersEdit()); $entitledKusersNoPrivacyContext = array_merge($entitledKusersPublish, $entitledKusersEdit); $entitledKusersNoPrivacyContext[] = $this->getKuserId(); foreach ($entitledKusersNoPrivacyContext as $key => $value) { if (!$value) { unset($entitledKusersNoPrivacyContext[$key]); } } $entitledKusers = array(); if (count(array_unique($entitledKusersNoPrivacyContext))) { $entitledKusers[kEntitlementUtils::ENTRY_PRIVACY_CONTEXT] = array_unique($entitledKusersNoPrivacyContext); } $allCategoriesIds = $this->getAllCategoriesIds(true); if (!count($allCategoriesIds)) { return kEntitlementUtils::ENTRY_PRIVACY_CONTEXT . '_' . implode(' ' . kEntitlementUtils::ENTRY_PRIVACY_CONTEXT . '_', $entitledKusersNoPrivacyContext); } $categoryGroupSize = kConf::get('max_number_of_memebrs_to_be_indexed_on_entry'); $partner = $this->getPartner(); if ($partner && $partner->getCategoryGroupSize()) { $categoryGroupSize = $partner->getCategoryGroupSize(); } //get categories for this entry that have small amount of members. $c = KalturaCriteria::create(categoryPeer::OM_CLASS); $c->add(categoryPeer::ID, $allCategoriesIds, Criteria::IN); $c->add(categoryPeer::MEMBERS_COUNT, $categoryGroupSize, Criteria::LESS_EQUAL); $c->add(categoryPeer::ENTRIES_COUNT, kConf::get('category_entries_count_limit_to_be_indexed'), Criteria::LESS_EQUAL); $c->dontCount(); KalturaCriterion::disableTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY); $categories = categoryPeer::doSelect($c); KalturaCriterion::restoreTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY); //get all memebrs foreach ($categories as $category) { if (!count($category->getMembers())) { continue; } $privacyContexts = explode(',', $category->getPrivacyContexts()); if (!count($privacyContexts)) { $privacyContexts = array(kEntitlementUtils::DEFAULT_CONTEXT . $this->getPartnerId()); } foreach ($privacyContexts as $privacyContext) { $privacyContext = trim($privacyContext); if (isset($entitledKusers[$privacyContext])) { $entitledKusers[$privacyContext] = array_merge($entitledKusers[$privacyContext], $category->getMembers()); } else { $entitledKusers[$privacyContext] = $category->getMembers(); } } } $entitledKusersByContexts = array(); foreach ($entitledKusers as $privacyContext => $kusers) { $entitledKusersByContexts[] = $privacyContext . '_' . implode(' ' . $privacyContext . '_', $kusers); } return implode(' ', $entitledKusersByContexts); }
public static function filterEntriesByPartnerOrKalturaNetwork(array $entryIds, $partnerId) { $c = KalturaCriteria::create(entryPeer::OM_CLASS); $c->addAnd(entryPeer::ID, $entryIds, Criteria::IN); $criterionPartnerOrKn = $c->getNewCriterion(entryPeer::PARTNER_ID, $partnerId); $criterionPartnerOrKn->addOr($c->getNewCriterion(entryPeer::DISPLAY_IN_SEARCH, mySearchUtils::DISPLAY_IN_SEARCH_KALTURA_NETWORK)); $c->addAnd($criterionPartnerOrKn); KalturaCriterion::disableTag(KalturaCriterion::TAG_WIDGET_SESSION); $dbEntries = self::doSelect($c); KalturaCriterion::restoreTag(KalturaCriterion::TAG_WIDGET_SESSION); $entryIds = array(); foreach ($dbEntries as $dbEntry) { $entryIds[] = $dbEntry->getId(); } return $entryIds; }