<?php
defined('_VALID') or die('Restricted Access!');
require $config['BASE_DIR']. '/include/function_video.php';
require $config['BASE_DIR']. '/classes/filter.class.php';

if ( $config['video_module'] == '0' ) {
    VRedirect::go($config['BASE_URL']. '/error/page_invalid');
}

$upload_id          = mt_rand(). '_' .time();
$upload_max_size    = $config['video_max_size']*1024*1024;
$video_allowed_ext  = '(' .str_replace(',', '|', $config['video_allowed_extensions']). ')';
$video              = array('title' => '', 'keywords' => '', 'category' => 0, 'paysite' => '',
                            'privacy' => 'public', 'anonymous' => 'no');
if ( isset($_POST['video_upload_started']) ) {
    $filter     = new VFilter();
    $title      = $filter->get('video_title');
    $category   = $filter->get('video_category', 'INTEGER');
    $keywords   = $filter->get('video_keywords');
    $paysite    = $filter->get('video_paysite');
    $privacy    = $filter->get('video_privacy');
    $anonymous  = $filter->get('video_anonymous');

    if ( $title == '' ) {
        $errors[]           = 'Video title field cannot be blank!';
    } else {
        $video['title'] = $title;
    }

    if ( $keywords == '' ) {
        $errors[]           = 'Video keywords field cannot be blank!';
    } else {
        $keywords           = prepare_string($keywords, false);
        $video['keywords']  = $keywords;
    }

    if ( $category == '0' ) {
        $errors[]           = 'Please select a video category!';
    } else {
        $video['category']  = $category;
    }

    if ( $_FILES['video_file']['tmp_name'] == '' ) {
        $errors[]           = 'Please select a video file!';
    } elseif ( !is_uploaded_file($_FILES['video_file']['tmp_name']) ) {
        $errors[]           = 'Filename is not a valid uploaded file!';
    } else {
        $filename           = substr($_FILES['video_file']['name'], strrpos($_FILES['video_file']['name'], DIRECTORY_SEPARATOR)+1);
        $extension          = strtolower(substr($filename, strrpos($filename, '.')+1));
        $extensions_allowed = explode(',', $config['video_allowed_extensions']);
        if ( !in_array($extension, $extensions_allowed) ) {
            $errors[]       = 'Invalid video extension!';
        } else {
            $space = filesize($_FILES['video_file']['tmp_name']);
            if ( $space > $upload_max_size ) {
                $errors[]   = 'File exceeds maximul allowed video filesize of ' .$config['video_max_size']. 'MB!';
            }
        }
    }

    $video['paysite']       = $paysite;
    $video['privacy']       = ( $privacy == 'private' ) ? 'private' : 'public';
    $video['anonymous']     = ( $anonymous == 'yes' ) ? 'yes' : 'no';
    $uid                    = ( $anonymous == 'yes' ) ? getAnonymousUID() : intval($_SESSION['uid']);

    if ( !$errors ) {
        $sql        = "INSERT INTO video 
                       SET UID = " .$uid. ", title = '" .mysql_real_escape_string($title). "',
                           channel = " .$category. ", keyword = '" .mysql_real_escape_string($keywords). "',
                           space = '" .$space. "', addtime = '" .time(). "', adddate = '" .date('Y-m-d'). "', vkey = '" .mt_rand(). "',
                           type = '" .$video['privacy']. "', active = '2'";
        $conn->execute($sql);
        $video_id   = mysql_insert_id();
        $vdoname    = $video_id. '.' .$extension;
        $flvdoname  = $video_id. '.flv';
        $vdo_path   = $config['VDO_DIR']. '/' .$vdoname;
        if ( !move_uploaded_file($_FILES['video_file']['tmp_name'], $vdo_path) ) {
            $errors[]   = 'Failed to move uploaded file!';
        }

        if ( !$errors ) {
            $cmd        = $config['phppath']. ' ' .$config['BASE_DIR']. '/scripts/convert_video.php ' .$vdoname. ' ' .$video_id. ' ' .$vdo_path;
            log_conversion($config['LOG_DIR']. '/' .$video_id. '.log', $cmd);
            exec($cmd. '>/dev/null &');
            $duration   = get_video_duration($vdo_path, $video_id);
            $vkey       = substr(md5($video_id),11,20);
            $sql        = "UPDATE video SET duration = '" .mysql_real_escape_string($duration). "', vkey = '" .$vkey. "',
                                            vdoname = '" .mysql_real_escape_string($vdoname). "', flvdoname = '" .mysql_real_escape_string($flvdoname). "'
                           WHERE VID = " .intval($video_id). " LIMIT 1";
            $conn->execute($sql);
            
			
            $video_url  = $config['BASE_URL']. '/video/' .$video_id. '/' .prepare_string($title);
			$video_link = '<a href="'.$video_url.'">'.$video_url.'</a>';
            
            $sql        = "SELECT sv.SUID, s.username, s.email FROM video_subscribe AS sv, signup AS s
                           WHERE sv.UID = " .$uid. " AND sv.UID = s.UID";
            $rs         = $conn->execute($sql);
            if ( $conn->Affected_Rows() > 0 ) {
                $subscribers    = $rs->getrows();
                $mail           = new VMail();
                $mail->setNoReply();
                $sql            = "SELECT * FROM emailinfo WHERE email_id = 'subscribe_email' LIMIT 1";
                $rs             = $conn->execute($sql);
                $email_path     = $config['BASE_DIR']. '/templates/' .$rs->fields['email_path'];
                $sender         = ( $anonymous == 'yes' ) ? 'anonymous' : $_SESSION['username'];
                $mail->Subject  = str_replace('$sender_name', $sender, $rs->fields['email_subject']);
                foreach ( $subscribers as $subscriber ) {
                    $smarty->assign('video_link', $video_link);
                    $smarty->assign('username', $subscriber['username']);
                    $smarty->assign('sender_name', $_SESSION['username']);
                    $body               = $smarty->fetch($email_path);
                    $mail->AltBody      = $body;
                    $mail->Body         = nl2br($body);
                    $mail->AddAddress($subscriber['email']);
                    $mail->Send();
                    $mail->ClearAddresses();
                }
            }
          
            $search     = array('{$site_title}', '{$site_name}', '{$username}', '{$video_link}', '{$baseurl}');
            $replace    = array($config['site_title'], $config['site_name'], $_SESSION['username'], $video_link, $config['BASE_URL']);
            $mail       = new VMail();
            if ( $config['approve'] == '0' ) {
                $mail->sendPredefined($_SESSION['email'], 'video_approve', $search, $replace);
            } else {
                $mail->sendPredefined($_SESSION['email'], 'video_upload', $search, $replace);    
            }
          
            $sql        = "UPDATE channel SET total_videos = total_videos+1 WHERE CHID = " .$category. " LIMIT 1";
            $conn->execute($sql);
            $sql        = "UPDATE signup SET total_videos = total_videos+1, points = points+10 WHERE UID = " .$uid. " LIMIT 1";
            $conn->execute($sql);

            $video['title']     = '';
            $video['keywords']  = '';
            $video['category']  = 0;
            $video['paysite']   = '';
            $video['privacy']   = 'public';
            $video['anonymous'] = 'no';
            
            if ( $config['approve'] == '1' ) {
                $messages[] = 'Uploaded! Thank you for contributing ' .$config['site_name']. '. You will receive an email once your video is published!';
            } else {
                $messages[] = 'Uploaded! Thank you for contributing to ' .$config['site_name']. '.
                               Check out your video at <a href="' .$video_url. '">' .htmlspecialchars($title, ENT_QUOTES, 'UTF-8'). '</a> in a minute!';
            }
        }
    }
}

$smarty->assign('video', $video);
$smarty->assign('upload_id', $upload_id);
$smarty->assign('upload_max_size', $upload_max_size);
$smarty->assign('allowed_video_extensions', $video_allowed_ext);
$smarty->assign('upload_video', true);
$smarty->assign('categories', get_categories());
?>
