<?php

// Cron task to sync torrent information with uTorrent
// Also imports and deletes any finished torrents.
// Should be run every minute via a url call like this:
//   wget -O- http://yoursite.com/plugins/torrentdownload/site/cron_sync_torrents.php > /dev/null
// This cron script needs to be run on the same server as uTorrent
// Setup uTorrent so it saves in the _tmp folder:
//   /your/home/dir/path/public_html/files/_tmp

// setup includes
require_once('../../../core/includes/master.inc.php');

// load plugin details
$pluginDetails  = pluginHelper::pluginSpecificConfiguration('torrentdownload');
$pluginConfig   = $pluginDetails['config'];
$pluginSettings = json_decode($pluginDetails['data']['plugin_settings'], true);
$pluginInstance = pluginHelper::getInstance('torrentdownload');

// utorrent library
require_once('../includes/uTorrentRemote.class.php');

// add torrent
$uTorrentHost = $pluginSettings['utorrent_host'].(strlen($pluginSettings['utorrent_port'])?(':'.$pluginSettings['utorrent_port']):'');
$uTorrent = new uTorrentRemote($uTorrentHost, $pluginSettings['utorrent_username'], $pluginSettings['utorrent_password']);

// first delete any on uTorrent which don't exist in our local database
$localTorrentHashLookup = array();
$localTorrentData = $db->getRows('SELECT id, torrent_hash FROM plugin_torrentdownload_torrent');
if($localTorrentData)
{
	foreach($localTorrentData AS $localTorrentDataItem)
	{
		$localTorrentHashLookup[] = $localTorrentDataItem['torrent_hash'];
	}
}

$torrentInfo = $uTorrent->GrabTorrents();
if(is_array($torrentInfo))
{
	foreach($torrentInfo AS $torrentInfoItem)
	{
		// lookup locally
		if(!in_array($torrentInfoItem[0], $localTorrentHashLookup))
		{
			// remove torrent from uTorrent
			$uTorrent->ExecAction('removedata', $torrentInfoItem[0]);
		}
	}
}

// sync all data
$localTorrentData = $db->getRows('SELECT id, torrent_hash, user_id FROM plugin_torrentdownload_torrent WHERE save_status=\'downloading\'');
$torrentInfo = $uTorrent->GrabTorrents();
if($localTorrentData)
{
	foreach($localTorrentData AS $localTorrentDataItem)
	{
		// get hash and lookup from actual torrents
		$torrentHash = $localTorrentDataItem['torrent_hash'];
		foreach($torrentInfo AS $torrentInfoItem)
		{
			// if we've found the hash on uTorrent, sync progress
			if($torrentInfoItem[0] == $torrentHash)
			{
				// sync progress
				$pluginInstance->addUpdateTorrent($torrentInfoItem, $localTorrentDataItem['user_id']);
			}
		}
	}
}

// update any completed downloading
$db->query('UPDATE plugin_torrentdownload_torrent SET save_status=\'pending\' WHERE download_percent=1000 AND save_status=\'downloading\'');

// move any into storage which have a 'save_status' of 'pending'
$finishedItems = $db->getRows('SELECT * FROM plugin_torrentdownload_torrent WHERE save_status=\'pending\' ORDER BY id ASC LIMIT 1');
if($finishedItems)
{
	foreach($finishedItems AS $finishedItem)
	{
		// set to processing
		$db->query('UPDATE plugin_torrentdownload_torrent SET save_status=\'processing\' WHERE id='.(int)$finishedItem['id'].' LIMIT 1');
		
		// create folder in users accounts to save files
		$fileNameParts = pathinfo($finishedItem['torrent_name']);
		$folderName = isset($fileNameParts['filename'])?$fileNameParts['filename']:$finishedItem['torrent_name']; // Reguires PHP v5.2+
		
		// check for existing folder
        $rs = $db->getRow('SELECT id FROM file_folder WHERE folderName = ' . $db->quote($folderName) . ' AND userId = ' . (int) $finishedItem['user_id']);
        if ($rs)
        {
			$folderName .= ' ('.date('H:i:s').')';
		}
		
		// add folder
		$db->query('INSERT INTO file_folder (folderName, isPublic, userId, parentId, accessPassword) VALUES (:folderName, :isPublic, :userId, :parentId, :accessPassword)', array('folderName'     => $folderName, 'isPublic'       => 0, 'userId'         => (int) $finishedItem['user_id'], 'parentId'         => NULL, 'accessPassword' => ''));
		
		// get folder id
		$folderId = (int)$db->getValue('SELECT id FROM file_folder WHERE folderName='.$db->quote($folderName).' AND userId='.(int)$finishedItem['user_id'].' LIMIT 1');
		
		// get actual file list
		$fileArr = array();
		$fileList = $uTorrent->GrabListOfFiles($finishedItem['torrent_hash']);
		foreach($fileList[1] AS $fileListItem)
		{
			$fileArr[] = $finishedItem['save_path'].'/'.$fileListItem[0];
		}
		
		// move into storage
		if(COUNT($fileArr))
		{
			// consider any other users also downloading it
			//$otherUsersDownloading = $db->getRows('SELECT id, user_id FROM plugin_torrentdownload_torrent WHERE torrent_hash='.$db->quote($finishedItem['torrent_hash']).' AND (save_status=\'downloading\' OR save_status=\'pending\') AND id !='.(int)$finishedItem['id']);
			
			// loop files
			foreach($fileArr AS $fileArrItem)
			{
				$fileUpload   = new stdClass();
				$realFilename = trim(end(explode('/', $fileArrItem)));
				$fileUpload->name = $realFilename;
				$fileUpload->size = filesize($fileArrItem);
				$mimeType = file::estimateMimeTypeFromExtension($fileUpload->name, 'application/octet-stream');
				if (($mimeType == 'application/octet-stream') && (class_exists('finfo', false)))
				{
					$finfo    = new finfo;
					$mimeType = $finfo->file($fileArrItem, FILEINFO_MIME);
				}
				$fileUpload->type = $mimeType;
				
				$uploader = new uploader();
				$fileUpload = $uploader->moveIntoStorage($fileUpload, $fileArrItem);
				
				// success
				
				if ($fileUpload->error === null)
				{
					// update folder
					$shortUrl = $fileUpload->short_url;
					$db->query('UPDATE file SET userId='.(int)$finishedItem['user_id'].', folderId='.(int)$folderId.' WHERE shortUrl='.$db->quote($shortUrl).' LIMIT 1');
				}
			}
		}
		
		// set to complete
		$db->query('UPDATE plugin_torrentdownload_torrent SET save_status=\'complete\', status=\'Stopped\', date_completed=NOW() WHERE id='.(int)$finishedItem['id'].' LIMIT 1');
		
		// remove torrent from uTorrent
		$uTorrent->ExecAction('removedata', $finishedItem['torrent_hash']);
	}
}