<?php
// +----------------------------------------------------------------------
// | mobanbox [ Beautiful Digital Content Trading System ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015 http://mobanbox.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Email author@mobanbox.net
// +----------------------------------------------------------------------

_setView(__FILE__);
_setTitle($langArray['downloads_setTitle']);

if(!check_login_bool()) {
	$_SESSION['temp']['golink'] = '/'.$languageURL.'download/';
	refresh('/'.$languageURL.'sign_in/');
}

$usersClass = new users();

if(check_login_bool() && $_SESSION['user']['user_id'] != $users['user_id']) {
	$users['is_follow'] = $usersClass->isFollow($users['user_id']);
}

$users['profile_desc'] = replaceEmoticons($users['profile_desc']);

abr('user', $users);

abr('checkItemsType', 'yes');

if(check_login_bool() && ($username == '' || $username == $_SESSION['user']['username'])) {
	$username = $_SESSION['user']['username'];
	$whereQuery = " AND (`status` = 'active' OR `status` = 'unapproved' ) ";
}
else {
	$whereQuery = " AND `status` = 'active' ";
}
$user = $usersClass->getByUsername($username);
if(!is_array($user)) {
	header("HTTP/1.0 404 Not Found");
	header("Location: http://". DOMAIN ."/".$languageURL."error");
}
abr('user', $user);


$userss = $usersClass->getAll(0, 0, $itemsClass->usersWhere);
abr('userss', $userss);


#加载作品
require_once ROOT_PATH.'/apps/items/models/items.class.php';
$itemsClass = new items();

$limit = 8;
$start = (PAGE-1)*$limit;

$items = $itemsClass->getAll($start, $limit, " `user_id` = '".intval($user['user_id'])."' ".$whereQuery);
abr('items', $items);

abr('paging', paging('/'.$languageURL.'user/'.$username.'/?p=', '&sort_by='.$_GET['sort_by'].'&order='.$_GET['order'], PAGE, $limit, $itemsClass->foundRows));
$allRows = $itemsClass->foundRows;
abr('allRows',$allRows);

require_once ROOT_PATH.'/apps/items/models/orders.class.php';
$ordersClass = new orders();

#下载作品
$itemID = get_id(2);
if(is_numeric($itemID)) {
	require_once ROOT_PATH.'/apps/items/models/items.class.php';
	$itemsClass = new items();
	$item = $itemsClass->get($itemID);
	if(!is_array($item) || (check_login_bool() && $item['status'] == 'unapproved' && $item['user_id'] != $_SESSION['user']['user_id']) || $item['status'] == 'queue') {
		header("HTTP/1.0 404 Not Found");
		header("Location: http://". DOMAIN ."/".$languageURL."error");
	}
	if(isset($_POST['rating'])) {
		$_GET['rating'] = $_POST['rating'];
	}

	if(isset($_GET['rating'])) {
		if(!isset($_GET['rating']) || !is_numeric($_GET['rating']) || $_GET['rating'] > 5) {
			$_GET['rating'] = 5;
		}
		elseif($_GET['rating'] < 1) {
			$_GET['rating'] = 1;
		}

		$item = $itemsClass->rate($itemID, $_GET['rating']);

		$stars = '';
		for($i=1;$i<6;$i++) {
			if($item['rating'] >= $i) {
				$stars .= '<i class="icon-star-full text-warn"></i>';
			}
			else {
				$stars .= '<i class="icon-star-empty"></i>';
			}
		}

		die('<div class="row-col h-v">
    <div class="row-cell v-m">
      <div class="modal-dialog modal-sm">
        <div class="modal-content">
          <div class="modal-header">
          	<h5 class="modal-title">您的评分为</h5>
          </div>
          <div class="modal-body text-center p-lg">
            <p class="text-lg">'.$stars.'</p>
          </div>
          <div class="modal-footer">
            <a href="/'.$languageURL.'download/" type="button" class="btn skin p-x-md">确定</a>
          </div>
        </div>
      </div>
    </div>
  </div>');
	}
	elseif(isset($_GET['certificate'])) {
		if($ordersClass->isBuyed($item['id'])) {
			header('Content-Type: text/plain; charset=UTF-8');
			header('Content-Disposition: attachment; filename="item_licence.txt"');
			header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
			header('Pragma: public');
			header("Content-Transfer-Encoding: binary");
			header('Expires: 0');
//            @ob_clean();
			@flush();
			if($ordersClass->row['extended'] == 'true') {
				$licence = $langArray['one_extended_licence'];
			}
			else {
				$licence = $langArray['one_regular_licence'];
			}
			$usersClass = new users();
			$user = $usersClass->get($item['user_id']);
			#  作者后4位
			$auth=substr($user['username'],-4);
			#买家后4位
			$buy=substr($_SESSION['user']['username'],-4);
			echo langMessageReplace($langArray['licence_text'], array(
				'licence_type'=>'共享许可',
				'DOMAIN' => $config['domain'],
				'LICENCE' => $licence,
				'USERNAME' => $user['username'],
				'nickname' => $_SESSION['user']['username'],
				'ITEMNAME' => $item['name'],
				'ITEMID' => $item['id'],
				'LANGUAGEURL' => $languageURL,
				'ORDERID' =>$auth.'-'.$buy.'-'.$ordersClass->row['id']
			));
			die();
		}
		else {
			refresh('/'.$languageURL.'download/', $langArray['error_certificate'], 'error');
		}
	}
	if($ordersClass->isBuyed($item['id']) || $item['free_file'] == 'true') {
		if(file_exists(DATA_SERVER_PATH.'/uploads/items/'.$item['id'].'/'.$item['main_file'])) {
			$fileInfo = pathinfo(DATA_SERVER_PATH.'/uploads/items/'.$item['id'].'/'.$item['main_file']);
			if($fileInfo['extension']=='txt'){
				$txt_content=file_get_contents(DATA_SERVER_PATH.'/uploads/items/'.$item['id'].'/'.$item['main_file']);
				$txt_content=preg_replace('/\n|\r\n/','<br>',$txt_content);
				$txt_content=preg_replace('<script>','<br>',$txt_content);
				$txt_content=iconv('gb2312','utf-8',$txt_content);
				abr('txt_content',$txt_content);
			}else{
				$mimeTypes = array (
					'zip' => 'application/zip'
				);

				if(isset($mimeTypes[$fileInfo['extension']])) {
					header('Content-Type: '.$mimeTypes[$fileInfo['extension']]);
				} else {
					header('Content-Type: application/octet-stream');
				}
				header('Content-Disposition: attachment; filename="'.$item['main_file_name'].'"');
				header("Content-Length:".filesize(DATA_SERVER_PATH.'/uploads/items/'.$item['id'].'/'.$item['main_file']));
				header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
				header('Pragma: public');
				header("Content-Transfer-Encoding: binary");
				header('Expires: 0');
				header('Content-Description: '.$config['domain'].' Download');
				@ob_clean();
				@flush();
				readfile(DATA_SERVER_PATH.'/uploads/items/'.$item['id'].'/'.$item['main_file']) or die("ERROR!");
				die();
			}
		}
	}
	else {
		header("HTTP/1.0 404 Not Found");
		header("Location: http://". DOMAIN ."/".$languageURL."error");
	}

}


//勋章
require_once ROOT_PATH.'/apps/system/models/badges.class.php';
$badges = new badges();

$badges_data = $badges->getAllFront();

$user = $_SESSION['user'];

$other_badges = array_map('trim', explode(',', $user['badges']));

$user_badges = array();

if($user['exclusive_author'] == 'true' && isset($badges_data['system']['is_exclusive_author'])) {
	if($badges_data['system']['is_exclusive_author']['photo'] && file_exists(DATA_SERVER_PATH . "/uploads/badges/" . $badges_data['system']['is_exclusive_author']['photo'])) {
		$user_badges[] = array(
			'name' => $badges_data['system']['is_exclusive_author']['name'],
			'photo' => '/uploads/badges/' . $badges_data['system']['is_exclusive_author']['photo']
		);
	}
}

if($user['featured_author'] == 'true' && isset($badges_data['system']['has_been_featured'])) {
	if($badges_data['system']['has_been_featured']['photo'] && file_exists(DATA_SERVER_PATH . "/uploads/badges/" . $badges_data['system']['has_been_featured']['photo'])) {
		$user_badges[] = array(
			'name' => $badges_data['system']['has_been_featured']['name'],
			'photo' => '/uploads/badges/' . $badges_data['system']['has_been_featured']['photo']
		);
	}
}

if(isset($user['statuses']['freefile']) && $user['statuses']['freefile'] && isset($badges_data['system']['has_free_file_month'])) {
	if($badges_data['system']['has_free_file_month']['photo'] && file_exists(DATA_SERVER_PATH . "/uploads/badges/" . $badges_data['system']['has_free_file_month']['photo'])) {
		$user_badges[] = array(
			'name' => $badges_data['system']['has_free_file_month']['name'],
			'photo' => '/uploads/badges/' . $badges_data['system']['has_free_file_month']['photo']
		);
	}
}

if(isset($user['statuses']['featured']) && $user['statuses']['featured'] && isset($badges_data['system']['has_had_item_featured'])) {
	if($badges_data['system']['has_free_file_month']['photo'] && file_exists(DATA_SERVER_PATH . "/uploads/badges/" . $badges_data['system']['has_had_item_featured']['photo'])) {
		$user_badges[] = array(
			'name' => $badges_data['system']['has_had_item_featured']['name'],
			'photo' => '/uploads/badges/' . $badges_data['system']['has_had_item_featured']['photo']
		);
	}
}

if($user['buy'] && isset($badges_data['buyers']) && is_array($badges_data['buyers'])) {
	foreach($badges_data['buyers'] AS $k => $v) {
		list($from, $to) = explode('-', $k);
		if($from <= $user['buy'] && $to >= $user['buy']) {
			if($v['photo'] && file_exists(DATA_SERVER_PATH . "/uploads/badges/" . $v['photo'])) {
				$user_badges[] = array(
					'name' => $v['name'],
					'photo' => '/uploads/badges/' . $v['photo']
				);
			}
			break;
		}
	}
}

if($user['sold'] && isset($badges_data['authors']) && is_array($badges_data['authors'])) {
	foreach($badges_data['authors'] AS $k => $v) {
		list($from, $to) = explode('-', $k);
		if($from <= $user['sold'] && $to >= $user['sold']) {
			if($v['photo'] && file_exists(DATA_SERVER_PATH . "/uploads/badges/" . $v['photo'])) {
				$user_badges[] = array(
					'name' => $v['name'],
					'photo' => '/uploads/badges/' . $v['photo']
				);
			}
			break;
		}
	}
}

if($user['referals'] && isset($badges_data['referrals']) && is_array($badges_data['referrals'])) {
	foreach($badges_data['referrals'] AS $k => $v) {
		list($from, $to) = explode('-', $k);
		if($from <= $user['referals'] && $to >= $user['referals']) {
			if($v['photo'] && file_exists(DATA_SERVER_PATH . "/uploads/badges/" . $v['photo'])) {
				$user_badges[] = array(
					'name' => $v['name'],
					'photo' => '/uploads/badges/' . $v['photo']
				);
			}
			break;
		}
	}
}

if(isset($badges_data['other']) && is_array($badges_data['other'])) {
	foreach($badges_data['other'] AS $k => $b) {
		if(in_array($k, $other_badges) && $b['photo'] && file_exists(DATA_SERVER_PATH . "/uploads/badges/" . $b['photo'])) {
			$user_badges[] = array(
				'name' => $b['name'],
				'photo' => '/uploads/badges/' . $b['photo']
			);
		}
	}
}

if(isset($user['country']['photo']) && $user['country']['photo'] && file_exists(DATA_SERVER_PATH . "/uploads/countries/" . $user['country']['photo'])) {
	$user_badges[] = array(
		'name' => $user['country']['name'],
		'photo' => '/uploads/countries/' . $user['country']['photo']
	);
} elseif(isset($badges_data['system']['location_global_community']) && $badges_data['system']['location_global_community']['photo'] && file_exists(DATA_SERVER_PATH . "/uploads/badges/" . $badges_data['system']['location_global_community']['photo'])) {
	$user_badges[] = array(
		'name' => $badges_data['system']['location_global_community']['name'],
		'photo' => '/uploads/badges/' . $badges_data['system']['location_global_community']['photo']
	);
}

if($user['power_elite_author'] == 'true' && isset($badges_data['system']['power_elite_author'])) {
	if($badges_data['system']['power_elite_author']['photo'] && file_exists(DATA_SERVER_PATH . "/uploads/badges/" . $badges_data['system']['has_been_featured']['photo'])) {
		$user_badges[] = array(
			'name' => $badges_data['system']['power_elite_author']['name'],
			'photo' => '/uploads/badges/' . $badges_data['system']['power_elite_author']['photo']
		);
	}
}

if($user['elite_author'] == 'true' && isset($badges_data['system']['elite_author'])) {
	if($badges_data['system']['elite_author']['photo'] && file_exists(DATA_SERVER_PATH . "/uploads/badges/" . $badges_data['system']['has_been_featured']['photo'])) {
		$user_badges[] = array(
			'name' => $badges_data['system']['elite_author']['name'],
			'photo' => '/uploads/badges/' . $badges_data['system']['elite_author']['photo']
		);
	}
}

abr('user_badges', $user_badges);


#获取粉丝
$follow['to'] = $usersClass->getFollowers($user['user_id'], 0, 9, 'RAND()', true);
$follow['to_count'] = $usersClass->foundRows;
$follow['from'] = $usersClass->getFollowers($user['user_id'], 0, 9, 'RAND()');
$follow['from_count'] = $usersClass->foundRows;
abr('follow', $follow);


$follow['toto'] = $usersClass->getFollowers($user['user_id'], 0, 10000000, 'RAND()', true);
$follow['toto_count'] = $usersClass->foundRows;
$follow['fromfrom'] = $usersClass->getFollowers($user['user_id'], 0, 10000000, 'RAND()');
$follow['fromfrom_count'] = $usersClass->foundRows;
abr('follow', $follow);

#加载作品
$items = $ordersClass->getAllBuyed(" `user_id` = '".intval($_SESSION['user']['user_id'])."' AND `paid` = 'true' ");
abr('items', $items);


$ratedItems = $itemsClass->getRates(str_replace('`id`', '`item_id`', $ordersClass->whereQuery));
abr('ratedItems', $ratedItems);

#面包屑	
abr('breadcrumb', '<a href="/'.$languageURL.'" title="">'.$langArray['home'].'</a> \ <a href="/'.$languageURL.'users/dashboard/" title="">'.$langArray['my_account'].'</a> \ <a href="/'.$languageURL.'users/downloads/" title="">'.$langArray['downloads'].'</a>');


?>