/**
  * @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));
 }
 /**
  * @action sync
  * @param int $fileSyncId
  * @param file $fileData
  * @return KalturaFileSync
  */
 function syncAction($fileSyncId, $fileData)
 {
     $dbFileSync = FileSyncPeer::retrieveByPK($fileSyncId);
     if (!$dbFileSync) {
         throw new APIException(APIErrors::INVALID_FILE_SYNC_ID, $fileSyncId);
     }
     $key = kFileSyncUtils::getKeyForFileSync($dbFileSync);
     kFileSyncUtils::moveFromFile($fileData['tmp_name'], $key, false);
     list($file_root, $real_path) = kPathManager::getFilePathArr($key);
     $full_path = $file_root . $real_path;
     chmod($full_path, 0644);
     if (file_exists($full_path)) {
         $dbFileSync->setFileRoot($file_root);
         $dbFileSync->setFilePath($real_path);
         $dbFileSync->setFileSizeFromPath($full_path);
         $dbFileSync->setStatus(FileSync::FILE_SYNC_STATUS_READY);
     } else {
         $dbFileSync->setFileSize(-1);
         $dbFileSync->setStatus(FileSync::FILE_SYNC_STATUS_ERROR);
     }
     $dbFileSync->save();
     $fileSync = new KalturaFileSync();
     $fileSync->fromObject($dbFileSync);
     return $fileSync;
 }
 /**
  * Add new document entry after the specific document file was uploaded and the upload token id exists
  *
  * @action addFromUploadedFile
  * @param KalturaDocumentEntry $documentEntry Document entry metadata
  * @param string $uploadTokenId Upload token id
  * @return KalturaDocumentEntry The new document entry
  * 
  * @throws KalturaErrors::PROPERTY_VALIDATION_MIN_LENGTH
  * @throws KalturaErrors::PROPERTY_VALIDATION_CANNOT_BE_NULL
  * @throws KalturaErrors::UPLOADED_FILE_NOT_FOUND_BY_TOKEN
  */
 function addFromUploadedFileAction(KalturaDocumentEntry $documentEntry, $uploadTokenId)
 {
     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);
         }
     }
     $dbEntry = $this->prepareEntryForInsert($documentEntry);
     $dbEntry->setSource(KalturaSourceType::FILE);
     $dbEntry->setSourceLink("file:{$entryFullPath}");
     $dbEntry->save();
     $te = new TrackEntry();
     $te->setEntryId($dbEntry->getId());
     $te->setTrackEventTypeId(TrackEntry::TRACK_ENTRY_EVENT_TYPE_ADD_ENTRY);
     $te->setDescription(__METHOD__ . ":" . __LINE__ . "::ENTRY_MEDIA_SOURCE_FILE");
     TrackEntry::addTrackEntry($te);
     $msg = null;
     $flavorAsset = kFlowHelper::createOriginalFlavorAsset($this->getPartnerId(), $dbEntry->getId(), $msg);
     if (!$flavorAsset) {
         KalturaLog::err("Flavor asset not created for entry [" . $dbEntry->getId() . "] reason [{$msg}]");
         $dbEntry->setStatus(entryStatus::ERROR_CONVERTING);
         $dbEntry->save();
     } else {
         $ext = pathinfo($entryFullPath, PATHINFO_EXTENSION);
         KalturaLog::info("Uploaded file extension: {$ext}");
         $flavorAsset->setFileExt($ext);
         $flavorAsset->save();
         $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
         kFileSyncUtils::moveFromFile($entryFullPath, $syncKey);
         kEventsManager::raiseEvent(new kObjectAddedEvent($flavorAsset));
     }
     kUploadTokenMgr::closeUploadTokenById($uploadTokenId);
     myNotificationMgr::createNotification(kNotificationJobData::NOTIFICATION_TYPE_ENTRY_ADD, $dbEntry);
     $documentEntry->fromObject($dbEntry);
     return $documentEntry;
 }
 public static function handleJobFinished(BatchJob $job, kScheduledTaskJobData $data)
 {
     $resultFilePath = $data->getResultsFilePath();
     if (!file_exists($resultFilePath)) {
         return self::finishJobWithError($job, 'Results file was not found');
     }
     // we are using the bulk upload sync key, as this should actually be a generic sync key for batch job object
     $syncKey = $job->getSyncKey(BatchJob::FILE_SYNC_BATCHJOB_SUB_TYPE_BULKUPLOAD);
     try {
         kFileSyncUtils::moveFromFile($resultFilePath, $syncKey, true);
     } catch (Exception $ex) {
         KalturaLog::err($ex);
         return self::finishJobWithError($job, 'Failed to move file: ' . $ex->getMessage());
     }
     return $job;
 }
 /**
  * Add new bulk upload batch job
  * Conversion profile id can be specified in the API or in the CSV file, the one in the CSV file will be stronger.
  * If no conversion profile was specified, partner's default will be used
  * 
  * @action add
  * @param int $conversionProfileId Convertion profile id to use for converting the current bulk (-1 to use partner's default)
  * @param file $csvFileData CSV File
  * @return KalturaBulkUpload
  */
 function addAction($conversionProfileId, $csvFileData)
 {
     // first we copy the file to "content/batchfiles/[partner_id]/"
     $origFilename = $csvFileData["name"];
     $fileInfo = pathinfo($origFilename);
     $extension = strtolower($fileInfo["extension"]);
     if ($extension != "csv") {
         throw new KalturaAPIException(KalturaErrors::INVALID_FILE_EXTENSION);
     }
     $job = new BatchJob();
     $job->setPartnerId($this->getPartnerId());
     $job->save();
     $syncKey = $job->getSyncKey(BatchJob::FILE_SYNC_BATCHJOB_SUB_TYPE_BULKUPLOADCSV);
     //		kFileSyncUtils::file_put_contents($syncKey, file_get_contents($csvFileData["tmp_name"]));
     try {
         kFileSyncUtils::moveFromFile($csvFileData["tmp_name"], $syncKey, true);
     } catch (Exception $e) {
         throw new KalturaAPIException(KalturaErrors::BULK_UPLOAD_CREATE_CSV_FILE_SYNC_ERROR);
     }
     $csvPath = kFileSyncUtils::getLocalFilePathForKey($syncKey);
     $data = new KalturaBulkUploadJobData();
     $data->csvFilePath = $csvPath;
     $data->userId = $this->getKuser()->getPuserId();
     $data->uploadedBy = $this->getKuser()->getScreenName();
     if ($conversionProfileId === -1) {
         $conversionProfileId = $this->getPartner()->getDefaultConversionProfileId();
     }
     $kmcVersion = $this->getPartner()->getKmcVersion();
     $check = null;
     if ($kmcVersion < 2) {
         $check = ConversionProfilePeer::retrieveByPK($conversionProfileId);
     } else {
         $check = conversionProfile2Peer::retrieveByPK($conversionProfileId);
     }
     if (!$check) {
         throw new KalturaAPIException(KalturaErrors::CONVERSION_PROFILE_ID_NOT_FOUND, $conversionProfileId);
     }
     $data->conversionProfileId = $conversionProfileId;
     $dbJob = kJobsManager::addJob($job, $data->toObject(), KalturaBatchJobType::BULKUPLOAD);
     $bulkUpload = new KalturaBulkUpload();
     $bulkUpload->fromObject($dbJob);
     return $bulkUpload;
 }
 public function objectChanged(BaseObject $object, array $modifiedColumns)
 {
     // replacing the ismc file name in the ism file
     $ismPrevVersionFileSyncKey = $object->getSyncKey(flavorAsset::FILE_SYNC_ASSET_SUB_TYPE_ASSET);
     $ismContents = kFileSyncUtils::file_get_contents($ismPrevVersionFileSyncKey);
     $ismcPrevVersionFileSyncKey = $object->getSyncKey(flavorAsset::FILE_SYNC_ASSET_SUB_TYPE_ISMC);
     $ismcContents = kFileSyncUtils::file_get_contents($ismcPrevVersionFileSyncKey);
     $ismcPrevVersionFilePath = kFileSyncUtils::getLocalFilePathForKey($ismcPrevVersionFileSyncKey);
     $object->incrementVersion();
     $object->save();
     $ismcFileSyncKey = $object->getSyncKey(flavorAsset::FILE_SYNC_ASSET_SUB_TYPE_ISMC);
     kFileSyncUtils::moveFromFile($ismcPrevVersionFilePath, $ismcFileSyncKey);
     $ismcNewName = basename(kFileSyncUtils::getLocalFilePathForKey($ismcFileSyncKey));
     KalturaLog::debug("Editing ISM set content to [{$ismcNewName}]");
     $ismXml = new SimpleXMLElement($ismContents);
     $ismXml->head->meta['content'] = $ismcNewName;
     $tmpPath = kFileSyncUtils::getLocalFilePathForKey($ismPrevVersionFileSyncKey) . '.tmp';
     file_put_contents($tmpPath, $ismXml->asXML());
     kFileSyncUtils::moveFromFile($tmpPath, $object->getSyncKey(flavorAsset::FILE_SYNC_ASSET_SUB_TYPE_ASSET));
     return true;
 }
 public function executeImpl($partner_id, $subp_id, $puser_id, $partner_prefix, $puser_kuser)
 {
     $fileField = "csv_file";
     $profileId = $this->getP("profile_id");
     if (count($_FILES) == 0) {
         $this->addError(APIErrors::NO_FILES_RECEIVED);
         return;
     }
     if (!@$_FILES[$fileField]) {
         $this->addError(APIErrors::INVALID_FILE_FIELD, $fileField);
         return;
     }
     // first we copy the file to "content/batchfiles/[partner_id]/"
     $origFilename = $_FILES[$fileField]['name'];
     $fileInfo = pathinfo($origFilename);
     $extension = strtolower($fileInfo['extension']);
     if ($extension != "csv") {
         $this->addError(APIErrors::INVALID_FILE_EXTENSION);
         return;
     }
     $job = new BatchJob();
     $job->setPartnerId($partner_id);
     $job->save();
     $syncKey = $job->getSyncKey(BatchJob::FILE_SYNC_BATCHJOB_SUB_TYPE_BULKUPLOADCSV);
     //		kFileSyncUtils::file_put_contents($syncKey, file_get_contents($csvFileData["tmp_name"]));
     try {
         kFileSyncUtils::moveFromFile($_FILES[$fileField]['tmp_name'], $syncKey, true);
     } catch (Exception $e) {
         throw new KalturaAPIException(KalturaErrors::BULK_UPLOAD_CREATE_CSV_FILE_SYNC_ERROR);
     }
     $csvPath = kFileSyncUtils::getLocalFilePathForKey($syncKey);
     $data = new kBulkUploadJobData();
     $data->setCsvFilePath($csvPath);
     $data->setUserId($puser_kuser->getPuserId());
     $data->setUploadedBy($puser_kuser->getPuserName());
     $data->setConversionProfileId($profileId);
     kJobsManager::addJob($job, $data, BatchJobType::BULKUPLOAD);
     $this->addMsg("status", "ok");
 }
 private function onBulkUploadJobStatusUpdated(BatchJob $dbBatchJob)
 {
     $xmlDropFolderFile = DropFolderFilePeer::retrieveByPK($dbBatchJob->getObjectId());
     if (!$xmlDropFolderFile) {
         return;
     }
     KalturaLog::debug('object id ' . $dbBatchJob->getObjectId());
     switch ($dbBatchJob->getStatus()) {
         case BatchJob::BATCHJOB_STATUS_QUEUED:
             $jobData = $dbBatchJob->getData();
             if (!is_null($jobData->getFilePath())) {
                 $syncKey = $dbBatchJob->getSyncKey(BatchJob::FILE_SYNC_BATCHJOB_SUB_TYPE_BULKUPLOAD);
                 try {
                     kFileSyncUtils::moveFromFile($jobData->getFilePath(), $syncKey, true);
                 } catch (Exception $e) {
                     KalturaLog::err($e);
                     throw new APIException(APIErrors::BULK_UPLOAD_CREATE_CSV_FILE_SYNC_ERROR);
                 }
                 $filePath = kFileSyncUtils::getLocalFilePathForKey($syncKey);
                 $jobData->setFilePath($filePath);
                 //save new info on the batch job
                 $dbBatchJob->setData($jobData);
                 $dbBatchJob->save();
             }
             break;
         case BatchJob::BATCHJOB_STATUS_FINISHED:
         case BatchJob::BATCHJOB_STATUS_FINISHED_PARTIALLY:
             KalturaLog::debug("Handling Bulk Upload finished");
             $xmlDropFolderFile->setStatus(DropFolderFileStatus::HANDLED);
             $xmlDropFolderFile->save();
             break;
         case BatchJob::BATCHJOB_STATUS_FAILED:
         case BatchJob::BATCHJOB_STATUS_FATAL:
             KalturaLog::debug("Handling Bulk Upload failed");
             $relatedFiles = DropFolderFilePeer::retrieveByLeadIdAndStatuses($xmlDropFolderFile->getId(), array(DropFolderFileStatus::PROCESSING));
             foreach ($relatedFiles as $relatedFile) {
                 $this->setFileError($relatedFile, DropFolderFileStatus::ERROR_HANDLING, DropFolderXmlBulkUploadPlugin::getErrorCodeCoreValue(DropFolderXmlBulkUploadErrorCode::ERROR_IN_BULK_UPLOAD), DropFolderXmlBulkUploadPlugin::ERROR_IN_BULK_UPLOAD_MESSAGE);
             }
             break;
     }
 }
 /**
  * @action addFromImage
  * @param string $entryId
  * @param file $fileData
  * @return KalturaThumbAsset
  * 
  * @throws KalturaErrors::ENTRY_ID_NOT_FOUND
  */
 public function addFromImageAction($entryId, $fileData)
 {
     $dbEntry = entryPeer::retrieveByPK($entryId);
     if (!$dbEntry) {
         throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId);
     }
     $ext = pathinfo($fileData["name"], PATHINFO_EXTENSION);
     $dbThumbAsset = new thumbAsset();
     $dbThumbAsset->setPartnerId($dbEntry->getPartnerId());
     $dbThumbAsset->setEntryId($dbEntry->getId());
     $dbThumbAsset->setStatus(thumbAsset::FLAVOR_ASSET_STATUS_QUEUED);
     $dbThumbAsset->setFileExt($ext);
     $dbThumbAsset->incrementVersion();
     $dbThumbAsset->save();
     $syncKey = $dbThumbAsset->getSyncKey(thumbAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     kFileSyncUtils::moveFromFile($fileData["tmp_name"], $syncKey);
     $finalPath = kFileSyncUtils::getLocalFilePathForKey($syncKey);
     list($width, $height, $type, $attr) = getimagesize($finalPath);
     $dbThumbAsset->setWidth($width);
     $dbThumbAsset->setHeight($height);
     $dbThumbAsset->setSize(filesize($finalPath));
     $dbThumbAsset->setStatus(thumbAsset::FLAVOR_ASSET_STATUS_READY);
     $dbThumbAsset->save();
     $thumbAssets = new KalturaThumbAsset();
     $thumbAssets->fromObject($dbThumbAsset);
     return $thumbAssets;
 }
// ---------------------------------------------------------------------------
$xsltFilePath = '';
//TODO: change to valid xslt file path
$metadataProfileId = null;
//TODO: change to a valid metadata profile id
// ---------------------------------------------------------------------------
if (!$xsltFilePath) {
    die('ERROR - Missing parameter [$xsltFilePath]' . PHP_EOL);
}
if (!$metadataProfileId) {
    die('ERROR - Missing parameter [$metadataProfileId]' . PHP_EOL);
}
if (!file_exists($xsltFilePath)) {
    die('ERROR - Cannot find file at [' . $xsltFilePath . ']' . PHP_EOL);
}
require_once dirname(__FILE__) . '/../bootstrap.php';
require_once dirname(__FILE__) . '/../../api_v3/bootstrap.php';
KAutoloader::addClassPath(KAutoloader::buildPath(KALTURA_ROOT_PATH, "vendor", "propel", "*"));
KAutoloader::addClassPath(KAutoloader::buildPath(KALTURA_ROOT_PATH, "plugins", "metadata", "*"));
KAutoloader::setClassMapFilePath(kConf::get("cache_root_path") . '/scripts/' . basename(__FILE__) . '.cache');
KAutoloader::register();
KalturaPluginManager::addPlugin('MetadataPlugin');
$dbMetadataProfile = MetadataProfilePeer::retrieveById($metadataProfileId);
if (!$dbMetadataProfile) {
    die('ERROR - Cannot find metadata profile with id [' . $metadataProfileId . ']' . PHP_EOL);
}
$dbMetadataProfile->incrementXsltVersion();
$dbMetadataProfile->save();
$key = $dbMetadataProfile->getSyncKey(MetadataProfile::FILE_SYNC_METADATA_XSLT);
kFileSyncUtils::moveFromFile($xsltFilePath, $key, true, true);
echo 'Done' . PHP_EOL;
 /**
  * decideThumbGenerate is the decision layer for a single thumbnail generation 
  * 
  * @param entry $entry
  * @param thumbParams $destThumbParams
  * @param BatchJob $parentJob
  * @return thumbAsset 
  */
 public static function decideThumbGenerate(entry $entry, thumbParams $destThumbParams, BatchJob $parentJob = null, $sourceAssetId = null, $runSync = false)
 {
     $srcAsset = null;
     assetPeer::resetInstanceCriteriaFilter();
     if ($sourceAssetId) {
         $srcAsset = assetPeer::retrieveById($sourceAssetId);
     } else {
         if ($destThumbParams->getSourceParamsId()) {
             KalturaLog::debug("Look for flavor params [" . $destThumbParams->getSourceParamsId() . "]");
             $srcAsset = assetPeer::retrieveByEntryIdAndParams($entry->getId(), $destThumbParams->getSourceParamsId());
         }
         if (is_null($srcAsset)) {
             KalturaLog::debug("Look for original flavor");
             $srcAsset = flavorAssetPeer::retrieveOriginalByEntryId($entry->getId());
         }
         if (is_null($srcAsset) || $srcAsset->getStatus() != flavorAsset::FLAVOR_ASSET_STATUS_READY) {
             KalturaLog::debug("Look for highest bitrate flavor");
             $srcAsset = flavorAssetPeer::retrieveHighestBitrateByEntryId($entry->getId());
         }
     }
     if (is_null($srcAsset)) {
         throw new APIException(APIErrors::FLAVOR_ASSET_IS_NOT_READY);
     }
     $errDescription = null;
     $mediaInfo = mediaInfoPeer::retrieveByFlavorAssetId($srcAsset->getId());
     $destThumbParamsOutput = self::validateThumbAndMediaInfo($destThumbParams, $mediaInfo, $errDescription);
     $thumbAsset = thumbAssetPeer::retrieveByEntryIdAndParams($entry->getId(), $destThumbParams->getId());
     if ($thumbAsset) {
         $description = $thumbAsset->getDescription() . "\n" . $errDescription;
         $thumbAsset->setDescription($description);
     } else {
         $thumbAsset = new thumbAsset();
         $thumbAsset->setPartnerId($entry->getPartnerId());
         $thumbAsset->setEntryId($entry->getId());
         $thumbAsset->setDescription($errDescription);
         $thumbAsset->setFlavorParamsId($destThumbParams->getId());
     }
     $thumbAsset->incrementVersion();
     $thumbAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_CONVERTING);
     $thumbAsset->setTags($destThumbParamsOutput->getTags());
     $thumbAsset->setFileExt($destThumbParamsOutput->getFileExt());
     if (!$destThumbParamsOutput) {
         $thumbAsset->setStatus(thumbAsset::FLAVOR_ASSET_STATUS_ERROR);
         $thumbAsset->save();
         return null;
     }
     $thumbAsset->save();
     // save flavor params
     $destThumbParamsOutput->setPartnerId($entry->getPartnerId());
     $destThumbParamsOutput->setEntryId($entry->getId());
     $destThumbParamsOutput->setFlavorAssetId($thumbAsset->getId());
     $destThumbParamsOutput->setFlavorAssetVersion($thumbAsset->getVersion());
     $destThumbParamsOutput->save();
     $srcSyncKey = $srcAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     $srcAssetType = $srcAsset->getType();
     if (!$runSync) {
         $job = kJobsManager::addCapturaThumbJob($parentJob, $entry->getPartnerId(), $entry->getId(), $thumbAsset->getId(), $srcSyncKey, $srcAssetType, $destThumbParamsOutput);
         return $thumbAsset;
     }
     $errDescription = null;
     $capturedPath = self::generateThumbnail($srcAsset, $destThumbParamsOutput, $errDescription);
     // failed
     if (!$capturedPath) {
         $thumbAsset->incrementVersion();
         $thumbAsset->setStatus(thumbAsset::FLAVOR_ASSET_STATUS_ERROR);
         $thumbAsset->setDescription($thumbAsset->getDescription() . "\n{$errDescription}");
         $thumbAsset->save();
         return $thumbAsset;
     }
     $thumbAsset->incrementVersion();
     $thumbAsset->setStatus(thumbAsset::FLAVOR_ASSET_STATUS_READY);
     if (file_exists($capturedPath)) {
         list($width, $height, $type, $attr) = getimagesize($capturedPath);
         $thumbAsset->setWidth($width);
         $thumbAsset->setHeight($height);
         $thumbAsset->setSize(filesize($capturedPath));
     }
     $logPath = $capturedPath . '.log';
     if (file_exists($logPath)) {
         $thumbAsset->incLogFileVersion();
         $thumbAsset->save();
         // creats the file sync
         $logSyncKey = $thumbAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_CONVERT_LOG);
         kFileSyncUtils::moveFromFile($logPath, $logSyncKey);
         KalturaLog::debug("Log archived file to: " . kFileSyncUtils::getLocalFilePathForKey($logSyncKey));
     } else {
         $thumbAsset->save();
     }
     $syncKey = $thumbAsset->getSyncKey(thumbAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     kFileSyncUtils::moveFromFile($capturedPath, $syncKey);
     KalturaLog::debug("Thumbnail archived file to: " . kFileSyncUtils::getLocalFilePathForKey($syncKey));
     if ($thumbAsset->hasTag(thumbParams::TAG_DEFAULT_THUMB)) {
         // increment thumbnail version
         $entry->setThumbnail(".jpg");
         $entry->save();
         $entrySyncKey = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_THUMB);
         $syncFile = kFileSyncUtils::createSyncFileLinkForKey($entrySyncKey, $syncKey, false);
         if ($syncFile) {
             // removes the DEFAULT_THUMB tag from all other thumb assets
             $entryThumbAssets = thumbAssetPeer::retrieveByEntryId($thumbAsset->getEntryId());
             foreach ($entryThumbAssets as $entryThumbAsset) {
                 if ($entryThumbAsset->getId() == $thumbAsset->getId()) {
                     continue;
                 }
                 if (!$entryThumbAsset->hasTag(thumbParams::TAG_DEFAULT_THUMB)) {
                     continue;
                 }
                 $entryThumbAsset->removeTags(array(thumbParams::TAG_DEFAULT_THUMB));
                 $entryThumbAsset->save();
             }
         }
     }
     if (!is_null($thumbAsset->getFlavorParamsId())) {
         kFlowHelper::generateThumbnailsFromFlavor($thumbAsset->getEntryId(), null, $thumbAsset->getFlavorParamsId());
     }
     return $thumbAsset;
 }
 /**
  * @param string $entryFullPath
  * @param entry $dbEntry
  * @param asset $dbAsset
  * @return asset
  * @throws KalturaErrors::UPLOAD_TOKEN_INVALID_STATUS_FOR_ADD_ENTRY
  * @throws KalturaErrors::UPLOADED_FILE_NOT_FOUND_BY_TOKEN
  */
 protected function attachFile($entryFullPath, entry $dbEntry, asset $dbAsset = null, $copyOnly = false)
 {
     // TODO - move image handling to media service
     if ($dbEntry->getMediaType() == KalturaMediaType::IMAGE) {
         $exifImageType = @exif_imagetype($entryFullPath);
         $validTypes = array(IMAGETYPE_JPEG, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM, IMAGETYPE_IFF, IMAGETYPE_PNG);
         if (in_array($exifImageType, $validTypes)) {
             $exifData = @exif_read_data($entryFullPath);
             if ($exifData && isset($exifData["DateTimeOriginal"]) && $exifData["DateTimeOriginal"]) {
                 $mediaDate = $exifData["DateTimeOriginal"];
                 $ts = strtotime($mediaDate);
                 // handle invalid dates either due to bad format or out of range
                 if ($ts === -1 || $ts === false || $ts < strtotime('2000-01-01') || $ts > strtotime('2015-01-01')) {
                     $mediaDate = null;
                 }
                 $dbEntry->setMediaDate($mediaDate);
             }
         }
         list($width, $height, $type, $attr) = getimagesize($entryFullPath);
         $dbEntry->setDimensions($width, $height);
         $dbEntry->setData(".jpg");
         // this will increase the data version
         $dbEntry->save();
         $syncKey = $dbEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA);
         try {
             kFileSyncUtils::moveFromFile($entryFullPath, $syncKey, true, $copyOnly);
         } catch (Exception $e) {
             if ($dbEntry->getStatus() == entryStatus::NO_CONTENT) {
                 $dbEntry->setStatus(entryStatus::ERROR_CONVERTING);
                 $dbEntry->save();
             }
             throw $e;
         }
         $dbEntry->setStatus(entryStatus::READY);
         $dbEntry->save();
         return null;
     }
     $isNewAsset = false;
     if (!$dbAsset) {
         $isNewAsset = true;
         $dbAsset = kFlowHelper::createOriginalFlavorAsset($this->getPartnerId(), $dbEntry->getId());
     }
     if (!$dbAsset && $dbEntry->getStatus() == entryStatus::NO_CONTENT) {
         $dbEntry->setStatus(entryStatus::ERROR_CONVERTING);
         $dbEntry->save();
     }
     $ext = pathinfo($entryFullPath, PATHINFO_EXTENSION);
     $dbAsset->setFileExt($ext);
     $dbAsset->save();
     if ($dbAsset && $dbAsset instanceof thumbAsset) {
         list($width, $height, $type, $attr) = getimagesize($entryFullPath);
         $dbAsset->setWidth($width);
         $dbAsset->setHeight($height);
         $dbAsset->save();
     }
     $syncKey = $dbAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     try {
         kFileSyncUtils::moveFromFile($entryFullPath, $syncKey, true, $copyOnly);
     } catch (Exception $e) {
         if ($dbEntry->getStatus() == entryStatus::NO_CONTENT) {
             $dbEntry->setStatus(entryStatus::ERROR_CONVERTING);
             $dbEntry->save();
         }
         $dbAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_ERROR);
         $dbAsset->save();
         throw $e;
     }
     if ($dbAsset && !$dbAsset instanceof flavorAsset) {
         $dbAsset->setStatusLocalReady();
         if ($dbAsset->getFlavorParamsId()) {
             $dbFlavorParams = assetParamsPeer::retrieveByPK($dbAsset->getFlavorParamsId());
             if ($dbFlavorParams) {
                 $dbAsset->setTags($dbFlavorParams->getTags());
             }
         }
         $dbAsset->save();
     }
     if ($isNewAsset) {
         kEventsManager::raiseEvent(new kObjectAddedEvent($dbAsset));
     }
     kEventsManager::raiseEvent(new kObjectDataChangedEvent($dbAsset));
     return $dbAsset;
 }
 /**
  * decideThumbGenerate is the decision layer for a single thumbnail generation 
  * 
  * @param entry $entry
  * @param thumbParams $destThumbParams
  * @param BatchJob $parentJob
  * @return thumbAsset 
  */
 public static function decideThumbGenerate(entry $entry, thumbParams $destThumbParams, BatchJob $parentJob = null, $sourceAssetId = null, $runSync = false, $srcAsset = null)
 {
     if (is_null($srcAsset)) {
         $srcAsset = self::getSourceAssetForGenerateThumbnail($sourceAssetId, $destThumbParams->getSourceParamsId(), $entry->getId());
         if (is_null($srcAsset)) {
             throw new APIException(APIErrors::FLAVOR_ASSET_IS_NOT_READY);
         }
     }
     $errDescription = null;
     $mediaInfo = mediaInfoPeer::retrieveByFlavorAssetId($srcAsset->getId());
     $destThumbParamsOutput = self::validateThumbAndMediaInfo($destThumbParams, $mediaInfo, $errDescription);
     if ($srcAsset->getType() == assetType::FLAVOR && is_null($destThumbParamsOutput->getVideoOffset())) {
         $destThumbParamsOutput->setVideoOffset($entry->getThumbOffset());
     }
     $destThumbParamsOutput->setVideoOffset(min($destThumbParamsOutput->getVideoOffset(), $entry->getDuration()));
     if (!$destThumbParamsOutput->getDensity()) {
         $partner = $entry->getPartner();
         if (!is_null($partner)) {
             $destThumbParamsOutput->setDensity($partner->getDefThumbDensity());
         }
     }
     $thumbAsset = assetPeer::retrieveByEntryIdAndParams($entry->getId(), $destThumbParams->getId());
     if ($thumbAsset) {
         $description = $thumbAsset->getDescription() . "\n" . $errDescription;
         $thumbAsset->setDescription($description);
     } else {
         $thumbAsset = new thumbAsset();
         $thumbAsset->setPartnerId($entry->getPartnerId());
         $thumbAsset->setEntryId($entry->getId());
         $thumbAsset->setDescription($errDescription);
         $thumbAsset->setFlavorParamsId($destThumbParams->getId());
     }
     $thumbAsset->incrementVersion();
     $thumbAsset->setTags($destThumbParamsOutput->getTags());
     $thumbAsset->setFileExt($destThumbParamsOutput->getFileExt());
     if ($thumbAsset->getStatus() != asset::ASSET_STATUS_READY) {
         $thumbAsset->setStatus(asset::ASSET_STATUS_CONVERTING);
     }
     //Sets the default thumb if this the only default thumb
     kBusinessPreConvertDL::setIsDefaultThumb($thumbAsset);
     if (!$destThumbParamsOutput) {
         $thumbAsset->setStatus(thumbAsset::FLAVOR_ASSET_STATUS_ERROR);
         $thumbAsset->save();
         return null;
     }
     $thumbAsset->save();
     // save flavor params
     $destThumbParamsOutput->setPartnerId($entry->getPartnerId());
     $destThumbParamsOutput->setEntryId($entry->getId());
     $destThumbParamsOutput->setFlavorAssetId($thumbAsset->getId());
     $destThumbParamsOutput->setFlavorAssetVersion($thumbAsset->getVersion());
     $destThumbParamsOutput->save();
     $srcSyncKey = $srcAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     $srcAssetType = $srcAsset->getType();
     if (!$runSync) {
         $job = kJobsManager::addCapturaThumbJob($parentJob, $entry->getPartnerId(), $entry->getId(), $thumbAsset->getId(), $srcSyncKey, $srcAsset->getId(), $srcAssetType, $destThumbParamsOutput);
         return $thumbAsset;
     }
     $errDescription = null;
     // Since this method is called when trying to crop an existing thumbnail, need to add this check - thumbAssets have no mediaInfo.
     $capturedPath = self::generateThumbnail($srcAsset, $destThumbParamsOutput, $errDescription, $mediaInfo ? $mediaInfo->getVideoRotation() : null);
     // failed
     if (!$capturedPath) {
         $thumbAsset->incrementVersion();
         $thumbAsset->setStatus(thumbAsset::FLAVOR_ASSET_STATUS_ERROR);
         $thumbAsset->setDescription($thumbAsset->getDescription() . "\n{$errDescription}");
         $thumbAsset->save();
         return $thumbAsset;
     }
     $thumbAsset->incrementVersion();
     $thumbAsset->setStatus(thumbAsset::FLAVOR_ASSET_STATUS_READY);
     if (file_exists($capturedPath)) {
         list($width, $height, $type, $attr) = getimagesize($capturedPath);
         $thumbAsset->setWidth($width);
         $thumbAsset->setHeight($height);
         $thumbAsset->setSize(filesize($capturedPath));
     }
     $logPath = $capturedPath . '.log';
     if (file_exists($logPath)) {
         $thumbAsset->incLogFileVersion();
         $thumbAsset->save();
         // creats the file sync
         $logSyncKey = $thumbAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_CONVERT_LOG);
         kFileSyncUtils::moveFromFile($logPath, $logSyncKey);
         KalturaLog::debug("Log archived file to: " . kFileSyncUtils::getLocalFilePathForKey($logSyncKey));
     } else {
         $thumbAsset->save();
     }
     $syncKey = $thumbAsset->getSyncKey(thumbAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     kFileSyncUtils::moveFromFile($capturedPath, $syncKey);
     KalturaLog::debug("Thumbnail archived file to: " . kFileSyncUtils::getLocalFilePathForKey($syncKey));
     if ($thumbAsset->hasTag(thumbParams::TAG_DEFAULT_THUMB)) {
         // increment thumbnail version
         $entry->setThumbnail(".jpg");
         $entry->setCreateThumb(false);
         $entry->save();
         $entrySyncKey = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_THUMB);
         $syncFile = kFileSyncUtils::createSyncFileLinkForKey($entrySyncKey, $syncKey);
         if ($syncFile) {
             // removes the DEFAULT_THUMB tag from all other thumb assets
             $entryThumbAssets = assetPeer::retrieveThumbnailsByEntryId($thumbAsset->getEntryId());
             foreach ($entryThumbAssets as $entryThumbAsset) {
                 if ($entryThumbAsset->getId() == $thumbAsset->getId()) {
                     continue;
                 }
                 if (!$entryThumbAsset->hasTag(thumbParams::TAG_DEFAULT_THUMB)) {
                     continue;
                 }
                 $entryThumbAsset->removeTags(array(thumbParams::TAG_DEFAULT_THUMB));
                 $entryThumbAsset->save();
             }
         }
     }
     if (!is_null($thumbAsset->getFlavorParamsId())) {
         kFlowHelper::generateThumbnailsFromFlavor($thumbAsset->getEntryId(), null, $thumbAsset->getFlavorParamsId());
     }
     return $thumbAsset;
 }
Exemple #14
0
 /**
  * Function adds bulk upload job to the queue
  * @param Partner $partner
  * @param kBulkUploadJobData $jobData
  * @param string $bulkUploadType
  * @throws APIException
  * @return BatchJob
  */
 public static function addBulkUploadJob(Partner $partner, kBulkUploadJobData $jobData, $bulkUploadType = null, $objectId = null, $objectType = null)
 {
     KalturaLog::debug("adding BulkUpload job");
     $job = new BatchJob();
     $job->setPartnerId($partner->getId());
     $job->setJobType(BatchJobType::BULKUPLOAD);
     $job->setJobSubType($bulkUploadType);
     if (!is_null($objectId) && !is_null($objectType)) {
         $job->setObjectId($objectId);
         $job->setObjectType($objectType);
     }
     if (is_null($jobData)) {
         throw new APIException(APIErrors::BULK_UPLOAD_BULK_UPLOAD_TYPE_NOT_VALID, $bulkUploadType);
     }
     $job->setStatus(BatchJob::BATCHJOB_STATUS_DONT_PROCESS);
     $job = kJobsManager::addJob($job, $jobData, BatchJobType::BULKUPLOAD, $bulkUploadType);
     if (!is_null($jobData->getFilePath())) {
         $syncKey = $job->getSyncKey(BatchJob::FILE_SYNC_BATCHJOB_SUB_TYPE_BULKUPLOAD);
         //		kFileSyncUtils::file_put_contents($syncKey, file_get_contents($csvFileData["tmp_name"]));
         try {
             kFileSyncUtils::moveFromFile($jobData->getFilePath(), $syncKey, true);
         } catch (Exception $e) {
             KalturaLog::err($e);
             throw new APIException(APIErrors::BULK_UPLOAD_CREATE_CSV_FILE_SYNC_ERROR);
         }
         $filePath = kFileSyncUtils::getLocalFilePathForKey($syncKey);
         $jobData->setFilePath($filePath);
     }
     if (!$jobData->getBulkUploadObjectType()) {
         $jobData->setBulkUploadObjectType(BulkUploadObjectType::ENTRY);
     }
     if ($jobData->getBulkUploadObjectType() == BulkUploadObjectType::ENTRY && !$jobData->getObjectData()->getConversionProfileId()) {
         $jobData->setConversionProfileId($partner->getDefaultConversionProfileId());
         $kmcVersion = $partner->getKmcVersion();
         $check = null;
         if ($kmcVersion < 2) {
             $check = ConversionProfilePeer::retrieveByPK($jobData->getConversionProfileId());
         } else {
             $check = conversionProfile2Peer::retrieveByPK($jobData->getConversionProfileId());
         }
         if (!$check) {
             throw new APIException(APIErrors::CONVERSION_PROFILE_ID_NOT_FOUND, $jobData->getConversionProfileId());
         }
     }
     $job->setData($jobData);
     return kJobsManager::updateBatchJob($job, BatchJob::BATCHJOB_STATUS_PENDING);
 }
 /**
  * @param flavorAsset $flavorAsset
  * @param string $fullPath
  * @param bool $copyOnly
  */
 protected function attachFile(flavorAsset $flavorAsset, $fullPath, $copyOnly = false)
 {
     $ext = pathinfo($fullPath, PATHINFO_EXTENSION);
     $flavorAsset->setFileExt($ext);
     $flavorAsset->setSize(kFile::fileSize($fullPath));
     $flavorAsset->incrementVersion();
     $flavorAsset->save();
     $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     try {
         kFileSyncUtils::moveFromFile($fullPath, $syncKey, true, $copyOnly);
     } catch (Exception $e) {
         if ($flavorAsset->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_QUEUED || $flavorAsset->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_NOT_APPLICABLE) {
             $flavorAsset->setDescription($e->getMessage());
             $flavorAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_ERROR);
             $flavorAsset->save();
         }
         throw $e;
     }
     if (!$flavorAsset->isLocalReadyStatus()) {
         $flavorAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_QUEUED);
     }
     $flavorAsset->save();
 }
Exemple #16
0
 /**
  * @param FileAsset $dbFileAsset
  * @param string $fullPath
  * @param bool $copyOnly
  */
 protected function attachFile(FileAsset $dbFileAsset, $fullPath, $copyOnly = false)
 {
     if (!$dbFileAsset->getFileExt()) {
         $ext = pathinfo($fullPath, PATHINFO_EXTENSION);
         $dbFileAsset->setFileExt($ext);
     }
     $dbFileAsset->setSize(kFile::fileSize($fullPath));
     $dbFileAsset->incrementVersion();
     $dbFileAsset->save();
     $syncKey = $dbFileAsset->getSyncKey(FileAsset::FILE_SYNC_ASSET);
     kFileSyncUtils::moveFromFile($fullPath, $syncKey, true, $copyOnly);
     $dbFileAsset->setStatus(FileAssetStatus::READY);
     $dbFileAsset->save();
 }
 public static function createThumbnailFromEntry(entry $entry, entry $source_entry, $time_offset, $flavorParamsId = null)
 {
     $media_type = $source_entry->getMediaType();
     // should capture thumbnail from video
     if ($media_type == entry::ENTRY_MEDIA_TYPE_VIDEO && $time_offset != -1) {
         $flavorAsset = null;
         if ($flavorParamsId) {
             $flavorAsset = flavorAssetPeer::retrieveByEntryIdAndFlavorParams($source_entry->getId(), $flavorParamsId);
         }
         if (is_null($flavorAsset) || $flavorAsset->getStatus() != flavorAsset::FLAVOR_ASSET_STATUS_READY) {
             $flavorAsset = flavorAssetPeer::retrieveOriginalByEntryId($source_entry->getId());
         }
         if (is_null($flavorAsset)) {
             $flavorAsset = flavorAssetPeer::retrieveHighestBitrateByEntryId($source_entry->getId());
         }
         if (is_null($flavorAsset)) {
             throw new Exception("Flavor asset not found");
         }
         $flavorSyncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
         if (!$flavorSyncKey) {
             return false;
         }
         $dataPath = kFileSyncUtils::getReadyLocalFilePathForKey($flavorSyncKey);
         $tempPath = myContentStorage::getFSUploadsPath();
         $tempThumbPrefix = $tempPath . "temp_thumb" . microtime(true);
         $thumbBigFullPath = $tempThumbPrefix . "big_1.jpg";
         $thumbFullPath = $tempThumbPrefix . '1.jpg';
         myFileConverter::autoCaptureFrame($dataPath, $tempThumbPrefix . "big_", $time_offset, -1, -1);
         // removed creation of "small thumb" - not in use
         myFileConverter::convertImage($thumbBigFullPath, $thumbFullPath);
         $bigThumbExists = file_exists($thumbBigFullPath) && filesize($thumbBigFullPath);
         if (!$bigThumbExists) {
             return false;
         }
         $entry->setThumbnail(".jpg");
         $entry->save();
         // create new thumb file for entry
         $newThumbKey = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_THUMB);
         kFileSyncUtils::moveFromFile($thumbBigFullPath, $newThumbKey);
     } else {
         if ($media_type == entry::ENTRY_MEDIA_TYPE_VIDEO && $time_offset == -1 || $media_type == entry::ENTRY_MEDIA_TYPE_SHOW) {
             $thumbBigFullKey = $source_entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_THUMB);
             if (!kFileSyncUtils::fileSync_exists($thumbBigFullKey)) {
                 return false;
             }
             $entry->setThumbnail(".jpg");
             $entry->save();
             // copy existing thumb
             $newThumbKey = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_THUMB);
             kFileSyncUtils::softCopy($thumbBigFullKey, $newThumbKey);
         } elseif ($media_type == entry::ENTRY_MEDIA_TYPE_IMAGE) {
             $thumb_key = $source_entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA);
             $thumb_path = kFileSyncUtils::getLocalFilePathForKey($thumb_key);
             $entry->setThumbnail(".jpg");
             $entry->save();
             // copy existing thumb
             $newThumbKey = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_THUMB);
             kFileSyncUtils::copyFromFile($thumb_path, $newThumbKey);
         } else {
             return false;
         }
     }
     self::disableAutoThumbnailCreation($entry->getId());
     return true;
 }
Exemple #18
0
 /**
  * @param UploadToken $uploadToken
  */
 public static function handleUploadFinished(UploadToken $uploadToken)
 {
     if (!is_subclass_of($uploadToken->getObjectType(), assetPeer::OM_CLASS) && $uploadToken->getObjectType() != FileAssetPeer::OM_CLASS && $uploadToken->getObjectType() != entryPeer::OM_CLASS) {
         KalturaLog::info("Class [" . $uploadToken->getObjectType() . "] not supported");
         return;
     }
     $fullPath = kUploadTokenMgr::getFullPathByUploadTokenId($uploadToken->getId());
     if (!file_exists($fullPath)) {
         KalturaLog::info("File path [{$fullPath}] not found");
         $remoteDCHost = kUploadTokenMgr::getRemoteHostForUploadToken($uploadToken->getId(), kDataCenterMgr::getCurrentDcId());
         if (!$remoteDCHost) {
             KalturaLog::err("File path [{$fullPath}] could not be redirected");
             return;
         }
         kFileUtils::dumpApiRequest($remoteDCHost);
     }
     if ($uploadToken->getObjectType() == FileAssetPeer::OM_CLASS) {
         $dbFileAsset = FileAssetPeer::retrieveByPK($uploadToken->getObjectId());
         if (!$dbFileAsset) {
             KalturaLog::err("File asset id [" . $uploadToken->getObjectId() . "] not found");
             return;
         }
         if (!$dbFileAsset->getFileExt()) {
             $dbFileAsset->setFileExt(pathinfo($fullPath, PATHINFO_EXTENSION));
         }
         $dbFileAsset->incrementVersion();
         $dbFileAsset->save();
         $syncKey = $dbFileAsset->getSyncKey(FileAsset::FILE_SYNC_ASSET);
         try {
             kFileSyncUtils::moveFromFile($fullPath, $syncKey, true);
         } catch (Exception $e) {
             $dbFileAsset->setStatus(FileAssetStatus::ERROR);
             $dbFileAsset->save();
             throw $e;
         }
         if ($dbFileAsset->getStatus() == FileAssetStatus::UPLOADING) {
             $finalPath = kFileSyncUtils::getLocalFilePathForKey($syncKey);
             $dbFileAsset->setSize(kFile::fileSize($finalPath));
             $dbFileAsset->setStatus(FileAssetStatus::READY);
             $dbFileAsset->save();
         }
         $uploadToken->setStatus(UploadToken::UPLOAD_TOKEN_CLOSED);
         $uploadToken->save();
         KalturaLog::info("File asset [" . $dbFileAsset->getId() . "] handled");
         return;
     }
     if (is_subclass_of($uploadToken->getObjectType(), assetPeer::OM_CLASS)) {
         $dbAsset = assetPeer::retrieveById($uploadToken->getObjectId());
         if (!$dbAsset) {
             KalturaLog::err("Asset id [" . $uploadToken->getObjectId() . "] not found");
             return;
         }
         $ext = pathinfo($fullPath, PATHINFO_EXTENSION);
         $dbAsset->setFileExt($ext);
         $dbAsset->incrementVersion();
         $dbAsset->save();
         $syncKey = $dbAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
         try {
             kFileSyncUtils::moveFromFile($fullPath, $syncKey, true);
         } catch (Exception $e) {
             if ($dbAsset instanceof flavorAsset) {
                 kBatchManager::updateEntry($dbAsset->getEntryId(), entryStatus::ERROR_IMPORTING);
             }
             $dbAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_ERROR);
             $dbAsset->save();
             throw $e;
         }
         if ($dbAsset->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_IMPORTING) {
             $finalPath = kFileSyncUtils::getLocalFilePathForKey($syncKey);
             $dbAsset->setSize(kFile::fileSize($finalPath));
             if ($dbAsset instanceof flavorAsset) {
                 if ($dbAsset->getIsOriginal()) {
                     $dbAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_QUEUED);
                 } else {
                     $dbAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_VALIDATING);
                 }
             } else {
                 $dbAsset->setStatus(thumbAsset::FLAVOR_ASSET_STATUS_READY);
             }
             if ($dbAsset instanceof thumbAsset) {
                 list($width, $height, $type, $attr) = getimagesize($finalPath);
                 $dbAsset->setWidth($width);
                 $dbAsset->setHeight($height);
             }
             $dbAsset->save();
             kEventsManager::raiseEvent(new kObjectAddedEvent($dbAsset));
         }
         $uploadToken->setStatus(UploadToken::UPLOAD_TOKEN_CLOSED);
         $uploadToken->save();
     }
     if ($uploadToken->getObjectType() == entryPeer::OM_CLASS) {
         $dbEntry = entryPeer::retrieveByPK($uploadToken->getObjectId());
         if (!$dbEntry) {
             KalturaLog::err("Entry id [" . $uploadToken->getObjectId() . "] not found");
             return;
         }
         //Keep original extention
         $ext = pathinfo($fullPath, PATHINFO_EXTENSION);
         // increments version
         $dbEntry->setData('100000.' . $ext);
         $dbEntry->save();
         $syncKey = $dbEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA);
         try {
             kFileSyncUtils::moveFromFile($fullPath, $syncKey, true);
         } catch (Exception $e) {
             if ($dbAsset instanceof flavorAsset) {
                 kBatchManager::updateEntry($dbEntry->getId(), entryStatus::ERROR_IMPORTING);
             }
             throw $e;
         }
         $dbEntry->setStatus(entryStatus::READY);
         $dbEntry->save();
         $uploadToken->setStatus(UploadToken::UPLOAD_TOKEN_CLOSED);
         $uploadToken->save();
     }
 }
 private function handleEntry($onlyExtractThumb, $prefix, $type, $entry_id, $name = null, $tags = null, $entry = null)
 {
     KalturaLog::debug("handleEntry({$type}, {$entry_id}, {$name})");
     $this->clear($prefix, $entry_id);
     $kuser_id = $this->kuser_id;
     $entry_data_prefix = $kuser_id . '_' . ($prefix == '' ? 'data' : rtrim($prefix, '_'));
     $uploads = myContentStorage::getFSUploadsPath();
     $content = myContentStorage::getFSContentRootPath();
     $media_source = $this->getParam('entry_media_source');
     $media_type = $this->getParam('entry_media_type');
     $entry_url = $this->getParam('entry_url');
     $entry_source_link = $this->getParam('entry_source_link');
     $entry_fileName = $this->getParam('entry_data');
     $entry_thumbNum = $this->getParam('entry_thumb_num', 0);
     $entry_thumbUrl = $this->getParam('entry_thumb_url', '');
     $should_copy = $this->getParam('should_copy', false);
     $skip_conversion = $this->getParam('skip_conversion', false);
     $webcam_suffix = $this->getParam('webcam_suffix', '');
     $duration = $this->getParam('duration', null);
     $entry_fullPath = "";
     $ext = null;
     $entry = null;
     if ($entry_id) {
         $entry = entryPeer::retrieveByPK($entry_id);
     } else {
         $entry = new entry();
     }
     $this->entry = $entry;
     $entry_status = $entry->getStatus();
     if (is_null($entry_status)) {
         $entry_status = entryStatus::READY;
     }
     // by the end of this block of code $entry_fullPath will point to the location of the entry
     // the entry status will be set (IMPORT / PRECONVERT / READY)
     // a background image is always previewed by the user no matter what source he used
     // so the entry is already in the /uploads directory
     // continue tracking the file upload
     $te = new TrackEntry();
     $te->setEntryId($entry_id);
     $te->setTrackEventTypeId(TrackEntry::TRACK_ENTRY_EVENT_TYPE_ADD_ENTRY);
     KalturaLog::debug("handleEntry: media_source: {$media_source}, prefix: {$prefix}");
     if ($media_source == entry::ENTRY_MEDIA_SOURCE_FILE || $prefix == 'bg_') {
         $full_path = $this->getParam('entry_full_path');
         if ($full_path) {
             $entry_fullPath = $full_path;
         } else {
             $entry_fullPath = $uploads . $entry_data_prefix . strrchr($entry_fileName, '.');
         }
         if ($media_type == entry::ENTRY_MEDIA_TYPE_VIDEO || $media_type == entry::ENTRY_MEDIA_TYPE_AUDIO) {
             $entry_status = entryStatus::PRECONVERT;
         }
         $te->setParam3Str($entry_fullPath);
         $te->setDescription(__METHOD__ . ":" . __LINE__ . "::ENTRY_MEDIA_SOURCE_FILE");
     } else {
         if ($media_source == entry::ENTRY_MEDIA_SOURCE_WEBCAM) {
             // set $entry_fileName to webcam output file and flag that conversion is not needed
             $webcam_basePath = $content . '/content/webcam/' . ($webcam_suffix ? $webcam_suffix : 'my_recorded_stream_' . $kuser_id);
             $entry_fullPath = $webcam_basePath . '.' . kWAMSWebcam::OUTPUT_FILE_EXT;
             $ext = kWAMSWebcam::OUTPUT_FILE_EXT;
             if (file_exists($entry_fullPath)) {
                 // continue tracking the webcam
                 $te->setParam3Str($entry_fullPath);
                 $te->setDescription(__METHOD__ . ":" . __LINE__ . "::ENTRY_MEDIA_SOURCE_WEBCAM");
             } else {
                 KalturaLog::err("File [{$entry_fullPath}] does not exist");
                 $entry_status = entryStatus::ERROR_IMPORTING;
             }
         } else {
             // if the url ends with .ext, we'll extract it this way
             $urlext = strrchr($entry_url, '.');
             // TODO: fix this patch
             if (strlen($urlext) > 4) {
                 $urlext = '.jpg';
             }
             // if we got something wierd, assume we're downloading a jpg
             $entry_fileName = $entry_data_prefix . $urlext;
             KalturaLog::debug("handleEntry: media_type: {$media_type}");
             if ($media_type == entry::ENTRY_MEDIA_TYPE_IMAGE) {
                 $duration = 0;
                 $entry_fullPath = $uploads . $entry_fileName;
                 if (!kFile::downloadUrlToFile($entry_url, $entry_fullPath)) {
                     KalturaLog::debug("Failed downloading file[{$entry_url}]");
                     $entry_status = entryStatus::ERROR_IMPORTING;
                 }
                 // track images
                 $te->setParam3Str($entry_fullPath);
                 $te->setDescription(__METHOD__ . ":" . __LINE__ . "::ENTRY_MEDIA_SOURCE_URL:ENTRY_MEDIA_TYPE_IMAGE");
             } else {
                 if ($media_type == entry::ENTRY_MEDIA_TYPE_VIDEO) {
                     //fixme - we can extract during import
                     $ext = "flv";
                 } else {
                     $ext = "mp3";
                 }
                 $entry_status = entryStatus::IMPORT;
                 // track images
                 $te->setParam3Str($ext);
                 $te->setDescription(__METHOD__ . ":" . __LINE__ . "::ENTRY_MEDIA_SOURCE_URL:ENTRY_MEDIA_TYPE_VIDEO");
             }
         }
     }
     if ($ext == null) {
         $entry_fullPathTmp = $entry_fullPath;
         $qpos = strpos($entry_fullPathTmp, "?");
         if ($qpos !== false) {
             $entry_fullPathTmp = substr($entry_fullPathTmp, 0, $qpos);
         }
         $ext = strtolower(pathinfo($entry_fullPathTmp, PATHINFO_EXTENSION));
     }
     // save the Trackentry
     TrackEntry::addTrackEntry($te);
     KalturaLog::debug("handleEntry: ext: {$ext}");
     //		We don't want to reject entries based on file extentions anumore
     //		Remarked by Tan-Tan
     //
     //		if ($entry_status == entryStatus::PRECONVERT && !myContentStorage::fileExtNeedConversion($ext))
     //		{
     //
     //			$this->errorMsg = "insertEntryAction Error - PRECONVERT file type not acceptable ($ext)";
     //			KalturaLog::debug("handleEntry: err: $this->errorMsg");
     //			if(is_null($entry) && $this->entry_id)
     //			{
     //				$entry = entryPeer::retrieveByPK($this->entry_id);
     //			}
     //			if($entry)
     //			{
     //				$entry->setStatus(entryStatus::ERROR_CONVERTING);
     //				$entry->save();
     //			}
     //			return false;
     //		}
     $media_date = null;
     //		We don't want to reject entries based on file extentions anumore
     //		Remarked by Tan-Tan
     //
     //		// if entry is ready, validate file type (webcam is an exception since we control the file type - flv)
     //		if ($entry_status == entryStatus::READY &&
     //			$media_source != entry::ENTRY_MEDIA_SOURCE_WEBCAM && !myContentStorage::fileExtAccepted($ext))
     //		{
     //			$this->errorMsg = "insertEntryAction Error - READY file type not acceptable ($ext)";
     //			KalturaLog::debug("handleEntry: err: $this->errorMsg");
     //			if(is_null($entry) && $this->entry_id)
     //			{
     //				$entry = entryPeer::retrieveByPK($this->entry_id);
     //			}
     //			if($entry)
     //			{
     //				$entry->setStatus(entryStatus::ERROR_CONVERTING);
     //				$entry->save();
     //			}
     //			return false;
     //		}
     if ($entry_status == entryStatus::ERROR_IMPORTING) {
         $need_thumb = false;
         // we wont be needing a thumb for an errornous entry
         KalturaLog::debug("handleEntry: error importing, thumb not needed");
     } else {
         // thumbs are created by one of the following ways:
         // 1. Image - images are already on disk for every selection method, so we can just create a thumb
         // 2. Audio - no thumb is needed
         // 3. Video -
         //		a. uploaded (file / webcam) - file is on disk and the user already selected a thumb
         //		b. imported - the source site had a thumbnail and we'll use it
         $thumbTempPrefix = $uploads . $entry_data_prefix . '_thumbnail_';
         $thumbBigFullPath = null;
         $need_thumb = $type == entryType::MEDIA_CLIP;
         KalturaLog::debug("handleEntry: handling media {$media_type}");
         if ($media_type == entry::ENTRY_MEDIA_TYPE_IMAGE) {
             // fetch media creation date
             $exif_image_type = @exif_imagetype($entry_fullPath);
             if ($exif_image_type == IMAGETYPE_JPEG || $exif_image_type == IMAGETYPE_TIFF_II || $exif_image_type == IMAGETYPE_TIFF_MM || $exif_image_type == IMAGETYPE_IFF || $exif_image_type == IMAGETYPE_PNG) {
                 $exif_data = @exif_read_data($entry_fullPath);
                 if ($exif_data && isset($exif_data["DateTimeOriginal"]) && $exif_data["DateTimeOriginal"]) {
                     $media_date = $exif_data["DateTimeOriginal"];
                     $ts = strtotime($media_date);
                     // handle invalid dates either due to bad format or out of range
                     if ($ts === -1 || $ts === false || $ts < strtotime('2000-01-01') || $ts > strtotime('2015-01-01')) {
                         $media_date = null;
                     }
                 }
             }
             // create thumb
             $thumbFullPath = $thumbTempPrefix . '1.jpg';
             $entry_thumbNum = 1;
             $need_thumb = true;
             //copy($entry_fullPath, $thumbFullPath);
             myFileConverter::createImageThumbnail($entry_fullPath, $thumbFullPath, "image2");
             //$thumbBigFullPath = $thumbFullPath; // no filesync for thumbnail of image
         } else {
             if ($media_type == entry::ENTRY_MEDIA_TYPE_VIDEO) {
                 if ($entry_status == entryStatus::IMPORT || $media_source == entry::ENTRY_MEDIA_SOURCE_URL) {
                     // import thumb and convert to our size
                     $thumbFullPath = $thumbTempPrefix . '1.jpg';
                     $entry_thumbNum = 1;
                     $importedThumbPath = $uploads . $entry_data_prefix . '_temp_thumb' . strrchr($entry_thumbUrl, '.');
                     if (kFile::downloadUrlToFile($entry_thumbUrl, $importedThumbPath)) {
                         myFileConverter::createImageThumbnail($importedThumbPath, $thumbFullPath, "image2");
                         // set thumb as big thumb so fileSync will be created.
                         $thumbBigFullPath = $thumbFullPath;
                     } else {
                         $need_thumb = false;
                     }
                 } else {
                     if ($entry_thumbNum == 0) {
                         $entry_thumbNum = 1;
                         $thumbTime = 3;
                         if ($duration && $duration < $thumbTime * 1000) {
                             $thumbTime = floor($duration / 1000);
                         }
                         // for videos - thumbail should be created in post convert
                         // otherwise this code will fail if the thumbanil wasn't created successfully (roman)
                         //myFileConverter::autoCaptureFrame($entry_fullPath, $thumbTempPrefix."big_", $thumbTime, -1, -1);
                         $need_thumb = false;
                         $thumbBigFullPath = $thumbTempPrefix . "big_" . $entry_thumbNum . '.jpg';
                     }
                 }
                 //else select existing thumb ($entry_thumbNum already points to the right thumbnail)
             }
         }
         $thumbFullPath = $thumbTempPrefix . $entry_thumbNum . '.jpg';
         // if we arrived here both entry and thumbnail are valid we can now update the db
         // in order to have the final entry_id and move its data to its final destination
         if ($onlyExtractThumb) {
             return $thumbFullPath;
         }
     }
     $entry->setkshowId($this->kshow_id);
     $entry->setKuserId($kuser_id);
     $entry->setCreatorKuserId($kuser_id);
     if ($this->partner_id != null) {
         $entry->setPartnerId($this->partner_id);
         $entry->setSubpId($this->subp_id);
     }
     $entry->setName($name ? $name : $this->getParam('entry_name'));
     //		$entry->setDescription('');//$this->getParam('entry_description'));
     $entry->setType($type);
     $entry->setMediaType($media_type);
     $entry->setTags($tags ? $tags : $this->getParam('entry_tags'));
     $entry->setSource($media_source);
     $entry->setSourceId($this->getParam('entry_media_id'));
     if ($media_date) {
         $entry->setMediaDate($media_date);
     }
     // if source_link wasnt given use the entry_url HOWEVER, use it only if id doesnt contain @ which suggests the use of a password
     $entry->setSourceLink($entry_source_link ? $entry_source_link : (strstr($entry_url, '@') ? "" : $entry_url));
     if ($media_source == entry::ENTRY_MEDIA_SOURCE_FILE) {
         $entry->setSourceLink("file:{$entry_fullPath}");
     }
     $entry->setLicenseType($this->getParam('entry_license'));
     $entry->setCredit($this->getParam('entry_credit'));
     $entry->setStatus($entry_status);
     if ($duration !== null) {
         $entry->setLengthInMsecs($duration);
     }
     if ($this->entry_id == 0) {
         $entry->save();
         $this->entry_id = $entry->getId();
     }
     // move thumb to final destination and set db entry
     if ($media_type != entry::ENTRY_MEDIA_TYPE_AUDIO && $entry_thumbNum && $need_thumb) {
         KalturaLog::debug("handleEntry: saving none audio thumb [{$thumbBigFullPath}]");
         $entry->setThumbnail('.jpg');
         if ($thumbBigFullPath) {
             if ($media_type != entry::ENTRY_MEDIA_TYPE_IMAGE) {
                 myFileConverter::convertImage($thumbBigFullPath, $thumbFullPath);
             }
             /*$thumbBigFinalPath = $content.$entry->getBigThumbnailPath();
             		myContentStorage::moveFile($thumbBigFullPath, $thumbBigFinalPath, true , $should_copy );
             		*/
             $entryThumbKey = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_THUMB);
             try {
                 if (!$should_copy) {
                     kFileSyncUtils::moveFromFile($thumbBigFullPath, $entryThumbKey);
                 } else {
                     kFileSyncUtils::copyFromFile($thumbBigFullPath, $entryThumbKey);
                 }
             } catch (Exception $e) {
                 $entry->setStatus(entryStatus::ERROR_CONVERTING);
                 $entry->save();
                 throw $e;
             }
         }
     }
     // after extracting the thumb we can move the entry to its next destination
     KalturaLog::debug("handleEntry: current status [" . $entry->getStatus() . "]");
     // if needed a job will be submitted for importing external media sources
     if ($entry->getStatus() == entryStatus::IMPORT) {
         KalturaLog::debug("handleEntry: creating import job");
         // changed by Tan-Tan, Nov 09 to support the new batch mechanism
         kJobsManager::addImportJob(null, $this->entry_id, $this->partner_id, $entry_url);
         // remarked by Tan-Tan
         //			$entry_fullPath = $content.'/content/imports/data/'.$this->entry_id.".".$ext;
         //			myContentStorage::fullMkdir($entry_fullPath);
         //
         //			$batchClient = new myBatchUrlImportClient();
         // 			$batchClient->addJob($this->entry_id, $entry_url, $entry_fullPath);
     } else {
         if ($entry->getStatus() == entryStatus::PRECONVERT) {
             if (!$skip_conversion) {
                 // changed by Tan-Tan, Dec 09 to support the new batch mechanism
                 KalturaLog::debug("handleEntry: creating original flavor asset for pre convert");
                 $flavorAsset = kFlowHelper::createOriginalFlavorAsset($this->partner_id, $this->entry_id);
                 if ($flavorAsset) {
                     $flavorAsset->setFileExt($ext);
                     $flavorAsset->save();
                     $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
                     try {
                         kFileSyncUtils::moveFromFile($entry_fullPath, $syncKey);
                     } catch (Exception $e) {
                         $entry->setStatus(entryStatus::ERROR_CONVERTING);
                         $flavorAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_ERROR);
                         $entry->save();
                         $flavorAsset->save();
                         throw $e;
                     }
                     kEventsManager::raiseEvent(new kObjectAddedEvent($flavorAsset));
                 } else {
                     $entry->setStatus(entryStatus::ERROR_CONVERTING);
                 }
                 //				Remarked by Tan-Tan
                 //				$targetFileName = $this->entry_id.".".$ext;
                 //				if ( false /* old conversion */)
                 //				{
                 //								// if we need to convert move entry to conversion directory
                 //								$preConvPath = $content.'/content/preconvert/';
                 //								myContentStorage::moveFile($entry_fullPath, $preConvPath."data/".$targetFileName, true , $should_copy );
                 //
                 //								$signalFilePath = $preConvPath."files/".$targetFileName;
                 //								myContentStorage::fullMkdir($signalFilePath);
                 //								touch($signalFilePath);
                 //				}
                 //				else
                 //				{
                 //								$preConvPath = myContentStorage::getFSContentRootPath (). "/content/new_preconvert";
                 //								$to_data = $preConvPath . "/$targetFileName" ;
                 //								myContentStorage::moveFile($entry_fullPath, $to_data , true);
                 //								touch ( $to_data . ".indicator" );
                 //				}
             }
         } else {
             if ($entry->getStatus() == entryStatus::PENDING || $media_source == entry::ENTRY_MEDIA_SOURCE_WEBCAM) {
                 $entry->setData($entry_fullPath);
                 $entry->save();
                 if ($media_type == entry::ENTRY_MEDIA_TYPE_VIDEO || $media_type == entry::ENTRY_MEDIA_TYPE_AUDIO) {
                     KalturaLog::debug("handleEntry: creating original flavor asset for ready entry");
                     $flavorAsset = kFlowHelper::createOriginalFlavorAsset($this->partner_id, $this->entry_id);
                     if ($flavorAsset) {
                         $ext = pathinfo($entry_fullPath, PATHINFO_EXTENSION);
                         $flavorAsset->setFileExt($ext);
                         $flavorAsset->save();
                         $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
                         try {
                             if (!$should_copy) {
                                 kFileSyncUtils::moveFromFile($entry_fullPath, $syncKey);
                             } else {
                                 // copy & create file sync from $entry_fullPath
                                 kFileSyncUtils::copyFromFile($entry_fullPath, $syncKey);
                             }
                         } catch (Exception $e) {
                             $entry->setStatus(entryStatus::ERROR_CONVERTING);
                             $flavorAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_ERROR);
                             $entry->save();
                             $flavorAsset->save();
                             throw $e;
                         }
                         //					// bypass to conversion
                         //					kBusinessPreConvertDL::bypassConversion($flavorAsset, $entry);
                         /**
                          * if this is webcam entry, create mediaInfo for the source flavor asset synchronously
                          * since entry is ready right at the beginning
                          */
                         if ($media_source == entry::ENTRY_MEDIA_SOURCE_WEBCAM) {
                             require_once SF_ROOT_DIR . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . "api_v3" . DIRECTORY_SEPARATOR . "bootstrap.php";
                             // extract file path
                             $sourceFileKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
                             $sourceFilePath = kFileSyncUtils::getLocalFilePathForKey($sourceFileKey);
                             // call mediaInfo for file
                             $mediaInfo = new mediaInfo();
                             try {
                                 $mediaInfoParser = new KMediaInfoMediaParser($sourceFilePath, kConf::get('bin_path_mediainfo'));
                                 $KalturaMediaInfo = new KalturaMediaInfo();
                                 $KalturaMediaInfo = $mediaInfoParser->getMediaInfo();
                                 $mediaInfo = $KalturaMediaInfo->toInsertableObject($mediaInfo);
                                 $mediaInfo->setFlavorAssetId($flavorAsset->getId());
                                 $mediaInfo->save();
                             } catch (Exception $e) {
                                 KalturaLog::err("Getting media info: " . $e->getMessage());
                                 $mediaInfo = null;
                             }
                             // fix flavor asset according to mediainfo
                             if ($mediaInfo) {
                                 KDLWrap::ConvertMediainfoCdl2FlavorAsset($mediaInfo, $flavorAsset);
                                 $flavorTags = KDLWrap::CDLMediaInfo2Tags($mediaInfo, array(flavorParams::TAG_WEB, flavorParams::TAG_MBR));
                                 $flavorAsset->setTags(implode(',', $flavorTags));
                             }
                             $flavorAsset->save();
                         }
                         kEventsManager::raiseEvent(new kObjectAddedEvent($flavorAsset));
                         $flavorAsset->setStatusLocalReady();
                         $flavorAsset->save();
                     } else {
                         $entry->setStatus(entryStatus::ERROR_IMPORTING);
                     }
                 } else {
                     if ($entry->getType() == entryType::DOCUMENT) {
                         //TODO: document should be handled by the plugin manager)
                         KalturaLog::debug("handleEntry: creating original flavor asset for ready entry");
                         $flavorAsset = kFlowHelper::createOriginalFlavorAsset($this->partner_id, $this->entry_id);
                         if ($flavorAsset) {
                             $ext = pathinfo($entry_fullPath, PATHINFO_EXTENSION);
                             $flavorAsset->setFileExt($ext);
                             $flavorAsset->save();
                             $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
                             try {
                                 if (!$should_copy) {
                                     kFileSyncUtils::moveFromFile($entry_fullPath, $syncKey);
                                 } else {
                                     // copy & create file sync from $entry_fullPath
                                     kFileSyncUtils::copyFromFile($entry_fullPath, $syncKey);
                                 }
                             } catch (Exception $e) {
                                 $entry->setStatus(entryStatus::ERROR_CONVERTING);
                                 $flavorAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_ERROR);
                                 $entry->save();
                                 $flavorAsset->save();
                                 throw $e;
                             }
                             kEventsManager::raiseEvent(new kObjectAddedEvent($flavorAsset));
                         }
                     } else {
                         KalturaLog::debug("handleEntry: creating data file sync for file [{$entry_fullPath}]");
                         $entryDataKey = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA);
                         if (!kFileSyncUtils::file_exists($entryDataKey)) {
                             try {
                                 if (!$should_copy) {
                                     kFileSyncUtils::moveFromFile($entry_fullPath, $entryDataKey);
                                 } else {
                                     // copy & create file sync from $entry_fullPath
                                     kFileSyncUtils::copyFromFile($entry_fullPath, $entryDataKey);
                                 }
                             } catch (Exception $e) {
                                 $entry->setStatus(entryStatus::ERROR_CONVERTING);
                                 $entry->save();
                                 throw $e;
                             }
                         }
                         $entry->setStatus(entryStatus::READY);
                         $entry->save();
                     }
                 }
                 //			Remarked by Tan-Tan, the flavor asset should be synced instead of the entry
                 //
                 //			$entryDataKey = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA);
                 //			if(!$should_copy)
                 //			{
                 //				kFileSyncUtils::moveFromFile($entry_fullPath, $entryDataKey);
                 //			}
                 //			else
                 //			{
                 //				// copy & create file sync from $entry_fullPath
                 //				kFileSyncUtils::copyFromFile($entry_fullPath, $entryDataKey);
                 //			}
             }
         }
     }
     if ($entry->getStatus() == entryStatus::READY) {
         $entry->updateDimensions();
     }
     $entry->save();
     return true;
 }
 /**
  * Update an existing metadata object views file
  * 
  * @action updateViewsFromFile
  * @param int $id 
  * @param file $viewsFile UI views file
  * @return KalturaMetadataProfile
  * @throws KalturaErrors::INVALID_OBJECT_ID
  * @throws MetadataErrors::METADATA_FILE_NOT_FOUND
  */
 function updateViewsFromFileAction($id, $viewsFile)
 {
     $dbMetadataProfile = MetadataProfilePeer::retrieveByPK($id);
     if (!$dbMetadataProfile) {
         throw new KalturaAPIException(KalturaErrors::INVALID_OBJECT_ID, $id);
     }
     $filePath = null;
     if ($viewsFile) {
         $filePath = $viewsFile['tmp_name'];
         if (!file_exists($filePath)) {
             throw new KalturaAPIException(MetadataErrors::METADATA_FILE_NOT_FOUND, $viewsFile['name']);
         }
     }
     $dbMetadataProfile->incrementViewsVersion();
     $dbMetadataProfile->save();
     if (trim(file_get_contents($filePath)) != '') {
         $key = $dbMetadataProfile->getSyncKey(MetadataProfile::FILE_SYNC_METADATA_VIEWS);
         kFileSyncUtils::moveFromFile($filePath, $key);
     }
     $metadataProfile = new KalturaMetadataProfile();
     $metadataProfile->fromObject($dbMetadataProfile);
     return $metadataProfile;
 }
Exemple #21
0
 /**
  * @param BatchJob $dbBatchJob
  * @param kPostConvertJobData $data
  */
 protected static function createThumbnail(BatchJob $dbBatchJob, kPostConvertJobData $data)
 {
     KalturaLog::debug("Post Convert finished with thumnail: " . $data->getThumbPath());
     $ignoreThumbnail = false;
     // this logic decide when this thumbnail should be used
     $rootBatchJob = $dbBatchJob->getRootJob();
     if ($rootBatchJob->getJobType() == BatchJobType::CONVERT_PROFILE) {
         $thisFlavorHeight = $data->getThumbHeight();
         $thisFlavorBitrate = $data->getThumbBitrate();
         $rootBatchJobData = $rootBatchJob->getData();
         if (!$rootBatchJobData->getCreateThumb() || $rootBatchJobData->getThumbBitrate() > $thisFlavorBitrate) {
             $ignoreThumbnail = true;
         } elseif ($rootBatchJobData->getThumbBitrate() == $thisFlavorBitrate && $rootBatchJobData->getThumbHeight() > $thisFlavorHeight) {
             $ignoreThumbnail = true;
         } else {
             $rootBatchJobData->setThumbHeight($thisFlavorHeight);
             $rootBatchJobData->setThumbBitrate($thisFlavorBitrate);
             $rootBatchJob->setData($rootBatchJobData);
             $rootBatchJob->save();
         }
     }
     if (!$ignoreThumbnail) {
         KalturaLog::debug("Saving thumbnail from: " . $data->getThumbPath());
         // creats thumbnail the file sync
         $entry = $dbBatchJob->getEntry(false, false);
         if (!$entry) {
             KalturaLog::err("Entry not found [" . $dbBatchJob->getEntryId() . "]");
             return;
         }
         KalturaLog::debug("Entry duration: " . $entry->getLengthInMsecs());
         if (!$entry->getLengthInMsecs()) {
             KalturaLog::debug("Copy duration from flvor asset: " . $data->getFlavorAssetId());
             $mediaInfo = mediaInfoPeer::retrieveByFlavorAssetId($data->getFlavorAssetId());
             if ($mediaInfo) {
                 KalturaLog::debug("Set duration to: " . $mediaInfo->getContainerDuration());
                 $entry->setDimensions($mediaInfo->getVideoWidth(), $mediaInfo->getVideoHeight());
                 $entry->setLengthInMsecs($mediaInfo->getContainerDuration());
             }
         }
         $entry->reload();
         // make sure that the thumbnail version is the latest
         $entry->setThumbnail(".jpg");
         $entry->save();
         $syncKey = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_THUMB);
         kFileSyncUtils::moveFromFile($data->getThumbPath(), $syncKey);
     }
 }
 /**
  * @action addFromImage
  * @param string $entryId
  * @param file $fileData
  * @return KalturaThumbAsset
  * 
  * @throws KalturaErrors::ENTRY_ID_NOT_FOUND
  * @validateUser entry entryId edit
  */
 public function addFromImageAction($entryId, $fileData)
 {
     $dbEntry = entryPeer::retrieveByPK($entryId);
     if (!$dbEntry) {
         throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId);
     }
     $ext = pathinfo($fileData["name"], PATHINFO_EXTENSION);
     $dbThumbAsset = new thumbAsset();
     $dbThumbAsset->setPartnerId($dbEntry->getPartnerId());
     $dbThumbAsset->setEntryId($dbEntry->getId());
     $dbThumbAsset->setStatus(thumbAsset::ASSET_STATUS_QUEUED);
     $dbThumbAsset->setFileExt($ext);
     $dbThumbAsset->incrementVersion();
     $dbThumbAsset->save();
     $syncKey = $dbThumbAsset->getSyncKey(thumbAsset::FILE_SYNC_ASSET_SUB_TYPE_ASSET);
     kFileSyncUtils::moveFromFile($fileData["tmp_name"], $syncKey);
     $finalPath = kFileSyncUtils::getLocalFilePathForKey($syncKey);
     list($width, $height, $type, $attr) = getimagesize($finalPath);
     $dbThumbAsset->setWidth($width);
     $dbThumbAsset->setHeight($height);
     $dbThumbAsset->setSize(filesize($finalPath));
     $dbThumbAsset->setStatus(thumbAsset::ASSET_STATUS_READY);
     $dbThumbAsset->save();
     $dbEntryThumbs = assetPeer::retrieveThumbnailsByEntryId($entryId);
     //If the thums has the default tag or the entry is in no content and this is the first thumb
     if ($dbEntry->getCreateThumb() && ($dbThumbAsset->hasTag(thumbParams::TAG_DEFAULT_THUMB) || $dbEntry->getStatus() == KalturaEntryStatus::NO_CONTENT && count($dbEntryThumbs) == 1)) {
         $this->setAsDefaultAction($dbThumbAsset->getId());
     }
     $thumbAssets = new KalturaThumbAsset();
     $thumbAssets->fromObject($dbThumbAsset);
     return $thumbAssets;
 }
 public static function copyFromFile($temp_file_path, FileSyncKey $target_key, $strict = true)
 {
     KalturaLog::debug("copy file: [{$temp_file_path}] to key [{$target_key}], ");
     kFileSyncUtils::moveFromFile($temp_file_path, $target_key, $strict, true);
 }
 private function ingestAsset(entry $entry, $dbAsset, $filename)
 {
     $flavorParamsId = $dbAsset->getFlavorParamsId();
     $flavorParams = assetParamsPeer::retrieveByPKNoFilter($flavorParamsId);
     // is first chunk
     $recordedAsset = assetPeer::retrieveByEntryIdAndParams($entry->getId(), $flavorParamsId);
     if ($recordedAsset) {
         KalturaLog::info("Asset [" . $recordedAsset->getId() . "] of flavor params id [{$flavorParamsId}] already exists");
         return;
     }
     // create asset
     $recordedAsset = assetPeer::getNewAsset(assetType::FLAVOR);
     $recordedAsset->setPartnerId($entry->getPartnerId());
     $recordedAsset->setEntryId($entry->getId());
     $recordedAsset->setStatus(asset::FLAVOR_ASSET_STATUS_QUEUED);
     $recordedAsset->setFlavorParamsId($flavorParams->getId());
     $recordedAsset->setFromAssetParams($flavorParams);
     if ($dbAsset->hasTag(assetParams::TAG_RECORDING_ANCHOR)) {
         $recordedAsset->addTags(array(assetParams::TAG_RECORDING_ANCHOR));
     }
     if ($flavorParams->hasTag(assetParams::TAG_SOURCE)) {
         $recordedAsset->setIsOriginal(true);
     }
     $ext = pathinfo($filename, PATHINFO_EXTENSION);
     if ($ext) {
         $recordedAsset->setFileExt($ext);
     }
     $recordedAsset->save();
     // create file sync
     $recordedAssetKey = $recordedAsset->getSyncKey(flavorAsset::FILE_SYNC_ASSET_SUB_TYPE_ASSET);
     kFileSyncUtils::moveFromFile($filename, $recordedAssetKey, true, true);
     kEventsManager::raiseEvent(new kObjectAddedEvent($recordedAsset));
 }
 /**
  * @param AttachmentAsset $attachmentAsset
  * @param string $fullPath
  * @param bool $copyOnly
  */
 protected function attachFile(AttachmentAsset $attachmentAsset, $fullPath, $copyOnly = false)
 {
     $ext = pathinfo($fullPath, PATHINFO_EXTENSION);
     $attachmentAsset->incrementVersion();
     $attachmentAsset->setFileExt($ext);
     $attachmentAsset->setSize(kFile::fileSize($fullPath));
     $attachmentAsset->save();
     $syncKey = $attachmentAsset->getSyncKey(AttachmentAsset::FILE_SYNC_ASSET_SUB_TYPE_ASSET);
     try {
         kFileSyncUtils::moveFromFile($fullPath, $syncKey, true, $copyOnly);
     } catch (Exception $e) {
         if ($attachmentAsset->getStatus() == AttachmentAsset::ASSET_STATUS_QUEUED || $attachmentAsset->getStatus() == AttachmentAsset::ASSET_STATUS_NOT_APPLICABLE) {
             $attachmentAsset->setDescription($e->getMessage());
             $attachmentAsset->setStatus(AttachmentAsset::ASSET_STATUS_ERROR);
             $attachmentAsset->save();
         }
         throw $e;
     }
     $finalPath = kFileSyncUtils::getLocalFilePathForKey($syncKey);
     $wamsURL = kFileSyncUtils::getWamsURLForKey($syncKey);
     if (empty($wamsURL)) {
         list($width, $height, $type, $attr) = getimagesize($finalPath);
         $fileSize = kFile::fileSize($finalPath);
     } else {
         list($width, $height, $type, $attr) = getimagesize($wamsURL);
         $wamsAssetId = kFileSyncUtils::getWamsAssetIdForKey($syncKey);
         $fileSize = kWAMS::getInstance($syncKey->getPartnerId())->getFileSizeForAssetId($wamsAssetId, pathinfo($finalPath, PATHINFO_EXTENSION));
     }
     $attachmentAsset->setWidth($width);
     $attachmentAsset->setHeight($height);
     $attachmentAsset->setSize($fileSize);
     $attachmentAsset->setStatus(AttachmentAsset::ASSET_STATUS_READY);
     $attachmentAsset->save();
 }
 /**
  * @param CaptionAsset $captionAsset
  * @param string $fullPath
  * @param bool $copyOnly
  */
 protected function attachFile(CaptionAsset $captionAsset, $fullPath, $copyOnly = false)
 {
     $ext = pathinfo($fullPath, PATHINFO_EXTENSION);
     $captionAsset->incrementVersion();
     $captionAsset->setFileExt($ext);
     $captionAsset->setSize(filesize($fullPath));
     $captionAsset->save();
     $syncKey = $captionAsset->getSyncKey(CaptionAsset::FILE_SYNC_ASSET_SUB_TYPE_ASSET);
     try {
         kFileSyncUtils::moveFromFile($fullPath, $syncKey, true, $copyOnly);
     } catch (Exception $e) {
         if ($captionAsset->getStatus() == CaptionAsset::ASSET_STATUS_QUEUED || $captionAsset->getStatus() == CaptionAsset::ASSET_STATUS_NOT_APPLICABLE) {
             $captionAsset->setDescription($e->getMessage());
             $captionAsset->setStatus(CaptionAsset::ASSET_STATUS_ERROR);
             $captionAsset->save();
         }
         throw $e;
     }
     $finalPath = kFileSyncUtils::getLocalFilePathForKey($syncKey);
     list($width, $height, $type, $attr) = getimagesize($finalPath);
     $captionAsset->setWidth($width);
     $captionAsset->setHeight($height);
     $captionAsset->setSize(filesize($finalPath));
     $captionAsset->setStatus(CaptionAsset::ASSET_STATUS_READY);
     $captionAsset->save();
 }
 /**
  * Add MRSS transform file to generic distribution provider action
  * 
  * @action addResultsTransformFromFile
  * @param int $id the id of the generic distribution provider action
  * @param file $transformFile transformation file xsl, xPath or regex
  * @return KalturaGenericDistributionProviderAction
  * @throws ContentDistributionErrors::GENERIC_DISTRIBUTION_PROVIDER_ACTION_NOT_FOUND
  * @throws KalturaErrors::UPLOADED_FILE_NOT_FOUND
  */
 function addResultsTransformFromFileAction($id, $transformFile)
 {
     $dbGenericDistributionProviderAction = GenericDistributionProviderActionPeer::retrieveByPK($id);
     if (!$dbGenericDistributionProviderAction) {
         throw new KalturaAPIException(ContentDistributionErrors::GENERIC_DISTRIBUTION_PROVIDER_ACTION_NOT_FOUND, $id);
     }
     $filePath = $transformFile['tmp_name'];
     if (!file_exists($filePath)) {
         throw new KalturaAPIException(KalturaErrors::UPLOADED_FILE_NOT_FOUND, $transformFile['name']);
     }
     $dbGenericDistributionProviderAction->incrementResultsTransformerVersion();
     $dbGenericDistributionProviderAction->save();
     $key = $dbGenericDistributionProviderAction->getSyncKey(GenericDistributionProviderAction::FILE_SYNC_DISTRIBUTION_PROVIDER_ACTION_RESULTS_TRANSFORMER);
     kFileSyncUtils::moveFromFile($filePath, $key);
     $genericDistributionProviderAction = new KalturaGenericDistributionProviderAction();
     $genericDistributionProviderAction->fromObject($dbGenericDistributionProviderAction);
     return $genericDistributionProviderAction;
 }
Exemple #28
0
 /**
  * Update an existing metadata object with new XML file
  * 
  * @action updateFromFile
  * @param int $id 
  * @param file $xmlFile XML metadata
  * @return KalturaMetadata
  * @throws KalturaErrors::INVALID_OBJECT_ID
  * @throws MetadataErrors::METADATA_FILE_NOT_FOUND
  * @throws MetadataErrors::INVALID_METADATA_DATA
  */
 function updateFromFileAction($id, $xmlFile = null)
 {
     $dbMetadata = MetadataPeer::retrieveByPK($id);
     if (!$dbMetadata) {
         throw new KalturaAPIException(KalturaErrors::INVALID_OBJECT_ID, $id);
     }
     $filePath = null;
     if ($xmlFile) {
         $filePath = $xmlFile['tmp_name'];
         if (!file_exists($filePath)) {
             throw new KalturaAPIException(MetadataErrors::METADATA_FILE_NOT_FOUND, $xmlFile['name']);
         }
     }
     $previousVersion = null;
     if ($dbMetadata->getStatus() == Metadata::STATUS_VALID) {
         $previousVersion = $dbMetadata->getVersion();
     }
     if ($filePath) {
         $dbMetadata->incrementVersion();
     }
     $dbMetadata->save();
     if ($filePath) {
         $key = $dbMetadata->getSyncKey(Metadata::FILE_SYNC_METADATA_DATA);
         kFileSyncUtils::moveFromFile($filePath, $key);
         $errorMessage = '';
         $status = kMetadataManager::validateMetadata($dbMetadata, $errorMessage);
         kEventsManager::raiseEvent(new kObjectDataChangedEvent($dbMetadata, $previousVersion));
         if ($status != KalturaMetadataStatus::VALID) {
             throw new KalturaAPIException(MetadataErrors::INVALID_METADATA_DATA, $errorMessage);
         }
     }
     $metadata = new KalturaMetadata();
     $metadata->fromObject($dbMetadata);
     return $metadata;
 }