<?php
defined('VSIGN') or die("Sorry, you are not allowed to directly access this page.<br /> Please press the back button in your browser.");
 
class videoDAO 
{
	private $db;
	private $user;
	private $isadmin = false;
	private $has_permissions = true;
	private $sub_page = "";

	function __construct(database $db, user $user) 
	{
		$this->db 	=& $db;
		$this->user =& $user;
		
		$usertype = Kit::GetParam('usertype', _SESSION, _INT, 0);
		
		if ($usertype == 1) $this->isadmin = true;
		
		$this->sub_page = Kit::GetParam('sp', _GET, _WORD, 'view');
		
		return;
	}
	
	function on_page_load() 
	{
		return '';
	}
	
	function echo_page_heading() 
	{
		echo __("Library");
		
		return true;
	}
	
	/**
	 * Library Filter form
	 * @return 
	 */	
	function LibraryFilter() 
	{
		$db =& $this->db;
		
		$mediatype = ""; //1
		$usertype = 0; //3
		$playlistid = ""; //4
		
		if (isset($_SESSION['content']['mediatype'])) $mediatype = $_SESSION['content']['mediatype'];
		if (isset($_SESSION['content']['usertype'])) $usertype = $_SESSION['content']['usertype'];
		if (isset($_SESSION['content']['playlistid'])) $playlistid = $_SESSION['content']['playlistid'];
		
		$filter_userid = "";
		if (isset($_SESSION['content']['filter_userid'])) $filter_userid = $_SESSION['content']['filter_userid'];
		
		$user_list = listcontent("all|All,".userlist("SELECT DISTINCT userid FROM video"),"filter_userid", $filter_userid);
		
		//retired list
		$retired = "0";
		if(isset($_SESSION['playlist']['filter_retired'])) $retired = $_SESSION['playlist']['retired'];
		$retired_list = listcontent("all|All,1|Yes,0|No","filter_retired",$retired);
		
		// Messages
		$msgName	= __('Name');
		$msgType	= __('Type');
		$msgRetired	= __('Retired');
		$msgOwner	= __('Owner');
                $msgShowOriginal = __('Show the original file name for each media item?');

		$filterForm = <<<END
			<div class="FilterDiv" id="LibraryFilter">
				<form>
					<input type="hidden" name="p" value="video">
					<input type="hidden" name="q" value="LibraryGrid">
					<input type="hidden" name="pages" id="pages">
					
					<table id="content_filterform" class="filterform">
						<tr>
							<td>$msgRetired</td>
							<td>$retired_list</td>
							<td>$msgOwner</td>
							<td>$user_list</td>
						</tr>
					</table>
			</form>
		</div>
END;

							// disable filter by name. raw name is in base32 format
							// one method is to add another column for original name
							//<td>$msgName</td>
							//<td><input type='text' name='2' id='2' /></td>

            $id = uniqid();

            $VsignGrid = <<<HTML
            <div class="VsignGrid" id="$id">
                <div class="VsignFilter">
                        $filterForm
                </div>
                <div class="VsignData">

                </div>
            </div>
HTML;
            echo $VsignGrid;
	}
	
	/**
	 * Prints out a Table of all media items
	 *
	 */
	function LibraryGrid() 
	{
		$db 		=& $this->db;
		$user		=& $this->user;
		$response	= new ResponseManager();

		//Get the input params and store them
		$mediatype 		= Kit::GetParam('mediatype', _REQUEST, _WORD, 'all');
		$name 			= Kit::GetParam('2', _REQUEST, _STRING);
		$shared 		= Kit::GetParam('shared', _REQUEST, _STRING);
		$filter_userid 	= Kit::GetParam('filter_userid', _REQUEST, _STRING, 'all');
		$filter_retired = Kit::GetParam('filter_retired', _REQUEST, _STRING, 'all');
                $filterShowOriginal = Kit::GetParam('filter_showOriginal', _REQUEST, _CHECKBOX, 'off');
		
		setSession('content', 'mediatype', $mediatype);
		setSession('content', 'name', $name);
		setSession('content', 'shared', $shared);
		setSession('content', 'filter_userid', $filter_userid);
		setSession('content', 'filter_retired', $filter_userid);
		
		// Construct the SQL
		$SQL  = "";
		$SQL .= "SELECT  video.videoID, ";
		$SQL .= "        video.filename, ";
		$SQL .= "        video.duration, ";
		$SQL .= "        video.userID, ";
		$SQL .= "        video.FileSize, ";
		$SQL .= "        IFNULL((SELECT parentvideo.videoid FROM video parentvideo WHERE parentvideo.editedvideoid = video.videoid),0) AS ParentID, ";
		$SQL .= "        video.filename as originalFileName ";
		$SQL .= "FROM    video ";
		$SQL .= " LEFT OUTER JOIN video parentvideo ";
		$SQL .= " ON parentvideo.videoID = video.videoID ";
		$SQL .= "WHERE   video.isEdited = 0 ";
		if ($name != "") 
		{
			$SQL .= " AND video.filename LIKE '%$name%' ";
		}
		if ($filter_userid != 'all') 
		{
			$SQL .= sprintf(" AND video.userid = %d ", $filter_userid);
		}
		//retired options
		if ($filter_retired == '1') 
		{
			$SQL .= " AND video.retired = 1 ";
		}
		elseif ($filter_retired == '0') 
		{
			$SQL .= " AND video.retired = 0 ";			
		}
		$SQL .= " ORDER BY video.filename ";

		Debug::LogEntry($db, 'audit', $SQL);

		if (!$results = $db->query($SQL)) 
		{
			trigger_error($db->error());
			trigger_error(__('Cant get content list'), E_USER_ERROR);			
		}
		
		// Messages
		$msgName	= __('Name');
		$msgOwner	= __('Owner');
		$msgFileSize	= __('Size');
                $msgRevisions = __('Revised');
                $msgOriginal = __('Original Filename');
		$msgShared	= __('Permissions');
		$msgAction	= __('Action');

    	$output = '';
	$output.= '<div class="info_table">';
	$output.= ' <table style="width:100%">';
	$output.= '     <thead>';
	$output.= '         <tr>';
	$output.= '             <th>' . $msgName . '</th>';
	$output.= '             <th>h:mi:ss</th>';         
	$output.= '             <th>' . $msgFileSize . '</th>';
        $output.= '             <th>' . $msgOwner . '</th>';
	$output.= '             <th>' . $msgShared . '</th>';      
	$output.= '             <th>' . $msgRevisions . '</th>';
        
        if ($filterShowOriginal == 1)
            $output.= '             <th>' . $msgOriginal . '</th>';
        
	$output.= '             <th>' . $msgAction . '</th>'; 
	$output.= '         </tr>';
	$output.= '     </thead>';
	$output.= '     <tbody>';
		
        while ($aRow = $db->get_row($results))
        {
            $mediaid 		= Kit::ValidateParam($aRow[0], _INT);
            $media 			= Kit::ValidateParam(Kit::base32_decode($aRow[1]), _STRING);
            $length 		= sec2hms(Kit::ValidateParam($aRow[2], _DOUBLE));
            $ownerid 		= Kit::ValidateParam($aRow[3], _INT);
            $fileSize = Kit::ValidateParam($aRow[4], _INT);
            $revisions = (Kit::ValidateParam($aRow[5], _INT) != 0) ? '<img src="img/act.gif" />' : '';
            $originalFileName = Kit::ValidateParam($aRow[6], _STRING);
            
            // Size in MB
            $sz = 'BKMGTP';
            $factor = floor((strlen($fileSize) - 1) / 3);
            $fileSize = sprintf('%.2f', $fileSize / pow(1024, $factor)) . @$sz[$factor];

            //get the username from the userID using the user module
            $username = $user->getNameFromID($ownerid);

            $group = $this->GroupsForMedia($mediaid);

            // Permissions
            $auth = $this->user->MediaAuth($mediaid, true, 'video');

            if ($auth->view) //is this user allowed to see this
            {
                if ($auth->edit)
                {
                    //double click action - depends on what type of media we are
                    $output .= <<<END
                    <tr href='index.php?p=module&mod=$mediatype&q=Exec&method=EditForm&mediaid=$mediaid' ondblclick="VsignFormRender($(this).attr('href'))">
END;
                }
                else
                {
                    $output .= '<tr ondblclick="alert(' . __('You do not have permission to edit this media') . ')">';
                }

                $output .= "<td>$media</td>\n";
                $output .= "<td>$length</td>\n";
                $output .= "<td>$fileSize</td>\n";
                $output .= "<td>$username</td>";
                $output .= "<td>$group</td>";
                $output .= '<td>' . $revisions . '</td>';
                
                if ($filterShowOriginal == 1)
                    $output .= '<td>' . $originalFileName . '</td>';

                // ACTION buttons
                if ($auth->edit)
                {
                    $msgEdit	= __('Edit');
                    $msgDelete	= __('Delete');

                    $buttons 	= "<button class='VsignFormButton' title='$msgEdit' href='index.php?p=module&mod=video&q=Exec&method=EditForm&mediaid=$mediaid'><span>$msgEdit</span></button>";
                    
                    if ($auth->del)
                        $buttons .= "<button class='VsignFormButton' title='$msgDelete' href='index.php?p=module&mod=video&q=Exec&method=DeleteForm&mediaid=$mediaid'><span>$msgDelete</span></button>";

                    if ($auth->modifyPermissions)
                        $buttons .= "<button class='VsignFormButton' title='$msgShared' href='index.php?p=module&mod=video&q=Exec&method=PermissionsForm&mediaid=$mediaid'><span>$msgShared</span></button>";
                }
                else
                {
                    $buttons = __("No available actions.");
                }

                $output .= <<<END
                <td>
                        <div class='buttons'>
                                $buttons
                        </div>
                </td>
END;

                $output .= "</tr>\n";
            }
        }
		
    	$output .= "</tbody></table>\n</div>\n";

    	$response->SetGridResponse($output);
        $response->Respond();
    }
	
	/**
	 * Display the forms
	 * @return 
	 */
	function displayForms() 
	{
		$db 	=& $this->db;
		$user 	=& $this->user;
                $helpManager    = new HelpManager($db, $user);
		
		//displays all the content add forms - tabbed.
		$response = new ResponseManager();
		
		// Get a list of the enabled modules and then create buttons for them
		if (!$enabledModules = new ModuleManager($db, $user, 0)) 
                    trigger_error($enabledModules->message, E_USER_ERROR);
		
		$buttons = '';
		
		// Loop through the buttons we have and output store HTML for each one in $buttons.
		while ($modulesItem = $enabledModules->GetNextModule())
		{
			$mod 		= Kit::ValidateParam($modulesItem['Module'], _STRING);
			$caption 	= __('Add') . ' ' . Kit::ValidateParam($modulesItem['Name'], _STRING);
			if ($caption == 'Add Video')
				continue;
			$mod		= strtolower($mod);
			$title 		= Kit::ValidateParam($modulesItem['Description'], _STRING);
			$img 		= Kit::ValidateParam($modulesItem['ImageUri'], _STRING);
			
			$uri		= 'index.php?p=module&q=Exec&mod=' . $mod . '&method=AddForm';
			
			$buttons .= <<<HTML
			<div class="regionicons">
				<a class="VsignFormButton" title="$title" href="$uri">
				<img class="dash_button" src="$img" />
				<span class="dash_text">$caption</span></a>
			</div>
HTML;
		}
		
		$options = <<<END
		<div id="canvas">
			<div id="buttons">
				$buttons
			</div>
		</div>
END;
		
		$response->html 		= $options;
		$response->dialogTitle 	= __('Add Media to the Library');
		$response->dialogSize 	= true;
		$response->dialogWidth 	= '650px';
		$response->dialogHeight = '280px';
                $response->AddButton(__('Help'), 'VsignHelpRender("' . $helpManager->Link('Content', 'AddtoLibrary') . '")');
		$response->AddButton(__('Close'), 'VsignDialogClose()');

		$response->Respond();
	}

	/**
	 * Displays the page logic
	 *
	 * @return unknown
	 */
	function displayPage() 
	{
		$db =& $this->db;
		
		if (!$this->has_permissions) 
		{
			trigger_error(__("You do not have permissions to access this page"), E_USER_ERROR);
			return false;
		}
		
		switch ($this->sub_page) 
		{	
			case 'view':
				require("template/pages/video_view.php");
				break;
					
			default:
				break;
		}
		
		return false;
	}
	
    /**
     * Displays the Library Assign form
     * @return
     */
    function LibraryAssignForm()
    {
        $db 			=& $this->db;
        $user			=& $this->user;
        $response		= new ResponseManager();
        $formMgr 		= new FormManager($db, $user);
        $helpManager    = new HelpManager($db, $user);

        $mediatype              = '';
        $name                   = '';

        //Input vars
        $layoutId = Kit::GetParam('layoutid', _REQUEST, _INT);
        $regionId = Kit::GetParam('regionid', _REQUEST, _STRING);

        // Messages
        $msgName	= __('Name');

        $form = <<<HTML
        <form>
            <input type="hidden" name="p" value="video">
            <input type="hidden" name="q" value="LibraryAssignView">
            <table>
                <tr>
                    <td>$msgName</td>
                    <td><input type="text" name="name" id="name" value="$name"></td>
                </tr>
            </table>
        </form>
HTML;
		
        $id = uniqid();

        $msgAssignBox = __('Video to Assign');
        $msgInfoMessage = __('Drag or double click to move items between lists');

        $VsignGrid = <<<HTML
        <div class="VsignGrid LibraryAssign" id="$id">
            <div class="VsignFilter">
                $form
            </div>
            <center>$msgInfoMessage</center>
            <div class="VsignData LibraryAssignLeftSortableList connectedlist">

            </div>
            <div class="LibraryAssignRightSortableList connectedlist">
                <h3>$msgAssignBox</h3>
                <ul id="LibraryAssignSortable" class="connectedSortable">

                </ul>
            </div>
        </div>
HTML;
		
        // Construct the Response
        $response->html         = $VsignGrid;
        $response->success	= true;
        $response->dialogSize	= true;
        $response->dialogWidth	= '780px';
        $response->dialogHeight = '580px';
        $response->dialogTitle	= __('Assign an item from the Library');

        $response->AddButton(__('Help'), 'VsignHelpRender("' . $helpManager->Link('Library', 'Assign') . '")');
        $response->AddButton(__('Cancel'), 'VsignSwapDialog("index.php?p=layout&layoutid=' . $layoutId . '&regionid=' . $regionId . '&q=RegionOptions")');
        $response->AddButton(__('Assign'), 'LibraryAssignSubmit("' . $layoutId . '","' . $regionId . '")');

        $response->Respond();
    }
	
    /**
     * Show the library
     * @return 
     */
    function LibraryAssignView() 
    {
        $db =& $this->db;
        $user =& $this->user;
        $response = new ResponseManager();

        //Input vars
        $mediatype = Kit::GetParam('type', _POST, _STRING, 'all');
        $name = Kit::GetParam('name', _POST, _STRING, '');

        setSession('content', 'mediatype', $mediatype);
        setSession('content', 'name', $name);

        // query to get all video that is in the database ready to display
        $SQL  = "";
        $SQL .= "SELECT videoID, ";
        $SQL .= "       filename, ";
        $SQL .= "       filesize, ";
        $SQL .= "       duration ";
        $SQL .= "  FROM video ";
        //$SQL .= " WHERE retired = 0 AND isEdited = 0 ";

        // Filter on name
        //if ($name != "all") 
            $SQL.= " WHERE filename LIKE '%" . sprintf('%s', $name) . "%'";

        $SQL .= " ORDER BY filename ";

        if(!$results = $db->query($SQL)) 
        {
            trigger_error($db->error());
            trigger_error(__($SQL), E_USER_ERROR);			
            //trigger_error(__('Cannot get list of video in the library'), E_USER_ERROR);			
        }

        $response->html  = '<h3>' . __('Library') . '</h3>';
        $response->html .= '<ul id="LibraryAvailableSortable" class="connectedSortable">';

        // Size in MB
        $sz = 'BKMGTP';

        // while loop
        while ($row = $db->get_row($results)) 
        {			
            $mediaId = Kit::ValidateParam($row[0], _INT);
            $media = Kit::ValidateParam(Kit::base32_decode($row[1]), _STRING);
            $filesize = Kit::ValidateParam($row[2], _INT);
            $length = sec2hms(Kit::ValidateParam($row[3], _DOUBLE));            
            
            $factor = floor((strlen($filesize) - 1) / 3);
            $filesize = sprintf('%.2f', $filesize / pow(1024, $factor)) . @$sz[$factor];

            // Permissions
            $auth = $this->user->MediaAuth($mediaId, true, 'video');

            // Is this user allowed to see this
            if ($auth->view) 
                $response->html .= '<li class="li-sortable" id="videoID_' . $mediaId . '">' . $media . ' - Size: ' . $filesize . ' - Duration (sec) ' . $length . '</li>';
        }

        //table ending
        $response->html .= '</ul>';

        // Construct the Response
        $response->success = true;
        $response->callBack = 'LibraryAssignCallback';
        $response->Respond();
    }
	
    /**
     * Gets called by the SWFUpload Object for uploading files
     * @return
     */
    function FileUpload()
    {
        $db =& $this->db;

        Debug::LogEntry($db, 'audit', 'Uploading a file', 'Library', 'FileUpload');

        Kit::ClassLoader('file');
        $fileObject = new File($db);

        
        // Check we got a valid file
        if (isset($_FILES['media_file']) && is_uploaded_file($_FILES['media_file']['tmp_name']) && $_FILES['media_file']['error'] == 0)
        {
            Debug::LogEntry($db, 'audit', 'Valid Upload', 'Library', 'FileUpload');

            // Directory location
            $libraryFolder  = Config::GetSetting($db, 'LIBRARY_LOCATION');
            $error          = 0;
            $fileName       = Kit::ValidateParam($_FILES['media_file']['name'], _FILENAME);
            $fileId         = $fileObject->GenerateFileId($this->user->userid);
            $fileLocation   = $libraryFolder . 'temp/' . $fileId;

            // Make sure the library exists
            $fileObject->EnsureLibraryExists();

            // Save the FILE
            Debug::LogEntry($db, 'audit', 'Saving the file to: ' . $fileLocation, 'FileUpload');

            move_uploaded_file($_FILES['media_file']['tmp_name'], $fileLocation);

            Debug::LogEntry($db, 'audit', 'Upload Success', 'FileUpload');
        }
        else
        {
            Debug::LogEntry($db, 'audit', 'Error uploading the file. Error Number: ' . $_FILES['media_file']['error'] , 'FileUpload');

            $error      = $_FILES['media_file']['error'];
            $fileName   = 'Error';
            $fileId     = 0;
        }

        $complete_page = <<<HTML
        <html>
            <head>
                <script type="text/javascript" src="3rdparty/jQuery/jquery.min.js"></script>
                <script type="text/javascript">

                    var fileId = '$fileId';
                    var fileName = '$fileName';
                    var errorNo = $error;

                    function report()
                    {
                        var form = window.parent.fileUploadReport(fileName, fileId, errorNo);
                    }

                    window.onload = report;

                </script>
            </head>
            <body></body>
        </html>
HTML;

        echo $complete_page;

        Debug::LogEntry($db, "audit", $complete_page, "FileUpload");
        Debug::LogEntry($db, "audit", "[OUT]", "FileUpload");
        exit;
    }

    /**
     * Get a list of group names for a layout
     * @param <type> $layoutId
     * @return <type>
     */
    private function GroupsForMedia($mediaId)
    {
        $db =& $this->db;

        $SQL = '';
        $SQL .= 'SELECT `group`.Group ';
        $SQL .= '  FROM `group` ';
        $SQL .= '   INNER JOIN lkmediagroup ';
        $SQL .= '   ON `group`.GroupID = lkmediagroup.GroupID ';
        $SQL .= ' WHERE lkmediagroup.MediaID = %d ';

        $SQL = sprintf($SQL, $mediaId);

        if (!$results = $db->query($SQL))
        {
            trigger_error($db->error());
            trigger_error(__('Unable to get group information for media'), E_USER_ERROR);
        }

        $groups = '';

        while ($row = $db->get_assoc_row($results))
        {
            $groups .= $row['Group'] . ', ';
        }

        $groups = trim($groups);
        $groups = trim($groups, ',');

        return $groups;
    }
}
?>