<?php

/* setup includes */
require_once 'includes/master.inc.php';
/* fusion charts php class */
require_once 'js/fusionCharts/Code/PHPClass/Includes/FusionCharts.php';
/* setup page */
define("PAGE_NAME", t("stats_page_name", "View file statistics"));
define("PAGE_DESCRIPTION", t("stats_meta_description", "Uploaded file statistics"));
define("PAGE_KEYWORDS", t("stats_meta_keywords", "stats, statistics, unique, visitors, hits, file, upload"));
$file = null;
if (isset($_REQUEST['u'])) {
    // only keep the initial part if there's a forward slash
    $shortUrl = current(explode("/", str_replace("~s", "", $_REQUEST['u'])));
    $file = file::loadByShortUrl($shortUrl);
}
/* load file details */
if (!$file) {
    /* if no file found, redirect to home page */
    redirect(WEB_ROOT . "/index." . SITE_CONFIG_PAGE_EXTENSION);
}
require_once '_header.php';
/* setup colours */
$colours = explode("|", "B02B2C|D15600|C79810|73880A|6BBA70|3F4C6B|356AA0|D01F3C");
?>

<script src="js/yui_combo.js" type="text/javascript"></script>

<div class="statsHeaderWrapper">
	<div class="statsHeader" style="background: url(<?php 
echo SITE_IMAGE_PATH;
 private function handle_file_upload($uploaded_file, $name, $size, $type, $error)
 {
     $fileUpload = new stdClass();
     $fileUpload->name = basename(stripslashes($name));
     $fileUpload->size = intval($size);
     $fileUpload->type = $type;
     $fileUpload->error = null;
     $extension = end(explode(".", $fileUpload->name));
     $fileUpload->error = $this->has_error($uploaded_file, $fileUpload, $error);
     if (!$fileUpload->error) {
         if (strlen(trim($fileUpload->name)) == 0) {
             $fileUpload->error = 'Filename not found.';
         }
     } elseif (intval($size) == 0) {
         $fileUpload->error = 'File received has zero size.';
     } elseif (intval($size) > $this->options['max_file_size']) {
         $fileUpload->error = 'File received is larger than permitted.';
     }
     if (!$fileUpload->error && $fileUpload->name) {
         if ($fileUpload->name[0] === '.') {
             $fileUpload->name = substr($fileUpload->name, 1);
         }
         $newFilename = MD5(microtime());
         // figure out upload type
         $file_size = 0;
         // select server from pool
         $uploadServerId = getAvailableServerId();
         $db = Database::getDatabase(true);
         $uploadServerDetails = $db->getRow('SELECT * FROM file_server WHERE id = ' . $db->quote($uploadServerId));
         // override storage path
         if (strlen($uploadServerDetails['storagePath'])) {
             $this->options['upload_dir'] = $uploadServerDetails['storagePath'];
             if (substr($this->options['upload_dir'], strlen($this->options['upload_dir']) - 1, 1) == '/') {
                 $this->options['upload_dir'] = substr($this->options['upload_dir'], 0, strlen($this->options['upload_dir']) - 1);
             }
             $this->options['upload_dir'] .= '/';
         }
         // move remotely via ftp
         if ($uploadServerDetails['serverType'] == 'remote') {
             // connect ftp
             $conn_id = ftp_connect($uploadServerDetails['ipAddress'], $uploadServerDetails['ftpPort'], 30);
             if ($conn_id === false) {
                 $fileUpload->error = 'Could not connect to file server ' . $uploadServerDetails['ipAddress'];
             }
             // authenticate
             if (!$fileUpload->error) {
                 $login_result = ftp_login($conn_id, $uploadServerDetails['ftpUsername'], $uploadServerDetails['ftpPassword']);
                 if ($login_result === false) {
                     $fileUpload->error = 'Could not authenticate with file server ' . $uploadServerDetails['ipAddress'];
                 }
             }
             // create the upload folder
             if (!$fileUpload->error) {
                 $uploadPathDir = $this->options['upload_dir'] . substr($newFilename, 0, 2);
                 if (!ftp_mkdir($conn_id, $uploadPathDir)) {
                     // Error reporting removed for now as it causes issues with existing folders. Need to add a check in before here
                     // to see if the folder exists, then create if not.
                     // $fileUpload->error = 'There was a problem creating the storage folder on '.$uploadServerDetails['ipAddress'];
                 }
             }
             // upload via ftp
             if (!$fileUpload->error) {
                 $file_path = $uploadPathDir . '/' . $newFilename;
                 clearstatcache();
                 if ($uploaded_file && is_uploaded_file($uploaded_file)) {
                     // initiate ftp
                     $ret = ftp_nb_put($conn_id, $file_path, $uploaded_file, FTP_BINARY, FTP_AUTORESUME);
                     while ($ret == FTP_MOREDATA) {
                         // continue uploading
                         $ret = ftp_nb_continue($conn_id);
                     }
                     if ($ret != FTP_FINISHED) {
                         $fileUpload->error = 'There was a problem uploading the file to ' . $uploadServerDetails['ipAddress'];
                     } else {
                         $file_size = filesize($uploaded_file);
                         @unlink($uploaded_file);
                     }
                 }
             }
             // close ftp connection
             ftp_close($conn_id);
         } else {
             // create the upload folder
             $uploadPathDir = $this->options['upload_dir'] . substr($newFilename, 0, 2);
             @mkdir($uploadPathDir);
             $file_path = $uploadPathDir . '/' . $newFilename;
             clearstatcache();
             if ($uploaded_file && is_uploaded_file($uploaded_file)) {
                 move_uploaded_file($uploaded_file, $file_path);
             }
             $file_size = filesize($file_path);
         }
         // check filesize uploaded matches tmp uploaded
         if ($file_size === $fileUpload->size) {
             $fileUpload->url = $this->options['upload_url'] . rawurlencode($fileUpload->name);
             // insert into the db
             $fileUpload->size = $file_size;
             $fileUpload->delete_url = '~d?' . $this->options['delete_hash'];
             $fileUpload->info_url = '~i?' . $this->options['delete_hash'];
             $fileUpload->delete_type = 'DELETE';
             // create delete hash, make sure it's unique
             $deleteHash = md5($fileUpload->name . getUsersIPAddress() . microtime());
             $existingFile = file::loadByDeleteHash($deleteHash);
             while ($existingFile != false) {
                 $deleteHash = md5($fileUpload->name . getUsersIPAddress() . microtime());
                 $existingFile = file::loadByDeleteHash($deleteHash);
             }
             // store in db
             $db = Database::getDatabase(true);
             $dbInsert = new DBObject("file", array("originalFilename", "shortUrl", "fileType", "extension", "fileSize", "localFilePath", "userId", "totalDownload", "uploadedIP", "uploadedDate", "statusId", "deleteHash", "serverId"));
             $dbInsert->originalFilename = $fileUpload->name;
             $dbInsert->shortUrl = 'temp';
             $dbInsert->fileType = $fileUpload->type;
             $dbInsert->extension = $extension;
             $dbInsert->fileSize = $fileUpload->size;
             $dbInsert->localFilePath = substr($file_path, strlen($this->options['upload_dir']), 99999);
             // add user id if user is logged in
             $dbInsert->userId = NULL;
             $Auth = Auth::getAuth();
             if ($Auth->loggedIn()) {
                 $dbInsert->userId = (int) $Auth->id;
             }
             $dbInsert->totalDownload = 0;
             $dbInsert->uploadedIP = getUsersIPAddress();
             $dbInsert->uploadedDate = sqlDateTime();
             $dbInsert->statusId = 1;
             $dbInsert->deleteHash = $deleteHash;
             $dbInsert->serverId = $uploadServerId;
             if (!$dbInsert->insert()) {
                 $fileUpload->error = 'abort';
             }
             // create short url
             $tracker = 1;
             $shortUrl = file::createShortUrlPart($tracker . $dbInsert->id);
             $fileTmp = file::loadByShortUrl($shortUrl);
             while ($fileTmp) {
                 $shortUrl = file::createShortUrlPart($tracker . $dbInsert->id);
                 $fileTmp = file::loadByShortUrl($shortUrl);
                 $tracker++;
             }
             // update short url
             file::updateShortUrl($dbInsert->id, $shortUrl);
             // update fileUpload with file location
             $file = file::loadByShortUrl($shortUrl);
             $fileUpload->url = $file->getFullShortUrl();
             $fileUpload->delete_url = $file->getDeleteUrl();
             $fileUpload->info_url = $file->getInfoUrl();
             $fileUpload->stats_url = $file->getStatisticsUrl();
             $fileUpload->short_url = $shortUrl;
         } else {
             if ($this->options['discard_aborted_uploads']) {
                 //@TODO - made ftp compatible
                 @unlink($file_path);
                 @unlink($uploaded_file);
                 if (!isset($fileUpload->error)) {
                     $fileUpload->error = 'maxFileSize';
                 }
             }
         }
     }
     return $fileUpload;
 }