Ejemplo n.º 1
0
 public function executeImpl(kshow $kshow, entry &$entry)
 {
     $genericWidget = "";
     $myspaceWidget = "";
     $kshow_id = $kshow->getId();
     $entry_id = $entry->getId();
     if (!$kshow->getPartnerId() && !$this->forceViewPermissions($kshow, $kshow_id, false, false)) {
         die;
     }
     $this->kshow_category = $kshow->getTypeText();
     $this->kshow_description = $kshow->getDescription();
     $this->kshow_name = $kshow->getName();
     $this->kshow_tags = $kshow->getTags();
     $kdata = @$_REQUEST["kdata"];
     if ($kdata == "null") {
         $kdata = "";
     }
     $this->widget_type = @$_REQUEST["widget_type"];
     list($genericWidget, $myspaceWidget) = myKshowUtils::getEmbedPlayerUrl($kshow_id, $entry_id, false, $kdata);
     if ($entry_id == 1002) {
         $this->share_url = requestUtils::getHost() . "/index.php/corp/kalturaPromo";
     } else {
         if ($kdata) {
             $this->share_url = myKshowUtils::getWidgetCmdUrl($kdata, "share");
         } else {
             $this->share_url = myKshowUtils::getUrl($kshow_id) . "&entry_id={$entry_id}";
         }
     }
     //list($status, $kmediaType, $kmediaData) = myContentRender::createPlayerMedia($entry); // myContentRender class removed, old code
     $status = $entry->getStatus();
     $kmediaType = $entry->getMediaType();
     $kmediaData = "";
     $this->message = $kmediaType == entry::ENTRY_MEDIA_TYPE_TEXT ? $kmediaData : "";
     $this->generic_embed_code = $genericWidget;
     $this->myspace_embed_code = $myspaceWidget;
     $this->thumbnail = $entry ? $entry->getBigThumbnailPath(true) : "";
     $this->kuser = $entry->getKuser();
     $this->entry = $entry;
 }
Ejemplo n.º 2
0
 public function execute()
 {
     $this->entryId = $this->getRequestParameter("entryId", null);
     $this->flavorId = $this->getRequestParameter("flavorId", null);
     $this->storageId = $this->getRequestParameter("storageId", null);
     $this->maxBitrate = $this->getRequestParameter("maxBitrate", null);
     $flavorIdsStr = $this->getRequestParameter("flavorIds", null);
     if ($flavorIdsStr) {
         $this->flavorIds = explode(",", $flavorIdsStr);
     }
     $this->entry = entryPeer::retrieveByPKNoFilter($this->entryId);
     if (!$this->entry) {
         KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
     }
     if (!$this->flavorId) {
         $flavorParamId = $this->getRequestParameter("flavorParamId", null);
         if ($flavorParamId) {
             $flavorAsset = flavorAssetPeer::retrieveByEntryIdAndFlavorParams($entry->getId(), $flavorParamId);
             if (!$flavorAsset) {
                 KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
             }
             $this->flavorId = $flavorAsset->getId();
         }
     }
     $this->validateStorageId();
     $this->protocol = $this->getRequestParameter("protocol", null);
     if (!$this->protocol) {
         $this->protocol = StorageProfile::PLAY_FORMAT_HTTP;
     }
     $this->format = $this->getRequestParameter("format");
     if (!$this->format) {
         $this->format = StorageProfile::PLAY_FORMAT_HTTP;
     }
     $this->cdnHost = $this->getRequestParameter("cdnHost", null);
     $partner = $this->entry->getPartner();
     if (!$this->cdnHost || $partner->getForceCdnHost()) {
         $this->cdnHost = myPartnerUtils::getCdnHost($this->entry->getPartnerId(), $this->protocol);
     }
     if ($this->maxBitrate && (!is_numeric($this->maxBitrate) || $this->maxBitrate <= 0)) {
         KExternalErrors::dieError(KExternalErrors::INVALID_MAX_BITRATE);
     }
     $ksStr = $this->getRequestParameter("ks");
     $base64Referrer = $this->getRequestParameter("referrer");
     $referrer = base64_decode($base64Referrer);
     if (!is_string($referrer)) {
         $referrer = "";
     }
     // base64_decode can return binary data
     $securyEntryHelper = new KSecureEntryHelper($this->entry, $ksStr, $referrer);
     if ($securyEntryHelper->shouldPreview()) {
         $this->clipTo = $securyEntryHelper->getPreviewLength() * 1000;
     } else {
         $securyEntryHelper->validateForPlay($this->entry, $ksStr);
     }
     // grab seekFrom parameter and normalize url
     $this->seekFrom = $this->getRequestParameter("seekFrom", -1);
     if ($this->seekFrom <= 0) {
         $this->seekFrom = -1;
     }
     if ($this->entry->getStatus() == entryStatus::DELETED) {
         // because the fiter was turned off - a manual check for deleted entries must be done.
         die;
     }
     $xml = null;
     switch ($this->format) {
         case StorageProfile::PLAY_FORMAT_HTTP:
             $xml = $this->serveHttp();
             break;
         case StorageProfile::PLAY_FORMAT_RTMP:
             $xml = $this->serveRtmp();
             break;
         case StorageProfile::PLAY_FORMAT_SILVER_LIGHT:
             $xml = $this->serveSilverLight();
             break;
         case StorageProfile::PLAY_FORMAT_APPLE_HTTP:
             $xml = $this->serveAppleHttp();
             break;
         case "url":
             return $this->serveUrl();
             break;
         case "hdnetworksmil":
             $xml = $this->serveHDNetwork();
             break;
         case "hdnetwork":
             $duration = $this->entry->getDurationInt();
             $mediaUrl = "<media url=\"" . requestUtils::getHost() . str_replace("f4m", "smil", str_replace("hdnetwork", "hdnetworksmil", $_SERVER["REQUEST_URI"])) . "\"/>";
             $xml = $this->buildXml(self::PLAY_STREAM_TYPE_RECORDED, array(), 'video/x-flv', $duration, null, $mediaUrl);
             break;
     }
     if ($this->format == StorageProfile::PLAY_FORMAT_APPLE_HTTP) {
         header("Content-Type: text/plain; charset=UTF-8");
     } else {
         header("Content-Type: text/xml; charset=UTF-8");
         header("Content-Disposition: inline; filename=manifest.xml");
     }
     echo $xml;
     die;
 }
 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;
 }
Ejemplo n.º 4
0
 /**
  * @param BatchJob $batchJob
  * @param entry $entry
  * @param string $flavorAssetId
  * @param string $inputFileSyncLocalPath
  * @return BatchJob
  */
 public static function addConvertProfileJob(BatchJob $parentJob = null, entry $entry, $flavorAssetId, $inputFileSyncLocalPath)
 {
     KalturaLog::debug("Parent job [" . ($parentJob ? $parentJob->getId() : 'none') . "] entry [" . $entry->getId() . "] flavor asset [{$flavorAssetId}] input file [{$inputFileSyncLocalPath}]");
     if ($entry->getConversionQuality() == conversionProfile2::CONVERSION_PROFILE_NONE) {
         $entry->setStatus(entryStatus::PENDING);
         $entry->save();
         KalturaLog::notice('Entry should not be converted');
         return null;
     }
     $importingSources = false;
     // if file size is 0, do not create conversion profile and set entry status as error converting
     if (!file_exists($inputFileSyncLocalPath) || kFile::fileSize($inputFileSyncLocalPath) == 0) {
         KalturaLog::debug("Input file [{$inputFileSyncLocalPath}] does not exist");
         $partner = $entry->getPartner();
         $conversionProfile = myPartnerUtils::getConversionProfile2ForEntry($entry->getId());
         // load the asset params to the instance pool
         $flavorIds = flavorParamsConversionProfilePeer::getFlavorIdsByProfileId($conversionProfile->getId());
         assetParamsPeer::retrieveByPKs($flavorIds);
         $conversionRequired = false;
         $sourceFileRequiredStorages = array();
         $sourceIncludedInProfile = false;
         $flavorAsset = assetPeer::retrieveById($flavorAssetId);
         $flavors = flavorParamsConversionProfilePeer::retrieveByConversionProfile($conversionProfile->getId());
         KalturaLog::debug("Found flavors [" . count($flavors) . "] in conversion profile [" . $conversionProfile->getId() . "]");
         foreach ($flavors as $flavor) {
             /* @var $flavor flavorParamsConversionProfile */
             if ($flavor->getFlavorParamsId() == $flavorAsset->getFlavorParamsId()) {
                 KalturaLog::debug("Flavor [" . $flavor->getFlavorParamsId() . "] is ingested source");
                 $sourceIncludedInProfile = true;
                 continue;
             }
             $flavorParams = assetParamsPeer::retrieveByPK($flavor->getFlavorParamsId());
             if ($flavorParams instanceof liveParams || $flavor->getOrigin() == assetParamsOrigin::INGEST) {
                 KalturaLog::debug("Flavor [" . $flavor->getFlavorParamsId() . "] should be ingested");
                 continue;
             }
             if ($flavor->getOrigin() == assetParamsOrigin::CONVERT_WHEN_MISSING) {
                 $siblingFlavorAsset = assetPeer::retrieveByEntryIdAndParams($entry->getId(), $flavor->getFlavorParamsId());
                 if ($siblingFlavorAsset) {
                     KalturaLog::debug("Flavor [" . $flavor->getFlavorParamsId() . "] already ingested");
                     continue;
                 }
             }
             $sourceFileRequiredStorages[] = $flavorParams->getSourceRemoteStorageProfileId();
             $conversionRequired = true;
             break;
         }
         if ($conversionRequired) {
             foreach ($sourceFileRequiredStorages as $storageId) {
                 if ($storageId == StorageProfile::STORAGE_KALTURA_DC) {
                     $key = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
                     list($syncFile, $local) = kFileSyncUtils::getReadyFileSyncForKey($key, true, false);
                     if ($syncFile && $syncFile->getFileType() == FileSync::FILE_SYNC_FILE_TYPE_URL && $partner && $partner->getImportRemoteSourceForConvert()) {
                         KalturaLog::debug("Creates import job for remote file sync");
                         $url = $syncFile->getExternalUrl($entry->getId());
                         kJobsManager::addImportJob($parentJob, $entry->getId(), $partner->getId(), $url, $flavorAsset, null, null, true);
                         $importingSources = true;
                         continue;
                     }
                 } elseif ($flavorAsset->getExternalUrl($storageId)) {
                     continue;
                 }
                 kBatchManager::updateEntry($entry->getId(), entryStatus::ERROR_CONVERTING);
                 $flavorAsset = assetPeer::retrieveById($flavorAssetId);
                 $flavorAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_ERROR);
                 $flavorAsset->setDescription('Entry of size 0 should not be converted');
                 $flavorAsset->save();
                 KalturaLog::err('Entry of size 0 should not be converted');
                 return null;
             }
         } else {
             if ($flavorAsset->getStatus() == asset::FLAVOR_ASSET_STATUS_QUEUED) {
                 if ($sourceIncludedInProfile) {
                     $flavorAsset->setStatusLocalReady();
                 } else {
                     $flavorAsset->setStatus(asset::FLAVOR_ASSET_STATUS_DELETED);
                     $flavorAsset->setDeletedAt(time());
                 }
                 $flavorAsset->save();
                 if ($sourceIncludedInProfile) {
                     kBusinessPostConvertDL::handleConvertFinished(null, $flavorAsset);
                 }
             }
             return null;
         }
     }
     if ($entry->getStatus() != entryStatus::READY) {
         $entry->setStatus(entryStatus::PRECONVERT);
     }
     $jobData = new kConvertProfileJobData();
     $jobData->setFlavorAssetId($flavorAssetId);
     $jobData->setInputFileSyncLocalPath($inputFileSyncLocalPath);
     $jobData->setExtractMedia(true);
     if ($entry->getType() != entryType::MEDIA_CLIP) {
         $jobData->setExtractMedia(false);
         $entry->setCreateThumb(false);
     }
     $entry->save();
     $batchJob = null;
     if ($parentJob) {
         $batchJob = $parentJob->createChild(BatchJobType::CONVERT_PROFILE);
     } else {
         $batchJob = new BatchJob();
         $batchJob->setEntryId($entry->getId());
         $batchJob->setPartnerId($entry->getPartnerId());
         $batchJob->setUseNewRoot(true);
     }
     $batchJob->setObjectId($entry->getId());
     $batchJob->setObjectType(BatchJobObjectType::ENTRY);
     if ($importingSources) {
         $batchJob->setStatus(BatchJob::BATCHJOB_STATUS_DONT_PROCESS);
     }
     return self::addJob($batchJob, $jobData, BatchJobType::CONVERT_PROFILE);
 }
Ejemplo n.º 5
0
 public static function calcStorageSize(entry $entry)
 {
     if ($entry->getStatus() == entryStatus::DELETED) {
         return 0;
     }
     $size = 0;
     $entry_id = $entry->getId();
     $entrySyncKeys = array($entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA), $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_THUMB), $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA_EDIT), $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_ARCHIVE), $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DOWNLOAD), $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_OFFLINE_THUMB), $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_ISM), $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_ISMC), $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_CONVERSION_LOG));
     $flavorAssets = flavorAssetPeer::retrieveByEntryId($entry_id);
     foreach ($flavorAssets as $flavorAsset) {
         $entrySyncKeys[] = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
         $entrySyncKeys[] = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_CONVERT_LOG);
     }
     foreach ($entrySyncKeys as $syncKey) {
         $fileSync = kFileSyncUtils::getOriginFileSyncForKey($syncKey, false);
         if (!$fileSync || $fileSync->getStatus() != FileSync::FILE_SYNC_STATUS_READY) {
             continue;
         }
         $fileSize = $fileSync->getFileSize();
         if ($fileSize > 0) {
             $size += $fileSize;
         }
     }
     return $size;
 }
 protected function initEntry()
 {
     $this->entryId = $this->getRequestParameter("entryId", null);
     // look for a valid token
     $expiry = $this->getRequestParameter("expiry");
     if ($expiry && $expiry <= time()) {
         KExternalErrors::dieError(KExternalErrors::EXPIRED_TOKEN);
     }
     $urlToken = $this->getRequestParameter("kt");
     if ($urlToken) {
         if ($_SERVER["REQUEST_METHOD"] != "GET" || !self::validateKalturaToken($_SERVER["REQUEST_URI"], $urlToken)) {
             KExternalErrors::dieError(KExternalErrors::INVALID_TOKEN);
         }
     }
     // initalize the context
     $ksStr = $this->getRequestParameter("ks");
     if ($ksStr && !$urlToken) {
         try {
             kCurrentContext::initKsPartnerUser($ksStr);
         } catch (Exception $ex) {
             KExternalErrors::dieError(KExternalErrors::INVALID_KS);
         }
     } else {
         $this->entry = kCurrentContext::initPartnerByEntryId($this->entryId);
         if (!$this->entry || $this->entry->getStatus() == entryStatus::DELETED) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     // no need for any further check if a token was used
     if ($urlToken) {
         return;
     }
     // enforce entitlement
     kEntitlementUtils::initEntitlementEnforcement();
     if (!$this->entry) {
         $this->entry = entryPeer::retrieveByPKNoFilter($this->entryId);
         if (!$this->entry || $this->entry->getStatus() == entryStatus::DELETED) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     } else {
         if (!kEntitlementUtils::isEntryEntitled($this->entry)) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     // enforce access control
     $base64Referrer = $this->getRequestParameter("referrer");
     // replace space in the base64 string with + as space is invalid in base64 strings and caused
     // by symfony calling str_parse to replace + with spaces.
     // this happens only with params passed in the url path and not the query strings. specifically the ~ char at
     // a columns divided by 3 causes this issue (e.g. http://www.xyzw.com/~xxx)
     $referrer = base64_decode(str_replace(" ", "+", $base64Referrer));
     if (!is_string($referrer)) {
         $referrer = "";
     }
     // base64_decode can return binary data
     $this->secureEntryHelper = new KSecureEntryHelper($this->entry, $ksStr, $referrer, accessControlContextType::PLAY);
     if ($this->secureEntryHelper->shouldPreview()) {
         $this->clipTo = $this->secureEntryHelper->getPreviewLength() * 1000;
     } else {
         $this->secureEntryHelper->validateForPlay();
     }
 }
Ejemplo n.º 7
0
 public function validateConversionProfile(entry $sourceObject = null)
 {
     if (is_null($this->conversionProfileId)) {
         return;
     }
     if ($sourceObject && $sourceObject->getStatus() != entryStatus::NO_CONTENT) {
         throw new KalturaAPIException(KalturaErrors::PROPERTY_VALIDATION_ENTRY_STATUS, $this->getFormattedPropertyNameWithClassName('conversionProfileId'), $sourceObject->getStatus());
     }
     if ($this->conversionProfileId != conversionProfile2::CONVERSION_PROFILE_NONE) {
         $conversionProfile = conversionProfile2Peer::retrieveByPK($this->conversionProfileId);
         if (!$conversionProfile || $conversionProfile->getType() != ConversionProfileType::MEDIA) {
             throw new KalturaAPIException(KalturaErrors::CONVERSION_PROFILE_ID_NOT_FOUND, $this->conversionProfileId);
         }
     }
 }
Ejemplo n.º 8
0
 private static function createNotificationBulkDownloadSucceeded(BatchJob $dbBatchJob, entry $entry, flavorAsset $flavorAsset, FileSyncKey $syncKey)
 {
     $localPath = kFileSyncUtils::getLocalFilePathForKey($syncKey);
     $downloadUrl = $flavorAsset->getDownloadUrl();
     $notificationData = array("puserId" => $entry->getPuserId(), "entryId" => $entry->getId(), "entryIntId" => $entry->getIntId(), "entryVersion" => $entry->getVersion(), "fileFormat" => $flavorAsset->getFileExt(), "archivedFile" => $localPath, "downoladPath" => $localPath, "conversionQuality" => $entry->getConversionQuality(), "downloadUrl" => $downloadUrl);
     $extraData = array("data" => json_encode($notificationData), "partner_id" => $entry->getPartnerId(), "puser_id" => $entry->getPuserId(), "entry_id" => $entry->getId(), "entry_int_id" => $entry->getIntId(), "entry_version" => $entry->getVersion(), "file_format" => $flavorAsset->getFileExt(), "archived_file" => $localPath, "downolad_path" => $localPath, "target" => $localPath, "conversion_quality" => $entry->getConversionQuality(), "download_url" => $downloadUrl, "status" => $entry->getStatus(), "abort" => $dbBatchJob->getExecutionStatus() == BatchJobExecutionStatus::ABORTED, "message" => $dbBatchJob->getMessage(), "description" => $dbBatchJob->getDescription(), "job_type" => BatchJobType::DOWNLOAD, "status" => BatchJob::BATCHJOB_STATUS_FINISHED, "progress" => 100, "debug" => __LINE__);
     myNotificationMgr::createNotification(kNotificationJobData::NOTIFICATION_TYPE_BATCH_JOB_SUCCEEDED, $dbBatchJob, $dbBatchJob->getPartnerId(), null, null, $extraData, $dbBatchJob->getEntryId());
 }
Ejemplo n.º 9
0
 protected function validateEntryForRestoreDelete(entry $entry, array $fileSyncs, array $assets)
 {
     if ($entry->getStatus() != entryStatus::DELETED) {
         return false;
     }
     foreach ($fileSyncs as $fileSync) {
         if ($fileSync->getStatus() != FileSync::FILE_SYNC_STATUS_DELETED) {
             return false;
         }
     }
     foreach ($assets as $asset) {
         if ($asset->getStatus() != asset::ASSET_STATUS_DELETED) {
             return false;
         }
     }
     return true;
 }
 /**
  * @param entry $entry
  * @param SimpleXMLElement $mrss
  * @param kMrssParameters $mrssParams
  * @return SimpleXMLElement
  */
 public static function getEntryMrssXml(entry $entry, SimpleXMLElement $mrss = null, kMrssParameters $mrssParams = null)
 {
     if ($mrss === null) {
         $mrss = new SimpleXMLElement('<item/>');
     }
     $mrss->addChild('entryId', $entry->getId());
     if ($entry->getReferenceID()) {
         $mrss->addChild('referenceID', $entry->getReferenceID());
     }
     $mrss->addChild('createdAt', $entry->getCreatedAt(null));
     $mrss->addChild('updatedAt', $entry->getUpdatedAt(null));
     $mrss->addChild('title', self::stringToSafeXml($entry->getName()));
     if ($mrssParams && !is_null($mrssParams->getLink())) {
         $mrss->addChild('link', $mrssParams->getLink() . $entry->getId());
     }
     $mrss->addChild('type', $entry->getType());
     $mrss->addChild('licenseType', $entry->getLicenseType());
     $mrss->addChild('userId', $entry->getPuserId(true));
     $mrss->addChild('name', self::stringToSafeXml($entry->getName()));
     $mrss->addChild('status', self::stringToSafeXml($entry->getStatus()));
     $mrss->addChild('description', self::stringToSafeXml($entry->getDescription()));
     $thumbnailUrl = $mrss->addChild('thumbnailUrl');
     $thumbnailUrl->addAttribute('url', $entry->getThumbnailUrl());
     if (trim($entry->getTags(), " \r\n\t")) {
         $tags = $mrss->addChild('tags');
         foreach (explode(',', $entry->getTags()) as $tag) {
             $tags->addChild('tag', self::stringToSafeXml($tag));
         }
     }
     $categories = explode(',', $entry->getCategories());
     foreach ($categories as $category) {
         $category = trim($category);
         if ($category) {
             $categoryNode = $mrss->addChild('category', self::stringToSafeXml($category));
             if (strrpos($category, '>') > 0) {
                 $categoryNode->addAttribute('name', self::stringToSafeXml(substr($category, strrpos($category, '>') + 1)));
             } else {
                 $categoryNode->addAttribute('name', self::stringToSafeXml($category));
             }
         }
     }
     $mrss->addChild('partnerData', self::stringToSafeXml($entry->getPartnerData()));
     if ($entry->getAccessControlId()) {
         $mrss->addChild('accessControlId', $entry->getAccessControlId());
     }
     if ($entry->getConversionProfileId()) {
         $mrss->addChild('conversionProfileId', $entry->getConversionProfileId());
     }
     if ($entry->getStartDate(null)) {
         $mrss->addChild('startDate', $entry->getStartDate(null));
     }
     if ($entry->getEndDate(null)) {
         $mrss->addChild('endDate', $entry->getEndDate(null));
     }
     switch ($entry->getType()) {
         case entryType::MEDIA_CLIP:
             self::appendMediaEntryMrss($entry, $mrss);
             break;
         case entryType::MIX:
             self::appendMixEntryMrss($entry, $mrss);
             break;
         case entryType::PLAYLIST:
             self::appendPlaylistEntryMrss($entry, $mrss);
             break;
         case entryType::DATA:
             self::appendDataEntryMrss($entry, $mrss);
             break;
         case entryType::LIVE_STREAM:
             self::appendLiveStreamEntryMrss($entry, $mrss);
             break;
         default:
             break;
     }
     $assets = assetPeer::retrieveReadyByEntryId($entry->getId());
     foreach ($assets as $asset) {
         if ($mrssParams && !is_null($mrssParams->getFilterByFlavorParams()) && $asset->getFlavorParamsId() != $mrssParams->getFilterByFlavorParams()) {
             continue;
         }
         if ($asset instanceof flavorAsset) {
             self::appendFlavorAssetMrss($asset, $mrss, $mrssParams);
         }
         if ($asset instanceof thumbAsset) {
             self::appendThumbAssetMrss($asset, $mrss);
         }
     }
     $mrssContributors = self::getMrssContributors();
     if (count($mrssContributors)) {
         foreach ($mrssContributors as $mrssContributor) {
             $mrssContributor->contribute($entry, $mrss, $mrssParams);
         }
     }
     if ($mrssParams && $mrssParams->getIncludePlayerTag()) {
         $uiconfId = !is_null($mrssParams->getPlayerUiconfId()) ? '/ui_conf_id/' . $mrssParams->getPlayerUiconfId() : '';
         $playerUrl = 'http://' . kConf::get('www_host') . '/kwidget/wid/_' . $entry->getPartnerId() . '/entry_id/' . $entry->getId() . '/ui_conf' . ($uiconfId ? "/{$uiconfId}" : '');
         $player = $mrss->addChild('player');
         $player->addAttribute('url', $playerUrl);
     }
     return $mrss;
 }
Ejemplo n.º 11
0
 /**
  * @param entry $entry
  * @param SimpleXMLElement $mrss
  * @param kMrssParameters $mrssParams
  * @params string $features
  * @return SimpleXMLElement
  */
 public static function getEntryMrssXml(entry $entry, SimpleXMLElement $mrss = null, kMrssParameters $mrssParams = null, $features = null)
 {
     $instanceKey = self::generateInstanceKey($entry->getId(), $mrssParams, $features);
     if (is_null($mrss)) {
         $mrss = self::getInstanceFromPool($instanceKey);
         if ($mrss) {
             return $mrss;
         }
         $encoding = 'UTF-8';
         if ($mrssParams && !is_null($mrssParams->getEncoding())) {
             $encoding = $mrssParams->getEncoding();
         }
         if ($encoding) {
             $mrss = new SimpleXMLElement('<?xml version="1.0" encoding="' . $encoding . '"?><item/>');
         } else {
             $mrss = new SimpleXMLElement('<item/>');
         }
     }
     $mrss->addChild('entryId', $entry->getId());
     if ($entry->getReferenceID()) {
         $mrss->addChild('referenceID', self::stringToSafeXml($entry->getReferenceID()));
     }
     $mrss->addChild('createdAt', $entry->getCreatedAt(null));
     $mrss->addChild('updatedAt', $entry->getUpdatedAt(null));
     $mrss->addChild('title', self::stringToSafeXml($entry->getName()));
     if ($mrssParams && !is_null($mrssParams->getLink())) {
         $mrss->addChild('link', $mrssParams->getLink() . $entry->getId());
     }
     $mrss->addChild('type', $entry->getType());
     $mrss->addChild('licenseType', $entry->getLicenseType());
     $mrss->addChild('userId', $entry->getPuserId());
     $mrss->addChild('name', self::stringToSafeXml($entry->getName()));
     $mrss->addChild('status', self::stringToSafeXml($entry->getStatus()));
     $mrss->addChild('description', self::stringToSafeXml($entry->getDescription()));
     $thumbnailUrl = $mrss->addChild('thumbnailUrl');
     $thumbnailUrl->addAttribute('url', $entry->getThumbnailUrl());
     if (trim($entry->getTags(), " \r\n\t")) {
         $tags = $mrss->addChild('tags');
         foreach (explode(',', $entry->getTags()) as $tag) {
             $tags->addChild('tag', self::stringToSafeXml($tag));
         }
     }
     $categories = explode(',', $entry->getCategories());
     if (count($features) && in_array(ObjectFeatureType::CATEGORY_ENTRIES, $features)) {
         $partner = PartnerPeer::retrieveByPK(kCurrentContext::getCurrentPartnerId());
         $partnerEntitlement = $partner->getDefaultEntitlementEnforcement();
         kEntitlementUtils::initEntitlementEnforcement($partner->getId(), false);
         $categories = array();
         $categoryEntries = categoryEntryPeer::retrieveActiveByEntryId($entry->getId());
         $categoryIds = array();
         foreach ($categoryEntries as $categoryEntry) {
             $categoryIds[] = $categoryEntry->getCategoryId();
         }
         $entryCats = categoryPeer::retrieveByPKs($categoryIds);
         foreach ($entryCats as $entryCat) {
             $categories[] = $entryCat->getFullName();
         }
         if ($partnerEntitlement) {
             kEntitlementUtils::initEntitlementEnforcement($partner->getId(), true);
         }
         $keyToDelete = array_search(ObjectFeatureType::CATEGORY_ENTRIES, $features);
         unset($features[$keyToDelete]);
     }
     foreach ($categories as $category) {
         $category = trim($category);
         if ($category) {
             $categoryNode = $mrss->addChild('category', self::stringToSafeXml($category));
             if (strrpos($category, '>') > 0) {
                 $categoryNode->addAttribute('name', self::stringToSafeXml(substr($category, strrpos($category, '>') + 1)));
             } else {
                 $categoryNode->addAttribute('name', self::stringToSafeXml($category));
             }
         }
     }
     $mrss->addChild('partnerData', self::stringToSafeXml($entry->getPartnerData()));
     if ($entry->getAccessControlId()) {
         $mrss->addChild('accessControlId', $entry->getAccessControlId());
     }
     if ($entry->getConversionProfileId()) {
         $mrss->addChild('conversionProfileId', $entry->getConversionProfileId());
     }
     if ($entry->getStartDate(null)) {
         $mrss->addChild('startDate', $entry->getStartDate(null));
     }
     if ($entry->getEndDate(null)) {
         $mrss->addChild('endDate', $entry->getEndDate(null));
     }
     switch ($entry->getType()) {
         case entryType::MEDIA_CLIP:
             self::appendMediaEntryMrss($entry, $mrss);
             break;
         case entryType::MIX:
             self::appendMixEntryMrss($entry, $mrss);
             break;
         case entryType::PLAYLIST:
             self::appendPlaylistEntryMrss($entry, $mrss);
             break;
         case entryType::DATA:
             self::appendDataEntryMrss($entry, $mrss);
             break;
         case entryType::LIVE_STREAM:
             self::appendLiveStreamEntryMrss($entry, $mrss);
             break;
         default:
             break;
     }
     $assetsStatuses = array(asset::ASSET_STATUS_READY);
     if ($mrssParams && $mrssParams->getStatuses()) {
         $assetsStatuses = $mrssParams->getStatuses();
     }
     $assets = assetPeer::retrieveReadyByEntryId($entry->getId(), null, $assetsStatuses);
     foreach ($assets as $asset) {
         if ($mrssParams && !is_null($mrssParams->getFilterByFlavorParams()) && $asset->getFlavorParamsId() != $mrssParams->getFilterByFlavorParams()) {
             continue;
         }
         if ($asset instanceof flavorAsset) {
             self::appendFlavorAssetMrss($asset, $mrss, $mrssParams);
         }
         if ($asset instanceof thumbAsset) {
             self::appendThumbAssetMrss($asset, $mrss);
         }
     }
     $mrssContributors = self::getMrssContributors();
     if (count($mrssContributors)) {
         foreach ($mrssContributors as $mrssContributor) {
             try {
                 if (!count($features) || in_array($mrssContributor->getObjectFeatureType(), $features)) {
                     $mrssContributor->contribute($entry, $mrss, $mrssParams);
                 }
             } catch (kCoreException $ex) {
                 KalturaLog::err("Unable to add MRSS element for contributor [" . get_class($mrssContributor) . "] message [" . $ex->getMessage() . "]");
             }
         }
     }
     if ($mrssParams && $mrssParams->getIncludePlayerTag()) {
         $uiconfId = !is_null($mrssParams->getPlayerUiconfId()) ? '/ui_conf_id/' . $mrssParams->getPlayerUiconfId() : '';
         $playerUrl = kConf::get('apphome_url') . '/kwidget/wid/_' . $entry->getPartnerId() . '/entry_id/' . $entry->getId() . '/ui_conf' . ($uiconfId ? "/{$uiconfId}" : '');
         $player = $mrss->addChild('player');
         $player->addAttribute('url', $playerUrl);
     }
     if ($mrssParams && $mrssParams->getItemXpathsToExtend()) {
         self::addExtendingItemsToMrss($mrss, $mrssParams);
     }
     self::addInstanceToPool($instanceKey, $mrss);
     return $mrss;
 }
Ejemplo n.º 12
0
 /**
  * @param KalturaResource $resource
  * @param entry $dbEntry
  * @param int $conversionProfileId
  */
 protected function replaceResource(KalturaResource $resource, entry $dbEntry, $conversionProfileId = null, $advancedOptions = null)
 {
     if ($advancedOptions) {
         $dbEntry->setReplacementOptions($advancedOptions->toObject());
         $dbEntry->save();
     }
     if ($dbEntry->getStatus() == KalturaEntryStatus::NO_CONTENT || $dbEntry->getMediaType() == KalturaMediaType::IMAGE) {
         $resource->validateEntry($dbEntry);
         if ($conversionProfileId) {
             $dbEntry->setConversionQuality($conversionProfileId);
             $dbEntry->save();
         }
         $kResource = $resource->toObject();
         $this->attachResource($kResource, $dbEntry);
     } else {
         $kResource = $resource->toObject();
         if ($kResource instanceof kOperationResource && $this->isResourceKClip($kResource)) {
             $internalResource = $kResource->getResource();
             if ($dbEntry->getIsTrimDisabled() && $internalResource instanceof kFileSyncResource && $dbEntry->getId() == $internalResource->getOriginEntryId()) {
                 throw new KalturaAPIException(KalturaErrors::ENTRY_CANNOT_BE_TRIMMED);
             }
         }
         $tempMediaEntry = new KalturaMediaEntry();
         $tempMediaEntry->type = $dbEntry->getType();
         $tempMediaEntry->mediaType = $dbEntry->getMediaType();
         if (!$conversionProfileId) {
             $originalConversionProfileId = $dbEntry->getConversionQuality();
             $conversionProfile = conversionProfile2Peer::retrieveByPK($originalConversionProfileId);
             if (is_null($conversionProfile) || $conversionProfile->getType() != ConversionProfileType::MEDIA) {
                 $defaultConversionProfile = myPartnerUtils::getConversionProfile2ForPartner($this->getPartnerId());
                 if (!is_null($defaultConversionProfile)) {
                     $conversionProfileId = $defaultConversionProfile->getId();
                 }
             } else {
                 $conversionProfileId = $originalConversionProfileId;
             }
         }
         if ($conversionProfileId) {
             $tempMediaEntry->conversionProfileId = $conversionProfileId;
         }
         $this->replaceResourceByEntry($dbEntry, $resource, $tempMediaEntry);
     }
     $resource->entryHandled($dbEntry);
 }
Ejemplo n.º 13
0
 /**
  * for each storage profile check if it still fulfills the export rules and decide if it should be exported or deleted
  * 
  * @param entry $entry
  * 
  */
 public static function reExportEntry(entry $entry)
 {
     if (!PermissionPeer::isValidForPartner(PermissionName::FEATURE_REMOTE_STORAGE_RULE, $entry->getPartnerId())) {
         return;
     }
     if ($entry->getStatus() == entryStatus::NO_CONTENT) {
         return;
     }
     $storageProfiles = StorageProfilePeer::retrieveExternalByPartnerId($entry->getPartnerId());
     foreach ($storageProfiles as $profile) {
         /* @var $profile StorageProfile */
         KalturaLog::debug('Checking entry [' . $entry->getId() . ']re-export to storage [' . $profile->getId() . ']');
         $scope = $profile->getScope();
         $scope->setEntryId($entry->getId());
         if ($profile->triggerFitsReadyAsset($entry->getId()) && $profile->fulfillsRules($scope)) {
             self::tryExportEntry($entry, $profile);
         } else {
             self::deleteExportedEntry($entry, $profile);
         }
     }
 }
 /**
  * @param KalturaResource $resource
  * @param entry $dbEntry
  * @param int $conversionProfileId
  */
 protected function replaceResource(KalturaResource $resource, entry $dbEntry, $conversionProfileId = null)
 {
     if (!$this->getPartner()->getWamsAccountName() || !$this->getPartner()->getWamsAccountKey()) {
         exit;
     }
     if ($dbEntry->getStatus() == KalturaEntryStatus::NO_CONTENT || $dbEntry->getMediaType() == KalturaMediaType::IMAGE) {
         $resource->validateEntry($dbEntry);
         if ($conversionProfileId) {
             $dbEntry->setConversionQuality($conversionProfileId);
             $dbEntry->save();
         }
         $kResource = $resource->toObject();
         $this->attachResource($kResource, $dbEntry);
     } else {
         $partner = $this->getPartner();
         if (!$partner->getEnabledService(PermissionName::FEATURE_ENTRY_REPLACEMENT)) {
             KalturaLog::notice("Replacement is not allowed to the partner permission [FEATURE_ENTRY_REPLACEMENT] is needed");
             throw new KalturaAPIException(KalturaErrors::FEATURE_FORBIDDEN, PermissionName::FEATURE_ENTRY_REPLACEMENT);
         }
         if ($dbEntry->getReplacingEntryId()) {
             throw new KalturaAPIException(KalturaErrors::ENTRY_REPLACEMENT_ALREADY_EXISTS);
         }
         $resource->validateEntry($dbEntry);
         $tempMediaEntry = new KalturaMediaEntry();
         $tempMediaEntry->type = $dbEntry->getType();
         $tempMediaEntry->mediaType = $dbEntry->getMediaType();
         $tempMediaEntry->conversionProfileId = $dbEntry->getConversionQuality();
         if ($conversionProfileId) {
             $tempMediaEntry->conversionProfileId = $conversionProfileId;
         }
         $tempDbEntry = $this->prepareEntryForInsert($tempMediaEntry);
         $tempDbEntry->setDisplayInSearch(mySearchUtils::DISPLAY_IN_SEARCH_SYSTEM);
         $tempDbEntry->setPartnerId($dbEntry->getPartnerId());
         $tempDbEntry->setReplacedEntryId($dbEntry->getId());
         $tempDbEntry->save();
         $dbEntry->setReplacingEntryId($tempDbEntry->getId());
         $dbEntry->setReplacementStatus(entryReplacementStatus::NOT_READY_AND_NOT_APPROVED);
         if (!$partner->getEnabledService(PermissionName::FEATURE_ENTRY_REPLACEMENT_APPROVAL)) {
             $dbEntry->setReplacementStatus(entryReplacementStatus::APPROVED_BUT_NOT_READY);
         }
         $dbEntry->save();
         $kResource = $resource->toObject();
         $this->attachResource($kResource, $tempDbEntry);
     }
     $resource->entryHandled($dbEntry);
 }
Ejemplo n.º 15
0
 /**
  * @param KalturaResource $resource
  * @param entry $dbEntry
  * @param int $conversionProfileId
  */
 protected function replaceResource(KalturaResource $resource, entry $dbEntry, $conversionProfileId = null, $advancedOptions = null)
 {
     if ($advancedOptions) {
         $dbEntry->setReplacementOptions($advancedOptions->toObject());
         $dbEntry->save();
     }
     if ($dbEntry->getStatus() == KalturaEntryStatus::NO_CONTENT || $dbEntry->getMediaType() == KalturaMediaType::IMAGE) {
         $resource->validateEntry($dbEntry);
         if ($conversionProfileId) {
             $dbEntry->setConversionQuality($conversionProfileId);
             $dbEntry->save();
         }
         $kResource = $resource->toObject();
         $this->attachResource($kResource, $dbEntry);
     } else {
         $tempMediaEntry = new KalturaMediaEntry();
         $tempMediaEntry->type = $dbEntry->getType();
         $tempMediaEntry->mediaType = $dbEntry->getMediaType();
         if (!$conversionProfileId) {
             $originalConversionProfileId = $dbEntry->getConversionQuality();
             $conversionProfile = conversionProfile2Peer::retrieveByPK($originalConversionProfileId);
             if (is_null($conversionProfile) || $conversionProfile->getType() != ConversionProfileType::MEDIA) {
                 $defaultConversionProfile = myPartnerUtils::getConversionProfile2ForPartner($this->getPartnerId());
                 if (!is_null($defaultConversionProfile)) {
                     $conversionProfileId = $defaultConversionProfile->getId();
                 }
             } else {
                 $conversionProfileId = $originalConversionProfileId;
             }
         }
         if ($conversionProfileId) {
             $tempMediaEntry->conversionProfileId = $conversionProfileId;
         }
         $this->replaceResourceByEntry($dbEntry, $resource, $tempMediaEntry);
     }
     $resource->entryHandled($dbEntry);
 }
Ejemplo n.º 16
0
 /**
  * @param KalturaResource $resource
  * @param entry $dbEntry
  * @param int $conversionProfileId
  */
 protected function replaceResource(KalturaResource $resource, entry $dbEntry, $conversionProfileId = null)
 {
     if ($dbEntry->getStatus() == KalturaEntryStatus::NO_CONTENT) {
         $resource->validateEntry($dbEntry);
         if ($conversionProfileId) {
             $dbEntry->setConversionQuality($conversionProfileId);
             $dbEntry->save();
         }
         $kResource = $resource->toObject();
         $this->attachResource($kResource, $dbEntry);
     } else {
         $tempDocEntry = new KalturaDocumentEntry();
         $tempDocEntry->type = $dbEntry->getType();
         $tempDocEntry->mediaType = $dbEntry->getMediaType();
         $tempDocEntry->documentType = $dbEntry->getDocumentType();
         $tempDocEntry->conversionProfileId = $dbEntry->getConversionQuality();
         if ($conversionProfileId) {
             $tempDocEntry->conversionProfileId = $conversionProfileId;
         }
         $this->replaceResourceByEntry($dbEntry, $resource, $tempDocEntry);
     }
     $resource->entryHandled($dbEntry);
 }
 /**
  * @param entry $entry
  * @param array $modifiedColumns
  */
 public static function onEntryChanged(entry $entry, array $modifiedColumns)
 {
     if (!ContentDistributionPlugin::isAllowedPartner($entry->getPartnerId())) {
         return true;
     }
     $entryDistributions = EntryDistributionPeer::retrieveByEntryId($entry->getId());
     foreach ($entryDistributions as $entryDistribution) {
         $distributionProfileId = $entryDistribution->getDistributionProfileId();
         $distributionProfile = DistributionProfilePeer::retrieveByPK($distributionProfileId);
         if (!$distributionProfile) {
             KalturaLog::err("Entry distribution [" . $entryDistribution->getId() . "] profile [{$distributionProfileId}] not found");
             continue;
         }
         if (in_array(entrypeer::START_DATE, $modifiedColumns) || in_array(entrypeer::END_DATE, $modifiedColumns)) {
             $entryDistribution->setUpdatedAt(time());
             $entryDistribution->save();
         }
         switch ($entryDistribution->getStatus()) {
             case EntryDistributionStatus::DELETED:
             case EntryDistributionStatus::DELETING:
             case EntryDistributionStatus::REMOVED:
                 KalturaLog::log("Entry distribution [" . $entryDistribution->getId() . "] status [" . $entryDistribution->getStatus() . "] no update required");
                 continue;
             case EntryDistributionStatus::PENDING:
             case EntryDistributionStatus::ERROR_SUBMITTING:
                 $validationErrors = $distributionProfile->validateForSubmission($entryDistribution, DistributionAction::SUBMIT);
                 $entryDistribution->setValidationErrorsArray($validationErrors);
                 $entryDistribution->save();
                 KalturaLog::log("Entry distribution [" . $entryDistribution->getId() . "] validation errors [" . print_r($validationErrors, true) . "]");
                 if (count($distributionProfile->getAutoCreateFlavorsArray()) || count($distributionProfile->getAutoCreateThumbArray())) {
                     self::submitAddEntryDistribution($entryDistribution, $distributionProfile);
                 }
                 break;
             case EntryDistributionStatus::QUEUED:
                 $validationErrors = $distributionProfile->validateForSubmission($entryDistribution, DistributionAction::SUBMIT);
                 $entryDistribution->setValidationErrorsArray($validationErrors);
                 $entryDistribution->save();
                 KalturaLog::log("Entry distribution [" . $entryDistribution->getId() . "] validation errors [" . print_r($validationErrors, true) . "]");
                 if (!count($validationErrors) && $entry->getStatus() == entryStatus::READY) {
                     self::submitAddEntryDistribution($entryDistribution, $distributionProfile);
                 }
                 break;
             default:
                 if ($entryDistribution->getDirtyStatus() == EntryDistributionDirtyStatus::UPDATE_REQUIRED || $entryDistribution->getDirtyStatus() == EntryDistributionDirtyStatus::SUBMIT_REQUIRED) {
                     KalturaLog::log("Entry distribution [" . $entryDistribution->getId() . "] already flaged for updating");
                     //						continue;
                 }
                 $distributionProvider = $distributionProfile->getProvider();
                 if (!$distributionProvider) {
                     KalturaLog::err("Entry distribution [" . $entryDistribution->getId() . "] provider [" . $distributionProfile->getProviderType() . "] not found");
                     continue;
                 }
                 if (!$distributionProvider->isUpdateEnabled()) {
                     KalturaLog::log("Entry distribution [" . $entryDistribution->getId() . "] provider [" . $distributionProvider->getName() . "] does not support update");
                     continue;
                 }
                 $updateRequiredEntryFields = $distributionProvider->getUpdateRequiredEntryFields($distributionProfileId);
                 $updateRequired = false;
                 foreach ($updateRequiredEntryFields as $updateRequiredEntryField) {
                     if (in_array($updateRequiredEntryField, $modifiedColumns)) {
                         $updateRequired = true;
                         break;
                     }
                 }
                 $validationErrors = $distributionProfile->validateForSubmission($entryDistribution, DistributionAction::SUBMIT);
                 $entryDistribution->setValidationErrorsArray($validationErrors);
                 $entryDistribution->save();
                 if (!$updateRequired) {
                     KalturaLog::log("Entry distribution [" . $entryDistribution->getId() . "] update not required");
                     continue;
                 }
                 if ($distributionProfile->getUpdateEnabled() != DistributionProfileActionStatus::AUTOMATIC) {
                     KalturaLog::log("Entry distribution [" . $entryDistribution->getId() . "] should not be updated automatically");
                     $entryDistribution->setDirtyStatus(EntryDistributionDirtyStatus::UPDATE_REQUIRED);
                     $entryDistribution->save();
                     continue;
                 }
                 KalturaLog::log("Updating entry distribution [" . $entryDistribution->getId() . "]");
                 self::submitUpdateEntryDistribution($entryDistribution, $distributionProfile);
         }
     }
     return true;
 }
Ejemplo n.º 18
0
 public static function copyEntry(entry $entry, Partner $toPartner = null, $dontCopyUsers = false)
 {
     KalturaLog::log("copyEntry - Copying entry [" . $entry->getId() . "] to partner [" . $toPartner->getId() . "]");
     $newEntry = $entry->copy();
     $newEntry->setIntId(null);
     $newEntry->setCategories(null);
     $newEntry->setCategoriesIds(null);
     if ($toPartner instanceof Partner) {
         $newEntry->setPartnerId($toPartner->getId());
         $newEntry->setSubpId($toPartner->getId() * 100);
         $newEntry->setAccessControlId($toPartner->getDefaultAccessControlId());
     }
     $newKuser = null;
     if (!$dontCopyUsers) {
         // copy the kuser (if the same puser id exists its kuser will be used)
         kuserPeer::setUseCriteriaFilter(false);
         $kuser = $entry->getKuser();
         $newKuser = kuserPeer::createKuserForPartner($newEntry->getPartnerId(), $kuser->getPuserId());
         $newEntry->setKuserId($newKuser->getId());
         $newEntry->setCreatorKuserId($newKuser->getId());
         kuserPeer::setUseCriteriaFilter(true);
     }
     // copy the kshow
     kshowPeer::setUseCriteriaFilter(false);
     $kshow = $entry->getKshow();
     if ($kshow) {
         $newKshow = $kshow->copy();
         $newKshow->setIntId(null);
         $newKshow->setPartnerId($toPartner->getId());
         $newKshow->setSubpId($toPartner->getId() * 100);
         if ($newKuser) {
             $newKshow->setProducerId($newKuser->getId());
         }
         $newKshow->save();
         $newEntry->setKshowId($newKshow->getId());
     }
     kshowPeer::setUseCriteriaFilter(true);
     // reset the statistics
     myEntryUtils::resetEntryStatistics($newEntry);
     // set the new partner id into the default category criteria filter
     $defaultCategoryFilter = categoryPeer::getCriteriaFilter()->getFilter();
     $oldPartnerId = $defaultCategoryFilter->get(categoryPeer::PARTNER_ID);
     $defaultCategoryFilter->remove(categoryPeer::PARTNER_ID);
     $defaultCategoryFilter->addAnd(categoryPeer::PARTNER_ID, $newEntry->getPartnerId());
     // save the entry
     $newEntry->save();
     // restore the original partner id in the default category criteria filter
     $defaultCategoryFilter->remove(categoryPeer::PARTNER_ID);
     $defaultCategoryFilter->addAnd(categoryPeer::PARTNER_ID, $oldPartnerId);
     KalturaLog::log("copyEntry - New entry [" . $newEntry->getId() . "] was created");
     if ($entry->getStatus() != entryStatus::READY) {
         $clonePendingEntries = $entry->getClonePendingEntries();
         $clonePendingEntries[] = $newEntry->getId();
         $entry->setClonePendingEntries($clonePendingEntries);
         $entry->save();
     } else {
         self::copyEntryData($entry, $newEntry);
     }
     //if entry is a static playlist, link between it and its new child entries
     if ($entry->getType() == entryType::PLAYLIST) {
         switch ($entry->getMediaType()) {
             case entry::ENTRY_MEDIA_TYPE_TEXT:
                 $from = $entry->getDataContent();
                 KalturaLog::debug("Entries to copy from source static playlist: [{$from}]");
                 $fromEntryIds = explode(",", $from);
                 $toEntryIds = array();
                 foreach ($fromEntryIds as $fromEntryId) {
                     $toEntryIds[] = kObjectCopyHandler::getMappedId(entryPeer::OM_CLASS, $fromEntryId);
                 }
                 $newEntry->setDataContent(implode(",", $toEntryIds));
                 break;
             case entry::ENTRY_MEDIA_TYPE_XML:
                 list($totalResults, $fromFiltersList) = myPlaylistUtils::getPlaylistFilterListStruct($entry->getDataContent());
                 $toPlaylistXml = new SimpleXMLElement("<playlist/>");
                 $toPlaylistXml->addChild("total_results", $totalResults);
                 $toFiltersXml = $toPlaylistXml->addChild("filters");
                 foreach ($fromFiltersList as $filterXML) {
                     $entryFilter = new entryFilter();
                     $entryFilter->fillObjectFromXml($filterXML, "_");
                     if (isset($entryFilter->fields["_matchand_categories_ids"])) {
                         $categoriesIds = explode(",", $entryFilter->fields["_matchand_categories_ids"]);
                         $newCategoriesIds = array();
                         foreach ($categoriesIds as $categoryId) {
                             $newCategoriesIds[] = kObjectCopyHandler::getMappedId(categoryPeer::OM_CLASS, $categoryId);
                         }
                         $entryFilter->fields["_matchand_categories_ids"] = implode(",", $newCategoriesIds);
                     }
                     if (isset($entryFilter->fields["_matchor_categories_ids"])) {
                         $categoriesIds = explode(",", $entryFilter->fields["_matchor_categories_ids"]);
                         $newCategoriesIds = array();
                         foreach ($categoriesIds as $categoryId) {
                             $newCategoriesIds[] = kObjectCopyHandler::getMappedId(categoryPeer::OM_CLASS, $categoryId);
                         }
                         $entryFilter->fields["_matchor_categories_ids"] = implode(",", $newCategoriesIds);
                     }
                     if (isset($entryFilter->fields["_in_category_ancestor_id"])) {
                         $categoriesIds = explode(",", $entryFilter->fields["_in_category_ancestor_id"]);
                         $newCategoriesIds = array();
                         foreach ($categoriesIds as $categoryId) {
                             $newCategoriesIds[] = kObjectCopyHandler::getMappedId(categoryPeer::OM_CLASS, $categoryId);
                         }
                         $entryFilter->fields["_in_category_ancestor_id"] = implode(",", $newCategoriesIds);
                     }
                     $toEntryFilterXML = $toFiltersXml->addChild("filter");
                     $toEntryFilterXML = $entryFilter->toXml($toEntryFilterXML);
                 }
                 $newEntry->setDataContent($toPlaylistXml->asXML());
                 break;
         }
     }
     // copy relationships to categories
     KalturaLog::debug('Copy relationships to categories from entry [' . $entry->getId() . '] to entry [' . $newEntry->getId() . ']');
     $c = KalturaCriteria::create(categoryEntryPeer::OM_CLASS);
     $c->addAnd(categoryEntryPeer::ENTRY_ID, $entry->getId());
     $c->addAnd(categoryEntryPeer::STATUS, CategoryEntryStatus::ACTIVE, Criteria::EQUAL);
     $c->addAnd(categoryEntryPeer::PARTNER_ID, $entry->getPartnerId());
     categoryEntryPeer::setUseCriteriaFilter(false);
     $categoryEntries = categoryEntryPeer::doSelect($c);
     categoryEntryPeer::setUseCriteriaFilter(true);
     // Create srcCategoryIdToDstCategoryIdMap - a map of source partner category ids -> dst. partner category ids
     //
     // Build src category IDs set
     $srcCategoryIdSet = array();
     foreach ($categoryEntries as $categoryEntry) {
         $srcCategoryIdSet[] = $categoryEntry->getCategoryId();
     }
     $illegalCategoryStatus = array(CategoryStatus::DELETED, CategoryStatus::PURGED);
     // Get src category objects
     $c = KalturaCriteria::create(categoryPeer::OM_CLASS);
     $c->add(categoryPeer::ID, $srcCategoryIdSet, Criteria::IN);
     $c->addAnd(categoryPeer::PARTNER_ID, $entry->getPartnerId());
     $c->addAnd(categoryPeer::STATUS, $illegalCategoryStatus, Criteria::NOT_IN);
     categoryPeer::setUseCriteriaFilter(false);
     $srcCategories = categoryPeer::doSelect($c);
     categoryPeer::setUseCriteriaFilter(true);
     // Map the category names to their IDs
     $fullNamesToSrcCategoryIdMap = array();
     foreach ($srcCategories as $category) {
         $fullNamesToSrcCategoryIdMap[$category->getFullName()] = $category->getId();
     }
     // Get dst. partner categories based on src. category full-names
     $c = KalturaCriteria::create(categoryPeer::OM_CLASS);
     $c->add(categoryPeer::FULL_NAME, array_keys($fullNamesToSrcCategoryIdMap), KalturaCriteria::IN);
     $c->addAnd(categoryPeer::PARTNER_ID, $newEntry->getPartnerId());
     $c->addAnd(categoryPeer::STATUS, $illegalCategoryStatus, Criteria::NOT_IN);
     categoryPeer::setUseCriteriaFilter(false);
     $dstCategories = categoryPeer::doSelect($c);
     categoryPeer::setUseCriteriaFilter(true);
     $srcCategoryIdToDstCategoryIdMap = array();
     foreach ($dstCategories as $dstCategory) {
         $fullName = $dstCategory->getFullName();
         if (array_key_exists($fullName, $fullNamesToSrcCategoryIdMap)) {
             $srcCategoryId = $fullNamesToSrcCategoryIdMap[$fullName];
             $srcCategoryIdToDstCategoryIdMap[$srcCategoryId] = $dstCategory->getId();
         }
     }
     foreach ($categoryEntries as $categoryEntry) {
         /* @var $categoryEntry categoryEntry */
         $newCategoryEntry = $categoryEntry->copy();
         $newCategoryEntry->setPartnerId($newEntry->getPartnerId());
         $newCategoryEntry->setEntryId($newEntry->getId());
         $srcCategoryId = $categoryEntry->getCategoryId();
         if (!array_key_exists($srcCategoryId, $srcCategoryIdToDstCategoryIdMap)) {
             continue;
             // Skip the category_entry's creation
         }
         $dstCategoryId = $srcCategoryIdToDstCategoryIdMap[$srcCategoryId];
         $newCategoryEntry->setCategoryId($dstCategoryId);
         categoryPeer::setUseCriteriaFilter(false);
         entryPeer::setUseCriteriaFilter(false);
         $newCategoryEntry->save();
         entryPeer::setUseCriteriaFilter(true);
         categoryPeer::setUseCriteriaFilter(true);
     }
     return $newEntry;
 }
Ejemplo n.º 19
0
 /**
  * @param IRemoteStorageResource $resource
  * @param entry $dbEntry
  * @param asset $dbAsset
  * @return asset
  * @throws KalturaErrors::ORIGINAL_FLAVOR_ASSET_NOT_CREATED
  * @throws KalturaErrors::STORAGE_PROFILE_ID_NOT_FOUND
  */
 protected function attachRemoteStorageResource(IRemoteStorageResource $resource, entry $dbEntry, asset $dbAsset = null)
 {
     $resources = $resource->getResources();
     $fileExt = $resource->getFileExt();
     $dbEntry->setSource(KalturaSourceType::URL);
     // TODO - move image handling to media service
     if ($dbEntry->getMediaType() == KalturaMediaType::IMAGE) {
         $syncKey = $dbEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA);
         foreach ($resources as $currentResource) {
             $storageProfile = StorageProfilePeer::retrieveByPK($currentResource->getStorageProfileId());
             $fileSync = kFileSyncUtils::createReadyExternalSyncFileForKey($syncKey, $currentResource->getUrl(), $storageProfile);
         }
         $dbEntry->setStatus(entryStatus::READY);
         $dbEntry->save();
         return null;
     }
     $dbEntry->save();
     $isNewAsset = false;
     if (!$dbAsset) {
         $isNewAsset = true;
         $dbAsset = kFlowHelper::createOriginalFlavorAsset($this->getPartnerId(), $dbEntry->getId());
     }
     if (!$dbAsset) {
         KalturaLog::err("Flavor asset not created for entry [" . $dbEntry->getId() . "]");
         if ($dbEntry->getStatus() == entryStatus::NO_CONTENT) {
             $dbEntry->setStatus(entryStatus::ERROR_CONVERTING);
             $dbEntry->save();
         }
         throw new KalturaAPIException(KalturaErrors::ORIGINAL_FLAVOR_ASSET_NOT_CREATED);
     }
     $syncKey = $dbAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     foreach ($resources as $currentResource) {
         $storageProfile = StorageProfilePeer::retrieveByPK($currentResource->getStorageProfileId());
         $fileSync = kFileSyncUtils::createReadyExternalSyncFileForKey($syncKey, $currentResource->getUrl(), $storageProfile);
     }
     $dbAsset->setFileExt($fileExt);
     if ($dbAsset instanceof flavorAsset && !$dbAsset->getIsOriginal()) {
         $dbAsset->setStatus(asset::FLAVOR_ASSET_STATUS_READY);
     }
     $dbAsset->save();
     if ($isNewAsset) {
         kEventsManager::raiseEvent(new kObjectAddedEvent($dbAsset));
     }
     kEventsManager::raiseEvent(new kObjectDataChangedEvent($dbAsset));
     if ($dbAsset instanceof flavorAsset && !$dbAsset->getIsOriginal()) {
         kBusinessPostConvertDL::handleConvertFinished(null, $dbAsset);
     }
     return $dbAsset;
 }
Ejemplo n.º 20
0
 protected function initEntry()
 {
     $this->entryId = $this->getRequestParameter("entryId", null);
     // look for a valid token
     $expiry = $this->getRequestParameter("expiry");
     if ($expiry && $expiry <= time()) {
         KExternalErrors::dieError(KExternalErrors::EXPIRED_TOKEN);
     }
     $urlToken = $this->getRequestParameter("kt");
     if ($urlToken) {
         if ($_SERVER["REQUEST_METHOD"] != "GET" || !self::validateKalturaToken($_SERVER["REQUEST_URI"], $urlToken)) {
             KExternalErrors::dieError(KExternalErrors::INVALID_TOKEN);
         }
     }
     // initalize the context
     $ksStr = $this->getRequestParameter("ks");
     if ($ksStr && !$urlToken) {
         try {
             kCurrentContext::initKsPartnerUser($ksStr);
         } catch (Exception $ex) {
             KExternalErrors::dieError(KExternalErrors::INVALID_KS);
         }
     } else {
         $this->entry = kCurrentContext::initPartnerByEntryId($this->entryId);
         if (!$this->entry || $this->entry->getStatus() == entryStatus::DELETED) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     // no need for any further check if a token was used
     if ($urlToken) {
         return;
     }
     // enforce entitlement
     kEntitlementUtils::initEntitlementEnforcement();
     if (!$this->entry) {
         $this->entry = entryPeer::retrieveByPKNoFilter($this->entryId);
         if (!$this->entry || $this->entry->getStatus() == entryStatus::DELETED) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     } else {
         if (!kEntitlementUtils::isEntryEntitled($this->entry)) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     myPartnerUtils::blockInactivePartner($this->entry->getPartnerId());
     // enforce access control
     $base64Referrer = $this->getRequestParameter("referrer");
     $hashes = $this->getRequestParameter("hashes");
     $keyValueHashes = array();
     if ($hashes) {
         $hashes = urldecode($hashes);
         $hashes = explode(",", $hashes);
         foreach ($hashes as $keyValueHashString) {
             list($key, $value) = explode('=', $keyValueHashString);
             $keyValueHashes[$key] = $value;
         }
     }
     // replace space in the base64 string with + as space is invalid in base64 strings and caused
     // by symfony calling str_parse to replace + with spaces.
     // this happens only with params passed in the url path and not the query strings. specifically the ~ char at
     // a columns divided by 3 causes this issue (e.g. http://www.xyzw.com/~xxx)
     //replace also any - with + and _ with /
     $referrer = base64_decode(str_replace(array('-', '_', ' '), array('+', '/', '+'), $base64Referrer));
     if (!is_string($referrer)) {
         $referrer = "";
     }
     // base64_decode can return binary data
     $this->secureEntryHelper = new KSecureEntryHelper($this->entry, $ksStr, $referrer, ContextType::PLAY, $keyValueHashes);
     if ($this->secureEntryHelper->shouldPreview()) {
         $previewLengthInMsecs = $this->secureEntryHelper->getPreviewLength() * 1000;
         $entryLengthInMsecs = $this->entry->getLengthInMsecs();
         if ($previewLengthInMsecs < $entryLengthInMsecs) {
             $this->deliveryAttributes->setClipTo($previewLengthInMsecs);
         }
     } else {
         $this->secureEntryHelper->validateForPlay();
     }
     if (PermissionPeer::isValidForPartner(PermissionName::FEATURE_ENTITLEMENT, $this->entry->getPartnerId()) || $this->secureEntryHelper->hasRules()) {
         $this->forceUrlTokenization = true;
     }
 }
Ejemplo n.º 21
0
 /**
  * Convert all drop folder files' status from PROCESSING to HANDLED/DELETED in case of DropFolderFileDeletePolicy::AUTO_DELETE_WHEN_ENTRY_IS_READY
  * 
  * Note that if the entry reached entryStatus::ERROR_CONVERTING, then the drop folder files' 
  * conversions already failed, so there's no need to change their status (thus they won't be handled here).  
  *  
  * @param entry $entry
  */
 private function onEntryStatusChanged($entry)
 {
     // Handle only files that are still in the PROCESSING state, which were left
     // in this state due to AUTO_DELETE_WHEN_ENTRY_IS_READY delete policy.
     $dropFolderFiles = DropFolderFilePeer::retrieveByEntryIdPartnerIdAndStatuses($entry->getId(), $entry->getPartnerId(), array(DropFolderFileStatus::PROCESSING));
     $dropFolderIdToDropFolderCache = array();
     $entryStatus = $entry->getStatus();
     foreach ($dropFolderFiles as $dropFolderFile) {
         $newDropFolderFileStatus = null;
         if ($entryStatus == entryStatus::ERROR_CONVERTING) {
             $newDropFolderFileStatus = DropFolderFileStatus::ERROR_HANDLING;
         } elseif ($entryStatus == entryStatus::READY) {
             // Get the associated drop folder
             $dropFolderId = $dropFolderFile->getDropFolderId();
             if (key_exists($dropFolderId, $dropFolderIdToDropFolderCache)) {
                 $dropFolder = $dropFolderIdToDropFolderCache[$dropFolderId];
             } else {
                 $dropFolder = DropFolderPeer::retrieveByPK($dropFolderId);
                 $dropFolderIdToDropFolderCache[$dropFolderId] = $dropFolder;
             }
             if ($dropFolder->getFileDeletePolicy() == DropFolderFileDeletePolicy::AUTO_DELETE_WHEN_ENTRY_IS_READY) {
                 if ($dropFolder->getAutoFileDeleteDays() == 0) {
                     $newDropFolderFileStatus = DropFolderFileStatus::DELETED;
                     // Mark for immediate deletion
                 } else {
                     $newDropFolderFileStatus = DropFolderFileStatus::HANDLED;
                 }
             }
         }
         KalturaLog::info("Entry id [{$entry->getId()}] status [{$entryStatus}], drop folder file id [{$dropFolderFile->getId()}] status [{$dropFolderFile->getStatus()}] => [" . ($newDropFolderFileStatus ? $newDropFolderFileStatus : "{$dropFolderFile->getStatus()} (unchanged)") . "]");
         if ($newDropFolderFileStatus) {
             $dropFolderFile->setStatus($newDropFolderFileStatus);
             $dropFolderFile->save();
         }
     }
 }
Ejemplo n.º 22
0
 /**
  * @param BatchJob $batchJob
  * @param entry $entry
  * @param string $flavorAssetId
  * @param string $inputFileSyncLocalPath
  * @return BatchJob
  */
 public static function addConvertProfileJob(BatchJob $parentJob = null, entry $entry, $flavorAssetId, $inputFileSyncLocalPath)
 {
     // if file size is 0, do not create conversion profile and set entry status as error converting
     if (filesize($inputFileSyncLocalPath) == 0) {
         $entry->setStatus(entryStatus::ERROR_CONVERTING);
         $entry->save();
         $flavorAsset = flavorAssetPeer::retrieveById($flavorAssetId);
         $flavorAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_ERROR);
         $flavorAsset->setDescription('Entry of size 0 should not be converted');
         $flavorAsset->save();
         KalturaLog::err('Entry of size 0 should not be converted');
         return null;
     }
     if ($entry->getConversionQuality() == conversionProfile2::CONVERSION_PROFILE_NONE) {
         $entry->setStatus(entryStatus::PENDING);
         $entry->save();
         KalturaLog::notice('Entry should not be converted');
         return null;
     }
     if ($entry->getStatus() != entryStatus::READY) {
         $entry->setStatus(entryStatus::PRECONVERT);
         $entry->save();
     }
     $jobData = new kConvertProfileJobData();
     $jobData->setFlavorAssetId($flavorAssetId);
     $jobData->setInputFileSyncLocalPath($inputFileSyncLocalPath);
     $jobData->setExtractMedia(true);
     if ($entry->getType() != entryType::MEDIA_CLIP) {
         $jobData->setExtractMedia(false);
         $jobData->setCreateThumb(false);
     }
     $batchJob = null;
     if ($parentJob) {
         $batchJob = $parentJob->createChild();
     } else {
         $batchJob = new BatchJob();
         $batchJob->setEntryId($entry->getId());
         $batchJob->setPartnerId($entry->getPartnerId());
     }
     return self::addJob($batchJob, $jobData, BatchJobType::CONVERT_PROFILE);
 }