Example #1
0
 public function PreProcess()
 {
     $v = Validator::Create();
     $v->Register($this->source[Video_Source::FIELD_EMBED], Validator_Type::NOT_EMPTY, 'The Embed Code field is required');
     $v->Register($this->source[Video_Source::FIELD_DURATION], Validator_Type::VALID_TIME, 'The Video Duration field must be in HH:MM:SS format');
     $this->duration = Format::DurationToSeconds($this->source[Video_Source::FIELD_DURATION]);
     $this->video_dir = new Video_Dir(null, 0700);
     Request::FixFiles();
     // No thumbnails uploaded
     if (!isset($_FILES[Video_Source::FIELD_THUMBNAILS])) {
         return;
     }
     // Process each uploaded file
     foreach ($_FILES[Video_Source::FIELD_THUMBNAILS] as $upload) {
         // No file uploaded in this field
         if ($upload['error'] == UPLOAD_ERR_NO_FILE) {
             continue;
         }
         // Check for other errors
         if ($upload['error'] != UPLOAD_ERR_OK) {
             throw new BaseException(Uploads::CodeToMessage($upload['error']));
         }
         switch (File::Type($upload['name'])) {
             case File::TYPE_ZIP:
                 foreach (Zip::ExtractEntries($upload['tmp_name'], File::TYPE_JPEG) as $name => $data) {
                     $thumbs[] = $this->video_dir->AddTempFromVar($data, JPG_EXTENSION);
                 }
                 break;
             case File::TYPE_JPEG:
                 $thumbs[] = $this->video_dir->AddTempFromFile($upload['tmp_name'], JPG_EXTENSION);
                 break;
         }
     }
     // Resize (if possible) and move images to the correct directory
     if (Video_Thumbnail::CanResize()) {
         $this->thumbs = Video_Thumbnail::ResizeDirectory($this->video_dir->GetTempDir(), $this->video_dir->GetThumbsDir(), Config::Get('thumb_size'), Config::Get('thumb_quality'));
     } else {
         $this->thumbs = $this->video_dir->MoveFiles(Video_Dir::TEMP, Video_Dir::THUMBS, JPG_EXTENSION);
     }
     // Cleanup temp and processing dirs
     $this->video_dir->ClearTemp();
     $this->video_dir->ClearProcessing();
 }
Example #2
0
 public function Import()
 {
     $imported = 0;
     $DB = GetDB();
     $yt = new Zend_Gdata_YouTube();
     $video_feed = $yt->getVideoFeed($this->feed['feed_url']);
     $entry;
     foreach ($video_feed as $entry) {
         // Check for duplicates, and skip
         if ($DB->QueryCount('SELECT COUNT(*) FROM `tbx_video_feed_history` WHERE `feed_id`=? AND `unique_id`=?', array($this->feed['feed_id'], $entry->getVideoId()))) {
             continue;
         }
         // Video is not embeddable, skip
         if (!$entry->isVideoEmbeddable()) {
             continue;
         }
         // Setup defaults
         $video = $this->defaults;
         $video['title'] = $entry->getVideoTitle();
         $video['description'] = $entry->getVideoDescription();
         $video['tags'] = Tags::Format(implode(' ', $entry->getVideoTags()));
         $video['duration'] = $entry->getVideoDuration();
         // Get preview images
         $times = array();
         $thumbs = array();
         foreach ($entry->getVideoThumbnails() as $thumb) {
             if (!isset($times[$thumb['time']])) {
                 $times[$thumb['time']] = true;
                 $thumbs[] = array('thumbnail' => $thumb['url']);
             }
         }
         $clip = array('type' => 'Embed', 'clip' => '<object width="640" height="385">' . '<param name="movie" value="http://www.youtube.com/v/' . $entry->getVideoId() . '&fs=1"></param>' . '<param name="allowFullScreen" value="true"></param>' . '<param name="allowscriptaccess" value="always"></param>' . '<embed src="http://www.youtube.com/v/' . $entry->getVideoId() . '&fs=1" type="application/x-shockwave-flash" allowfullscreen="true" width="640" height="385"></embed>' . '</object>');
         $best_category = GetBestCategory(join(' ', array($video['title'], $video['description'], $video['tags'])));
         if (!empty($best_category)) {
             $video['category_id'] = $best_category;
         }
         $video['video_id'] = DatabaseAdd('tbx_video', $video);
         DatabaseAdd('tbx_video_custom', $video);
         DatabaseAdd('tbx_video_stat', $video);
         if (!$video['is_private']) {
             Tags::AddToFrequency($video['tags']);
         }
         UpdateCategoryStats($video['category_id']);
         $video_dir = new Video_Dir(Video_Dir::DirNameFromId($video['video_id']));
         $clip['video_id'] = $video['video_id'];
         DatabaseAdd('tbx_video_clip', $clip);
         $display_thumbnail = null;
         foreach ($thumbs as $thumb) {
             $thttp = new HTTP();
             if ($thttp->Get($thumb['thumbnail'], $thumb['thumbnail'])) {
                 $temp_file = $video_dir->AddTempFromVar($thttp->body, JPG_EXTENSION);
                 $imgsize = @getimagesize($temp_file);
                 if ($imgsize !== false) {
                     if (Video_Thumbnail::CanResize()) {
                         $local_filename = Video_Thumbnail::Resize($temp_file, Config::Get('thumb_size'), Config::Get('thumb_quality'), $video_dir->GetThumbsDir());
                     } else {
                         $local_filename = $video_dir->AddThumbFromFile($temp_file, JPG_EXTENSION);
                     }
                     $local_filename = str_replace(Config::Get('document_root'), '', $local_filename);
                     $thumb_id = DatabaseAdd('tbx_video_thumbnail', array('video_id' => $video['video_id'], 'thumbnail' => $local_filename));
                     if (empty($display_thumbnail)) {
                         $display_thumbnail = $thumb_id;
                     }
                 } else {
                     unlink($temp_file);
                 }
             }
         }
         if (!empty($display_thumbnail)) {
             $DB->Update('UPDATE `tbx_video` SET `display_thumbnail`=? WHERE `video_id`=?', array($display_thumbnail, $video['video_id']));
         }
         $DB->Update('INSERT INTO `tbx_video_feed_history` VALUES (?,?)', array($this->feed['feed_id'], $entry->getVideoId()));
         $imported++;
     }
     $DB->Update('UPDATE `tbx_video_feed` SET `date_last_read`=? WHERE `feed_id`=?', array(Database_MySQL::Now(), $this->feed['feed_id']));
     UpdateSponsorStats($this->feed['sponsor_id']);
     return $imported;
 }
Example #3
0
            <div class="field">
              <label>Audio Bitrate:</label>
              <span class="field-container">
                <input type="text" name="audio_bitrate" size="10" value="<?php 
    echo Config::Get('audio_bitrate');
    ?>
" />
              </span>
            </div>

            <?php 
}
?>

            <?php 
if (Video_Thumbnail::CanResize()) {
    ?>
            <div class="field">
              <label>Thumbnail Size:</label>
              <span class="field-container">
                <input type="text" name="thumb_size" size="10" value="<?php 
    echo Config::Get('thumb_size');
    ?>
" />
              </span>
            </div>
            <?php 
} else {
    ?>
            <input type="text" name="thumb_size" size="10" value="<?php 
    echo Config::Get('thumb_size');
Example #4
0
 public function PreProcess()
 {
     $this->video_dir = new Video_Dir(null, 0700);
     Request::FixFiles();
     if (!isset($_FILES[Video_Source::FIELD_UPLOADS])) {
         throw new BaseException('No files were uploaded');
     }
     foreach ($_FILES[Video_Source::FIELD_UPLOADS] as $upload) {
         // No file uploaded in this field
         if ($upload['error'] == UPLOAD_ERR_NO_FILE) {
             continue;
         }
         // Check for other errors
         if ($upload['error'] != UPLOAD_ERR_OK) {
             throw new BaseException(Uploads::CodeToMessage($upload['error']));
         }
         $thumbs = array();
         $will_grab = Video_Info::CanExtract() && Video_FrameGrabber::CanGrab();
         switch (File::Type($upload['name'])) {
             case File::TYPE_ZIP:
                 foreach (Zip::ExtractEntries($upload['tmp_name'], File::TYPE_JPEG) as $name => $data) {
                     $thumbs[] = $this->video_dir->AddTempFromVar($data, JPG_EXTENSION);
                 }
                 foreach (Zip::ExtractEntries($upload['tmp_name'], File::TYPE_VIDEO) as $name => $data) {
                     $this->clips[] = $this->video_dir->AddClipFromVar($data, File::Extension($name));
                 }
                 break;
             case File::TYPE_JPEG:
                 $thumbs[] = $this->video_dir->AddTempFromFile($upload['tmp_name'], JPG_EXTENSION);
                 break;
             case File::TYPE_VIDEO:
                 $this->clips[] = $this->video_dir->AddClipFromFile($upload['tmp_name'], File::Extension($upload['name']));
                 break;
         }
     }
     // Make sure at least one video clip was uploaded
     if (empty($this->clips)) {
         throw new BaseException('No video files were uploaded');
     }
     // Try to grab frames from video files
     if ($will_grab) {
         $amount = round(Config::Get('thumb_amount') / count($this->clips));
         foreach ($this->clips as $clip) {
             $vi = new Video_Info($clip);
             $vi->Extract();
             $this->duration += $vi->length;
             $temp_thumbs = Video_FrameGrabber::Grab($clip, $this->video_dir->GetProcessingDir(), $amount, Config::Get('thumb_quality'), Config::Get('thumb_size'));
             // Move generated thumbs from the processing directory
             foreach ($temp_thumbs as $temp_thumb) {
                 $this->thumbs[] = $this->video_dir->AddThumbFromFile($temp_thumb);
             }
             $this->video_dir->ClearProcessing();
         }
     } else {
         $this->duration = $this->source[Video_Source::FIELD_DURATION];
     }
     // Use uploaded images if none could be generated
     if (empty($this->thumbs) && !empty($thumbs)) {
         if (Video_Thumbnail::CanResize()) {
             $this->thumbs = Video_Thumbnail::ResizeDirectory($this->video_dir->GetTempDir(), $this->video_dir->GetThumbsDir(), Config::Get('thumb_size'), Config::Get('thumb_quality'));
         } else {
             $this->thumbs = $this->video_dir->MoveFiles(Video_Dir::TEMP, Video_Dir::THUMBS, JPG_EXTENSION);
         }
     }
     // Cleanup temp and processing dirs
     $this->video_dir->ClearTemp();
     $this->video_dir->ClearProcessing();
 }
Example #5
0
function tbxVideoEdit()
{
    Privileges::Check(Privileges::VIDEOS);
    $DB = GetDB();
    $schema = GetDBSchema();
    $v = Validator::Create();
    $v->RegisterFromXml($schema->el('//table[name="tbx_video"]'));
    $v->RegisterFromXml($schema->el('//table[name="tbx_video_custom"]'));
    if (!String::IsEmpty($_REQUEST['username'])) {
        $v->Register($DB->QueryCount('SELECT COUNT(*) FROM `tbx_user` WHERE `username`=?', array($_REQUEST['username'])) > 0, Validator_Type::IS_TRUE, 'The Username entered does not exist');
    }
    if (!$v->Validate()) {
        return JSON::Failure(array('message' => 'Video could not be updated; please fix the following items', 'errors' => $v->GetErrors()));
    }
    $_REQUEST['display_thumbnail'] = empty($_REQUEST['display_thumbnail']) ? null : $_REQUEST['display_thumbnail'];
    $_REQUEST['date_recorded'] = String::Nullify($_REQUEST['date_recorded']);
    $_REQUEST['tags'] = Tags::Format($_REQUEST['tags']);
    $_REQUEST['username'] = String::Nullify(Request::Get('username'));
    $_REQUEST['duration'] = Format::DurationToSeconds($_REQUEST['duration']);
    $original = $DB->Row('SELECT * FROM `tbx_video` WHERE `video_id`=?', array($_REQUEST['video_id']));
    // Handle uploaded thumbs, if any
    $dir = new Video_Dir(Video_Dir::DirNameFromId($original['video_id']));
    $thumbs_added = 0;
    $thumb_ids = array();
    Request::FixFiles();
    if (isset($_FILES['thumb_uploads'])) {
        foreach ($_FILES['thumb_uploads'] as $upload) {
            if (File::Extension($upload['name']) == JPG_EXTENSION && ($imgsize = getimagesize($upload['tmp_name'])) !== false) {
                $temp_file = $dir->AddTempFromFile($upload['tmp_name'], JPG_EXTENSION);
                if (Video_Thumbnail::CanResize()) {
                    $temp_file = Video_Thumbnail::Resize($temp_file, Config::Get('thumb_size'), Config::Get('thumb_quality'), $dir->GetTempDir());
                }
                $thumb = $dir->AddThumbFromFile($temp_file);
                $thumbs_added++;
                $thumb = str_replace(Config::Get('document_root'), '', $thumb);
                $thumb_ids[] = array('uri' => $thumb, 'id' => DatabaseAdd('tbx_video_thumbnail', array('video_id' => $original['video_id'], 'thumbnail' => $thumb)));
            }
        }
        if ($thumbs_added > 0) {
            $dir->ClearTemp();
            $_REQUEST['num_thumbnails'] = $original['num_thumbnails'] + $thumbs_added;
        }
    }
    // Update base database tables
    $video = DatabaseUpdate('tbx_video', $_REQUEST);
    DatabaseUpdate('tbx_video_custom', $_REQUEST);
    // Handle changes to video clips
    foreach ($_REQUEST['clips'] as $clip_id => $clip) {
        DatabaseUpdate('tbx_video_clip', array('video_id' => $video['video_id'], 'clip_id' => $clip_id, 'clip' => $clip['clip']));
    }
    if ($_REQUEST['is_private'] && !$original['is_private']) {
        $_REQUEST['private_id'] = sha1(uniqid(mt_rand(), true));
        DatabaseAdd('tbx_video_private', $_REQUEST);
        if ($original['status'] == STATUS_ACTIVE) {
            Tags::RemoveFromFrequency($original['tags']);
        }
    } else {
        if (!$_REQUEST['is_private']) {
            if ($original['status'] == STATUS_ACTIVE) {
                if ($original['is_private']) {
                    Tags::AddToFrequency($_REQUEST['tags']);
                } else {
                    Tags::UpdateFrequency($original['tags'], $_REQUEST['tags']);
                }
            }
            $DB->Update('DELETE FROM `tbx_video_private` WHERE `video_id`=?', array($_REQUEST['video_id']));
        }
    }
    if ($original['status'] == STATUS_ACTIVE) {
        $t = new Template();
        $t->ClearCache('categories.tpl');
    }
    UpdateCategoryStats($original['category_id'], $video['category_id']);
    UpdateSponsorStats($original['sponsor_id'], $_REQUEST['sponsor_id']);
    $output = array('id' => $video['video_id'], 'message' => 'Video has been successfully updated', 'html' => SearchItemHtml('video', $video), 'thumbs' => $thumb_ids);
    JSON::Success($output);
}
Example #6
0
 public static function Import($settings)
 {
     $DB = GetDB();
     ProgressBarShow('pb-import');
     $file = TEMP_DIR . '/' . File::Sanitize($settings['import_file']);
     $fp = fopen($file, 'r');
     $filesize = filesize($file);
     $line = $read = $imported = 0;
     $expected = count($settings['fields']);
     while (!feof($fp)) {
         $line++;
         $string = fgets($fp);
         $read += strlen($string);
         $data = explode($settings['delimiter'], trim($string));
         ProgressBarUpdate('pb-import', $read / $filesize * 100);
         // Line does not have the expected number of fields
         if (count($data) != $expected) {
             continue;
         }
         $video = array();
         $defaults = array('category_id' => $settings['category_id'], 'sponsor_id' => $settings['sponsor_id'], 'username' => $settings['username'], 'duration' => Format::DurationToSeconds($settings['duration']), 'status' => $settings['status'], 'next_status' => $settings['status'], 'allow_comments' => $settings['allow_comments'], 'allow_ratings' => $settings['allow_ratings'], 'allow_embedding' => $settings['allow_embedding'], 'is_private' => $settings['is_private'], 'date_added' => Database_MySQL::Now(), 'is_featured' => 0, 'is_user_submitted' => 0, 'conversion_failed' => 0, 'tags' => null, 'title' => null, 'description' => null);
         foreach ($settings['fields'] as $index => $field) {
             if (!empty($field)) {
                 $video[$field] = trim($data[$index]);
             }
         }
         // Setup clips
         $clips = array();
         $thumbs = array();
         $clip_type = 'URL';
         if (isset($video['embed_code'])) {
             // Cannot convert or thumbnail from embed code
             $settings['flag_convert'] = $settings['flag_thumb'] = false;
             $clips[] = $video['embed_code'];
             $clip_type = 'Embed';
         } else {
             if (isset($video['gallery_url'])) {
                 $http = new HTTP();
                 if (!$http->Get($video['gallery_url'])) {
                     // Broken gallery URL, continue
                     continue;
                 }
                 list($thumbs, $clips) = Video_Source_Gallery::ExtractUrls($http->url, $http->body);
             } else {
                 if (!isset($video['video_url']) && isset($video['base_video_url'])) {
                     if (!preg_match('~/$~', $video['base_video_url'])) {
                         $video['base_video_url'] .= '/';
                     }
                     foreach (explode(',', $video['video_filename']) as $filename) {
                         $clips[] = $video['base_video_url'] . $filename;
                     }
                 } else {
                     $clips[] = $video['video_url'];
                 }
             }
         }
         // Check for duplicate clips
         $duplicate = false;
         foreach ($clips as $clip) {
             if (!Request::Get('flag_skip_imported_check') && $DB->QueryCount('SELECT COUNT(*) FROM `tbx_imported` WHERE `video_url`=?', array($clip)) > 0) {
                 $duplicate = true;
             }
             $DB->Update('REPLACE INTO `tbx_imported` VALUES (?)', array($clip));
         }
         // Dupe found
         if ($duplicate) {
             continue;
         }
         // Setup thumbs
         if (!isset($video['gallery_url']) && !isset($video['thumbnail_url']) && isset($video['base_thumbnail_url'])) {
             if (!preg_match('~/$~', $video['base_thumbnail_url'])) {
                 $video['base_thumbnail_url'] .= '/';
             }
             foreach (explode(',', String::FormatCommaSeparated($video['thumbnail_filename'])) as $filename) {
                 $thumbs[] = $video['base_thumbnail_url'] . $filename;
             }
         } else {
             if (!isset($video['gallery_url']) && isset($video['thumbnail_url'])) {
                 $thumbs[] = $video['thumbnail_url'];
             }
         }
         // Setup duration
         if (isset($video['duration_seconds'])) {
             $video['duration'] = $video['duration_seconds'];
         } else {
             if (isset($video['duration_formatted'])) {
                 $video['duration'] = Format::DurationToSeconds($video['duration_formatted']);
             }
         }
         // Use description for title
         if (empty($video['title'])) {
             $video['title'] = isset($video['description']) ? $video['description'] : '';
         }
         // Use title for description
         if (empty($video['description'])) {
             $video['description'] = isset($video['title']) ? $video['title'] : '';
         }
         // Use title for tags
         if (empty($video['tags'])) {
             $video['tags'] = isset($video['title']) ? $video['title'] : '';
         }
         // Setup category
         if (isset($video['category']) && ($category_id = $DB->QuerySingleColumn('SELECT `category_id` FROM `tbx_category` WHERE `name` LIKE ?', array($video['category']))) !== false) {
             $video['category_id'] = $category_id;
         } else {
             if (($category_id = GetBestCategory($video['title'] . ' ' . $video['description'])) !== null) {
                 $video['category_id'] = $category_id;
             }
         }
         // Merge in the defaults
         $video = array_merge($defaults, $video);
         // Format tags and convert to UTF-8
         $video['tags'] = Tags::Format($video['tags']);
         $video = String::ToUTF8($video);
         if (Request::Get('flag_convert')) {
             $video['status'] = STATUS_QUEUED;
         }
         // Add to database
         $video['video_id'] = DatabaseAdd('tbx_video', $video);
         DatabaseAdd('tbx_video_custom', $video);
         DatabaseAdd('tbx_video_stat', $video);
         if ($video['is_private']) {
             $video['private_id'] = sha1(uniqid(mt_rand(), true));
             DatabaseAdd('tbx_video_private', $video);
         }
         if ($video['status'] == STATUS_QUEUED) {
             $video['queued'] = time();
             DatabaseAdd('tbx_conversion_queue', $video);
         }
         if (Request::Get('flag_thumb')) {
             $video['queued'] = time();
             DatabaseAdd('tbx_thumb_queue', $video);
         }
         if ($video['status'] == STATUS_ACTIVE && !$video['is_private']) {
             Tags::AddToFrequency($video['tags']);
         }
         // Add clips
         foreach ($clips as $clip) {
             DatabaseAdd('tbx_video_clip', array('video_id' => $video['video_id'], 'type' => $clip_type, 'clip' => $clip));
         }
         $dir = new Video_Dir(Video_Dir::DirNameFromId($video['video_id']));
         // Process thumbs
         $thumb_ids = array();
         foreach ($thumbs as $thumb) {
             $http = new HTTP();
             if ($http->Get($thumb, $thumb)) {
                 if (Video_Thumbnail::CanResize()) {
                     $thumb_temp = $dir->AddTempFromVar($http->body, 'jpg');
                     $thumb_file = Video_Thumbnail::Resize($thumb_temp, Config::Get('thumb_size'), Config::Get('thumb_quality'), $dir->GetThumbsDir());
                 } else {
                     $thumb_file = $dir->AddThumbFromVar($http->body);
                 }
                 if (!empty($thumb_file)) {
                     $thumb_ids[] = DatabaseAdd('tbx_video_thumbnail', array('video_id' => $video['video_id'], 'thumbnail' => str_replace(Config::Get('document_root'), '', $thumb_file)));
                 }
             }
         }
         // Determine number of thumbnails and select random display thumbnail
         $num_thumbnails = count($thumb_ids);
         $display_thumbnail = null;
         if ($num_thumbnails > 0) {
             // Select display thumbnail randomly from the first 40%
             $display_thumbnail = $thumb_ids[rand(0, floor(0.4 * $num_thumbnails))];
         }
         DatabaseUpdate('tbx_video', array('video_id' => $video['video_id'], 'num_thumbnails' => $num_thumbnails, 'display_thumbnail' => $display_thumbnail));
         $imported++;
     }
     fclose($fp);
     UpdateCategoryStats();
     UpdateSponsorStats($settings['sponsor_id']);
     $t = new Template();
     $t->ClearCache('categories.tpl');
     ProgressBarHide('pb-import', NumberFormatInteger($imported) . ' videos have been imported!');
     // Start up the thumbnail and converson queues if needed
     if (!Config::Get('flag_using_cron')) {
         if (Request::Get('flag_convert')) {
             ConversionQueue::Start();
         }
         if (Request::Get('flag_thumb')) {
             ThumbQueue::Start();
         }
     }
     File::Delete($file);
 }
Example #7
0
 public function PreProcess()
 {
     $this->video_dir = new Video_Dir(null, 0700);
     $thumbs = array();
     $clips = array();
     foreach ($this->source[Video_Source::FIELD_URLS] as $url) {
         $url_path = parse_url($url, PHP_URL_PATH);
         switch (File::Type($url_path)) {
             case File::TYPE_ZIP:
                 $http = new HTTP();
                 if ($http->Get($url, $url)) {
                     $zip = $this->video_dir->AddTempFromVar($http->body, ZIP_EXTENSION);
                     foreach (Zip::ExtractEntries($zip, File::TYPE_JPEG) as $name => $data) {
                         $thumbs[] = $this->video_dir->AddTempFromVar($data, JPG_EXTENSION);
                     }
                     foreach (Zip::ExtractEntries($zip, File::TYPE_VIDEO) as $name => $data) {
                         $this->clips[] = $this->video_dir->AddClipFromVar($data, File::Extension($name));
                     }
                 }
                 break;
             case File::TYPE_JPEG:
                 $http = new HTTP();
                 if ($http->Get($url, $url)) {
                     $thumbs[] = $this->video_dir->AddTempFromVar($http->body, JPG_EXTENSION);
                 }
                 break;
             case File::TYPE_VIDEO:
                 if ($this->source[Video_Source::FLAG_HOTLINK]) {
                     $clips[] = $url;
                     $this->duration = Format::DurationToSeconds($this->source[Video_Source::FIELD_DURATION]);
                 } else {
                     $http = new HTTP();
                     if ($http->Get($url, $url)) {
                         $this->clips[] = $this->video_dir->AddClipFromVar($http->body, File::Extension($http->url));
                     }
                 }
                 break;
         }
     }
     if (empty($clips)) {
         if (!empty($this->clips) && Video_Info::CanExtract() && Video_FrameGrabber::CanGrab()) {
             $amount = round(Config::Get('thumb_amount') / count($this->clips));
             foreach ($this->clips as $clip) {
                 $vi = new Video_Info($clip);
                 $vi->Extract();
                 $this->duration += $vi->length;
                 $temp_thumbs = Video_FrameGrabber::Grab($clip, $this->video_dir->GetProcessingDir(), $amount, Config::Get('thumb_quality'), Config::Get('thumb_size'));
                 // Move generated thumbs from the processing directory
                 foreach ($temp_thumbs as $temp_thumb) {
                     $this->thumbs[] = $this->video_dir->AddThumbFromFile($temp_thumb);
                 }
                 $this->video_dir->ClearProcessing();
             }
         }
     } else {
         $this->clips = $clips;
     }
     if (empty($this->clips)) {
         throw new BaseException('No valid video URLs were submitted');
     }
     // Use images from supplied URLs if none could be generated
     if (empty($this->thumbs) && !empty($thumbs)) {
         if (Video_Thumbnail::CanResize()) {
             $this->thumbs = Video_Thumbnail::ResizeDirectory($this->video_dir->GetTempDir(), $this->video_dir->GetThumbsDir(), Config::Get('thumb_size'), Config::Get('thumb_quality'));
         } else {
             $this->thumbs = $this->video_dir->MoveFiles($this->video_dir->GetTempDir(), $this->video_dir->GetThumbsDir(), JPG_EXTENSION);
         }
     }
     // Cleanup temp and processing dirs
     $this->video_dir->ClearTemp();
     $this->video_dir->ClearProcessing();
 }
Example #8
0
 public function PreProcess()
 {
     $this->video_dir = new Video_Dir(null, 0700);
     $http = new HTTP();
     if (!$http->Get($this->source[Video_Source::FIELD_GALLERY])) {
         throw new BaseException('Could not access gallery: ' . $http->error);
     }
     list($thumbs, $clips) = self::ExtractUrls($http->url, $http->body);
     if (empty($clips)) {
         throw new BaseException('No video files could be located on this gallery');
     }
     // Hotlinking video from gallery
     if ($this->source[Video_Source::FLAG_HOTLINK]) {
         $this->clips = $clips;
         $this->duration = Format::DurationToSeconds($this->source[Video_Source::FIELD_DURATION]);
     } else {
         // Download clips
         $amount = round(Config::Get('thumb_amount') / count($clips));
         foreach ($clips as $clip) {
             $chttp = new HTTP();
             if ($chttp->Get($clip, $http->url)) {
                 $clip = $this->video_dir->AddClipFromVar($chttp->body, File::Extension($chttp->url));
                 $this->clips[] = $clip;
                 $vi = new Video_Info($clip);
                 $vi->Extract();
                 $this->duration += $vi->length;
                 $temp_thumbs = Video_FrameGrabber::Grab($clip, $this->video_dir->GetProcessingDir(), $amount, Config::Get('thumb_quality'), Config::Get('thumb_size'));
                 // Move generated thumbs from the processing directory
                 foreach ($temp_thumbs as $temp_thumb) {
                     $this->thumbs[] = $this->video_dir->AddThumbFromFile($temp_thumb);
                 }
                 $this->video_dir->ClearProcessing();
             }
         }
     }
     // Download thumbs from gallery if none could be created from the video files
     // or video files are being hotlinked
     if (empty($this->thumbs)) {
         foreach ($thumbs as $thumb) {
             $coords = null;
             if (preg_match('~^\\[(.*?)\\](.*)~', $thumb, $matches)) {
                 $coords = $matches[1];
                 $thumb = $matches[2];
             }
             $thttp = new HTTP();
             if ($thttp->Get($thumb, $http->url)) {
                 $temp_file = $this->video_dir->AddTempFromVar($thttp->body, JPG_EXTENSION);
                 $imgsize = @getimagesize($temp_file);
                 $aspect = $imgsize !== false ? $imgsize[0] / $imgsize[1] : 0;
                 if ($imgsize !== false && $aspect >= self::MIN_ASPECT && $aspect <= self::MAX_ASPECT) {
                     if (Video_Thumbnail::CanResize()) {
                         $this->thumbs[] = Video_Thumbnail::Resize($temp_file, Config::Get('thumb_size'), Config::Get('thumb_quality'), $this->video_dir->GetThumbsDir(), $coords);
                     } else {
                         $this->thumbs[] = $this->video_dir->AddThumbFromFile($temp_file, JPG_EXTENSION);
                     }
                 } else {
                     unlink($temp_file);
                 }
             }
         }
     }
     // Cleanup temp and processing dirs
     $this->video_dir->ClearTemp();
     $this->video_dir->ClearProcessing();
 }
Example #9
0
 public static function Grab($filename, $directory, $num_frames = 10, $quality = 90, $dimensions = false, $vi = null)
 {
     if (!is_dir($directory) || !is_writeable($directory)) {
         throw new BaseException('Output directory is missing or not writeable', $directory);
     }
     if (!file_exists($filename)) {
         throw new BaseException('Input file is missing', $filename);
     }
     // Get video info if it was not provided
     if (!$vi instanceof Video_Info) {
         $vi = new Video_Info($filename);
         $vi->Extract();
     }
     $output = null;
     $tools = Video_Tools::Get();
     $filter = self::ScaleFilter($dimensions, $vi->video_width, $vi->video_height);
     // Extract frames from short videos (less than 1 minute)
     if ($vi->length < 60) {
         self::Log('Using short video frame extraction method');
         $framestep = floor($vi->video_frames / $num_frames);
         $end = floor($vi->length);
         $cmd = $tools->mplayer . ' -nosound' . ' -vo ' . escapeshellarg('jpeg:quality=' . $quality . ':outdir=' . $directory) . ' -endpos ' . escapeshellarg($end) . ' -sws 9' . ' -speed 100' . ' -vf ' . escapeshellarg('framestep=' . $framestep . ',' . $filter) . ' ' . escapeshellarg($filename) . ' 2>&1';
         self::Log($cmd);
         $output = shell_exec($cmd);
         self::Log($output);
         $frames = glob($directory . '/*.' . JPG_EXTENSION);
         $generated = count($frames);
         self::Log('Total frames generated: ' . $generated);
     } else {
         self::Log('Using long video frame extraction method');
         $start = min(ceil($vi->length * 0.01), 15);
         $end = floor($vi->length - $start);
         $interval = floor(($end - $start) / ($num_frames - 1));
         // Attempt to use the quick frame grab method
         $cmd = $tools->mplayer . ' -nosound' . ' -vo ' . escapeshellarg('jpeg:quality=' . $quality . ':outdir=' . $directory) . ' -frames ' . escapeshellarg($num_frames) . ' -ss ' . escapeshellarg($start) . ' -sstep ' . escapeshellarg($interval) . ' -endpos ' . escapeshellarg($end) . ' -sws 9 ' . ' -vf ' . escapeshellarg($filter) . ' ' . escapeshellarg($filename) . ' 2>&1';
         self::Log($cmd);
         $output = shell_exec($cmd);
         self::Log($output);
         $frames = glob($directory . '/*.' . JPG_EXTENSION);
         $generated = count($frames);
         self::Log('Total frames generated: ' . $generated);
         // Fall back to the slow frame grab method
         if ($generated < 1 || $num_frames > 1 && $generated == 1 || stristr($output, 'first frame is no keyframe')) {
             self::Log('Falling back to long video SLOW frame extraction method');
             // Reset values and directory contents
             $generated = 0;
             if (is_array($frames)) {
                 foreach ($frames as $frame) {
                     unlink($frame);
                 }
             }
             // Grab each frame individually
             for ($i = 0; $i < $num_frames; $i++) {
                 $cmd = $tools->mplayer . ' -nosound' . ' -vo ' . escapeshellarg('jpeg:quality=' . $quality . ':outdir=' . $directory) . ' -frames 1 ' . ' -sws 9 ' . ' -ss ' . ($start + $i * $interval) . ' -vf ' . escapeshellarg($filter) . ' ' . escapeshellarg($filename) . ' 2>&1';
                 self::Log($cmd);
                 $this_output = shell_exec($cmd);
                 $output .= $this_output;
                 self::Log($this_output);
                 if (file_exists("{$directory}/00000001.jpg")) {
                     $generated++;
                     rename("{$directory}/00000001.jpg", $directory . sprintf('/%s%08d.jpg', $generated == 1 ? 't' : '', $generated));
                 }
             }
             if (file_exists("{$directory}/t00000001.jpg")) {
                 rename("{$directory}/t00000001.jpg", "{$directory}/00000001.jpg");
             }
             $frames = glob($directory . '/*.' . JPG_EXTENSION);
             self::Log('Total frames generated: ' . $generated);
         }
     }
     if ($generated < 1) {
         throw new BaseException('Could not grab frames from this video file', $filename, $output);
     }
     if (Video_Thumbnail::CanResize()) {
         $frames = Video_Thumbnail::DiscardBlack($directory);
         self::Log('Total frames generated after black frame removal: ' . count($frames));
     }
     return $frames;
 }
Example #10
0
 public function Import()
 {
     $imported = 0;
     $http = new HTTP();
     if ($http->Get($this->feed['feed_url'])) {
         $xml = simplexml_load_string($this->ToUTF8($http->body), 'XML_Element', LIBXML_NOERROR, LIBXML_NOWARNING, LIBXML_NOCDATA);
         if ($xml !== false) {
             $DB = GetDB();
             foreach ($xml->xpath('//videos/video') as $xvideo) {
                 // Check for duplicates, and skip
                 if ($DB->QueryCount('SELECT COUNT(*) FROM `tbx_video_feed_history` WHERE `feed_id`=? AND `unique_id`=?', array($this->feed['feed_id'], $xvideo->id->val()))) {
                     continue;
                 }
                 // Setup defaults
                 $video = $this->defaults;
                 $video['title'] = $xvideo->title->val();
                 $video['description'] = $xvideo->description->val();
                 $video['tags'] = Tags::Format($xvideo->tags->val());
                 if (empty($video['description'])) {
                     $video['description'] = $video['title'];
                 }
                 // Process <clips>
                 $clips = array();
                 $screens = array();
                 foreach ($xvideo->xpath('./clips/clip') as $xclip) {
                     $video['duration'] += $xclip->duration;
                     $clip_url = $xvideo->clip_url->val();
                     $flv = $xclip->flv->val();
                     // Account for malformed feeds where the clip_url contains the URL to the video
                     // file rather than the required root URL
                     if (strstr($clip_url, $flv) === false) {
                         $clip_url = $clip_url . $flv;
                     }
                     $clips[] = array('type' => 'URL', 'clip' => $clip_url);
                     foreach ($xclip->xpath('./screens/screen') as $xscreen) {
                         $screen_url = $xvideo->screen_url->val();
                         $screen = $xscreen->val();
                         // Account for malformed feeds where the screen_url contains the URL to the image
                         // file rather than the required root URL
                         if (strstr($screen_url, $screen) === false) {
                             $screen_url = $screen_url . $screen;
                         }
                         $screens[] = array('thumbnail' => $screen_url);
                     }
                 }
                 if (count($clips) > 0) {
                     $best_category = GetBestCategory(join(' ', array($video['title'], $video['description'], $video['tags'])));
                     if (!empty($best_category)) {
                         $video['category_id'] = $best_category;
                     }
                     if ($this->feed['flag_convert']) {
                         $video['status'] = STATUS_QUEUED;
                         $video['next_status'] = $this->feed['status'];
                     }
                     $video['video_id'] = DatabaseAdd('tbx_video', $video);
                     DatabaseAdd('tbx_video_custom', $video);
                     DatabaseAdd('tbx_video_stat', $video);
                     if (!$video['is_private']) {
                         Tags::AddToFrequency($video['tags']);
                     }
                     $video['queued'] = time();
                     if ($this->feed['flag_convert']) {
                         DatabaseAdd('tbx_conversion_queue', $video);
                     }
                     if ($this->feed['flag_thumb']) {
                         DatabaseAdd('tbx_thumb_queue', $video);
                     }
                     UpdateCategoryStats($video['category_id']);
                     $video_dir = new Video_Dir(Video_Dir::DirNameFromId($video['video_id']));
                     foreach ($clips as $clip) {
                         $clip['video_id'] = $video['video_id'];
                         DatabaseAdd('tbx_video_clip', $clip);
                     }
                     $display_thumbnail = null;
                     foreach ($screens as $screen) {
                         $thttp = new HTTP();
                         if ($thttp->Get($screen['thumbnail'], $screen['thumbnail'])) {
                             $temp_file = $video_dir->AddTempFromVar($thttp->body, JPG_EXTENSION);
                             $imgsize = @getimagesize($temp_file);
                             if ($imgsize !== false) {
                                 if (Video_Thumbnail::CanResize()) {
                                     $local_filename = Video_Thumbnail::Resize($temp_file, Config::Get('thumb_size'), Config::Get('thumb_quality'), $video_dir->GetThumbsDir());
                                 } else {
                                     $local_filename = $video_dir->AddThumbFromFile($temp_file, JPG_EXTENSION);
                                 }
                                 $local_filename = str_replace(Config::Get('document_root'), '', $local_filename);
                                 $thumb_id = DatabaseAdd('tbx_video_thumbnail', array('video_id' => $video['video_id'], 'thumbnail' => $local_filename));
                                 if (empty($display_thumbnail)) {
                                     $display_thumbnail = $thumb_id;
                                 }
                             }
                         }
                     }
                     $video_dir->ClearTemp();
                     if (!empty($display_thumbnail)) {
                         $DB->Update('UPDATE `tbx_video` SET `display_thumbnail`=? WHERE `video_id`=?', array($display_thumbnail, $video['video_id']));
                     }
                     $DB->Update('INSERT INTO `tbx_video_feed_history` VALUES (?,?)', array($this->feed['feed_id'], $xvideo->id->val()));
                     $imported++;
                 }
             }
             $DB->Update('UPDATE `tbx_video_feed` SET `date_last_read`=? WHERE `feed_id`=?', array(Database_MySQL::Now(), $this->feed['feed_id']));
             UpdateSponsorStats($this->feed['sponsor_id']);
         }
         // Start up the thumbnail and converson queues if needed
         if (!Config::Get('flag_using_cron')) {
             if ($this->feed['flag_convert']) {
                 ConversionQueue::Start();
             }
             if ($this->feed['flag_thumb']) {
                 ThumbQueue::Start();
             }
         }
     }
     return $imported;
 }