<?php
/* PageCookery Microblog
*
* Author: Explon
*
* Copyright (C) 2007 Explon <explon@gmail.com>
*/

require_once('global.php');

if ($act != 'getavatar' AND $act != 'login' AND $act != 'logout' AND $act != 'save')
{
	if ((preg_match("/(iphone|ipod|android)/i", strtolower(Helper::UserAgent()))) AND strstr(strtolower(Helper::UserAgent()), 'webkit'))
	{ 
		header('Location: i/');
		exit;
	}
	else if (trim(Helper::UserAgent()) == '' OR preg_match("/(nokia|sony|ericsson|mot|htc|samsung|sgh|lg|philips|lenovo|ucweb|opera mobi|windows mobile|blackberry)/i", strtolower(Helper::UserAgent())))
	{
		header('Location: m/');
		exit;
	}
}

if ($Own['lastfm'])
{	
	$playing = get_recent_tracks();
}

switch ($act)
{
	default:					
		if ($User['id'])
		{
			$prefixs = $db->query("SELECT * FROM prefix WHERE id > 1 ORDER BY title ASC")->result_array();
		}
		
		if ($_GET['q'])
		{
			$keywords = explode(' ', trim(Format::Safe(urldecode($_GET['q']), TRUE)));

			foreach($keywords AS $keyword)
			{
				if (!$search_query)
				{
				   $search_query .= " WHERE `content` LIKE '%" . $keyword ."%'";
				}
				else
				{
				   $search_query .= " OR `content` LIKE '%" . $keyword ."%'";
				}
			}
			
			$navbar[] = '搜索: ' . urldecode($_GET['q']);
		}
		
		$entry = $db->query("SELECT SQL_CALC_FOUND_ROWS * FROM entry " . $search_query . " ORDER BY time DESC LIMIT " . Pages::GetQueryLimit(intval($_GET['page']), 20));
		
		$pages_total = $db->query("SELECT FOUND_ROWS() AS count")->row_array();
		
		$follow = $db->query("SELECT * FROM followlog ORDER BY time DESC LIMIT 20")->result_array();
		
		foreach ($follow AS $key => $item)
		{
			$follow[$key]['picture'] = unserialize($item['picture']);
			
			if (!$follower[$item['followid']])
			{
				$follower[$item['followid']] = $db->query("SELECT * FROM follow WHERE id = " . intval($item['followid']))->row_array();
			}
		}
		
		if (intval($_GET['page']) <= 1)
		{
			$last_entry = $entry->row_array();
			$entry = $entry->result_array();
			
			unset($entry[0]);
		}
		else
		{
			$last_entry = $db->query("SELECT * FROM entry ORDER BY time DESC LIMIT 0, 1")->row_array();
			
			$entry = $entry->result_array();
		}
		
		foreach ($entry AS $key => $item)
		{
			$entryids .= $item['id'] . ', ';
			$entry_reply[$item['id']] = $db->query("SELECT * FROM reply WHERE entryid = " . intval($item['id']))->result_array();
		}
		
		$entryids .= intval($last_entry['id']);
		
		if ($last_entry['id'])
		{
			$entry_reply[$last_entry['id']] = $db->query("SELECT * FROM reply WHERE entryid = " . $last_entry['id'])->result_array();
		}
		
		foreach ($entry_reply AS $entry_id => $item)
		{
			foreach ($item AS $m_key => $message)
			{
				$entry_reply[$entry_id][$m_key]['ip'] = explode('.', $message['ip']);
			}
		}
		
		$entry_picture = format_result_array_key($db->query("SELECT * FROM picture WHERE entryid IN (" . $entryids . ")")->result_array(), 'entryid');
		
		$pages = Pages::DrawPages($pages_total['count'], 20, BASE_URL, array('page' => intval($_GET['page'])));
		
		$title = SITE_NAME;
		
		$template = new Template('blog', NULL, 'blog');
	break;
	
	case 'comments':
		$comments = $db->query("SELECT SQL_CALC_FOUND_ROWS * FROM reply ORDER BY time DESC LIMIT " . Pages::GetQueryLimit(intval($_GET['page']), 50))->result_array();
		
		$pages_total = $db->query("SELECT FOUND_ROWS() AS count")->row_array();
		
		foreach ($comments AS $key => $item)
		{
			$even = $even == 'even' ? 'odd' : 'even';
			
			$comments[$key]['even'] = $even;
		}
		
		$title = _t('评论聚合') . ' - ' . SITE_NAME;
		
		$pages = Pages::DrawPages($pages_total['count'], 50, BASE_URL . '?act=comments', array('page' => intval($_GET['page'])));
		
		$template = new Template('comments', NULL, 'comments');
	break;
	
	case 'view':
		$entry = $db->query("SELECT * FROM entry WHERE id = " . intval($_GET['id']))->row_array();
		
		if (!$entry['id'])
		{
			redirect(BASE_URL);
		}
		
		$title_message = explode("\n", trim(strip_tags($entry['content'])));
		
		$title = $title_message[0] . ' - ' . SITE_NAME;
		
		$entry['picture'] = $db->query("SELECT * FROM picture WHERE entryid = " . $entry['id'])->row_array();
		
		if ($options['allow_comment'] != 'false')
		{
			$reply = $db->query("SELECT * FROM reply WHERE entryid = " . intval($entry['id']))->result_array();
		}

		$template = new Template('view', NULL, 'blog');
	break;
	
	case 'following':
		$following = $db->query("SELECT * FROM follow ORDER BY lastupdate DESC")->result_array();
		
		foreach ($following AS $key => $item)
		{
			$following[$key]['last_entry'] = $db->query("SELECT * FROM followlog WHERE followid = " . $item['id'] . " ORDER BY time DESC LIMIT 1")->row_array();
			
			$following[$key]['last_entry']['message'] = Format::ParseBBCode($following[$key]['last_entry']['message']);
		}
		
		$title = SITE_NAME . ' - ' . _t('关注');
		
		$template = new Template('following', NULL, 'following');
	break;
	
	case 'dofollow':
		$title = SITE_NAME . ' - Follow Me!';
		
		if ($_POST['blogurl'])
		{
			if (substr($_POST['blogurl'], -1, 1) != '/')
			{
				$_POST['blogurl'] = $_POST['blogurl'] . '/';
			}
			
			if (!is_array(@json_decode(file_get_contents($_POST['blogurl'] . 'httprequest.php?act=following'), TRUE)))
			{
				$message = _t('PageCookery 地址不正确或版本低于 v0.8 不能使用 follow 功能.');
			}
			else
			{
				redirect($_POST['blogurl'] . '?act=dofollow&blogurl=' . urlencode(BASE_URL));
			}
		}
		else if ($_GET['blogurl'])
		{
			if (urldecode($_GET['blogurl']) == BASE_URL)
			{
				Helper::PrintJavaScript("alert('" . _t('你不能 Follow 自己.') . "'); top.window.location = '" . BASE_URL . "';");
			}
			
			$bloginfo = @json_decode(file_get_contents(urldecode($_GET['blogurl']) . 'httprequest.php?act=bloginfo'), TRUE);
			
			$title = SITE_NAME . ' - Follow Me!';
			
			if (!is_array($bloginfo))
			{
				$message = _t('PageCookery 地址不正确或版本低于 v0.8 不能使用 follow 功能.');
			}
			else
			{
				$title = SITE_NAME . ' - Follow ' . $bloginfo['site_name'];
				
				if ($is_guest OR $User['id'] != 1)
				{
					show_login();
				}
				
				$check = $db->query("SELECT id FROM follow WHERE blogurl = '" . Format::Safe($bloginfo['base_url']) . "'")->row_array();
				
				if (!$check['id'])
				{
					$db->insert('follow', array(
						'blogurl' => $bloginfo['base_url'],
						'title' => $bloginfo['site_name']
					));
					
					$followid = $db->insert_id();
					
					fetch_follow($bloginfo['base_url'], $followid);
				}
				
				Helper::PrintJavaScript("alert('" . _t('已经成功 Follow:') . " " . Format::Safe($bloginfo['site_name']) . ".'); top.window.location = '" . BASE_URL . "?act=following';");
			}
		}

		$template = new Template('dofollow', NULL, 'dofollow');
	break;
	
	case 'music':
		if (!$Own['lastfm'])
		{
			redirect($_SERVER['HTTP_REFERER']);
		}
		
		$title = SITE_NAME . '- ' . _t('最近在听的音乐');
		
		$recent_tracks = json_decode(trim(str_replace("\'", "'", file_get_contents('music.json'))), TRUE);
		
		//$recent_tracks = json_decode(file_get_contents('music.json'), TRUE);
		
		if (!is_array($recent_tracks['recenttracks']['track']))
		{
			$recent_tracks['recenttracks']['track'] = array();
		}
		
		$template = new Template('music', NULL, 'music');
	break;
	
	case 'rssimport':
		if ($is_guest OR $User['id'] != 1)
		{
			show_login();
		}
		
		if ($_GET['do'] == 'delete' AND intval($_GET['id']) > 0)
		{
			$db->query("DELETE FROM rssfeeds WHERE id = " . intval($_GET['id']));
			
			$db->query("DELETE FROM rsslog WHERE rssid = " . intval($_GET['id']));
			
			redirect(BASE_URL . '?act=rssimport');
		}
		else if ($_POST['url'])
		{
			require_once('lib/class_rssparser.php');
			
			$rssparser = new RSSParser;
			
			$rssparser->cache_dir = 'cache/'; 
			$rssparser->cache_time = 0; 
			$rssparser->cp = 'UTF-8'; 
			
			$rss = $rssparser->get($_POST['url']);
			
			if ($rss['title'])
			{
				$db->insert('rssfeeds', array(
					'title' => Format::Safe($rss['title'], TRUE),
					'url' => Format::Safe($_POST['url']),
					'from' => Format::Safe($_POST['from'], TRUE),
					'field' => Format::Safe($_POST['field'], TRUE)
				));
				
				redirect(BASE_URL . '?act=rssimport');
			}
			else
			{
				Helper::PrintJavaScript("alert('" . _t('RSS 无法解析,可能是网络原因或者地址错误.') . "'); window.location = '?act=rssimport';");
			}
		}
		
		$feeds = $db->query("SELECT * FROM rssfeeds ORDER BY id DESC")->result_array();
		
		$title = SITE_NAME . '- RSS 导入';
		
		$template = new Template('rssimport', NULL, 'rssimport');
	break;
	
	case 'photos':
		if (!$flickr['feed'])
		{
			redirect(BASE_URL);
		}
		
		$title = SITE_NAME . '- 最近上传的照片';
		
		$recent_photos = json_decode(trim(str_replace("\'", "'", file_get_contents('photos.json'))), TRUE);
		
		if (!is_array($recent_photos))
		{
			$recent_photos['items'] = array();
			
			@unlink(str_replace(basename($_SERVER['PHP_SELF']), '', __FILE__) . 'cache/flickr_sync_tag.db');
		}
		
		$template = new Template('photos', NULL, 'photos');
	break;
	
	case 'login':
		if (!$is_guest)
		{
			if ($_GET['ajax'])
			{
				exit(BASE_URL);
			}
			
			redirect('./');
		}
		
		if ($_POST['referer'])
		{
			define('LOGIN_REFERER', $_POST['referer']);
		}
		else
		{
			define('LOGIN_REFERER', $_SERVER['HTTP_REFERER']);
		}
		
		if ($_POST['username'] AND $_POST['password'] OR $_GET['ajax'])
		{
			$get_user = $db->query("SELECT * FROM user WHERE username = '" . Format::Safe($_POST['username']) . "'")->row_array();
			
			if ($get_user['password'] == md5($_POST['password']))
			{
				if ($_POST['bymobile'] == 'TRUE' OR $_GET['byiphone'])
				{
					Helper::BakeCookie('username', $get_user['username'], time() + 3600 * 24 * 30);
					Helper::BakeCookie('password', $get_user['password'], time() + 3600 * 24 * 30);
				}
				else
				{
					Helper::BakeCookie('username', $get_user['username']);
					Helper::BakeCookie('password', $get_user['password']);
				}
				
				if ($_POST['referer'])
				{
					if ($_GET['ajax'])
					{
						exit($_POST['referer']);
					}
					
					redirect($_POST['referer']);
				}
				else
				{
					if ($_GET['ajax'])
					{
						exit($_SERVER['HTTP_REFERER']);
					}
					
					redirect($_SERVER['HTTP_REFERER']);
				}
				
			}
			else
			{
				if ($_POST['bymobile'] == 'TRUE')
				{
					header('Location: ' . BASE_URL . 'm/?act=login&username=' . urlencode($_POST['username']) . '&error=TRUE');
				}
				else
				{
					if ($_GET['ajax'])
					{
						exit('error');
					}
					
					show_login(_t('用户名或密码不正确'));
				}
				
			}
		}
		else
		{
			if (sizeof($_POST) > 0)
			{
				if ($_POST['bymobile'] == 'TRUE')
				{
					header('Location: ' . BASE_URL . 'm/?act=login&username=' . urlencode($_POST['username']) . '&error=TRUE');
				}
				else
				{
					show_login(_t('请输入用户名与密码登录'));
				}
			}
			else
			{
				show_login();
			}
		}
	break;

	case 'logout':
		Helper::BakeCookie('username', '');
		Helper::BakeCookie('password', '');
		
		if ($_SERVER['HTTP_REFERER'])
		{
			redirect($_SERVER['HTTP_REFERER']);
		}
		else
		{
			redirect(BASE_URL);
		}
	break;
	
	case 'save':
		if ($is_guest)
		{
			if ($_POST['byiphone'])
			{
				exit('show_login');
			}
			else if ($_POST['bymobile'])
			{
				header('Location: ' . BASE_URL . 'm/?act=login');
			}
			else
			{
				show_login();
			}
		}
		
		if ($_POST['message'])
		{
			if ($_POST['byiphone'])
			{
				$from = 'iPhone';
			}
			else if ($_POST['bymobile'])
			{
				$from = 'Mobile';
			}
			else
			{
				$from = 'Web';
			}
			
			$db->insert('entry', array(
				'prefix' => intval($_POST['prefix']),
				'content' => Format::Safe($_POST['message']),
				'time' => TIMENOW,
				'from' => $from,
				'userid' => $User['id']
			));
			
			$entryid = $db->insert_id();
			
			if ($_FILES['picture']['name'])
			{
				$pictureid = upload_picture($_FILES['picture'], $entryid);
			}
			
			if ($sync['api']['publish'] == 'true')
			{
				api_sync(Format::Safe($_POST['message'], TRUE), get_picture_url($pictureid, 'o'));
			}
			
			if ($_POST['wp_sync'] == 'true' AND $_POST['wp_title'] AND WP_ENABLED == TRUE)
			{
				if ($pictureid)
				{
					$_POST['message'] .= '<p class="image"><a href="' . get_picture_url($pictureid, 'o') . '" target="_blank"><img src="' . get_picture_url($pictureid, 'm') . '" alt="" /></a></p>';
				}
				
				wp_post(WP_URL, WP_USERNAME, WP_PASSWORD, $_POST['wp_title'], $_POST['message'], WP_CATEGORY_ID);
			}
		}
		
		if ($_POST['byiphone'])
		{
			exit('sucess');
		}
		else if ($_SERVER['HTTP_REFERER'] AND $_POST['bymobile'] == TRUE)
		{
			redirect($_SERVER['HTTP_REFERER']);
		}
		else
		{
			redirect(BASE_URL);
		}
	break;
	
	case 'edit':
		Helper::NoCacheHeader();
		
		$entry = $db->query("SELECT * FROM entry WHERE id = " . intval($_GET['id']))->row_array();
		
		if ($is_guest OR ($User['id'] > 1 AND $entry['userid'] != $User['id']))
		{
			echo 'authorizeerror';
			exit;
		}
		
		if ($_POST['message'] AND intval($_GET['id']) > 0)
		{
			$db->update('entry', array(
				'prefix' => intval($_POST['prefix']),
				'content' => Format::Safe($_POST['message'])
			), array('id' => intval($_GET['id'])));
		}
		
		$entry['content'] = $_POST['message'];
		$entry['reply'] = $db->query("SELECT COUNT(*) AS count FROM reply WHERE entryid = " . intval($entry['id']))->row_array();
		$entry['picture'] = $db->query("SELECT * FROM picture WHERE entryid = " . $entry['id'])->row_array();
		
		$template = new Template('ajax_entry', NULL, 'ajax_entry');
	break;
	
	case 'users':
		if ($is_guest OR $User['id'] != 1)
		{
			show_login();
		}
		
		if ($_GET['do'] == 'add' AND $_POST['username'] AND $_POST['password'])
		{
			$check = $db->query("SELECT id FROM user WHERE username = '" . Format::Safe($_POST['username'], TRUE) . "'")->row_array();
			
			if ($check['id'])
			{
				Helper::PrintJavaScript('alert(\'' . _t('已经存在同名用户.') . '\'); window.location = \'' . $_SERVER['HTTP_REFERER'] . '\'');
			}
			
			$db->insert('user', array(
				'username' => Format::Safe($_POST['username'], TRUE),
				'password' => Format::Safe(md5($_POST['password']), TRUE)
			));
			
			redirect(BASE_URL . '?act=users');
		}
		else if ($_GET['do'] == 'delete' AND intval($_GET['id']) > 1)
		{
			$db->query("DELETE FROM user WHERE id = " . intval($_GET['id']));
			$db->query("DELETE FROM entry WHERE userid = " . intval($_GET['id']));
			
			redirect(BASE_URL . '?act=users');
		}
		
		$users = $db->query("SELECT user.*, (SELECT COUNT(*) AS count FROM entry WHERE userid = user.id LIMIT 1) AS entrycount FROM user WHERE id > 1 ORDER BY id DESC")->result_array();
		
		$title = SITE_NAME . ' - ' . _t('用户');

		$template = new Template('users', NULL, 'users');
	break;
	
	case 'prefix':
		if ($is_guest OR $User['id'] != 1)
		{
			show_login();
		}
		
		if ($_GET['do'] == 'add' AND $_POST['title'] AND $_POST['class'])
		{
			$db->insert('prefix', array(
				'title' => Format::Safe($_POST['title'], TRUE),
				'class' => Format::Safe($_POST['class'], TRUE)
			));
			
			redirect(BASE_URL . '?act=prefix');
		}
		else if ($_GET['do'] == 'delete' AND intval($_GET['id']) > 0)
		{
			$db->query("DELETE FROM prefix WHERE id = " . intval($_GET['id']));
			
			$entry = $db->query("SELECT id FROM entry WHERE prefix = " . intval($_GET['id']))->result_array();
			
			foreach ($entry AS $key => $item)
			{
				$db->query("DELETE FROM entry WHERE id = " . $item['id']);
				$db->query("DELETE FROM reply WHERE entryid = " . $item['id']);	
			}
			
			redirect(BASE_URL . '?act=prefix');
		}
		
		$prefixs = $db->query("SELECT * FROM prefix WHERE id > 1 ORDER BY title ASC")->result_array();
		
		$title = SITE_NAME . ' - ' . _t('谓语');

		$template = new Template('prefix', NULL, 'prefix');
	break;
	
	case 'profile':
		if ($is_guest)
		{
			show_login();
		}
		
		session_start();
		
		if ($sync['api']['oauth_last_key']['oauth_token'])
		{
			$sina_client = new WeiboClient(WB_AKEY, WB_SKEY, $sync['api']['oauth_last_key']['oauth_token'], $sync['api']['oauth_last_key']['oauth_token_secret']);
			
			$sina_profile = $sina_client->verify_credentials();
			
			//print_r($sina_client->home_timeline()); exit;
			//print_r($sync['api']); exit;
		}
		
		if ($_REQUEST['oauth_verifier'])
		{
			$sina_oauth = new WeiboOAuth(WB_AKEY, WB_SKEY, $_SESSION['sina_keys']['oauth_token'], $_SESSION['sina_keys']['oauth_token_secret']);
			$sync['api']['oauth_last_key'] = $sina_oauth->getAccessToken($_REQUEST['oauth_verifier']);
			
			$sina_client = new WeiboClient(WB_AKEY, WB_SKEY, $sync['api']['oauth_last_key']['oauth_token'], $sync['api']['oauth_last_key']['oauth_token_secret']);
			
			$sync['api']['sina_profile'] = $sina_client->verify_credentials();

			$db->update('user', array('sync' => serialize($sync)), array('id' => $Own['id']));
			
			redirect('?act=profile');
		}
		else if ($_GET['do'] == 'update' AND sizeof($_POST) > 0)
		{
			if ($_FILES['avatar']['name'] AND $User['id'] == 1)
			{
				@set_time_limit(0);

				$image = @getimagesize($_FILES['avatar']['tmp_name']);
				
				if (is_array($image))
				{
					Image::Resize($_FILES['avatar']['tmp_name'], 'cache/avatar_' . $Own['id'], 48, 48);
						
					$encoded_avatar = base64_encode(file_get_contents('cache/avatar_' . $Own['id']));
						
					unlink('cache/avatar_' . $Own['id']);
					
					$db->update('user', array('avatar' => $encoded_avatar), array('id' => $Own['id']));
				}
			}

			if ($_POST['password'])
			{
				$db->update('user', array('password' => md5($_POST['password'])), array('id' => $User['id']));
				
				Helper::BakeCookie('password', md5($_POST['password']));
			}
			
			if ($User['id'] == 1)
			{				
				if ($_POST['flickr'] != $flickr['url'])
				{
					$flickr['feed'] = get_flickr_feed_url($_POST['flickr']);
					$flickr['url'] = $_POST['flickr'];
				}
				else if (!$_POST['flickr'])
				{
					$flickr = array();
				}
				
				if ($sync['api']['username'] != $_POST['sync']['api']['username'] OR $sync['api']['type'] != $_POST['sync']['api']['type'])
				{
					unset($_POST['sync']['api']['since']);
				}
				
				if ($_POST['sync']['api']['type'] == 'sina' AND $sync['api']['oauth_last_key'])
				{
					$_POST['sync']['api']['sina_profile'] = $sync['api']['sina_profile'];
					$_POST['sync']['api']['oauth_last_key'] = $sync['api']['oauth_last_key'];
				}
				
				$update_data = array(
					'about' => Format::Safe($_POST['about']),
					'lastfm' => Format::Safe($_POST['lastfm']),
					'sync' => serialize($_POST['sync']),
					'meta_keywords' => Format::Safe($_POST['meta_keywords']),
					'flickr' => serialize($flickr),
					'skin' => Format::Safe($_POST['skin'], TRUE),
					'options' => serialize($_POST['options'])
				);

				$db->update('user', $update_data, array('id' => $Own['id']));
				
				if ($_POST['wp_enabled'] == 'enabled')
				{
					$wordpress_config = "<?php\r\ndefine(WP_ENABLED, TRUE);\r\ndefine(WP_URL, '" . Format::Safe($_POST['wp_url'], TRUE) . "');\r\ndefine(WP_USERNAME, '" . Format::Safe($_POST['wp_username'], TRUE) . "');\r\ndefine(WP_PASSWORD, '" . Format::Safe($_POST['wp_password']) . "');\r\ndefine(WP_CATEGORY_ID, " . intval($_POST['wp_category_id']) . ");";
				}
				else
				{
					$wordpress_config = "<?php\r\ndefine(WP_ENABLED, FALSE);\r\ndefine(WP_URL, '');\r\ndefine(WP_USERNAME, '');\r\ndefine(WP_PASSWORD, '');\r\ndefine(WP_CATEGORY_ID, 0);";
				}
				
				file_put_contents('config.wordpress.php', $wordpress_config);
				
				if (isset($_POST['language']))
				{
					$lang_config = "<?php\r\ndefine(PG_LANG, '" . Format::Safe($_POST['language'], TRUE) . "');";
					
					file_put_contents('config.language.php', $lang_config);
				}
				
			}
			
			if ($_POST['do_sina_login'])
			{
				$sina_oauth = new WeiboOAuth(WB_AKEY, WB_SKEY);

				$sina_keys = $sina_oauth->getRequestToken();
				$sina_auth_url = $sina_oauth->getAuthorizeURL($sina_keys['oauth_token'], false, $_POST['sina_call_url']);

				$_SESSION['sina_keys'] = $sina_keys;
				
				redirect($sina_auth_url);
			}
			else
			{
				redirect($_SERVER['HTTP_REFERER']);
			}
		}
		
		if ($User['id'] == 1)
		{
			$skins = opendir('./css/skin/');

			while (($filename = readdir($skins)) !== false)
			{
			    if ($filename != '.' AND $filename != '..' AND Helper::GetFileExt($filename) == 'css')
			    {
			    	$filename = str_ireplace('.css', '', $filename);

			    	$title = strtoupper(substr($filename, 0, 1)) . substr($filename, 1);

			    	if ($filename == $Own['skin'])
			    	{
			    		$skin_chooser .= '<option value="' . $filename . '" selected="selected">' . $title . '</option>';
			    	}
			    	else
			    	{
			    		$skin_chooser .= '<option value="' . $filename . '">' . $title . '</option>';
			    	}
			    }
			}
			
			$langs = opendir('./language/');
			
			$lang_chooser = '<option value="">Chinese</option>';

			while (($filename = readdir($langs)) !== false)
			{
			    if ($filename != '.' AND $filename != '..' AND Helper::GetFileExt($filename) == 'php')
			    {
			    	$filename = str_ireplace('.php', '', $filename);

			    	$title = strtoupper(substr($filename, 0, 1)) . substr($filename, 1);
					
			    	if ($filename == PG_LANG)
			    	{
			    		$lang_chooser .= '<option value="' . $filename . '" selected="selected">' . $title . '</option>';
			    	}
			    	else
			    	{
			    		$lang_chooser .= '<option value="' . $filename . '">' . $title . '</option>';
			    	}
			    }
			}
			
			$twitter_server_status = TRUE;
			//$twitter_server_status = @fsockopen('twitter.com', 80, $errno, $errstr, 3);
		}
		
		$template = new Template('profile', NULL, 'profile');
		
		$title = SITE_NAME . ' - ' . _t('资料');
	break;
	
	case 'getavatar':
		header('Content-Type: image/jpeg');
		echo base64_decode($Own['avatar']);
		exit;
	break;
	
	case 'rss':
		redirect(BASE_URL . 'rss.xml', 'location', 301);
	break;
	
	case 'install':
		if (!$_install_check)
		{
			if ($_POST['step'] == 'check' AND $_GET['ajax'])
			{
				$ready_install = true;

				$config_wordpress_writable = is_really_writable('config.wordpress.php');
				$config_language_writable = is_really_writable('config.language.php');
				$cache_writable = is_really_writable('cache/');
				$uploads_writable = is_really_writable('uploads/');
				$music_json_writable = is_really_writable('music.json');
				$photos_json_writable = is_really_writable('photos.json');
				$rss_xml_writable = is_really_writable('rss.xml');
				

				if (function_exists('json_decode'))
				{
					$json_function = true;
				}
				
				if (!$config_wordpress_writable OR !$config_language_writable OR !$cache_writable OR !$uploads_writable OR !$music_json_writable OR !$photos_json_writable OR !$rss_xml_writable OR !$json_function)
				{
					$ready_install = false;
				}
				
				if ($ready_install)
				{
					echo 'success';
				}
				else
				{
					echo '<br /><b>' . _t('发现如下错误, 安装无法继续') . ':</b><br /><br />';
					
					if (!$config_wordpress_writable)
					{
						echo 'config.wordpress.php ' . _t('文件不可写入, 请设置权限为 777') . '<br />';
					}
					
					if (!$config_language_writable)
					{
						echo 'config.language.php ' . _t('文件不可写入, 请设置权限为 777') . '<br />';
					}
					
					if (!$cache_writable)
					{
						echo 'cache ' . _t('目录不可写入, 请设置权限为 777') . '<br />';
					}
					
					if (!$uploads_writable)
					{
						echo 'uploads ' . _t('目录不可写入, 请设置权限为 777') . '<br />';
					}
					
					if (!$music_json_writable)
					{
						echo 'music.json ' . _t('文件不可写入, 请设置权限为 777') . '<br />';
					}
					
					if (!$photos_json_writable)
					{
						echo 'photos.json ' . _t('文件不可写入, 请设置权限为 777') . '<br />';
					}
					
					if (!$rss_xml_writable)
					{
						echo 'rss.xml ' . _t('文件不可写入, 请设置权限为 777') . '<br />';
					}
					
					if (!$json_function)
					{
						echo _t('PHP JSON 扩展未启用, 请修改 PHP 配置') . '<br />';
					}
					
					echo '<p align="center"><a href="#" onclick="showInstall(); return false;" style="color:red">' . _t('强制安装 (一些功能可能不能正常使用)') . '</a></p>';
				}
				
				exit;
			}
			
			if ($_POST['username'] AND $_POST['password'] OR $_GET['ajax'])
			{
				if (file_exists('sql/install/database_' . str_replace('.', '', $_GET['PG_LANG']) . '.sql'))
				{
					$sql_file = 'sql/install/database_' . str_replace('.', '', $_GET['PG_LANG']) . '.sql';
					
					$lang_config = "<?php\r\ndefine(PG_LANG, '" . Format::Safe(str_replace('.', '', $_GET['PG_LANG']), TRUE) . "');";
					
					@file_put_contents('config.language.php', $lang_config);
				}
				else
				{
					$sql_file = 'sql/install/database.sql';
				}
				
				$database = explode(";\n", file_get_contents($sql_file));
				
				foreach ($database AS $_sql)
				{
					$query = trim(str_replace(array("\n", "\t"), '', $_sql));
					
					if ($query)
					{
						$db->query($query);
					}
				}
				
				$db->insert('user', array(
					'username' => Format::Safe($_POST['username']),
					'password' => md5($_POST['password']),
					'avatar' => 'iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAIAAADYYG7QAAALFElEQVRYhXVZaX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nO19btzyaZQRkM7glrX8tK6Xo9n03atXmweHBx/c3NreGgz66eSqscN7ee9ms/L0ZHTy8uX45MRdjjWvuFzEqkEDpXNxpDOlPK/81+aOT53TSz6RE8mH2iQwLAOALVAU7PbYH3SGK8PNrcFwpdvrWmuCg53zi2o+u7ycXpy72VTzuRYL1PN4xhgOl0LZFEAYmIb9hNPq323u1fEJecUzSEnWoDAAUHssnY+ZEzmaYWFlLIuC1oIWTJt4wTt5B+fgajgHhYP4mDRhbkkaxaKZUhgxZO0rtBFDdNJpfmHoPH0cECkJ8qgF1VwumiaEprNTkXamJt7shwzN3BhaB4FIjJFAhHMOLWPg1AYf0Jy2BtMimJWhmQlmM8gC14S0lGuOBpm7aVNL8xtecj5Elk7h0UxQrlxXuInySmogyvpkM1oSGDOLhOBDVSrya9EtkiCRSyd6tclElhjDwcgSGrbTFMVmLd8xrzf/UdQwZKZKUCjLylUV8bDWh2MtgIRvkbK2lc3O74fjx9hJ5jHhOSV2llvs/wF2v4BLgwirvgAAAABJRU5ErkJggg==',
					'administrator' => 1,
					'about' => _t('欢迎使用 PageCookery 的产品.'),
					'rpchash' => md5($_POST['username']. $_POST['password'] . microtime())
				));

				$db->insert('entry', array(
					'prefix' => 1,
					'content' => _t('欢迎使用 PageCookery 的产品, 这是一篇测试日志, 双击我可编辑.'),
					'time' => TIMENOW,
					'from' => 'PageCookery'
				));

				if ($_GET['ajax'])
				{
					exit(BASE_URL);
				}
				
				redirect(BASE_URL);
			}
			
			$langs = opendir('./language/');
			
			$lang_chooser = '<option value="">Chinese</option>';

			while (($filename = readdir($langs)) !== false)
			{
			    if ($filename != '.' AND $filename != '..' AND Helper::GetFileExt($filename) == 'php')
			    {
			    	$filename = str_ireplace('.php', '', $filename);

			    	$title = strtoupper(substr($filename, 0, 1)) . substr($filename, 1);
					
			    	if ($filename == PG_LANG)
			    	{
			    		$lang_chooser .= '<option value="' . $filename . '" selected="selected">' . $title . '</option>';
			    	}
			    	else
			    	{
			    		$lang_chooser .= '<option value="' . $filename . '">' . $title . '</option>';
			    	}
			    }
			}
			
			$title = SITE_NAME . ' - Install';

			$template = new Template('install', NULL, 'install');
		}
		else
		{
			redirect(BASE_URL);
		}
	break;
}

if (is_object($template))
{
	//eval($template->Parse());
	include $template->Parse();
}

