protected function deleteFilesPHP($searchPath, $minutesOld, $simulateOnly) { $secondsOld = $minutesOld * 60; $files = glob($searchPath); KalturaLog::debug("Found [" . count($files) . "] to scan"); $now = time(); KalturaLog::debug("The time now is: " . date('c', $now)); KalturaLog::debug("Deleting files that are " . $secondsOld . " seconds old (modified before " . date('c', $now - $secondsOld) . ")"); $deletedCount = 0; foreach ($files as $file) { $filemtime = filemtime($file); if ($filemtime > $now - $secondsOld) { continue; } if ($simulateOnly) { KalturaLog::debug("Simulating: Deleting file [{$file}], it's last modification time was " . date('c', $filemtime)); continue; } KalturaLog::debug("Deleting file [{$file}], it's last modification time was " . date('c', $filemtime)); $res = @unlink($file); if (!$res) { KalturaLog::debug("Error: problem while deleting [{$file}]"); continue; } $deletedCount++; } KalturaLog::debug("Deleted {$deletedCount} files"); }
public function apply(KalturaRelatedFilter $filter, KalturaObject $parentObject) { $filterProperty = $this->filterProperty; $parentProperty = $this->parentProperty; KalturaLog::debug("Mapping XPath {$parentProperty} to " . get_class($filter) . "::{$filterProperty}"); if (!$parentObject instanceof KalturaMetadata) { throw new KalturaAPIException(KalturaErrors::INVALID_OBJECT_TYPE, get_class($parentObject)); } if (!property_exists($filter, $filterProperty)) { throw new KalturaAPIException(KalturaErrors::PROPERTY_IS_NOT_DEFINED, $filterProperty, get_class($filter)); } $xml = $parentObject->xml; $doc = new KDOMDocument(); $doc->loadXML($xml); $xpath = new DOMXPath($doc); $metadataElements = $xpath->query($parentProperty); if ($metadataElements->length == 1) { $filter->{$filterProperty} = $metadataElements->item(0)->nodeValue; } elseif ($metadataElements->length > 1) { $values = array(); foreach ($metadataElements as $element) { $values[] = $element->nodeValue; } $filter->{$filterProperty} = implode(',', $values); } elseif (!$this->allowNull) { return false; } return true; }
public function validateForSubmission(EntryDistribution $entryDistribution, $action) { $validationErrors = parent::validateForSubmission($entryDistribution, $action); //validation of flavor format $flavorAsset = null; $flavorAssets = assetPeer::retrieveByIds(explode(',', $entryDistribution->getFlavorAssetIds())); // if we have specific flavor assets for this distribution, grab the first one if (count($flavorAssets)) { $flavorAsset = reset($flavorAssets); $fileExt = $flavorAsset->getFileExt(); $allowedExts = explode(',', self::FLAVOR_VALID_FORMATS); if (!in_array($fileExt, $allowedExts)) { KalturaLog::debug('flavor asset id [' . $flavorAsset->getId() . '] does not have a valid extension [' . $fileExt . ']'); $errorMsg = 'Flavor format must be one of [' . self::FLAVOR_VALID_FORMATS . ']'; $validationError = $this->createValidationError($action, DistributionErrorType::INVALID_DATA); $validationError->setValidationErrorType(DistributionValidationErrorType::CUSTOM_ERROR); $validationError->setValidationErrorParam($errorMsg); $validationError->setDescription($errorMsg); $validationErrors[] = $validationError; } } $inListOrNullFields = array(IdeticDistributionField::GENRE => explode(',', self::GENRE_VALID_VALUES)); $allFieldValues = $this->getAllFieldValues($entryDistribution); if (!$allFieldValues || !is_array($allFieldValues)) { KalturaLog::err('Error getting field values from entry distribution id [' . $entryDistribution->getId() . '] profile id [' . $this->getId() . ']'); return $validationErrors; } $validationErrors = array_merge($validationErrors, $this->validateInListOrNull($inListOrNullFields, $allFieldValues, $action)); //validating Slot is a whole number $validationErrors = array_merge($validationErrors, $this->validateIsWholeNumber(IdeticDistributionField::SLOT, $allFieldValues, $action)); return $validationErrors; }
private function recalculate(KalturaBatchJob $job, KalturaRecalculateCacheJobData $data) { KalturaLog::debug("Recalculate job id [{$job->id}]"); $engine = KRecalculateCacheEngine::getInstance($job->jobSubType); $recalculatedObjects = $engine->recalculate($data); return $this->closeJob($job, null, null, "Recalculated {$recalculatedObjects} cache objects", KalturaBatchJobStatus::FINISHED); }
/** * @param entry $object * @return bool true if should continue to the next consumer */ public function entryCreated(entry $object) { $mediaType = null; if ($object->getType() == entryType::AUTOMATIC) { KalturaLog::debug("entry id [" . $object->getId() . "] type [" . $object->getType() . "] source link [" . $object->getSourceLink() . "]"); $mediaType = $object->getMediaType(); if (isset(self::$fileExtensions[$mediaType])) { $object->setType(entryType::DOCUMENT); } elseif (is_null($mediaType) || $mediaType == entry::ENTRY_MEDIA_TYPE_ANY || $mediaType == entry::ENTRY_MEDIA_TYPE_AUTOMATIC) { $this->setDocumentType($object); } } if ($object->getType() != entryType::DOCUMENT) { KalturaLog::debug("entry id [" . $object->getId() . "] type [" . $object->getType() . "]"); return true; } if (is_null($mediaType) || $mediaType == entry::ENTRY_MEDIA_TYPE_ANY || $mediaType == entry::ENTRY_MEDIA_TYPE_AUTOMATIC) { $this->setDocumentType($object); } if ($object instanceof DocumentEntry) { KalturaLog::debug("entry id [" . $object->getId() . "] already handled"); return true; } KalturaLog::debug("Handling object [" . get_class($object) . "] type [" . $object->getType() . "] id [" . $object->getId() . "] status [" . $object->getStatus() . "]"); if ($object->getConversionProfileId()) { $object->setStatus(entryStatus::PRECONVERT); $object->save(); } return true; }
public function doFromObject($dbObject, KalturaDetachedResponseProfile $responseProfile = null) { /* @var $dbObject kHttpNotificationDataText */ parent::doFromObject($dbObject, $responseProfile); if ($this->shouldGet('content', $responseProfile)) { $contentType = get_class($dbObject->getContent()); KalturaLog::debug("Loading KalturaStringValue from type [{$contentType}]"); switch ($contentType) { case 'kStringValue': $this->content = new KalturaStringValue(); break; case 'kEvalStringField': $this->content = new KalturaEvalStringField(); break; default: $this->content = KalturaPluginManager::loadObject('KalturaStringValue', $contentType); break; } if ($this->content) { $this->content->fromObject($dbObject->getContent()); } } if ($this->shouldGet('data', $responseProfile)) { $this->data = $dbObject->getData(); } }
/** * Will return a JS library for integrating the KSR (similar to HTML5 in concept) * uiconfId specifies from which uiconf to fetch different settings that should be replaced in the JS */ public function execute() { // make sure output is not parsed as HTML header("Content-type: application/x-javascript"); $uiconfId = $this->getRequestParameter("uiconfId"); // replace all $_GET with $this->getRequestParameter() // load uiconf from DB. $this->uiconfObj = uiConfPeer::retrieveByPK($uiconfId); if (!$this->uiconfObj) { KExternalErrors::dieError(KExternalErrors::UI_CONF_NOT_FOUND); } $ui_conf_swf_url = $this->uiconfObj->getSwfUrl(); if (!$ui_conf_swf_url) { KExternalErrors::dieError(KExternalErrors::ILLEGAL_UI_CONF, "SWF URL not found in UI conf"); } @libxml_use_internal_errors(true); try { $this->uiconfXmlObj = new SimpleXMLElement(trim($this->uiconfObj->getConfFile())); } catch (Exception $e) { KalturaLog::debug("malformed uiconf XML - base64 encoded: [" . base64_encode(trim($this->uiconfObj->getConfFile())) . "]"); } if (!$this->uiconfXmlObj instanceof SimpleXMLElement) { // no xml or invalid XML, so throw exception throw new Exception('uiconf XML is invalid'); } // unsupress the xml errors @libxml_use_internal_errors(false); $this->_initReplacementTokens(); $this->_prepareLibJs(); $this->_prepareJs(); echo $this->jsResult; die; }
public static function getExclusiveFile($path, $process_id = 1, $log_number_of_files = false) { $indicators = glob($path . "/*" . self::INDICATOR_SUFFIX); $count = count($indicators); if ($count > 0 || $log_number_of_files) { KalturaLog::debug("[" . $count . "] indicator in directory [" . $path . "]"); } if ($indicators == null || count($indicators) == 0) { return null; } foreach ($indicators as $indicator) { $new_indicator = $indicator . "-{$process_id}"; $move_res = @rename($indicator, $new_indicator); // only one server will actually move the indicator ... if ($move_res) { $file = str_replace(kConversionCommand::INDICATOR_SUFFIX, "", $indicator); $file_name = basename($file); // now remove the indicator //unlink( $new_indicator ); // move to in-proc $in_proc = self::inProcFromIndicator($indicator); @rename($new_indicator, $in_proc); return array($file, $file_name, $in_proc); } else { KalturaLog::debug("[{$indicator}] grabbed by other process"); } // keep on trying ... } return null; }
protected function doOperation() { KalturaLog::debug('start ISM Manifest merge'); if (!$this->data->srcFileSyncs) { return true; } $ismFilePath = $this->outFilePath . ".ism"; $ismcFilePath = $this->outFilePath . ".ismc"; $ismcStr = $this->mergeIsmcManifests($this->data->srcFileSyncs); file_put_contents($ismcFilePath, $ismcStr); $ismStr = $this->mergeIsmManifests($this->data->srcFileSyncs, $ismcFilePath); file_put_contents($ismFilePath, $ismStr); $destFileSyncDescArr = array(); $fileSyncDesc = new KalturaDestFileSyncDescriptor(); $fileSyncDesc->fileSyncLocalPath = $ismFilePath; $fileSyncDesc->fileSyncObjectSubType = 1; //".ism"; $destFileSyncDescArr[] = $fileSyncDesc; $fileSyncDesc = new KalturaDestFileSyncDescriptor(); $fileSyncDesc->fileSyncLocalPath = $ismcFilePath; $fileSyncDesc->fileSyncObjectSubType = 4; //".ismc"; $destFileSyncDescArr[] = $fileSyncDesc; $this->data->extraDestFileSyncs = $destFileSyncDescArr; $this->data->destFileSyncLocalPath = null; $this->outFilePath = null; return true; }
/** * @return array */ protected function getSecureHdUrl() { $params = array(); if ($this->getSupportClipping()) { $seekStart = $this->params->getSeekFromTime(); $seekEnd = $this->params->getClipTo(); if ($seekStart != -1) { $params['start'] = floor($this->params->getSeekFromTime() / 1000); $this->params->setSeekFromTime(-1); } else { if ($seekEnd) { $params['start'] = 0; } } if ($seekEnd) { $params['end'] = ceil($this->params->getClipTo() / 1000); $this->params->setClipTo(null); } } $flavors = $this->buildHttpFlavorsArray(); $flavors = $this->sortFlavors($flavors); $flavor = AkamaiDeliveryUtils::getHDN2ManifestUrl($flavors, $this->params->getMediaProtocol(), $this->getUrl(), '/master.m3u8', '/i', $params); if (!$flavor) { KalturaLog::debug(get_class() . ' failed to find flavor'); return null; } return $flavor; }
/** * Get license for encrypted content playback * * @action getLicense * @param string $flavorAssetId * @param string $referrer 64base encoded * @return string $response * */ public function getLicenseAction($flavorAssetId, $referrer = null) { KalturaResponseCacher::disableCache(); KalturaLog::debug('get license for flavor asset: ' . $flavorAssetId); try { $requestParams = requestUtils::getRequestParams(); if (!array_key_exists(WidevineLicenseProxyUtils::ASSETID, $requestParams)) { KalturaLog::err('assetid is missing on the request'); return WidevineLicenseProxyUtils::createErrorResponse(KalturaWidevineErrorCodes::WIDEVINE_ASSET_ID_CANNOT_BE_NULL, 0); } $wvAssetId = $requestParams[WidevineLicenseProxyUtils::ASSETID]; $this->validateLicenseRequest($flavorAssetId, $wvAssetId, $referrer); $privileges = null; $isAdmin = false; if (kCurrentContext::$ks_object) { $privileges = kCurrentContext::$ks_object->getPrivileges(); $isAdmin = kCurrentContext::$ks_object->isAdmin(); } $response = WidevineLicenseProxyUtils::sendLicenseRequest($requestParams, $privileges, $isAdmin); } catch (KalturaWidevineLicenseProxyException $e) { KalturaLog::err($e); $response = WidevineLicenseProxyUtils::createErrorResponse($e->getWvErrorCode(), $wvAssetId); } catch (Exception $e) { KalturaLog::err($e); $response = WidevineLicenseProxyUtils::createErrorResponse(KalturaWidevineErrorCodes::GENERAL_ERROR, $wvAssetId); } WidevineLicenseProxyUtils::printLicenseResponseStatus($response); return $response; }
/** * Will return the first virus scan profile of the entry's partner, that defines an entry filter suitable for the given entry. * @param int $entryId * @return VirusScanProfile the suitable profile object, or null if none found */ public static function getSuitableProfile($entryId) { $entry = entryPeer::retrieveByPK($entryId); if (!$entry) { KalturaLog::err('Cannot find entry with id [' . $entryId . ']'); return null; } if ($entry->getSource() == entry::ENTRY_MEDIA_SOURCE_WEBCAM) { return null; } $cProfile = new Criteria(); $cProfile->addAnd(VirusScanProfilePeer::PARTNER_ID, $entry->getPartnerId()); $cProfile->addAnd(VirusScanProfilePeer::STATUS, VirusScanProfileStatus::ENABLED, Criteria::EQUAL); $profiles = VirusScanProfilePeer::doSelect($cProfile); if (!$profiles) { KalturaLog::debug('No virus scan profiles found for partner [' . $entry->getPartnerId() . ']'); return null; } foreach ($profiles as $profile) { $virusEntryFilter = $profile->getEntryFilterObject(); if ($virusEntryFilter->matches($entry)) { KalturaLog::debug('Returning profile with id [' . $profile->getId() . ']'); return $profile; } } return null; }
/** * @param int $taskIndex * @param string $logDir * @param string $phpPath * @param string $tasksetPath * @param KSchedularTaskConfig $taskConfig */ public function __construct($taskIndex, $logDir, $phpPath, $tasksetPath, KSchedularTaskConfig $taskConfig) { $taskConfig->setTaskIndex($taskIndex); $logName = str_replace('kasync', '', strtolower($taskConfig->name)); $logDate = date('Y-m-d'); $logFile = "{$logDir}/{$logName}-{$taskIndex}-{$logDate}.log"; $sysLogFile = "{$taskConfig->name}.{$taskIndex}"; $this->taskConfig = $taskConfig; $taskConfigStr = base64_encode(serialize($taskConfig)); $cmdLine = ''; $cmdLine .= is_null($taskConfig->affinity) ? '' : "{$tasksetPath} -c " . ($taskConfig->affinity + $taskIndex) . ' '; $cmdLine = "{$phpPath} "; $cmdLine .= "{$taskConfig->scriptPath} "; $cmdLine .= "{$taskConfigStr} "; $cmdLine .= "'[" . mt_rand() . "]' "; if ($taskConfig->getUseSyslog()) { $cmdLine .= "2>&1 | logger -t {$sysLogFile}"; } else { $cmdLine .= ">> {$logFile} 2>&1"; } $descriptorspec = array(); // stdin is a pipe that the child will read from // $descriptorspec = array(0 => array("pipe", "r")); // stdin is a pipe that the child will read from // 1 => array ( "file" ,$logFile , "a" ) , // 2 => array ( "file" ,$logFile , "a" ) , // 1 => array("pipe", "w"), // stdout is a pipe that the child will write to // 2 => array("pipe", "w"), // stdout is a pipe that the child will write to // 2 => array("file", "{$work_dir}/error-output.txt", "a") // stderr is a file to write to $other_options = array('suppress_errors' => FALSE, 'bypass_shell' => FALSE); KalturaLog::debug("Now executing [{$cmdLine}], [{$other_options}]"); $process = proc_open($cmdLine, $descriptorspec, $pipes, null, null, $other_options); $this->pipes = $pipes; $this->handle = $process; $this->dieTime = time() + $taskConfig->maximumExecutionTime + 5; }
public function execute() { $ksStr = $this->getP("ks"); if ($ksStr) { $ksObj = null; try { $ksObj = ks::fromSecureString($ksStr); } catch (Exception $e) { } if ($ksObj) { $partner = PartnerPeer::retrieveByPK($ksObj->partner_id); if (!$partner) { KExternalErrors::dieError(KExternalErrors::PARTNER_NOT_FOUND); } if (!$partner->validateApiAccessControl()) { KExternalErrors::dieError(KExternalErrors::SERVICE_ACCESS_CONTROL_RESTRICTED); } $ksObj->kill(); } KalturaLog::debug("Killing session with ks - [{$ksStr}], decoded - [" . base64_decode($ksStr) . "]"); } else { KalturaLog::err('logoutAction called with no KS'); } setcookie('pid', "", 0, "/"); setcookie('subpid', "", 0, "/"); setcookie('kmcks', "", 0, "/"); return sfView::NONE; //redirection to kmc/kmc is done from java script }
/** * Tests EntryDistributionService->addAction() * @param KalturaEntryDistribution $entryDistribution * @return int * @dataProvider provideData */ public function testAdd(KalturaEntryDistribution $entryDistribution) { try { $resultEntryDistribution = $this->client->entryDistribution->add($entryDistribution); $this->assertType('KalturaEntryDistribution', $resultEntryDistribution); $this->assertNotNull($resultEntryDistribution->id); KalturaLog::debug("Returns Entry Distribution ID [{$resultEntryDistribution->id}]"); return $resultEntryDistribution->id; } catch (KalturaException $e) { KalturaLog::err("Add EntryDistribution Exception code [" . $e->getCode() . "] message [" . $e->getMessage() . "]"); if ($e->getCode() != 'ENTRY_DISTRIBUTION_ALREADY_EXISTS') { throw $e; } } $entryDistributionFilter = new KalturaEntryDistributionFilter(); $entryDistributionFilter->entryIdIn = $entryDistribution->entryId; $entryDistributionFilter->distributionProfileIdEqual = $entryDistribution->distributionProfileId; $entryDistributionList = $this->client->entryDistribution->listAction($entryDistributionFilter); $this->assertType('KalturaEntryDistributionListResponse', $entryDistributionList); $this->assertNotEquals($entryDistributionList->totalCount, 0); $this->assertEquals($entryDistributionList->totalCount, count($entryDistributionList->objects)); $resultEntryDistribution = reset($entryDistributionList->objects); $this->assertType('KalturaEntryDistribution', $resultEntryDistribution); $this->assertNotNull($resultEntryDistribution->id); KalturaLog::debug("Returns Entry Distribution ID [{$resultEntryDistribution->id}]"); return $resultEntryDistribution->id; }
public function doFromObject($source_object, KalturaDetachedResponseProfile $responseProfile = null) { parent::doFromObject($source_object, $responseProfile); /* @var $source_object kBulkUploadFilterJobData */ $this->filter = null; switch (get_class($source_object->getFilter())) { case 'categoryEntryFilter': $this->filter = new KalturaCategoryEntryFilter(); break; case 'entryFilter': $this->filter = new KalturaBaseEntryFilter(); break; default: break; } if ($this->filter) { KalturaLog::debug("Filter class was found: " . get_class($this->filter)); $this->filter->fromObject($source_object->getFilter()); } $this->templateObject = null; KalturaLog::debug("template object class: " . get_class($source_object->getTemplateObject())); switch (get_class($source_object->getTemplateObject())) { case 'categoryEntry': $this->templateObject = new KalturaCategoryEntry(); break; default: break; } if ($this->templateObject) { KalturaLog::debug("Template object class was found: " . get_class($this->templateObject)); $this->templateObject->fromObject($source_object->getTemplateObject()); } }
protected function applyFilterFields(baseObjectFilter $filter) { /* @var $filter cuePointFilter */ // Reduce the cache expiry when fetching live stream cuepoints $entryId = $filter->get('_in_entry_id'); if ($entryId && strpos($entryId, ',') === false) { $entry = entryPeer::retrieveByPK($entryId); if ($entry && $entry->getType() == entryType::LIVE_STREAM) { kApiCache::setExpiry(self::LIVE_ENTRY_CUE_POINT_CACHE_EXPIRY_SECONDS); } } if ($filter->get('_free_text')) { $this->sphinxSkipped = false; $freeTexts = $filter->get('_free_text'); KalturaLog::debug("Attach free text [{$freeTexts}]"); $this->addFreeTextToMatchClauseByMatchFields($freeTexts, CuePointFilter::FREE_TEXT_FIELDS); } $filter->unsetByName('_free_text'); if ($filter->get('_eq_is_public')) { $this->sphinxSkipped = false; $isPublic = $filter->get('_eq_is_public'); $this->addCondition('is_public' . " = " . $isPublic); } $filter->unsetByName('_eq_is_public'); return parent::applyFilterFields($filter); }
private function syncCategoryPrivacyContext(KalturaBatchJob $job, KalturaSyncCategoryPrivacyContextJobData $data, $categoryId) { $categoryEntryPager = $this->getFilterPager(); $categoryEntryFilter = new KalturaCategoryEntryFilter(); $categoryEntryFilter->orderBy = KalturaCategoryEntryOrderBy::CREATED_AT_ASC; $categoryEntryFilter->categoryIdEqual = $categoryId; if ($data->lastUpdatedCategoryEntryCreatedAt) { $categoryEntryFilter->createdAtGreaterThanOrEqual = $data->lastUpdatedCategoryEntryCreatedAt; } $categoryEntryList = KBatchBase::$kClient->categoryEntry->listAction($categoryEntryFilter, $categoryEntryPager); while (count($categoryEntryList->objects)) { KBatchBase::$kClient->startMultiRequest(); foreach ($categoryEntryList->objects as $categoryEntry) { KalturaLog::debug('entryId ' . $categoryEntry->entryId . ' categoryId ' . $categoryEntry->categoryId); KBatchBase::$kClient->categoryEntry->syncPrivacyContext($categoryEntry->entryId, $categoryEntry->categoryId); } KBatchBase::$kClient->doMultiRequest(); $data->lastUpdatedCategoryEntryCreatedAt = $categoryEntry->createdAt; $categoryEntryPager->pageIndex++; KBatchBase::unimpersonate(); $this->updateJob($job, null, KalturaBatchJobStatus::PROCESSING, $data); KBatchBase::impersonate($job->partnerId); $categoryEntryList = KBatchBase::$kClient->categoryEntry->listAction($categoryEntryFilter, $categoryEntryPager); } }
protected function parseCreatedFiles() { $xmlPath = $this->outDir . DIRECTORY_SEPARATOR . $this->destFileName . '.ism'; KalturaLog::info("Parse created files from ism[{$xmlPath}]"); // in case of wma if (!file_exists($xmlPath)) { KalturaLog::info("ism file[{$xmlPath}] doesn't exist"); $wmaPath = $this->outDir . DIRECTORY_SEPARATOR . $this->destFileName . '.wma'; if (file_exists($wmaPath)) { KalturaLog::info("wma file[{$wmaPath}] found"); $this->outFilesPath[0] = $wmaPath; } return; } $xml = file_get_contents($xmlPath); $xml = mb_convert_encoding($xml, 'ASCII', 'UTF-16'); KalturaLog::debug("ism content:\n{$xml}"); $arr = null; if (preg_match('/(<smil[\\s\\w\\W]+<\\/smil>)/', $xml, $arr)) { $xml = $arr[1]; } file_put_contents($xmlPath, $xml); //echo $xml; $doc = new DOMDocument(); $doc->loadXML($xml); $videoEntities = $doc->getElementsByTagName('video'); foreach ($videoEntities as $videoEntity) { $src = $this->outDir . DIRECTORY_SEPARATOR . $videoEntity->getAttribute("src"); $bitrate = $videoEntity->getAttribute("systemBitrate") / 1000; KalturaLog::info("Media found in ism bitrate[{$bitrate}] source[{$src}]"); $this->outFilesPath[$bitrate] = $src; } }
public function objectReplaced(BaseObject $object, BaseObject $replacingObject, BatchJob $raisedJob = null) { KalturaLog::debug("check for DRM key replacement"); try { $replacingDrmKey = $this->getDrmKey($replacingObject); if ($replacingDrmKey) { $newKeyId = $replacingDrmKey->getDrmKey(); KalturaLog::debug("replacing drm key with: " . $newKeyId); $entryDrmKey = $this->getDrmKey($object); if (!$entryDrmKey) { $entryDrmKey = new DrmKey(); $entryDrmKey->setPartnerId($object->getPartnerId()); $entryDrmKey->setObjectId($object->getId()); $entryDrmKey->setObjectType(DrmKeyObjectType::ENTRY); $entryDrmKey->setProvider(PlayReadyPlugin::getPlayReadyProviderCoreValue()); } $entryDrmKey->setDrmKey($newKeyId); $entryDrmKey->save(); $object->putInCustomData(PlayReadyPlugin::ENTRY_CUSTOM_DATA_PLAY_READY_KEY_ID, $newKeyId); $object->save(); } } catch (Exception $e) { KalturaLog::err("Failed to update drm key for entry " . $object->getId()); } return true; }
private function call($method, $args = array()) { KalturaLog::debug("Call [{$method}] args [" . print_r($args, true) . "]"); $result = $this->api->call($method, $args); KalturaLog::debug("Result [" . print_r($result, true) . "]"); return $result; }
protected function doOperation() { KalturaLog::debug('starting smil manifest operation'); if (!$this->data->srcFileSyncs) { return true; } $smilTemplate = $this->getSmilTemplate(); $xpath = new DOMXPath($smilTemplate); $wrapperElement = $xpath->query('/smil/body/switch')->item(0); foreach ($this->data->srcFileSyncs as $srcFileSync) { /** @var KalturaSourceFileSyncDescriptor $srcFileSync */ $fileName = pathinfo($srcFileSync->actualFileSyncLocalPath, PATHINFO_BASENAME); $bitrate = $this->getBitrateForAsset($srcFileSync->assetId); $this->addSmilVideo($wrapperElement, $fileName, $bitrate); } $smilFilePath = $this->outFilePath . ".smil"; $smilData = $smilTemplate->saveXML(); file_put_contents($smilFilePath, $smilData); $destFileSyncDescArr = array(); $fileSyncDesc = new KalturaDestFileSyncDescriptor(); $fileSyncDesc->fileSyncLocalPath = $smilFilePath; $fileSyncDesc->fileSyncObjectSubType = 1; // asset; $destFileSyncDescArr[] = $fileSyncDesc; $this->data->extraDestFileSyncs = $destFileSyncDescArr; $this->data->destFileSyncLocalPath = null; $this->outFilePath = null; return true; }
/** * Get the total VOD offset for a given time. Total = the sum of all VOD delta times throughout the segments. * @return int|null The offset that should be subtracted from the given time, or * null to indicate that this time signature is in the gap between the end * of a VOD segment and the end of the live segment (marked with x's below). * <pre> * Live Start VOD End Live End * ^ ^ ^ * | |xxxxxxxxxxx| * +------------------+-----------+ * </pre> */ public function getTotalVodTimeOffset($time) { $numSegments = count($this->segments); $totalVodOffset = 0; // Initially zero because there's no time drift in the first segment. $i = 0; $dbgPrevSegment = null; while ($i < $numSegments) { $segment = $this->segments[$i]; $liveStart = $segment[self::LIVE_START]; $vodAdjustedEndTime = $this->getVodAdjustedEndTime($segment); if ($time <= $vodAdjustedEndTime) { if ($time >= $liveStart) { return $totalVodOffset; } else { KalturaLog::debug("Time [{$time}] <= {$vodAdjustedEndTime} but not >= {$liveStart}. Segment data: {$this->segmentAsString($dbgPrevSegment)}"); return null; } } else { // Add up this segment's offset and move on to the next segment $totalVodOffset += $segment[self::VOD_TO_LIVE_DELTA_TIME]; $dbgPrevSegment = $segment; $i++; } } // The time signature is greater than the total VOD duration KalturaLog::debug("Couldn't get offset for time [{$time}]. Segment data: {$this->segmentAsString($segment)}"); return null; }
protected function createOutputDirectory() { if (!kFile::fullMkfileDir($this->outFilePath)) { KalturaLog::debug('failed to create [' . $this->outFilePath . '] directory'); throw new KOperationEngineException('failed to create [' . $this->outFilePath . '] directory'); } }
public static function getIdByStrId($strId) { // try to get strId to id mapping form cache $cacheKey = 'UserRolePeer_role_str_id_' . $strId; if (kConf::get('enable_cache') && function_exists('apc_fetch') && function_exists('apc_store')) { $id = apc_fetch($cacheKey); // try to fetch from cache if ($id) { KalturaLog::debug("UserRole str_id [{$strId}] mapped to id [{$id}] - fetched from cache"); return $id; } } // not found in cache - get from database $c = new Criteria(); $c->addSelectColumn(UserRolePeer::ID); $c->addAnd(UserRolePeer::STR_ID, $strId, Criteria::EQUAL); $c->setLimit(1); $stmt = UserRolePeer::doSelectStmt($c); $id = $stmt->fetch(PDO::FETCH_COLUMN); if ($id) { // store the found id in cache for later use if (kConf::get('enable_cache') && function_exists('apc_fetch') && function_exists('apc_store')) { $success = apc_store($cacheKey, $id, kConf::get('apc_cache_ttl')); if ($success) { KalturaLog::debug("UserRole str_id [{$strId}] mapped to id [{$id}] - stored in cache"); } } } if (!$id) { KalturaLog::log("UserRole with str_id [{$strId}] not found in DB!"); } return $id; }
public function copyAssets(entry $toEntry, ThumbCuePoint $toCuePoint, $adjustedStartTime = null) { $timedThumbAsset = assetPeer::retrieveById($this->getAssetId()); if (!$timedThumbAsset) { KalturaLog::debug("Can't retrieve timedThumbAsset with id: {$this->getAssetId()}"); return; } // Offset the startTime according to the duration gap between the live and VOD entries if (!is_null($adjustedStartTime)) { $toCuePoint->setStartTime($adjustedStartTime); } $toCuePoint->save(); // Must save in order to produce an id $timedThumbAsset->setCuePointID($toCuePoint->getId()); // Set the destination cue point's id $timedThumbAsset->setCustomDataObj(); // Write the cached custom data object into the thumb asset // Make a copy of the current thumb asset // copyToEntry will create a filesync softlink to the original filesync $toTimedThumbAsset = $timedThumbAsset->copyToEntry($toEntry->getId(), $toEntry->getPartnerId()); $toCuePoint->setAssetId($toTimedThumbAsset->getId()); $toCuePoint->save(); // Restore the thumb asset's prev. cue point id (for good measures) $timedThumbAsset->setCuePointID($this->getId()); $timedThumbAsset->setCustomDataObj(); // Save the destination entry's thumb asset $toTimedThumbAsset->setCuePointID($toCuePoint->getId()); $toTimedThumbAsset->save(); KalturaLog::log("Saved cue point [{$toCuePoint->getId()}] and timed thumb asset [{$toTimedThumbAsset->getId()}]"); }
public function createQuestionPdf() { $dbEntry = entryPeer::retrieveByPK($this->entryId); $title = "Here are the questions from [" . $dbEntry->getName() . "]"; KalturaLog::debug("Questions from [" . $dbEntry->getName() . "]"); $this->pdf->addTitle($title, $this->titleStyle); $questionType = QuizPlugin::getCuePointTypeCoreValue(QuizCuePointType::QUIZ_QUESTION); $questions = CuePointPeer::retrieveByEntryId($this->entryId, array($questionType)); //arange the array so that the questions will be the key for the array $questArray = array(); foreach ($questions as $question) { $questArray[$question->getName()] = $question; } //sort the array alphabetically according to its key; i.e. the question ksort($questArray, SORT_LOCALE_STRING); $questNum = 0; foreach ($questArray as $question) { $questNum += 1; $this->pdf->addList($questNum, $question->getName(), $this->listWithAddLineBeforeStyle); $this->pdf->addHeadline(6, "Optional Answers:", $this->heading6Style); $ansNum = 0; foreach ($question->getOptionalAnswers() as $optionalAnswer) { $ansNum += 1; $this->pdf->addList($ansNum, $optionalAnswer->getText(), $this->indentListStyle); } } }
public function myServiceConfig($file_name, $service_name = null, $useDefualt = true) { $path = $this->getPath(); KalturaLog::debug("Path [{$path}] File [{$file_name}] Service [{$service_name}]"); $config_table_list = array(); if ($file_name == $this->getDefaultName()) { } else { if ($file_name) { $config_table_list[] = $path . $file_name; } } if (self::$secondary_config_tables) { // add the secondary before the end $config_table_list = array_merge($config_table_list, self::$secondary_config_tables); } // always append the defualt to the end if ($useDefualt) { $config_table_list[] = $path . $this->getDefaultName(); } // don't use the common path feature - add it to each config file separatly $this->config_chain = new kConfigTableChain($config_table_list, null); $tables = $this->config_chain->getTables(); self::$default_config_table = end($tables); $this->all_config_tables = $tables; if ($service_name) { $this->setServiceName($service_name); } }
public static function prepareNotificationData($url, $signature_key, KalturaBatchJob $job, KalturaNotificationJobData $data, $prefix = null) { KalturaLog::debug("sendSingleNotification({$url}, {$signature_key}, {$job->id}, data, {$prefix})"); $params = array("notification_id" => $job->id, "notification_type" => $data->typeAsString, "puser_id" => $data->userId, "partner_id" => $job->partnerId); switch ($data->objType) { case KalturaNotificationObjectType::USER: $params["user_id"] = $data->objectId; break; case KalturaNotificationObjectType::ENTRY: $params["entry_id"] = $data->objectId; break; case KalturaNotificationObjectType::KSHOW: $params["kshow_id"] = $data->objectId; break; case KalturaNotificationObjectType::BATCH_JOB: $params["job_id"] = $data->objectId; break; default: // VERY STARANGE - either objType not set properly or some error ! } $object_data_params = self::getDataAsArray($data->data); if ($object_data_params) { $params = array_merge($params, $object_data_params); } $params = self::fixParams($params, $prefix); $params['signed_fields'] = ''; foreach ($params as $key => $value) { $params['signed_fields'] .= $key . ','; } return self::signParams($signature_key, $params); }
/** * will return a pair of file_root and file_path * This is the only function that should be extended for building a different path * * @param ISyncableFile $object * @param int $subType * @param $version */ public function generateFilePathArr(ISyncableFile $object, $subType, $version = null) { // $traces = debug_backtrace(false); // foreach($traces as $i => $trace) // { // $file = $trace['file']; // $line = $trace['line']; // $class = $trace['class']; // $function = $trace['function']; // KalturaLog::debug("#$i Called from function [$class::$function] file[$file] line[$line]"); // } list($root, $path) = $object->generateFilePathArr($subType, $version); $root = str_replace('//', '/', $root); $path = str_replace('//', '/', $path); if (!kConf::hasParam('volumes')) { KalturaLog::debug("Path [{$root}{$path}]"); return array($root, $path); } if (isset(self::$sessionCache[$path])) { return array($root, self::$sessionCache[$path]); } $volumes = kConf::get('volumes'); $volume = $volumes[rand(0, count($volumes) - 1)]; $newPath = str_replace('/content/', "/content/{$volume}/", $path); self::$sessionCache[$path] = $newPath; $path = $newPath; KalturaLog::debug("Path [{$root}{$path}]"); return array($root, $path); }