protected function createDirDescriber($outDir, $fileName)
 {
     $fileList = kFile::dirList($outDir, false);
     $fileListXml = $this->createImagesListXML($fileList);
     kFile::setFileContent($outDir . DIRECTORY_SEPARATOR . $fileName, $fileListXml->asXML());
     KalturaLog::info('file list xml [' . $outDir . DIRECTORY_SEPARATOR . $fileName . '] created');
 }
 /**
  * @param string $type
  * @return KalturaTypeReflector
  */
 static function get($type)
 {
     if (!self::$_enabled) {
         return new KalturaTypeReflector($type);
     }
     if (!array_key_exists($type, self::$_loadedTypeReflectors)) {
         $cachedDir = KAutoloader::buildPath(kConf::get("cache_root_path"), "api_v3", "typeReflector");
         if (!is_dir($cachedDir)) {
             mkdir($cachedDir);
             chmod($cachedDir, 0755);
         }
         $cachedFilePath = $cachedDir . DIRECTORY_SEPARATOR . $type . ".cache";
         $typeReflector = null;
         if (file_exists($cachedFilePath)) {
             $cachedData = file_get_contents($cachedFilePath);
             $typeReflector = unserialize($cachedData);
         }
         if (!$typeReflector) {
             $typeReflector = new KalturaTypeReflector($type);
             $cachedData = serialize($typeReflector);
             $bytesWritten = kFile::safeFilePutContents($cachedFilePath, $cachedData);
             if (!$bytesWritten) {
                 $folderPermission = substr(decoct(fileperms(dirname($cachedFilePath))), 2);
                 error_log("Kaltura type reflector could not be saved to path [{$cachedFilePath}] type [{$type}] folder permisisons [{$folderPermission}]");
             }
         }
         self::$_loadedTypeReflectors[$type] = $typeReflector;
     }
     return self::$_loadedTypeReflectors[$type];
 }
 public function toObject($object_to_fill = null, $props_to_skip = array())
 {
     $dbUploadToken = UploadTokenPeer::retrieveByPK($this->token);
     if (is_null($dbUploadToken)) {
         throw new KalturaAPIException(KalturaErrors::UPLOAD_TOKEN_NOT_FOUND);
     }
     if (!$object_to_fill) {
         $object_to_fill = new kUploadedFileTokenResource();
     }
     $object_to_fill->setToken($this->token);
     if ($dbUploadToken->getStatus() != UploadToken::UPLOAD_TOKEN_FULL_UPLOAD) {
         $object_to_fill->setIsReady(false);
         return $object_to_fill;
     }
     try {
         $entryFullPath = kUploadTokenMgr::getFullPathByUploadTokenId($this->token);
     } catch (kCoreException $ex) {
         if ($ex->getCode() == kUploadTokenException::UPLOAD_TOKEN_INVALID_STATUS) {
         }
         throw new KalturaAPIException(KalturaErrors::UPLOAD_TOKEN_INVALID_STATUS_FOR_ADD_ENTRY);
         throw $ex;
     }
     if (!file_exists($entryFullPath)) {
         $remoteDCHost = kUploadTokenMgr::getRemoteHostForUploadToken($this->token, kDataCenterMgr::getCurrentDcId());
         if ($remoteDCHost) {
             kFile::dumpApiRequest($remoteDCHost);
         } else {
             throw new KalturaAPIException(KalturaErrors::UPLOADED_FILE_NOT_FOUND_BY_TOKEN);
         }
     }
     $object_to_fill->setLocalFilePath($entryFullPath);
     return $object_to_fill;
 }
예제 #4
0
 private static function sendRequest($params, $url = "rest")
 {
     $fullUrl = self::buildUrl($params, $url);
     $rsp = kFile::downloadUrlToString($fullUrl);
     $rsp_obj = unserialize($rsp);
     return $rsp_obj;
 }
예제 #5
0
    public function execute()
    {
        $this->forceSystemAuthentication();
        $this->basePath = "/content/dynamic/";
        $dynamicRoot = myContentStorage::getFSContentRootPath() . $this->basePath;
        if ($this->getRequest()->getMethod() == sfRequest::POST) {
            $origFilename = basename($_FILES['Filedata']['name']);
            $fullPath = $dynamicRoot . $origFilename;
            move_uploaded_file($_FILES['Filedata']['tmp_name'], $fullPath);
            chmod($fullPath, 0777);
            return $this->renderText("ok");
        } else {
            if ($this->getRequest()->getMethod() == sfRequest::DELETE) {
                $filename = basename($_REQUEST['fileName']);
                kFile::deleteFile($dynamicRoot . $filename);
                return $this->renderText("ok");
            }
        }
        $this->files = kFile::dirListExtended($dynamicRoot, false);
        $this->extraHead = <<<EOT
\t\t<style type="text/css">
\t\t\ttable{ font-size:1.2em; width:100%; margin:40px 0 0 0; }
\t\t\ttable thead{ font-size:1.4em; }
\t\t\t\ttable thead td{ border-bottom:1px solid #444; margin-bottom:20px; }
\t\t\ttable tbody td{ padding:2px 0; color:#ccc; }
\t\t\t\ttable tbody td b{ font-weight:normal; cursor:default; }
\t\t\t\ttable tbody td span.btn{ margin-right:12px;}
\t\t\tdiv#helper{ display:none; position:absolute; left:0; width:250px; }
\t\t\tdiv#helper img{ float:right; max-width:250px; }
\t\t</style>
EOT;
    }
 public function validateEntry(entry $dbEntry)
 {
     parent::validateEntry($dbEntry);
     $this->validatePropertyNotNull('resources');
     $dc = null;
     foreach ($this->resources as $resource) {
         $resource->validateEntry($dbEntry);
         if (!$resource instanceof KalturaDataCenterContentResource) {
             continue;
         }
         $theDc = $resource->getDc();
         if (is_null($theDc)) {
             continue;
         }
         if (is_null($dc)) {
             $dc = $theDc;
         } elseif ($dc != $theDc) {
             throw new KalturaAPIException(KalturaErrors::RESOURCES_MULTIPLE_DATA_CENTERS);
         }
     }
     if (!is_null($dc) && $dc != kDataCenterMgr::getCurrentDcId()) {
         $remoteHost = kDataCenterMgr::getRemoteDcExternalUrlByDcId($dc);
         kFile::dumpApiRequest($remoteHost);
     }
 }
예제 #7
0
 public function configure()
 {
     $this->tempDirectory = isset(KBatchBase::$taskConfig->params->tempDirectoryPath) ? KBatchBase::$taskConfig->params->tempDirectoryPath : sys_get_temp_dir();
     if (!is_dir($this->tempDirectory)) {
         kFile::fullMkfileDir($this->tempDirectory, 0700, true);
     }
 }
 /**
  * @param CaptionAsset $captionAsset
  * @param BatchJob $parentJob
  * @throws kCoreException FILE_NOT_FOUND
  * @return BatchJob
  */
 public function addParseCaptionAssetJob(CaptionAsset $captionAsset, BatchJob $parentJob = null)
 {
     $syncKey = $captionAsset->getSyncKey(asset::FILE_SYNC_ASSET_SUB_TYPE_ASSET);
     $fileSync = kFileSyncUtils::getReadyInternalFileSyncForKey($syncKey);
     if (!$fileSync) {
         if (!PermissionPeer::isValidForPartner(CaptionPermissionName::IMPORT_REMOTE_CAPTION_FOR_INDEXING, $captionAsset->getPartnerId())) {
             throw new kCoreException("File sync not found: {$syncKey}", kCoreException::FILE_NOT_FOUND);
         }
         $fileSync = kFileSyncUtils::getReadyExternalFileSyncForKey($syncKey);
         if (!$fileSync) {
             throw new kCoreException("File sync not found: {$syncKey}", kCoreException::FILE_NOT_FOUND);
         }
         $fullPath = myContentStorage::getFSUploadsPath() . '/' . $captionAsset->getId() . '.tmp';
         if (!kFile::downloadUrlToFile($fileSync->getExternalUrl($captionAsset->getEntryId()), $fullPath)) {
             throw new kCoreException("File sync not found: {$syncKey}", kCoreException::FILE_NOT_FOUND);
         }
         kFileSyncUtils::moveFromFile($fullPath, $syncKey, true, false, true);
     }
     $jobData = new kParseCaptionAssetJobData();
     $jobData->setCaptionAssetId($captionAsset->getId());
     $batchJob = null;
     if ($parentJob) {
         $batchJob = $parentJob->createChild();
     } else {
         $batchJob = new BatchJob();
         $batchJob->setEntryId($captionAsset->getEntryId());
         $batchJob->setPartnerId($captionAsset->getPartnerId());
     }
     return kJobsManager::addJob($batchJob, $jobData, CaptionSearchPlugin::getBatchJobTypeCoreValue(CaptionSearchBatchJobType::PARSE_CAPTION_ASSET));
 }
 private function moveFile(KalturaBatchJob $job, $fromPath, $toPath)
 {
     KalturaLog::debug("moveFile from[{$fromPath}] to[{$toPath}]");
     // move file/dir to the new location
     $res = @rename($fromPath, $toPath);
     // chmod + chown + check file seen by apache - for each moved file/directory
     if ($res) {
         if (is_dir($toPath)) {
             $contents = kFile::listDir($toPath);
             sort($contents, SORT_STRING);
             foreach ($contents as $current) {
                 $res = $res && $this->setAndCheck($toPath . '/' . $current);
             }
         } else {
             $res = $this->setAndCheck($toPath);
         }
     }
     if ($res) {
         $job->status = KalturaBatchJobStatus::FINISHED;
         $job->message = "File moved to final destination";
     } else {
         $job->status = KalturaBatchJobStatus::FAILED;
         $job->message = "File not moved correctly";
     }
     return $this->closeJob($job, null, null, $job->message, $job->status, null, $job->data);
 }
예제 #10
0
 /**
  * Executes addComment action, which returns a form enabling the insertion of a comment
  * The request may include 1 fields: entry id.
  */
 protected function executeImpl(kshow $kshow, entry &$entry)
 {
     $version = @$_REQUEST["version"];
     // it's a path on the disk
     if (kString::beginsWith($version, ".")) {
         // someone is trying to hack in the system
         return sfView::ERROR;
     }
     // in case we're making a roughcut out of a regular invite, we start from scratch
     if ($entry->getMediaType() != entry::ENTRY_MEDIA_TYPE_SHOW || $entry->getDataPath($version) === null) {
         $this->xml_content = "<xml></xml>";
         return;
     }
     // fetch content of file from disk - it should hold the XML
     $file_name = myContentStorage::getFSContentRootPath() . "/" . $entry->getDataPath($version);
     //echo "[$file_name]";
     if (kString::endsWith($file_name, "xml")) {
         if (file_exists($file_name)) {
             $this->xml_content = kFile::getFileContent($file_name);
             //	echo "[" . $this->xml_content . "]" ;
         } else {
             $this->xml_content = "<xml></xml>";
         }
         myMetadataUtils::updateEntryForPending($entry, $version, $this->xml_content);
     } else {
         return sfView::ERROR;
     }
     // this is NOT an xml file we are looking for !
 }
 public function crop($quality, $cropType, $width = 0, $height = 0, $cropX = 0, $cropY = 0, $cropWidth = 0, $cropHeight = 0, $scaleWidth = 1, $scaleHeight = 1, $bgcolor = 0xffffff, $density = 0, $forceRotation = null, $strip = false)
 {
     if (is_null($quality)) {
         $quality = 100;
     }
     if (is_null($cropType)) {
         $cropType = 1;
     }
     if (is_null($width)) {
         $width = 0;
     }
     if (is_null($height)) {
         $height = 0;
     }
     if (is_null($cropX)) {
         $cropX = 0;
     }
     if (is_null($cropY)) {
         $cropY = 0;
     }
     if (is_null($cropWidth)) {
         $cropWidth = 0;
     }
     if (is_null($cropHeight)) {
         $cropHeight = 0;
     }
     if (is_null($scaleWidth)) {
         $scaleWidth = 1;
     }
     if (is_null($scaleHeight)) {
         $scaleHeight = 1;
     }
     if (is_null($bgcolor)) {
         $bgcolor = 0;
     }
     $cmd = $this->getCommand($quality, $cropType, $width, $height, $cropX, $cropY, $cropWidth, $cropHeight, $scaleWidth, $scaleHeight, $bgcolor, $density, $forceRotation, $strip);
     if ($cmd) {
         KalturaLog::info("Executing: {$cmd}");
         $returnValue = null;
         $output = system($cmd, $returnValue);
         KalturaLog::debug("Returned value: '{$returnValue}'");
         if ($returnValue) {
             return false;
         }
         // Support animated gifs - KImageMagick generates multiple images with a postfix of '-<frame num>'
         if (!kFile::fileSize($this->targetPath)) {
             $targetFiledir = pathinfo($this->targetPath, PATHINFO_DIRNAME);
             $targetFilename = pathinfo($this->targetPath, PATHINFO_FILENAME);
             $targetFileext = pathinfo($this->targetPath, PATHINFO_EXTENSION);
             $firstFrameTargetFile = "{$targetFiledir}/{$targetFilename}-0.{$targetFileext}";
             if (kFile::fileSize($firstFrameTargetFile)) {
                 kFile::moveFile($firstFrameTargetFile, $this->targetPath);
             }
         }
         return true;
     }
     KalturaLog::info("No conversion required, copying source[{$this->srcPath}] to target[{$this->targetPath}]");
     return copy($this->srcPath, $this->targetPath);
 }
예제 #12
0
 /**
  * Append recorded video to live entry
  * 
  * @action appendRecording
  * @param string $entryId Live entry id
  * @param string $assetId Live asset id
  * @param KalturaMediaServerIndex $mediaServerIndex
  * @param KalturaDataCenterContentResource $resource
  * @param float $duration in seconds
  * @param bool $isLastChunk Is this the last recorded chunk in the current session (i.e. following a stream stop event)
  * @return KalturaLiveEntry The updated live entry
  * 
  * @throws KalturaErrors::ENTRY_ID_NOT_FOUND
  */
 function appendRecordingAction($entryId, $assetId, $mediaServerIndex, KalturaDataCenterContentResource $resource, $duration, $isLastChunk = false)
 {
     $dbEntry = entryPeer::retrieveByPK($entryId);
     if (!$dbEntry || !$dbEntry instanceof LiveEntry) {
         throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId);
     }
     $dbAsset = assetPeer::retrieveById($assetId);
     if (!$dbAsset || !$dbAsset instanceof liveAsset) {
         throw new KalturaAPIException(KalturaErrors::ASSET_ID_NOT_FOUND, $assetId);
     }
     $lastDuration = $dbEntry->getLengthInMsecs();
     if (!$lastDuration) {
         $lastDuration = 0;
     }
     $liveSegmentDurationInMsec = (int) ($duration * 1000);
     $currentDuration = $lastDuration + $liveSegmentDurationInMsec;
     $maxRecordingDuration = (kConf::get('max_live_recording_duration_hours') + 1) * 60 * 60 * 1000;
     if ($currentDuration > $maxRecordingDuration) {
         KalturaLog::err("Entry [{$entryId}] duration [" . $dbEntry->getLengthInMsecs() . "] and current duration [{$currentDuration}] is more than max allwoed duration [{$maxRecordingDuration}]");
         throw new KalturaAPIException(KalturaErrors::LIVE_STREAM_EXCEEDED_MAX_RECORDED_DURATION, $entryId);
     }
     $kResource = $resource->toObject();
     $filename = $kResource->getLocalFilePath();
     if (!$resource instanceof KalturaServerFileResource) {
         $filename = kConf::get('uploaded_segment_destination') . basename($kResource->getLocalFilePath());
         kFile::moveFile($kResource->getLocalFilePath(), $filename);
         chgrp($filename, kConf::get('content_group'));
         chmod($filename, 0640);
     }
     if ($dbAsset->hasTag(assetParams::TAG_RECORDING_ANCHOR) && $mediaServerIndex == KalturaMediaServerIndex::PRIMARY) {
         KalturaLog::debug("Appending assetId {$assetId} to entryId {$entryId}");
         $dbEntry->setLengthInMsecs($currentDuration);
         // Extract the exact video segment duration from the recorded file
         $mediaInfoParser = new KMediaInfoMediaParser($filename, kConf::get('bin_path_mediainfo'));
         $recordedSegmentDurationInMsec = $mediaInfoParser->getMediaInfo()->videoDuration;
         $currentSegmentVodToLiveDeltaTime = $liveSegmentDurationInMsec - $recordedSegmentDurationInMsec;
         $recordedSegmentsInfo = $dbEntry->getRecordedSegmentsInfo();
         $recordedSegmentsInfo->addSegment($lastDuration, $recordedSegmentDurationInMsec, $currentSegmentVodToLiveDeltaTime);
         $dbEntry->setRecordedSegmentsInfo($recordedSegmentsInfo);
         if ($isLastChunk) {
             // Save last elapsed recording time
             $dbEntry->setLastElapsedRecordingTime($currentDuration);
         }
         $dbEntry->save();
     }
     kJobsManager::addConvertLiveSegmentJob(null, $dbAsset, $mediaServerIndex, $filename, $currentDuration);
     if ($mediaServerIndex == KalturaMediaServerIndex::PRIMARY) {
         if (!$dbEntry->getRecordedEntryId()) {
             $this->createRecordedEntry($dbEntry, $mediaServerIndex);
         }
         $recordedEntry = entryPeer::retrieveByPK($dbEntry->getRecordedEntryId());
         if ($recordedEntry) {
             $this->ingestAsset($recordedEntry, $dbAsset, $filename);
         }
     }
     $entry = KalturaEntryFactory::getInstanceByType($dbEntry->getType());
     $entry->fromObject($dbEntry, $this->getResponseProfile());
     return $entry;
 }
예제 #13
0
 private function getAssetDataFilesArray(kConvertLiveSegmentJobData $data)
 {
     $amfFilesDir = dirname($data->getDestDataFilePath());
     $pattern = "/{$data->getEntryId()}_{$data->getAssetId()}_{$data->getMediaServerIndex()}_[0-9]*.data/";
     $files = kFile::recursiveDirList($amfFilesDir, true, false, $pattern);
     natsort($files);
     return $files;
 }
예제 #14
0
 /**
  * Will forward to the regular swf player according to the widget_id 
  */
 public function execute()
 {
     $ui_conf_id = $this->getRequestParameter("ui_conf_id");
     $preloader_path = myContentStorage::getFSContentRootPath() . "/content" . myContentStorage::getFSUiconfRootPath() . "/preloader_{$ui_conf_id}.swf";
     if (!file_exists($preloader_path)) {
         $preloader_path = myContentStorage::getFSContentRootPath() . "/content" . myContentStorage::getFSUiconfRootPath() . "/preloader_2.swf";
     }
     kFile::dumpFile($preloader_path);
 }
 /**
  * Will forward to the regular swf player according to the widget_id 
  */
 public function execute()
 {
     $uiconf_id = $this->getRequestParameter('uiconf_id');
     if (!$uiconf_id) {
         KExternalErrors::dieError(KExternalErrors::MISSING_PARAMETER, 'uiconf_id');
     }
     $uiConf = uiConfPeer::retrieveByPK($uiconf_id);
     if (!$uiConf) {
         KExternalErrors::dieError(KExternalErrors::UI_CONF_NOT_FOUND);
     }
     $partner_id = $this->getRequestParameter('partner_id', $uiConf->getPartnerId());
     if (!$partner_id) {
         KExternalErrors::dieError(KExternalErrors::MISSING_PARAMETER, 'partner_id');
     }
     $partner_host = myPartnerUtils::getHost($partner_id);
     $partner_cdnHost = myPartnerUtils::getCdnHost($partner_id);
     $use_cdn = $uiConf->getUseCdn();
     $host = $use_cdn ? $partner_cdnHost : $partner_host;
     $ui_conf_html5_url = $uiConf->getHtml5Url();
     if (kConf::hasMap("optimized_playback")) {
         $optimizedPlayback = kConf::getMap("optimized_playback");
         if (array_key_exists($partner_id, $optimizedPlayback)) {
             // force a specific kdp for the partner
             $params = $optimizedPlayback[$partner_id];
             if (array_key_exists('html5_url', $params)) {
                 $ui_conf_html5_url = $params['html5_url'];
             }
         }
     }
     if (kString::beginsWith($ui_conf_html5_url, "http")) {
         $url = $ui_conf_html5_url;
         // absolute URL
     } else {
         if ($ui_conf_html5_url) {
             $url = $host . $ui_conf_html5_url;
         } else {
             $html5_version = kConf::get('html5_version');
             $url = "{$host}/html5/html5lib/{$html5_version}/mwEmbedLoader.php";
         }
     }
     // append uiconf_id and partner id for optimizing loading of html5 library. append them only for "standard" urls by looking for the mwEmbedLoader.php suffix
     if (kString::endsWith($url, "mwEmbedLoader.php")) {
         $url .= "/p/{$partner_id}/uiconf_id/{$uiconf_id}";
         $entry_id = $this->getRequestParameter('entry_id');
         if ($entry_id) {
             $url .= "/entry_id/{$entry_id}";
         }
     }
     requestUtils::sendCachingHeaders(60);
     header("Pragma:");
     kFile::cacheRedirect($url);
     header("Location:{$url}");
     die;
 }
 private static function search($searchText, $page, $pageSize)
 {
     if (!$pageSize) {
         $pageSize = 100;
     }
     $pageSize = min($pageSize, 100);
     $startIndex = ($page - 1) * $pageSize;
     $url = self::$domain . "/api/videos/?vq=" . urlencode($searchText) . "&max-results=" . $pageSize . "&start-index=" . $startIndex . "&time=all_time";
     $content = kFile::downloadUrlToString($url);
     return $content;
 }
예제 #17
0
 public function operate(kOperator $operator = null, $inFilePath, $configFilePath = null)
 {
     //$this->outFilePath = "k:".$this->outFilePath;
     KalturaLog::debug("creating directory:" . $this->outFilePath);
     kFile::fullMkfileDir($this->outFilePath, 0777, true);
     $res = parent::operate($operator, $inFilePath, $configFilePath);
     rename("{$this->outFilePath}//playlist.m3u8", "{$this->outFilePath}//playlist.tmp");
     self::parsePlayList("{$this->outFilePath}//playlist.tmp", "{$this->outFilePath}//playlist.m3u8");
     //		rename("out_dummy.m3u8", "$this->outFilePath//out_dummy.m3u8");
     //		KalturaLog::info("operator($operator), inFilePath($inFilePath), configFilePath($configFilePath)");
     return $res;
 }
 /**
  * @see IDistributionEngine::configure()
  */
 public function configure(KSchedularTaskConfig $taskConfig)
 {
     if ($taskConfig->params->tempFilePath) {
         $this->tempFilePath = $taskConfig->params->tempFilePath;
         if (!is_dir($this->tempFilePath)) {
             kFile::fullMkfileDir($this->tempFilePath, 0777, true);
         }
     } else {
         $this->tempFilePath = sys_get_temp_dir();
         KalturaLog::info('params.tempFilePath configuration not supplied, using default system directory [' . $this->tempFilePath . ']');
     }
 }
 private function createImagesListXML($outDirPath)
 {
     $imagesList = kFile::dirList($outDirPath, false);
     sort($imagesList);
     $imagesListXML = new SimpleXMLElement('<' . self::IMAGES_LIST_XML_LABEL_ITEMS . '/>');
     foreach ($imagesList as $image) {
         $imageNode = $imagesListXML->addChild(self::IMAGES_LIST_XML_LABEL_ITEM);
         $imageNode->addChild(self::IMAGES_LIST_XML_LABEL_NAME, $image);
     }
     $imagesListXML->addAttribute(self::IMAGES_LIST_XML_ATTRIBUTE_COUNT, count($imagesList));
     return $imagesListXML;
 }
예제 #20
0
 public function configure(KSchedularTaskConfig $taskConfig)
 {
     if ($taskConfig->params->tempXmlPath) {
         $this->tempXmlPath = $taskConfig->params->tempXmlPath;
         if (!is_dir($this->tempXmlPath)) {
             kFile::fullMkfileDir($this->tempXmlPath, 0777, true);
         }
     } else {
         KalturaLog::err("params.tempXmlPath configuration not supplied");
         $this->tempXmlPath = sys_get_temp_dir();
     }
 }
예제 #21
0
 /**
  * Generic add entry using an uploaded file, should be used when the uploaded entry type is not known
  *
  * @action addFromUploadedFile
  * @param KalturaBaseEntry $entry
  * @param string $uploadTokenId
  * @param KalturaEntryType $type
  * @return KalturaBaseEntry
  */
 function addFromUploadedFileAction(KalturaBaseEntry $entry, $uploadTokenId, $type = -1)
 {
     try {
         // check that the uploaded file exists
         $entryFullPath = kUploadTokenMgr::getFullPathByUploadTokenId($uploadTokenId);
     } catch (kCoreException $ex) {
         if ($ex->getCode() == kUploadTokenException::UPLOAD_TOKEN_INVALID_STATUS) {
         }
         throw new KalturaAPIException(KalturaErrors::UPLOAD_TOKEN_INVALID_STATUS_FOR_ADD_ENTRY);
         throw $ex;
     }
     if (!file_exists($entryFullPath)) {
         $remoteDCHost = kUploadTokenMgr::getRemoteHostForUploadToken($uploadTokenId, kDataCenterMgr::getCurrentDcId());
         if ($remoteDCHost) {
             kFile::dumpApiRequest($remoteDCHost);
         } else {
             throw new KalturaAPIException(KalturaErrors::UPLOADED_FILE_NOT_FOUND_BY_TOKEN);
         }
     }
     // validate the input object
     //$entry->validatePropertyMinLength("name", 1);
     if (!$entry->name) {
         $entry->name = $this->getPartnerId() . '_' . time();
     }
     // first copy all the properties to the db entry, then we'll check for security stuff
     $dbEntry = $entry->toInsertableObject(new entry());
     $dbEntry->setType($type);
     $dbEntry->setMediaType(entry::ENTRY_MEDIA_TYPE_AUTOMATIC);
     $this->checkAndSetValidUser($entry, $dbEntry);
     $this->checkAdminOnlyInsertProperties($entry);
     $this->validateAccessControlId($entry);
     $this->validateEntryScheduleDates($entry);
     $dbEntry->setPartnerId($this->getPartnerId());
     $dbEntry->setSubpId($this->getPartnerId() * 100);
     $dbEntry->setSourceId($uploadTokenId);
     $dbEntry->setSourceLink($entryFullPath);
     $dbEntry->setDefaultModerationStatus();
     $dbEntry->save();
     $kshow = $this->createDummyKShow();
     $kshowId = $kshow->getId();
     myEntryUtils::setEntryTypeAndMediaTypeFromFile($dbEntry, $entryFullPath);
     // setup the needed params for my insert entry helper
     $paramsArray = array("entry_media_source" => KalturaSourceType::FILE, "entry_media_type" => $dbEntry->getMediaType(), "entry_full_path" => $entryFullPath, "entry_license" => $dbEntry->getLicenseType(), "entry_credit" => $dbEntry->getCredit(), "entry_source_link" => $dbEntry->getSourceLink(), "entry_tags" => $dbEntry->getTags());
     $token = $this->getKsUniqueString();
     $insert_entry_helper = new myInsertEntryHelper(null, $dbEntry->getKuserId(), $kshowId, $paramsArray);
     $insert_entry_helper->setPartnerId($this->getPartnerId(), $this->getPartnerId() * 100);
     $insert_entry_helper->insertEntry($token, $dbEntry->getType(), $dbEntry->getId(), $dbEntry->getName(), $dbEntry->getTags(), $dbEntry);
     $dbEntry = $insert_entry_helper->getEntry();
     kUploadTokenMgr::closeUploadTokenById($uploadTokenId);
     myNotificationMgr::createNotification(kNotificationJobData::NOTIFICATION_TYPE_ENTRY_ADD, $dbEntry);
     $entry->fromObject($dbEntry);
     return $entry;
 }
 public function exec(KalturaBatchJob $job)
 {
     $sharedPath = $this->getAdditionalParams('sharedTempPath');
     if (!is_dir($sharedPath)) {
         kFile::fullMkfileDir($sharedPath);
         if (!is_dir($sharedPath)) {
             throw new Exception('Shared path [' . $sharedPath . '] doesn\'t exist and could not be created');
         }
     }
     KalturaLog::debug('Temp shared path: ' . $sharedPath);
     /** @var KalturaScheduledTaskJobData $jobData */
     $jobData = $job->data;
     $profileId = $job->jobObjectId;
     $maxResults = $jobData->maxResults ? $jobData->maxResults : 500;
     $scheduledTaskClient = $this->getScheduledTaskClient();
     $scheduledTaskProfile = $scheduledTaskClient->scheduledTaskProfile->get($profileId);
     $pager = new KalturaFilterPager();
     $pager->pageSize = 500;
     $pager->pageIndex = 1;
     $response = new KalturaObjectListResponse();
     $response->objects = array();
     $response->totalCount = 0;
     $resultsCount = 0;
     while (true) {
         $client = $this->getClient();
         $ks = $this->createKs($client, $jobData);
         $client->setKs($ks);
         $this->impersonate($scheduledTaskProfile->partnerId);
         try {
             $results = ScheduledTaskBatchHelper::query($client, $scheduledTaskProfile, $pager);
             $this->unimpersonate();
         } catch (Exception $ex) {
             $this->unimpersonate();
             throw $ex;
         }
         if (!count($results->objects)) {
             break;
         }
         $resultsCount += count($results->objects);
         if ($resultsCount >= $maxResults) {
             break;
         }
         $response->objects = array_merge($response->objects, $results->objects);
         $response->totalCount += count($results->objects);
         $pager->pageIndex++;
     }
     $sharedFilePath = $sharedPath . '/' . uniqid('sheduledtask_');
     KalturaLog::debug('Temp shared file: ' . $sharedFilePath);
     file_put_contents($sharedFilePath, serialize($response));
     $jobData->resultsFilePath = $sharedFilePath;
     return $this->closeJob($job, null, null, 'Dry run finished', KalturaBatchJobStatus::FINISHED, $jobData);
 }
예제 #23
0
 public function convert(kConversionCommand $conv_cmd, kConversionResult $conv_result, $start_params_index = 0, $end_params_index = -1)
 {
     if (!file_exists($conv_cmd->source_file)) {
         TRACE("File [{$conv_cmd->source_file} does not exist");
         return array(false, 0);
     }
     // make sure all the output directories exist - if not create
     kFile::fullMkdir($conv_cmd->target_file);
     kFile::fullMkdir($conv_cmd->log_file);
     self::fixConvParams($conv_cmd);
     $conv_params_list = $conv_cmd->conversion_params_list;
     if ($end_params_index == -1) {
         $end_params_index = count($conv_params_list);
     }
     $start_i = max($start_params_index, 0);
     $end_i = min($end_params_index, count($conv_params_list));
     for ($i = $start_i; $i < $end_i; ++$i) {
         $conv_res_info = new kConvResInfo();
         $conv_res_info->engine = $this->getName();
         $conv_res_info->index = $i;
         $conv_params = @$conv_cmd->conversion_params_list[$i];
         if ($conv_params) {
             $conv_res_info->conv_params_name = $conv_params->name;
         }
         $log_file = $conv_cmd->getLogFileWithSuffix($i);
         $conv_res_info->target = $conv_cmd->getTargetFileWithSuffix($i);
         list($execution_command_str, $conversion_str) = $this->getExecutionCommandAndConversionString($conv_cmd, $i);
         $conv_res_info->conv_str = $conversion_str;
         // assume there always will be this index
         self::logMediaInfo($conv_cmd->source_file);
         self::addToLogFile($log_file, $execution_command_str);
         self::addToLogFile($log_file, $conversion_str);
         $return_value = "";
         $conv_result->appendResult($this->getName() . ": " . $execution_command_str);
         TRACE($execution_command_str);
         $start = microtime(true);
         exec($execution_command_str, $output, $return_value);
         $end = microtime(true);
         TRACE($this->getName() . ": [{$return_value}]");
         // $return_value == 0 is success. if not - return the index of the failed conversion
         $conv_result->appendResult($this->getName() . ": [{$return_value}]");
         $conv_res_info->duration = $end - $start;
         $conv_res_info->res = $return_value;
         $conv_result->appendResInfo($conv_res_info);
         if ($return_value != 0) {
             return array(false, $i);
         }
         self::logMediaInfo($conv_cmd->getTargetFileWithSuffix($i));
     }
     return array(true, -1);
     // indicate all was converted properly
 }
 /**
  * @param KalturaBatchJob $job
  * @param KalturaConcatJobData $data
  * @param string $localTempFilePath
  * @param string $sharedTempFilePath
  * @return KalturaBatchJob
  */
 protected function moveFile(KalturaBatchJob $job, KalturaConvertLiveSegmentJobData $data, $localTempFilePath, $sharedTempFilePath)
 {
     $this->updateJob($job, "Moving file from [{$localTempFilePath}] to [{$sharedTempFilePath}]", KalturaBatchJobStatus::MOVEFILE);
     kFile::moveFile($localTempFilePath, $sharedTempFilePath, true);
     clearstatcache();
     $fileSize = kFile::fileSize($sharedTempFilePath);
     $this->setFilePermissions($sharedTempFilePath);
     if (!$this->checkFileExists($sharedTempFilePath, $fileSize)) {
         return $this->closeJob($job, KalturaBatchJobErrorTypes::APP, KalturaBatchJobAppErrors::NFS_FILE_DOESNT_EXIST, 'File not moved correctly', KalturaBatchJobStatus::RETRY);
     }
     $data->destFilePath = $sharedTempFilePath;
     return $this->closeJob($job, null, null, 'Succesfully moved file', KalturaBatchJobStatus::FINISHED, $data);
 }
예제 #25
0
 public function configure()
 {
     parent::configure();
     if (KBatchBase::$taskConfig->params->tempXmlPath) {
         $this->tempXmlPath = KBatchBase::$taskConfig->params->tempXmlPath;
         if (!is_dir($this->tempXmlPath)) {
             kFile::fullMkfileDir($this->tempXmlPath, 0777, true);
         }
     } else {
         KalturaLog::err("params.tempXmlPath configuration not supplied");
         $this->tempXmlPath = sys_get_temp_dir();
     }
 }
 protected function moveFile(KalturaBatchJob $job, KalturaLiveReportExportJobData $data, $partnerId)
 {
     $fileName = basename($data->outputPath);
     $sharedLocation = self::$taskConfig->params->sharedPath . DIRECTORY_SEPARATOR . $partnerId . "_" . $fileName;
     $fileSize = kFile::fileSize($data->outputPath);
     rename($data->outputPath, $sharedLocation);
     $data->outputPath = $sharedLocation;
     $this->setFilePermissions($sharedLocation);
     if (!$this->checkFileExists($sharedLocation, $fileSize)) {
         return $this->closeJob($job, KalturaBatchJobErrorTypes::APP, KalturaBatchJobAppErrors::NFS_FILE_DOESNT_EXIST, 'Failed to move report file', KalturaBatchJobStatus::RETRY);
     }
     return $this->closeJob($job, null, null, 'CSV created successfully', KalturaBatchJobStatus::FINISHED, $data);
 }
예제 #27
0
 public function execute()
 {
     $this->forceSystemAuthentication();
     $file_path = $this->getP("file_path");
     if (!file_exists($file_path)) {
         echo "Cannot find file [{$file_path}]";
         die;
     }
     $mime_type = kFile::mimeType($file_path);
     //		echo "[[$mime_type]]";
     kFile::dumpFile($file_path, $mime_type);
     die;
 }
 public function validateEntry(entry $dbEntry)
 {
     parent::validateEntry($dbEntry);
     $dc = $this->getDc();
     if ($dc == kDataCenterMgr::getCurrentDcId()) {
         return;
     }
     $remoteDCHost = kDataCenterMgr::getRemoteDcExternalUrlByDcId($dc);
     if ($remoteDCHost) {
         kFile::dumpApiRequest($remoteDCHost);
     }
     throw new KalturaAPIException(KalturaErrors::REMOTE_DC_NOT_FOUND, $dc);
 }
 private static function readLog($name, $size)
 {
     $pattern = "/" . $name . "\$/";
     $files = kFile::recursiveDirList(self::LOG_DIR, true, false, $pattern);
     $result = array();
     if ($files) {
         foreach ($files as $file) {
             $data = kFile::getFileData($file);
             $data->content = kFile::readLastBytesFromFile($file, $size);
             $result[] = $data;
         }
     }
     return $result;
 }
예제 #30
0
 public function removeIndicator()
 {
     // delete any of the indicators available
     $indicator_list = kFile::recursiveDirList(self::$s_indicator_path, true, false, $this->pattern);
     if (count($indicator_list) > 0) {
         kFile::deleteFile($indicator_list[0]);
     }
     if (count($indicator_list) > 100) {
         // many file indicator - no real reason to leave them all
         for ($i = 1; $i < 50; $i++) {
             kFile::deleteFile($indicator_list[$i]);
         }
     }
 }