Example #1
0
    public function execute()
    {
        $this->forceSystemAuthentication();
        $this->basePath = "/content/dynamic/";
        $dynamicRoot = myContentStorage::getFSContentRootPath() . $this->basePath;
        if ($this->getRequest()->getMethod() == sfRequest::POST) {
            $origFilename = basename($_FILES['Filedata']['name']);
            $fullPath = $dynamicRoot . $origFilename;
            move_uploaded_file($_FILES['Filedata']['tmp_name'], $fullPath);
            chmod($fullPath, 0777);
            return $this->renderText("ok");
        } else {
            if ($this->getRequest()->getMethod() == sfRequest::DELETE) {
                $filename = basename($_REQUEST['fileName']);
                kFile::deleteFile($dynamicRoot . $filename);
                return $this->renderText("ok");
            }
        }
        $this->files = kFile::dirListExtended($dynamicRoot, false);
        $this->extraHead = <<<EOT
\t\t<style type="text/css">
\t\t\ttable{ font-size:1.2em; width:100%; margin:40px 0 0 0; }
\t\t\ttable thead{ font-size:1.4em; }
\t\t\t\ttable thead td{ border-bottom:1px solid #444; margin-bottom:20px; }
\t\t\ttable tbody td{ padding:2px 0; color:#ccc; }
\t\t\t\ttable tbody td b{ font-weight:normal; cursor:default; }
\t\t\t\ttable tbody td span.btn{ margin-right:12px;}
\t\t\tdiv#helper{ display:none; position:absolute; left:0; width:250px; }
\t\t\tdiv#helper img{ float:right; max-width:250px; }
\t\t</style>
EOT;
    }
 public function toObject($object_to_fill = null, $props_to_skip = array())
 {
     $this->validateForUsage($object_to_fill, $props_to_skip);
     if (!$object_to_fill) {
         $object_to_fill = new kLocalFileResource();
     }
     $content = myContentStorage::getFSContentRootPath();
     $entryFullPaths = array('flv' => "{$content}/content/webcam/{$this->token}.flv", 'f4v' => "{$content}/content/webcam/{$this->token}.f4v", 'mp4' => "{$content}/content/webcam/{$this->token}.f4v.mp4");
     foreach ($entryFullPaths as $type => $entryFullPath) {
         if (file_exists($entryFullPath)) {
             if ($type == 'flv') {
                 $entryFixedFullPath = $entryFullPath . '.fixed.flv';
                 KalturaLog::debug("Fix webcam full path from [{$entryFullPath}] to [{$entryFixedFullPath}]");
                 myFlvStaticHandler::fixRed5WebcamFlv($entryFullPath, $entryFixedFullPath);
                 $entryNewFullPath = $entryFullPath . '.clipped.flv';
                 KalturaLog::debug("Clip webcam full path from [{$entryFixedFullPath}] to [{$entryNewFullPath}]");
                 myFlvStaticHandler::clipToNewFile($entryFixedFullPath, $entryNewFullPath, 0, 0);
                 $entryFullPath = $entryNewFullPath;
                 if (!file_exists($entryFullPath)) {
                     throw new KalturaAPIException(KalturaErrors::RECORDED_WEBCAM_FILE_NOT_FOUND);
                 }
             }
             $object_to_fill->setSourceType(KalturaSourceType::WEBCAM);
             $object_to_fill->setLocalFilePath($entryFullPath);
             return $object_to_fill;
         }
     }
     throw new KalturaAPIException(KalturaErrors::RECORDED_WEBCAM_FILE_NOT_FOUND);
 }
 /**
  * Executes addComment action, which returns a form enabling the insertion of a comment
  * The request may include 1 fields: entry id.
  */
 protected function executeImpl(kshow $kshow, entry &$entry)
 {
     $version = @$_REQUEST["version"];
     // it's a path on the disk
     if (kString::beginsWith($version, ".")) {
         // someone is trying to hack in the system
         return sfView::ERROR;
     }
     // in case we're making a roughcut out of a regular invite, we start from scratch
     if ($entry->getMediaType() != entry::ENTRY_MEDIA_TYPE_SHOW || $entry->getDataPath($version) === null) {
         $this->xml_content = "<xml></xml>";
         return;
     }
     // fetch content of file from disk - it should hold the XML
     $file_name = myContentStorage::getFSContentRootPath() . "/" . $entry->getDataPath($version);
     //echo "[$file_name]";
     if (kString::endsWith($file_name, "xml")) {
         if (file_exists($file_name)) {
             $this->xml_content = kFile::getFileContent($file_name);
             //	echo "[" . $this->xml_content . "]" ;
         } else {
             $this->xml_content = "<xml></xml>";
         }
         myMetadataUtils::updateEntryForPending($entry, $version, $this->xml_content);
     } else {
         return sfView::ERROR;
     }
     // this is NOT an xml file we are looking for !
 }
 /**
  * Will investigate a single entry
  */
 public function execute()
 {
     $this->forceSystemAuthentication();
     myDbHelper::$use_alternative_con = null;
     //myDbHelper::DB_HELPER_CONN_PROPEL2;
     $status_list = $this->getP("status");
     $mode = $this->getP("mode");
     if ($mode == "old") {
         $preconvert = glob(myContentStorage::getFSContentRootPath() . "/content/preconvert/data/*");
         $preconvert_indicators = glob(myContentStorage::getFSContentRootPath() . "/content/preconvert/files/*");
         // indicators or inproc
     } else {
         $preconvert = glob(myContentStorage::getFSContentRootPath() . "/content/new_preconvert/*");
         $preconvert_indicators = glob(myContentStorage::getFSContentRootPath() . "/new_content/preconvert/*.in*");
         // indicators or inproc
     }
     $indicators = array();
     foreach ($preconvert_indicators as $file) {
         $file = pathinfo($file, PATHINFO_BASENAME);
         $name = substr($file, 0, strpos($file, "."));
         $indicators[$name] = $name;
     }
     $entry_ids = array();
     foreach ($preconvert as $file) {
         $file = pathinfo($file, PATHINFO_BASENAME);
         $name = substr($file, 0, strpos($file, "."));
         if (!isset($indicators[$name])) {
             $entry_ids[] = $name;
             // only those that don't have indicators
         }
     }
     $ids_str = "'" . implode("','", $entry_ids) . "'";
     echo "<html><body style='font-family:arial; font-size:12px;'>";
     echo "preconvert files: [" . count($preconvert) . "]<br>";
     echo "preconvert indicators : [" . count($preconvert_indicators) . "] [" . count($indicators) . "]<br>";
     echo "entry_ids: [" . count($entry_ids) . "]<br>";
     if (count($entry_ids)) {
         if (!$status_list) {
             $status_list = "1";
         }
         $connection = Propel::getConnection();
         $query = "SELECT id,partner_id,status,created_at FROM entry WHERE status IN ({$status_list}) AND id IN ({$ids_str}) ORDER BY created_at ASC ";
         echo "query: {$query}<br>";
         $statement = $connection->prepareStatement($query);
         $resultset = $statement->executeQuery();
         echo "<table cellpadding=2 cellspacing=0 border=1 style='font-family:arial; font-size:12px;'>";
         echo "<tr><td>partner_id</td><td>id</td><td>status</td><td>created_at</td></tr>";
         $real_count = 0;
         while ($resultset->next()) {
             echo "<tr>" . "<td>" . $resultset->getInt('partner_id') . "</td>" . "<td>" . $resultset->getString('id') . "</td>" . "<td>" . $resultset->getInt('status') . "</td>" . "<td>" . $resultset->get('created_at') . "</td>" . "</tr>";
             $real_count++;
         }
         echo "</table>";
         echo "count [{$real_count}]";
         $resultset->close();
     }
     echo "</body></html>";
     die;
 }
 public function myFileIndicator($file_name)
 {
     if (!self::$s_indicator_path) {
         self::$s_indicator_path = myContentStorage::getFSContentRootPath() . "/indicators/";
         kFile::fullMkdir(self::$s_indicator_path . "dummy.txt");
     }
     $this->file_name = $file_name;
     $this->pattern = "/" . $this->file_name . '\\..*/';
 }
Example #6
0
 public function generateFilePathArr($sub_type, $version = null)
 {
     static::validateFileSyncSubType($sub_type);
     if ($sub_type == self::FILE_SYNC_ENTRY_SUB_TYPE_LIVE_PRIMARY || $sub_type == self::FILE_SYNC_ENTRY_SUB_TYPE_LIVE_SECONDARY) {
         $res = myContentStorage::getGeneralEntityPath('entry/data', $this->getIntId(), $this->getId(), $sub_type);
         return array(myContentStorage::getFSContentRootPath(), $res);
     }
     return parent::generateFilePathArr($sub_type, $version);
 }
 /**
  * Will forward to the regular swf player according to the widget_id 
  */
 public function execute()
 {
     $ui_conf_id = $this->getRequestParameter("ui_conf_id");
     $preloader_path = myContentStorage::getFSContentRootPath() . "/content" . myContentStorage::getFSUiconfRootPath() . "/preloader_{$ui_conf_id}.swf";
     if (!file_exists($preloader_path)) {
         $preloader_path = myContentStorage::getFSContentRootPath() . "/content" . myContentStorage::getFSUiconfRootPath() . "/preloader_2.swf";
     }
     kFile::dumpFile($preloader_path);
 }
 public function execute()
 {
     $this->forceSystemAuthentication();
     $kshow_id = @$_REQUEST["kshow_id"];
     $this->kshow_id = $kshow_id;
     $this->kshow = NULL;
     $entry_id = @$_REQUEST["entry_id"];
     $this->entry_id = $entry_id;
     $this->entry = NULL;
     $this->message = "";
     if (!empty($kshow_id)) {
         $this->kshow = kshowPeer::retrieveByPK($kshow_id);
         if (!$this->kshow) {
             $this->message = "Cannot find kshow [{$kshow_id}]";
         } else {
             $this->entry = $this->kshow->getShowEntry();
         }
     } elseif (!empty($kshow_id)) {
         $this->entry = entryPeer::retrieveByPK($entry_id);
         if (!$this->entry) {
             $this->message = "Cannot find entry [{$entry_id}]";
         } else {
             $this->kshow = $this->{$this}->entry->getKshow();
         }
     }
     if ($this->kshow) {
         $this->metadata = $this->kshow->getMetadata();
     } else {
         $this->metadata = "";
     }
     $pending_str = $this->getP("pending");
     $remove_pending = $this->getP("remove_pending");
     if ($this->metadata && ($remove_pending || $pending_str)) {
         if ($remove_pending) {
             $pending_str = "";
         }
         $xml_doc = new DOMDocument();
         $xml_doc->loadXML($this->metadata);
         $metadata = kXml::getFirstElement($xml_doc, "MetaData");
         $should_save = kXml::setChildElement($xml_doc, $metadata, "Pending", $pending_str, true);
         if ($remove_pending) {
             $should_save = kXml::setChildElement($xml_doc, $metadata, "LastPendingTimeStamp", "", true);
         }
         if ($should_save) {
             $fixed_content = $xml_doc->saveXML();
             $content_dir = myContentStorage::getFSContentRootPath();
             $file_name = realpath($content_dir . $this->entry->getDataPath());
             $res = file_put_contents($file_name, $fixed_content);
             // sync - NOTOK
             $this->metadata = $fixed_content;
         }
     }
     $this->pending = $pending_str;
     $this->kshow_id = $kshow_id;
     $this->entry_id = $entry_id;
 }
Example #9
0
 public function generateFilePathArr($sub_type, $version = null)
 {
     self::validateFileSyncSubType($sub_type);
     if (!$version) {
         $version = $this->getFileSyncVersion($sub_type);
     }
     $dir = intval($this->getId() / 1000000) . '/' . intval($this->getId() / 1000) % 1000;
     $path = "/content/distribution/profile/{$dir}/" . $this->generateFileName($sub_type, $version);
     return array(myContentStorage::getFSContentRootPath(), $path);
 }
 /**
  * Will forward to the regular swf player according to the widget_id 
  */
 public function execute()
 {
     $ui_conf_id = $this->getRequestParameter("ui_conf_id");
     if (!is_numeric($ui_conf_id)) {
         throw new Exception("Illegal Input was supplied");
     }
     $preloader_path = myContentStorage::getFSContentRootPath() . "/content" . myContentStorage::getFSUiconfRootPath() . "/preloader_{$ui_conf_id}.swf";
     if (!file_exists($preloader_path)) {
         $preloader_path = myContentStorage::getFSContentRootPath() . "/content" . myContentStorage::getFSUiconfRootPath() . "/preloader_2.swf";
     }
     kFileUtils::dumpFile($preloader_path);
 }
Example #11
0
 /**
  * Serve update file
  *
  * @action serveUpdate
  * @param string $os
  * @param string $version
  * @return file
  * @throws CaptureSpaceErrors::NO_UPDATE_IS_AVAILABLE
  */
 public function serveUpdateAction($os, $version)
 {
     $filename = kCaptureSpaceVersionManager::getUpdateFile($os, $version);
     if (!$filename) {
         throw new KalturaAPIException(CaptureSpaceErrors::NO_UPDATE_IS_AVAILABLE, $version, $os);
     }
     $actualFilePath = myContentStorage::getFSContentRootPath() . "/content/third_party/capturespace/{$filename}";
     if (!file_exists($actualFilePath)) {
         throw new KalturaAPIException(CaptureSpaceErrors::NO_UPDATE_IS_AVAILABLE, $version, $os);
     }
     $mimeType = kFile::mimeType($actualFilePath);
     header("Content-Disposition: attachment; filename=\"{$filename}\"");
     return $this->dumpFile($actualFilePath, $mimeType);
 }
 public function executeImpl($partner_id, $subp_id, $puser_id, $partner_prefix, $puser_kuser)
 {
     $filename = $this->getP('filename');
     // strip the filename from invalid characters
     $token = $this->getKsUniqueString();
     //		$res = myUploadUtils::uploadFileByToken ( $_FILES['Filedata'] , $token , $filename );
     $origFilename = $_FILES['Filedata']['name'];
     $parts = pathinfo($origFilename);
     $extension = "flv";
     // always flv ! //strtolower($parts['extension']);
     $extra_id = null;
     $file_alias = $token . '_' . $filename;
     // add the file extension after the "." character
     $fullPath = myContentStorage::getFSContentRootPath() . "content/webcam/my_recorded_stream_" . $file_alias . ($extra_id ? "_" . $extra_id : "") . "." . $extension;
     myContentStorage::fullMkdir($fullPath);
     move_uploaded_file($_FILES['Filedata']['tmp_name'], $fullPath);
     chmod($fullPath, 0777);
     $res = array("token" => $token, "filename" => $filename, "origFilename" => $origFilename);
     // should upload the file with the token as the prefix
     $this->addMsg("result_ok", $res);
 }
function executeCropProvider($source_file, $target_file, $width, $height, $crop_type, $bgcolor, $force_jpeg)
{
    $content_path = myContentStorage::getFSContentRootPath();
    list($sourcewidth, $sourceheight, $type, $attr, $thumbail_image) = myFileConverter::createImageByFile($target_file);
    $wordpress_placeholder_image_path = $content_path . "content/templates/wordpress/wordpress_comment_player_placeholder.gif";
    list($placeholder_width, $placeholder_height, $type, $attr, $place_holder_image) = myFileConverter::createImageByFile($wordpress_placeholder_image_path);
    $wordpress_placeholder_image_path = $content_path . "content/templates/wordpress/wordpress_comment_play_overlay.png";
    list($overlay_width, $overlay_height, $type, $attr, $play_overlay_image) = myFileConverter::createImageByFile($wordpress_placeholder_image_path);
    $width = 240;
    $height = 180;
    $im = imagecreatetruecolor($placeholder_width, $placeholder_height);
    imagecopy($im, $place_holder_image, 0, 0, 0, 0, $placeholder_width, $placeholder_height);
    //imagecopyresampled($im, $thumbail_image, 5, 30, 0, 0, $width, $height, $width, $height);
    // copy with opacity change
    imagecopymerge($im, $thumbail_image, 5 + ($width - $sourcewidth) / 2, 30 + ($height - $sourceheight) / 2, 0, 0, $sourcewidth, $sourceheight, 50);
    imagecopy($im, $play_overlay_image, ($placeholder_width - $overlay_width) / 2, ($placeholder_height - $overlay_height) / 2, 0, 0, $overlay_width, $overlay_height);
    imagedestroy($place_holder_image);
    imagedestroy($thumbail_image);
    imagedestroy($play_overlay_image);
    imagejpeg($im, $target_file, 90);
    imagedestroy($im);
}
function executeCropProvider($source_file, $target_file, $width, $height, $crop_type, $bgcolor, $force_jpeg)
{
    $content_path = myContentStorage::getFSContentRootPath();
    list($sourcewidth, $sourceheight, $type, $attr, $thumbail_image) = myFileConverter::createImageByFile($target_file);
    if ($width == 400 && $height == 300) {
        $wordpress_placeholder_image_path = $content_path . "content/templates/wordpress/wordpress_large_player_placeholder.jpg";
        list($sourcewidth, $sourceheight, $type, $attr, $place_holder_image) = myFileConverter::createImageByFile($wordpress_placeholder_image_path);
        imagecopyresampled($place_holder_image, $thumbail_image, 6, 36, 0, 0, $width, $height, $width, $height);
    } elseif ($width == 400 && $height == 225) {
        $wordpress_placeholder_image_path = $content_path . "content/templates/wordpress/wordpress_large_wide_screen_player_placeholder.jpg";
        list($sourcewidth, $sourceheight, $type, $attr, $place_holder_image) = myFileConverter::createImageByFile($wordpress_placeholder_image_path);
        imagecopyresampled($place_holder_image, $thumbail_image, 6, 36, 0, 0, $width, $height, $width, $height);
    } else {
        $width = 240;
        $height = 180;
        $wordpress_placeholder_image_path = $content_path . "content/templates/wordpress/wordpress_small_player_placeholder.jpg";
        list($sourcewidth, $sourceheight, $type, $attr, $place_holder_image) = myFileConverter::createImageByFile($wordpress_placeholder_image_path);
        imagecopyresampled($place_holder_image, $thumbail_image, 6, 28, 0, 0, $width, $height, $width, $height);
    }
    imagedestroy($thumbail_image);
    imagejpeg($place_holder_image, $target_file, 90);
    imagedestroy($place_holder_image);
}
 /**
  * Executes index action
  */
 protected function executeImpl(kshow $kshow)
 {
     $this->xml_content = "";
     $kshow_id = $this->kshow_id;
     if ($kshow_id == NULL || $kshow_id == 0) {
         return sfView::SUCCESS;
     }
     $metadata_creator = new myKshowMetadataCreator();
     $this->show_metadata = $metadata_creator->createMetadata($kshow_id);
     //		$kshow = kshowPeer:retrieveByPK( $kshow_id );
     $entry = entryPeer::retrieveByPK($kshow->getShowEntryId());
     // TODO - this should never happen
     if ($entry == NULL) {
         // there is no show entry for this show !
         $entry = $kshow->createEntry(entry::ENTRY_MEDIA_TYPE_SHOW, $kshow->getProducerId());
     }
     $content_path = myContentStorage::getFSContentRootPath();
     $file_path = $content_path . $entry->getDataPath();
     // check to see if the content of the file changed
     $current_metadata = kFile::getFileContent($file_path);
     $comp_result = strcmp($this->show_metadata, $current_metadata);
     if ($comp_result != 0) {
         $ext = pathinfo($file_path, PATHINFO_EXTENSION);
         if ($ext != "xml") {
             // this is for the first time - override the template path by setting the data to NULL
             $entry->setData(NULL);
             $file_path = pathinfo($file_path, PATHINFO_DIRNAME) . "/" . kFile::getFileNameNoExtension($file_path) . ".xml";
         }
         // this will increment the name if needed
         $entry->setData($file_path);
         $file_path = $content_path . $entry->getDataPath();
         $entry->save();
         kFile::fullMkdir($file_path);
         kFile::setFileContent($file_path, $this->show_metadata);
         $this->xml_content = $this->show_metadata;
     }
 }
 protected function prepare(KalturaBatchJob $job, KalturaWebcamPrepareJobData $data)
 {
     DbManager::setConfig(kConf::getDB());
     DbManager::initialize();
     $dbEntry = entryPeer::retrieveByPK($job->entryId);
     $webcamTokenId = $data->webcamTokenId;
     $dbEntry->setStatus(entryStatus::PRECONVERT);
     $dbEntry->save();
     // check that the webcam file exists
     $content = myContentStorage::getFSContentRootPath();
     $this->webcam_basePath = $content . "/content/webcam/" . $webcamTokenId;
     $this->entryFullPath = $this->webcam_basePath . '.flv';
     if (!file_exists($this->entryFullPath)) {
         $dbEntry->setStatus(entryStatus::ERROR_CONVERTING);
         $dbEntry->save();
         return $this->closeJob($job, KalturaBatchJobErrorTypes::RUNTIME, null, "Error: " . self::MSG_ERROR_FILE_NOT_EXISTS, KalturaBatchJobStatus::FAILED);
     }
     $duration = myFlvStaticHandler::getLastTimestamp($this->entryFullPath);
     $this->fixFlv();
     $kWAMSWebcam = new kWAMSWebcam($this->webcam_basePath);
     if ($kWAMSWebcam->prepare()) {
         $this->entryFullPath = $kWAMSWebcam->getOutputFilePath();
     } else {
         $dbEntry->setStatus(entryStatus::ERROR_CONVERTING);
         $dbEntry->save();
         return $this->closeJob($job, KalturaBatchJobErrorTypes::RUNTIME, null, "Error: " . self::MSG_ERROR_WAMS_FAIL, KalturaBatchJobStatus::FAILED);
     }
     $kshowId = $dbEntry->getKshowId();
     // setup the needed params for my insert entry helper
     $paramsArray = array("entry_media_source" => KalturaSourceType::WEBCAM, "entry_media_type" => $dbEntry->getMediaType(), "webcam_suffix" => $webcamTokenId, "entry_license" => $dbEntry->getLicenseType(), "entry_credit" => $dbEntry->getCredit(), "entry_source_link" => $dbEntry->getSourceLink(), "entry_tags" => $dbEntry->getTags(), "duration" => $duration);
     $token = $this->getClient()->getKs();
     $insert_entry_helper = new myInsertEntryHelper(null, $dbEntry->getKuserId(), $kshowId, $paramsArray);
     $insert_entry_helper->setPartnerId($job->partnerId, $job->partnerId * 100);
     $insert_entry_helper->insertEntry($token, $dbEntry->getType(), $dbEntry->getId(), $dbEntry->getName(), $dbEntry->getTags(), $dbEntry);
     myNotificationMgr::createNotification(kNotificationJobData::NOTIFICATION_TYPE_ENTRY_ADD, $dbEntry);
     return $this->closeJob($job, null, null, '', KalturaBatchJobStatus::FINISHED, $data);
 }
 /**
  * Will forward to the regular swf player according to the widget_id 
  */
 public function execute()
 {
     myDbHelper::$use_alternative_con = myDbHelper::DB_HELPER_CONN_PROPEL2;
     requestUtils::handleConditionalGet();
     ignore_user_abort();
     $entry_id = $this->getRequestParameter("entry_id");
     $widget_id = $this->getRequestParameter("widget_id", 0);
     $upload_token_id = $this->getRequestParameter("upload_token_id");
     $version = $this->getIntRequestParameter("version", null, 0, 10000000);
     $type = $this->getIntRequestParameter("type", 1, 1, 5);
     //Hack: if KMS sends thumbnail request containing "!" char, the type should be treated as 5.
     $width = $this->getRequestParameter("width", -1);
     $height = $this->getRequestParameter("height", -1);
     if (strpos($width, "!") || strpos($height, "!")) {
         $type = 5;
     }
     $width = $this->getFloatRequestParameter("width", -1, -1, 10000);
     $height = $this->getFloatRequestParameter("height", -1, -1, 10000);
     $crop_provider = $this->getRequestParameter("crop_provider", null);
     $quality = $this->getIntRequestParameter("quality", 0, 0, 100);
     $src_x = $this->getFloatRequestParameter("src_x", 0, 0, 10000);
     $src_y = $this->getFloatRequestParameter("src_y", 0, 0, 10000);
     $src_w = $this->getFloatRequestParameter("src_w", 0, 0, 10000);
     $src_h = $this->getFloatRequestParameter("src_h", 0, 0, 10000);
     $vid_sec = $this->getFloatRequestParameter("vid_sec", -1, -1);
     $vid_slice = $this->getRequestParameter("vid_slice", -1);
     $vid_slices = $this->getRequestParameter("vid_slices", -1);
     $density = $this->getFloatRequestParameter("density", 0, 0);
     $stripProfiles = $this->getRequestParameter("strip", null);
     $flavor_id = $this->getRequestParameter("flavor_id", null);
     $file_name = $this->getRequestParameter("file_name", null);
     $file_name = basename($file_name);
     // actual width and height of image from which the src_* values were taken.
     // these will be used to multiply the src_* parameters to make them relate to the original image size.
     $rel_width = $this->getFloatRequestParameter("rel_width", -1, -1, 10000);
     $rel_height = $this->getFloatRequestParameter("rel_height", -1, -1, 10000);
     if ($width == -1 && $height == -1) {
         $width = 120;
         $height = 90;
     } else {
         if ($width == -1) {
             // if only either width or height is missing reset them to zero, and convertImage will handle them
             $width = 0;
         } else {
             if ($height == -1) {
                 $height = 0;
             }
         }
     }
     $bgcolor = $this->getRequestParameter("bgcolor", "ffffff");
     $partner = null;
     // validating the inputs
     if (!is_numeric($quality) || $quality < 0 || $quality > 100) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'quality must be between 20 and 100');
     }
     if (!is_numeric($src_x) || $src_x < 0 || $src_x > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'src_x must be between 0 and 10000');
     }
     if (!is_numeric($src_y) || $src_y < 0 || $src_y > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'src_y must be between 0 and 10000');
     }
     if (!is_numeric($src_w) || $src_w < 0 || $src_w > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'src_w must be between 0 and 10000');
     }
     if (!is_numeric($src_h) || $src_h < 0 || $src_h > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'src_h must be between 0 and 10000');
     }
     if (!is_numeric($width) || $width < 0 || $width > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'width must be between 0 and 10000');
     }
     if (!is_numeric($height) || $height < 0 || $height > 10000) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'height must be between 0 and 10000');
     }
     if (!is_numeric($density) || $density < 0) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'density must be positive');
     }
     if (!is_numeric($vid_sec) || $vid_sec < -1) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'vid_sec must be positive');
     }
     if (!preg_match('/^[0-9a-fA-F]{1,6}$/', $bgcolor)) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'bgcolor must be six hexadecimal characters');
     }
     if ($upload_token_id) {
         $upload_token = UploadTokenPeer::retrieveByPK($upload_token_id);
         if ($upload_token) {
             $partnerId = $upload_token->getPartnerId();
             $partner = PartnerPeer::retrieveByPK($partnerId);
             if ($density == 0) {
                 $density = $partner->getDefThumbDensity();
             }
             if (is_null($stripProfiles)) {
                 $stripProfiles = $partner->getStripThumbProfile();
             }
             $thumb_full_path = myContentStorage::getFSCacheRootPath() . myContentStorage::getGeneralEntityPath("uploadtokenthumb", $upload_token->getIntId(), $upload_token->getId(), $upload_token->getId() . ".jpg");
             kFile::fullMkdir($thumb_full_path);
             if (file_exists($upload_token->getUploadTempPath())) {
                 $src_full_path = $upload_token->getUploadTempPath();
                 $valid_image_types = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP, IMAGETYPE_WBMP);
                 $image_type = exif_imagetype($src_full_path);
                 if (!in_array($image_type, $valid_image_types)) {
                     // capture full frame
                     myFileConverter::captureFrame($src_full_path, $thumb_full_path, 1, "image2", -1, -1, 3);
                     if (!file_exists($thumb_full_path)) {
                         myFileConverter::captureFrame($src_full_path, $thumb_full_path, 1, "image2", -1, -1, 0);
                     }
                     $src_full_path = $thumb_full_path;
                 }
                 // and resize it
                 myFileConverter::convertImage($src_full_path, $thumb_full_path, $width, $height, $type, $bgcolor, true, $quality, $src_x, $src_y, $src_w, $src_h, $density, $stripProfiles);
                 kFile::dumpFile($thumb_full_path);
             } else {
                 KalturaLog::debug("token_id [{$upload_token_id}] not found in DC [" . kDataCenterMgr::getCurrentDcId() . "]. dump url to romote DC");
                 $remoteUrl = kDataCenterMgr::getRemoteDcExternalUrlByDcId(1 - kDataCenterMgr::getCurrentDcId()) . $_SERVER['REQUEST_URI'];
                 kFile::dumpUrl($remoteUrl);
             }
         }
     }
     if ($entry_id) {
         $entry = entryPeer::retrieveByPKNoFilter($entry_id);
         if (!$entry) {
             // problem could be due to replication lag
             kFile::dumpApiRequest(kDataCenterMgr::getRemoteDcExternalUrlByDcId(1 - kDataCenterMgr::getCurrentDcId()));
         }
     } else {
         // get the widget
         $widget = widgetPeer::retrieveByPK($widget_id);
         if (!$widget) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_AND_WIDGET_NOT_FOUND);
         }
         // get the kshow
         $kshow_id = $widget->getKshowId();
         $kshow = kshowPeer::retrieveByPK($kshow_id);
         if ($kshow) {
             $entry_id = $kshow->getShowEntryId();
         } else {
             $entry_id = $widget->getEntryId();
         }
         $entry = entryPeer::retrieveByPKNoFilter($entry_id);
         if (!$entry) {
             KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
         }
     }
     $partner = $entry->getPartner();
     if ($density == 0) {
         $density = $partner->getDefThumbDensity();
     }
     $thumbParams = new kThumbnailParameters();
     $thumbParams->setSupportAnimatedThumbnail($partner->getSupportAnimatedThumbnails());
     if (is_null($stripProfiles)) {
         $stripProfiles = $partner->getStripThumbProfile();
     }
     //checks whether the thumbnail display should be restricted by KS
     $base64Referrer = $this->getRequestParameter("referrer");
     $referrer = base64_decode($base64Referrer);
     if (!is_string($referrer)) {
         $referrer = "";
     }
     // base64_decode can return binary data
     if (!$referrer) {
         $referrer = kApiCache::getHttpReferrer();
     }
     $ksStr = $this->getRequestParameter("ks");
     $securyEntryHelper = new KSecureEntryHelper($entry, $ksStr, $referrer, accessControlContextType::THUMBNAIL);
     $securyEntryHelper->validateForPlay();
     // multiply the passed $src_* values so that they will relate to the original image size, according to $src_display_*
     if ($rel_width != -1) {
         $widthRatio = $entry->getWidth() / $rel_width;
         $src_x = $src_x * $widthRatio;
         $src_w = $src_w * $widthRatio;
     }
     if ($rel_height != -1) {
         $heightRatio = $entry->getHeight() / $rel_height;
         $src_y = $src_y * $heightRatio;
         $src_h = $src_h * $heightRatio;
     }
     $subType = entry::FILE_SYNC_ENTRY_SUB_TYPE_THUMB;
     if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_IMAGE) {
         $subType = entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA;
     }
     KalturaLog::debug("get thumbnail filesyncs");
     $dataKey = $entry->getSyncKey($subType);
     list($file_sync, $local) = kFileSyncUtils::getReadyFileSyncForKey($dataKey, true, false);
     $tempThumbPath = null;
     $entry_status = $entry->getStatus();
     // both 640x480 and 0x0 requests are probably coming from the kdp
     // 640x480 - old kdp version requesting thumbnail
     // 0x0 - new kdp version requesting the thumbnail of an unready entry
     // we need to distinguish between calls from the kdp and calls from a browser: <img src=...>
     // that can't handle swf input
     if (($width == 640 && $height == 480 || $width == 0 && $height == 0) && ($entry_status == entryStatus::PRECONVERT || $entry_status == entryStatus::IMPORT || $entry_status == entryStatus::ERROR_CONVERTING || $entry_status == entryStatus::DELETED)) {
         $contentPath = myContentStorage::getFSContentRootPath();
         $msgPath = $contentPath . "content/templates/entry/bigthumbnail/";
         if ($entry_status == entryStatus::DELETED) {
             $msgPath .= $entry->getModerationStatus() == moderation::MODERATION_STATUS_BLOCK ? "entry_blocked.swf" : "entry_deleted.swf";
         } else {
             $msgPath .= $entry_status == entryStatus::ERROR_CONVERTING ? "entry_error.swf" : "entry_converting.swf";
         }
         kFile::dumpFile($msgPath, null, 0);
     }
     if (!$file_sync) {
         $tempThumbPath = $entry->getLocalThumbFilePath($entry, $version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices, $density, $stripProfiles, $flavor_id, $file_name);
         if (!$tempThumbPath) {
             KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
         }
     }
     if (!$local && !$tempThumbPath && $file_sync) {
         if (!in_array($file_sync->getDc(), kDataCenterMgr::getDcIds())) {
             $remoteUrl = $file_sync->getExternalUrl($entry->getId());
             header("Location: {$remoteUrl}");
             die;
         }
         $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($file_sync, $_SERVER['REQUEST_URI']);
         kFile::dumpUrl($remoteUrl);
     }
     // if we didnt return a template for the player die and dont return the original deleted thumb
     if ($entry_status == entryStatus::DELETED) {
         KExternalErrors::dieError(KExternalErrors::ENTRY_DELETED_MODERATED);
     }
     if (!$tempThumbPath) {
         try {
             $tempThumbPath = myEntryUtils::resizeEntryImage($entry, $version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices, null, $density, $stripProfiles, $thumbParams);
         } catch (Exception $ex) {
             if ($ex->getCode() != kFileSyncException::FILE_DOES_NOT_EXIST_ON_CURRENT_DC) {
                 KalturaLog::log("Error - resize image failed");
                 KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
             }
             // get original flavor asset
             $origFlavorAsset = assetPeer::retrieveOriginalByEntryId($entry_id);
             if (!$origFlavorAsset) {
                 KalturaLog::log("Error - no original flavor for entry [{$entry_id}]");
                 KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
             }
             $syncKey = $origFlavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
             $remoteFileSync = kFileSyncUtils::getOriginFileSyncForKey($syncKey, false);
             if (!$remoteFileSync) {
                 // file does not exist on any DC - die
                 KalturaLog::log("Error - no FileSync for entry [{$entry_id}]");
                 KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
             }
             if ($remoteFileSync->getDc() == kDataCenterMgr::getCurrentDcId()) {
                 KalturaLog::log("ERROR - Trying to redirect to myself - stop here.");
                 KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
             }
             if (!in_array($remoteFileSync->getDc(), kDataCenterMgr::getDcIds())) {
                 KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
             }
             $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($remoteFileSync);
             kFile::dumpUrl($remoteUrl);
         }
     }
     $nocache = strpos($tempThumbPath, "_NOCACHE_") !== false;
     if ($securyEntryHelper->shouldDisableCache() || kApiCache::hasExtraFields() || !$securyEntryHelper->isKsWidget() && $securyEntryHelper->hasRules()) {
         $nocache = true;
     }
     // notify external proxy, so it'll cache this url
     if (!$nocache && requestUtils::getHost() == kConf::get("apphome_url") && file_exists($tempThumbPath)) {
         self::notifyProxy($_SERVER["REQUEST_URI"]);
     }
     // cache result
     if (!$nocache) {
         $requestKey = $_SERVER["REQUEST_URI"];
         $cache = new myCache("thumb", 86400 * 30);
         // 30 days
         $cache->put($requestKey, $tempThumbPath);
     }
     kFile::dumpFile($tempThumbPath, null, $nocache ? 0 : null);
     // TODO - can delete from disk assuming we caneasily recreate it and it will anyway be cached in the CDN
     // however dumpfile dies at the end so we cant just write it here (maybe register a shutdown callback)
 }
 public static function shalowClone(kshow $source_kshow, $new_prodcuer_id)
 {
     $target_kshow = $source_kshow->copy();
     $target_kshow->setProducerId($new_prodcuer_id);
     $target_kshow->save();
     self::resetKshowStats($target_kshow, true);
     if (!$source_kshow->getEpisodeId()) {
         $target_kshow->setEpisodeId($source_kshow->getId());
     }
     //$target_kshow->setHasRoughcut($source_kshow->getHasRoughcut());
     $target_show_entry = $target_kshow->createEntry(entry::ENTRY_MEDIA_TYPE_SHOW, $new_prodcuer_id);
     $content = myContentStorage::getFSContentRootPath();
     $source_thumbnail_path = $source_kshow->getThumbnailPath();
     $target_kshow->setThumbnail(null);
     $target_kshow->setThumbnail($source_kshow->getThumbnail());
     $target_thumbnail_path = $target_kshow->getThumbnailPath();
     //		myContentStorage::moveFile( $content . $source_thumbnail_path , $content . $target_thumbnail_path , false , true );
     $target_kshow->save();
     // copy the show_entry file content
     $source_show_entry = entryPeer::retrieveByPK($source_kshow->getShowEntryId());
     $source_show_entry_data_key = $source_show_entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA);
     $target_show_entry->setData(null);
     $target_show_entry->setData($source_show_entry->getData());
     $target_show_entry_data_key = $target_show_entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA);
     $target_show_entry->setName($source_show_entry->getName());
     $target_show_entry->setLengthInMsecs($source_show_entry->getLengthInMsecs());
     kFileSyncUtils::softCopy($source_show_entry_data_key, $target_show_entry_data_key);
     //myContentStorage::moveFile( $content . $source_show_entry_path , $content . $target_show_entry_path , false , true );
     myEntryUtils::createThumbnail($target_show_entry, $source_show_entry, true);
     //		$target_kshow->setHasRoughcut(true);
     //		$target_kshow->save();
     $target_show_entry->save();
     return $target_kshow;
 }
<?php

require_once "../bootstrap.php";
$root = myContentStorage::getFSContentRootPath();
$outputPathBase = "{$root}/content/clientlibs";
$fileLocation = "{$outputPathBase}/KalturaClient.xml";
if (!file_exists($fileLocation)) {
    die("KalturaClient.xml was not found");
}
header("Content-Type: text/xml");
readfile($fileLocation);
Example #20
0
 private function dumpConvertErrors($query)
 {
     $headerStyle = "bgcolor='lightgray'";
     $oddStyle = "bgcolor='cyan'";
     $evenStyle = "bgcolor='lightblue'";
     $statement = $this->connection->prepareStatement($query);
     $resultset = $statement->executeQuery();
     $has_results = $resultset->getRecordCount() > 0;
     $title = "Conversion Errors";
     echo "<H2>{$title} " . ($has_results ? "" : "- NONE") . "</H2>";
     echo $query;
     if ($has_results) {
         $lines = array();
         $lines[] = array();
         $lines[] = array();
         while ($resultset->next()) {
             $partner_id = $resultset->getInt("partner_id");
             $entry_id = $resultset->getString("id");
             $source = $resultset->getInt("source");
             $date = $resultset->getDate("date", "%Y-%m-%d %H:%M:%S");
             $diff = $resultset->getString("diff");
             $entry = entryPeer::retrieveByPK($entry_id);
             if ($entry) {
                 $batchjob_query = "SELECT description FROM batch_job WHERE job_type=" . BatchJobType::IMPORT . " and entry_id='{$entry_id}'";
                 $batchjob_statement = $this->connection->prepareStatement($batchjob_query);
                 $batchjob_resultset = $batchjob_statement->executeQuery();
                 $batchjob_description = "NO BATCHJOB";
                 while ($batchjob_resultset->next()) {
                     $batchjob_description = $batchjob_resultset->get("description");
                     break;
                 }
                 $data_path = myContentStorage::getFSContentRootPath() . $entry->getDataPath();
                 $data_dir = pathinfo($data_path, PATHINFO_DIRNAME);
                 $archive_file = $archive_path = str_replace("content/entry", "archive", $data_dir);
                 $archive_files = glob($archive_path . "/{$entry_id}.*");
                 $archive_file = "MISSING";
                 $size = "";
                 if (count($archive_files)) {
                     $archive_file = pathinfo($archive_files[0], PATHINFO_BASENAME);
                     $size = filesize($archive_files[0]);
                 }
                 $list_type = $size > 100000 ? 0 : 1;
                 $cnt = count($lines[$list_type]) + 1;
                 $lines[$list_type][] = "<TD>{$cnt}</TD><TD>{$partner_id}</TD><TD>{$entry_id}</TD><TD><A target='_blank' href='/index.php/system/investigate?entry_id={$entry_id}'>{$data_path}</A></TD><TD><A target='_blank' href='/index.php/system/investigate?entry_id={$entry_id}'>{$archive_file}</A></TD><TD>{$size}</TD><TD>{$source}</TD><TD>{$date}</TD><TD>{$diff}</TD><TD>{$batchjob_description}</TD>";
             }
         }
         for ($j = 0; $j < 2; $j++) {
             if (!count($lines[$j])) {
                 continue;
             }
             echo "<TABLE>\n";
             echo "<THEAD>\n";
             echo "<TR {$headerStyle}><TH>#</TH><TH>PARTNER_ID</TH><TH>ID</TH><TH>PATH</TH><TH>ARCHIVE</TH><TH>SIZE</TH><TH>SOURCE</TH><TH>LAST DATE</TH><TH>PASSED TIME</TH><TH>IMPORT ERROR</TH></TR>";
             echo "</THEAD>\n";
             echo "<TBODY>\n";
             $i = 0;
             foreach ($lines[$j] as $line) {
                 $style = ++$i % 2 ? $evenStyle : $oddStyle;
                 echo "<TR {$style}>{$line}</TR>";
             }
             echo "</TBODY>\n";
             echo "</TABLE>\n";
             echo "<BR/>\n";
         }
     }
 }
Example #21
0
 /**
  * Add new entry after the file was recored on the server and the token id exists
  *
  * @action addFromRecordedWebcam
  * @param KalturaMediaEntry $mediaEntry Media entry metadata
  * @param string $webcamTokenId Token id for the recored webcam file 
  * @return KalturaMediaEntry The new media entry
  * 
  * @throws KalturaErrors::PROPERTY_VALIDATION_MIN_LENGTH
  * @throws KalturaErrors::PROPERTY_VALIDATION_CANNOT_BE_NULL
  * @throws KalturaErrors::RECORDED_WEBCAM_FILE_NOT_FOUND
  */
 function addFromRecordedWebcamAction(KalturaMediaEntry $mediaEntry, $webcamTokenId)
 {
     // check that the webcam file exists
     $content = myContentStorage::getFSContentRootPath();
     $webcamBasePath = $content . "/content/webcam/" . $webcamTokenId;
     // filesync ok
     $entryFullPath = $webcamBasePath . '.flv';
     if (!file_exists($entryFullPath)) {
         throw new KalturaAPIException(KalturaErrors::RECORDED_WEBCAM_FILE_NOT_FOUND);
     }
     $dbEntry = $this->prepareEntryForInsert($mediaEntry);
     $kshowId = $dbEntry->getKshowId();
     // setup the needed params for my insert entry helper
     $paramsArray = array("entry_media_source" => KalturaSourceType::WEBCAM, "entry_media_type" => $dbEntry->getMediaType(), "webcam_suffix" => $webcamTokenId, "entry_license" => $dbEntry->getLicenseType(), "entry_credit" => $dbEntry->getCredit(), "entry_source_link" => $dbEntry->getSourceLink(), "entry_tags" => $dbEntry->getTags());
     $token = $this->getKsUniqueString();
     $insert_entry_helper = new myInsertEntryHelper(null, $dbEntry->getKuserId(), $kshowId, $paramsArray);
     $insert_entry_helper->setPartnerId($this->getPartnerId(), $this->getPartnerId() * 100);
     $insert_entry_helper->insertEntry($token, $dbEntry->getType(), $dbEntry->getId(), $dbEntry->getName(), $dbEntry->getTags(), $dbEntry);
     $dbEntry = $insert_entry_helper->getEntry();
     myNotificationMgr::createNotification(kNotificationJobData::NOTIFICATION_TYPE_ENTRY_ADD, $dbEntry);
     $mediaEntry->fromObject($dbEntry);
     return $mediaEntry;
 }
Example #22
0
 protected function getReportDirectory($partnerId)
 {
     $folderPath = "/content/reports/live/{$partnerId}";
     $directory = myContentStorage::getFSContentRootPath() . $folderPath;
     if (!file_exists($directory)) {
         mkdir($directory);
     }
     return $directory;
 }
Example #23
0
 /**
 Returns an array of total_length and a list of all relevant assets
 */
 private static function getAssets($filePath, $timeline, $streamNum, $addPadding)
 {
     $contentRoot = myContentStorage::getFSContentRootPath();
     if (substr_count($filePath, $contentRoot)) {
         $contentRoot = '';
     }
     $xml_doc = new DOMDocument();
     if (!file_exists($contentRoot . $filePath)) {
         return null;
     }
     try {
         @$xml_doc->loadXML(file_get_contents($contentRoot . $filePath));
     } catch (Exception $ex) {
         KalturaLog::log("Cannot find XML file at [" . $contentRoot . $filePath . "],  timeline:{$timeline}, streamNum:{$streamNum}");
         return null;
     }
     list($already_pending, $already_pending_arr) = myMetadataUtils::getPending($xml_doc);
     $fileTimestamp = filectime($contentRoot . $filePath);
     $xpath = new DOMXPath($xml_doc);
     $assets = $xpath->query($timeline == "video" ? "//VideoAssets/vidAsset" : ($timeline == "audio" ? "//AudioAssets/AudAsset" : "//VoiceAssets/voiAsset"));
     $total_length = 13;
     $assetArray = array();
     $num = 2;
     foreach ($assets as $asset) {
         $num = 3 - $num;
         $type = $asset->getAttribute("type");
         if ($type != "VIDEO" && $type != "AUDIO") {
             continue;
         }
         $stream_info_list = $asset->getElementsByTagName("StreamInfo");
         foreach ($stream_info_list as $stream_info) {
             $file_name = $stream_info->getAttribute("file_name");
             $start_byte = $stream_info->getAttribute("start_byte");
             $end_byte = $stream_info->getAttribute("end_byte");
             $start_byte_play = $stream_info->getAttribute("start_byte_play");
             $end_byte_play = $stream_info->getAttribute("end_byte_play");
             if ($file_name == NULL || ($start_byte == NULL || $end_byte == NULL) && ($start_byte_play == NULL || $end_byte_play == NULL)) {
                 KalturaLog::log("qqq INVALID ENTRY {$file_name}");
                 echo "qqq INVALID ENTRY {$file_name}";
                 return;
                 //TODO handle invalid entries???
             }
             if ($streamNum == 3 || $num == $streamNum) {
                 $asset_entry = entryPeer::retrieveByPK($asset->getAttribute("k_id"));
                 $flavor_asset_edit = assetPeer::retrieveBestEditByEntryId($asset_entry->getId());
                 $flavor_asset_play = assetPeer::retrieveBestPlayByEntryId($asset_entry->getId());
                 // make sure asset exists before trying to get key or file path
                 if ($flavor_asset_edit) {
                     $asset_file_name_edit = kFileSyncUtils::getReadyLocalFilePathForKey($flavor_asset_edit->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET), false);
                 }
                 // make sure asset exists before trying to get key or file path
                 if ($flavor_asset_play) {
                     $asset_file_name_data = kFileSyncUtils::getReadyLocalFilePathForKey($flavor_asset_play->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET), false);
                 }
                 // make sure  both variable are set
                 if (!$asset_file_name_data && $asset_file_name_edit) {
                     $asset_file_name_data = $asset_file_name_edit;
                 }
                 if (!$asset_file_name_edit && $asset_file_name_data) {
                     $asset_file_name_edit = $asset_file_name_data;
                 }
                 $assetArray[] = array("file_name_data" => $asset_file_name_data, "file_name_edit" => $asset_file_name_edit, "start_byte" => $start_byte, "end_byte" => $end_byte, "start_byte_play" => $start_byte_play, "end_byte_play" => $end_byte_play);
                 $total_length += $stream_info->getAttribute("total_bytes");
                 if ($addPadding) {
                     $total_length += self::PADDING_TAG_SIZE * self::PADDING_TAGS;
                 }
             }
         }
     }
     $streamInfo = array($filePath, $timeline, $streamNum, $fileTimestamp);
     return array($total_length, $assetArray, $streamInfo, $already_pending_arr);
 }
 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;
 }
Example #25
0
 /**
  * (non-PHPdoc)
  * @see lib/model/ISyncableFile#generateFilePathArr()
  */
 public function generateFilePathArr($sub_type, $version = null)
 {
     self::validateFileSyncSubType($sub_type);
     $path = '/content/batchfiles/' . $this->getPartnerId() . '/' . $this->generateFileName($sub_type, $version);
     return array(myContentStorage::getFSContentRootPath(), $path);
 }
Example #26
0
 public static function createWidgetImage($partner, $create)
 {
     $contentPath = myContentStorage::getFSContentRootPath();
     $path = kFile::fixPath($contentPath . $partner->getWidgetImagePath());
     // if the create flag is not set and the file doesnt exist exit
     // e.g. the roughcut name has change, we update the image only if it was already in some widget
     if (!$create && !file_exists($path)) {
         return;
     }
     $im = imagecreatetruecolor(400, 20);
     $green = imagecolorallocate($im, 188, 230, 99);
     $white = imagecolorallocate($im, 255, 255, 255);
     $font = SF_ROOT_DIR . '/web/ttf/arial.ttf';
     $fontSize = 9;
     $bottom = 15;
     $pos = imagettftext($im, $fontSize, 0, 10, $bottom, $green, $font, $partner->getPartnerName() . " Collaborative Video");
     $pos = imagettftext($im, $fontSize, 0, $pos[2], $bottom, $white, $font, " powered by ");
     imagettftext($im, $fontSize, 0, $pos[2], $bottom, $green, $font, "Kaltura");
     kFile::fullMkdir($path);
     imagegif($im, $path);
     imagedestroy($im);
 }
 public function execute()
 {
     //entitlement should be disabled to serveFlavor action as we do not get ks on this action.
     KalturaCriterion::disableTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY);
     requestUtils::handleConditionalGet();
     $flavorId = $this->getRequestParameter("flavorId");
     $shouldProxy = $this->getRequestParameter("forceproxy", false);
     $fileName = $this->getRequestParameter("fileName");
     $fileParam = $this->getRequestParameter("file");
     $fileParam = basename($fileParam);
     $pathOnly = $this->getRequestParameter("pathOnly", false);
     $referrer = base64_decode($this->getRequestParameter("referrer"));
     if (!is_string($referrer)) {
         // base64_decode can return binary data
         $referrer = '';
     }
     $flavorAsset = assetPeer::retrieveById($flavorId);
     if (is_null($flavorAsset)) {
         KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
     }
     $entryId = $this->getRequestParameter("entryId");
     if (!is_null($entryId) && $flavorAsset->getEntryId() != $entryId) {
         KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND);
     }
     if ($fileName) {
         header("Content-Disposition: attachment; filename=\"{$fileName}\"");
         header("Content-Type: application/force-download");
         header("Content-Description: File Transfer");
     }
     $clipTo = null;
     $entry = $flavorAsset->getentry();
     if (!$entry) {
         KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND);
     }
     KalturaMonitorClient::initApiMonitor(false, 'extwidget.serveFlavor', $flavorAsset->getPartnerId());
     myPartnerUtils::enforceDelivery($entry, $flavorAsset);
     $version = $this->getRequestParameter("v");
     if (!$version) {
         $version = $flavorAsset->getVersion();
     }
     $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, $version);
     if ($pathOnly && kIpAddressUtils::isInternalIp($_SERVER['REMOTE_ADDR'])) {
         $path = null;
         list($file_sync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, false, false);
         if ($file_sync) {
             $parent_file_sync = kFileSyncUtils::resolve($file_sync);
             $path = $parent_file_sync->getFullPath();
             if ($fileParam && is_dir($path)) {
                 $path .= "/{$fileParam}";
             }
         }
         $renderer = new kRendererString('{"sequences":[{"clips":[{"type":"source","path":"' . $path . '"}]}]}', 'application/json');
         if ($path) {
             $this->storeCache($renderer, $flavorAsset->getPartnerId());
         }
         $renderer->output();
         KExternalErrors::dieGracefully();
     }
     if (kConf::hasParam('serve_flavor_allowed_partners') && !in_array($flavorAsset->getPartnerId(), kConf::get('serve_flavor_allowed_partners'))) {
         KExternalErrors::dieError(KExternalErrors::ACTION_BLOCKED);
     }
     if (!kFileSyncUtils::file_exists($syncKey, false)) {
         list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false);
         if (is_null($fileSync)) {
             KalturaLog::log("Error - no FileSync for flavor [" . $flavorAsset->getId() . "]");
             KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND);
         }
         // always dump remote urls so they will be cached by the cdn transparently
         $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync);
         kFileUtils::dumpUrl($remoteUrl);
     }
     $path = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey);
     $isFlv = false;
     if (!$shouldProxy) {
         $flvWrapper = new myFlvHandler($path);
         $isFlv = $flvWrapper->isFlv();
     }
     $clipFrom = $this->getRequestParameter("clipFrom", 0);
     // milliseconds
     if (is_null($clipTo)) {
         $clipTo = $this->getRequestParameter("clipTo", self::NO_CLIP_TO);
     }
     // milliseconds
     if ($clipTo == 0) {
         $clipTo = self::NO_CLIP_TO;
     }
     if (!is_numeric($clipTo) || $clipTo < 0) {
         KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'clipTo must be a positive number');
     }
     $seekFrom = $this->getRequestParameter("seekFrom", -1);
     if ($seekFrom <= 0) {
         $seekFrom = -1;
     }
     $seekFromBytes = $this->getRequestParameter("seekFromBytes", -1);
     if ($seekFromBytes <= 0) {
         $seekFromBytes = -1;
     }
     if ($fileParam && is_dir($path)) {
         $path .= "/{$fileParam}";
         kFileUtils::dumpFile($path, null, null);
         KExternalErrors::dieGracefully();
     } else {
         if (!$isFlv || $clipTo == self::NO_CLIP_TO && $seekFrom < 0 && $seekFromBytes < 0) {
             $limit_file_size = 0;
             if ($clipTo != self::NO_CLIP_TO) {
                 if (strtolower($flavorAsset->getFileExt()) == 'mp4' && PermissionPeer::isValidForPartner(PermissionName::FEATURE_ACCURATE_SERVE_CLIPPING, $flavorAsset->getPartnerId())) {
                     $contentPath = myContentStorage::getFSContentRootPath();
                     $tempClipName = $version . '_' . $clipTo . '.mp4';
                     $tempClipPath = $contentPath . myContentStorage::getGeneralEntityPath("entry/tempclip", $flavorAsset->getIntId(), $flavorAsset->getId(), $tempClipName);
                     if (!file_exists($tempClipPath)) {
                         kFile::fullMkdir($tempClipPath);
                         $clipToSec = round($clipTo / 1000, 3);
                         $cmdLine = kConf::get("bin_path_ffmpeg") . " -i {$path} -vcodec copy -acodec copy -f mp4 -t {$clipToSec} -y {$tempClipPath} 2>&1";
                         KalturaLog::log("Executing {$cmdLine}");
                         $output = array();
                         $return_value = "";
                         exec($cmdLine, $output, $return_value);
                         KalturaLog::log("ffmpeg returned {$return_value}, output:" . implode("\n", $output));
                     }
                     if (file_exists($tempClipPath)) {
                         KalturaLog::log("Dumping {$tempClipPath}");
                         kFileUtils::dumpFile($tempClipPath);
                     } else {
                         KalturaLog::err('Failed to clip the file using ffmpeg, falling back to rough clipping');
                     }
                 }
                 $mediaInfo = mediaInfoPeer::retrieveByFlavorAssetId($flavorAsset->getId());
                 if ($mediaInfo && ($mediaInfo->getVideoDuration() || $mediaInfo->getAudioDuration() || $mediaInfo->getContainerDuration())) {
                     $duration = $mediaInfo->getVideoDuration() ? $mediaInfo->getVideoDuration() : ($mediaInfo->getAudioDuration() ? $mediaInfo->getAudioDuration() : $mediaInfo->getContainerDuration());
                     $limit_file_size = floor(@kFile::fileSize($path) * ($clipTo / $duration) * 1.2);
                 }
             }
             $renderer = kFileUtils::getDumpFileRenderer($path, null, null, $limit_file_size);
             if (!$fileName) {
                 $this->storeCache($renderer, $flavorAsset->getPartnerId());
             }
             $renderer->output();
             KExternalErrors::dieGracefully();
         }
     }
     $audioOnly = $this->getRequestParameter("audioOnly");
     // milliseconds
     if ($audioOnly === '0') {
         // audioOnly was explicitly set to 0 - don't attempt to make further automatic investigations
     } elseif ($flvWrapper->getFirstVideoTimestamp() < 0) {
         $audioOnly = true;
     }
     $bytes = 0;
     if ($seekFrom !== -1 && $seekFrom !== 0) {
         list($bytes, $duration, $firstTagByte, $toByte) = $flvWrapper->clip(0, -1, $audioOnly);
         list($bytes, $duration, $fromByte, $toByte, $seekFromTimestamp) = $flvWrapper->clip($seekFrom, -1, $audioOnly);
         $seekFromBytes = myFlvHandler::FLV_HEADER_SIZE + $flvWrapper->getMetadataSize($audioOnly) + $fromByte - $firstTagByte;
     } else {
         list($bytes, $duration, $fromByte, $toByte, $fromTs, $cuepointPos) = myFlvStaticHandler::clip($path, $clipFrom, $clipTo, $audioOnly);
     }
     $metadataSize = $flvWrapper->getMetadataSize($audioOnly);
     $dataOffset = $metadataSize + myFlvHandler::getHeaderSize();
     $totalLength = $dataOffset + $bytes;
     list($bytes, $duration, $fromByte, $toByte, $fromTs, $cuepointPos) = myFlvStaticHandler::clip($path, $clipFrom, $clipTo, $audioOnly);
     list($rangeFrom, $rangeTo, $rangeLength) = requestUtils::handleRangeRequest($totalLength);
     if ($totalLength < 1000) {
         // (actually $total_length is probably 13 or 143 - header + empty metadata tag) probably a bad flv maybe only the header - dont cache
         requestUtils::sendCdnHeaders("flv", $rangeLength, 0);
     } else {
         requestUtils::sendCdnHeaders("flv", $rangeLength);
     }
     // dont inject cuepoint into the stream
     $cuepointTime = 0;
     $cuepointPos = 0;
     try {
         Propel::close();
     } catch (Exception $e) {
         $this->logMessage("serveFlavor: error closing db {$e}");
     }
     header("Content-Type: video/x-flv");
     $flvWrapper->dump(self::CHUNK_SIZE, $fromByte, $toByte, $audioOnly, $seekFromBytes, $rangeFrom, $rangeTo, $cuepointTime, $cuepointPos);
     KExternalErrors::dieGracefully();
 }
Example #28
0
 /**
  * (non-PHPdoc)
  * @see lib/model/ISyncableFile#generateFilePathArr()
  */
 public function generateFilePathArr($sub_type, $version = null)
 {
     self::validateFileSyncSubType($sub_type);
     $version = is_null($version) ? $this->getVersion() : $version;
     $entry = $this->getentry();
     $dir = intval($entry->getIntId() / 1000000) . '/' . intval($entry->getIntId() / 1000) % 1000;
     $path = "/content/entry/data/{$dir}/" . $this->generateFileName($sub_type, $version);
     return array(myContentStorage::getFSContentRootPath(), $path);
 }
Example #29
0
 /**
  * will create thumbnail according to the entry type
  * @return the thumbnail path.
  */
 public function getLocalThumbFilePath($version, $width, $height, $type, $bgcolor = "ffffff", $crop_provider = null, $quality = 0, $src_x = 0, $src_y = 0, $src_w = 0, $src_h = 0, $vid_sec = -1, $vid_slice = 0, $vid_slices = -1, $density = 0, $stripProfiles = false, $flavorId = null, $fileName = null)
 {
     $contentPath = myContentStorage::getFSContentRootPath();
     // if entry type is audio - serve generic thumb:
     if ($this->getMediaType() == entry::ENTRY_MEDIA_TYPE_AUDIO) {
         if ($this->getStatus() == entryStatus::DELETED || $this->getModerationStatus() == moderation::MODERATION_STATUS_BLOCK) {
             KalturaLog::log("rejected audio entry - not serving thumbnail");
             KExternalErrors::dieError(KExternalErrors::ENTRY_DELETED_MODERATED);
         }
         $audioEntryExist = false;
         $audioThumbEntry = null;
         $audioThumbEntryId = null;
         $partner = $this->getPartner();
         if ($partner) {
             $audioThumbEntryId = $partner->getAudioThumbEntryId();
         }
         if ($audioThumbEntryId) {
             $audioThumbEntry = entryPeer::retrieveByPK($audioThumbEntryId);
         }
         if ($audioThumbEntry && $audioThumbEntry->getMediaType() == entry::ENTRY_MEDIA_TYPE_IMAGE) {
             $fileSyncVersion = $partner->getAudioThumbEntryVersion();
             $audioEntryKey = $audioThumbEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA, $fileSyncVersion);
             $contentPath = kFileSyncUtils::getLocalFilePathForKey($audioEntryKey);
             if ($contentPath) {
                 $msgPath = $contentPath;
                 $audioEntryExist = true;
             } else {
                 KalturaLog::err('no local file sync for entry id');
             }
         }
         if (!$audioEntryExist) {
             $msgPath = $contentPath . "content/templates/entry/thumbnail/audio_thumb.jpg";
         }
         return myEntryUtils::resizeEntryImage($this, $version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices, $msgPath, $density, $stripProfiles);
     } elseif ($this->getMediaType() == entry::ENTRY_MEDIA_TYPE_SHOW) {
         // roughcut without any thumbnail, probably just created
         $msgPath = $contentPath . "content/templates/entry/thumbnail/auto_edit.jpg";
         return myEntryUtils::resizeEntryImage($this, $version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices, $msgPath, $density, $stripProfiles);
     } elseif ($this->getType() == entryType::MEDIA_CLIP) {
         try {
             return myEntryUtils::resizeEntryImage($this, $version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices);
         } catch (Exception $ex) {
             if ($ex->getCode() == kFileSyncException::FILE_DOES_NOT_EXIST_ON_CURRENT_DC) {
                 // get original flavor asset
                 $origFlavorAsset = assetPeer::retrieveOriginalByEntryId($this->getId());
                 if ($origFlavorAsset) {
                     $syncKey = $origFlavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
                     list($readyFileSync, $isLocal) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, TRUE, FALSE);
                     if ($readyFileSync) {
                         if ($isLocal) {
                             KalturaLog::err('Trying to redirect to myself - stop here.');
                             KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
                         }
                         //Ready fileSync is on the other DC - dumping
                         kFileUtils::dumpApiRequest(kDataCenterMgr::getRemoteDcExternalUrlByDcId(1 - kDataCenterMgr::getCurrentDcId()));
                     }
                     KalturaLog::err('No ready fileSync found on any DC.');
                     KExternalErrors::dieError(KExternalErrors::MISSING_THUMBNAIL_FILESYNC);
                 }
             }
         }
     }
 }
Example #30
0
 /**
  * Add new entry after the file was recored on the server and the token id exists
  *
  * @action addFromRecordedWebcam
  * @param KalturaMediaEntry $mediaEntry Media entry metadata
  * @param string $webcamTokenId Token id for the recored webcam file
  * @return KalturaMediaEntry The new media entry
  *
  * @throws KalturaErrors::PROPERTY_VALIDATION_MIN_LENGTH
  * @throws KalturaErrors::PROPERTY_VALIDATION_CANNOT_BE_NULL
  * @throws KalturaErrors::RECORDED_WEBCAM_FILE_NOT_FOUND
  *
  * @deprecated use media.add instead
  */
 function addFromRecordedWebcamAction(KalturaMediaEntry $mediaEntry, $webcamTokenId)
 {
     if ($mediaEntry->conversionQuality && !$mediaEntry->conversionProfileId) {
         $mediaEntry->conversionProfileId = $mediaEntry->conversionQuality;
     }
     // check that the webcam file exists
     $content = myContentStorage::getFSContentRootPath();
     $webcamContentRootDir = $content . "/content/webcam/";
     $webcamBasePath = $webcamContentRootDir . $webcamTokenId;
     // Make sure that the root path of the webcam content is not modified by $webcamTokenId (with the value of "../" for example )
     $webcamContentRootDir = realpath($webcamContentRootDir);
     $webcamBaseRootDir = realpath(dirname($webcamBasePath));
     // Get realpath of target directory
     if (strpos($webcamBaseRootDir, $webcamContentRootDir) !== 0) {
         KalturaLog::err("webcamTokenId [{$webcamTokenId}] points outside of webcam content directory");
         throw new KalturaAPIException(KalturaErrors::INVALID_WEBCAM_TOKEN_ID);
     }
     if (!file_exists("{$webcamBasePath}.flv") && !file_exists("{$webcamBasePath}.f4v") && !file_exists("{$webcamBasePath}.f4v.mp4")) {
         if (kDataCenterMgr::dcExists(1 - kDataCenterMgr::getCurrentDcId())) {
             kFileUtils::dumpApiRequest(kDataCenterMgr::getRemoteDcExternalUrlByDcId(1 - kDataCenterMgr::getCurrentDcId()));
         }
         throw new KalturaAPIException(KalturaErrors::RECORDED_WEBCAM_FILE_NOT_FOUND);
     }
     $dbEntry = $this->prepareEntryForInsert($mediaEntry);
     $kshowId = $dbEntry->getKshowId();
     // setup the needed params for my insert entry helper
     $paramsArray = array("entry_media_source" => KalturaSourceType::WEBCAM, "entry_media_type" => $dbEntry->getMediaType(), "webcam_suffix" => $webcamTokenId, "entry_license" => $dbEntry->getLicenseType(), "entry_credit" => $dbEntry->getCredit(), "entry_source_link" => $dbEntry->getSourceLink(), "entry_tags" => $dbEntry->getTags());
     $token = $this->getKsUniqueString();
     $insert_entry_helper = new myInsertEntryHelper(null, $dbEntry->getKuserId(), $kshowId, $paramsArray);
     $insert_entry_helper->setPartnerId($this->getPartnerId(), $this->getPartnerId() * 100);
     $insert_entry_helper->insertEntry($token, $dbEntry->getType(), $dbEntry->getId(), $dbEntry->getName(), $dbEntry->getTags(), $dbEntry);
     $dbEntry = $insert_entry_helper->getEntry();
     myNotificationMgr::createNotification(kNotificationJobData::NOTIFICATION_TYPE_ENTRY_ADD, $dbEntry);
     $mediaEntry->fromObject($dbEntry, $this->getResponseProfile());
     return $mediaEntry;
 }