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

function show_login($message = NULL)
{
	global $PG_LANG;
	
	if (!defined('LOGIN_REFERER'))
	{
		define('LOGIN_REFERER', '');
	}
	
	$title = SITE_NAME . ' - ' . _t('登录');
	
	$template = new Template('login', NULL, 'login');
	
	include $template->Parse();
}

function get_username_by_id($userid)
{
	global $db;
	
	$user = $db->query("SELECT username FROM user WHERE id = " . intval($userid))->row_array();
	
	return $user['username'];
}

function get_prefix($pid)
{
	global $db;
	
	if (intval($pid) == 0)
	{
		$pid = 1;
	}
	
	$prefix = $db->query("SELECT * FROM prefix WHERE id = " . intval($pid))->row_array();
	
	return '<span id="prefix" class="' . $prefix['class'] . '">' . $prefix['title'] . '</span>';
}

function api_sync($message, $picture = false)
{
	global $sync;
	
	switch ($sync['api']['type'])
	{
		case 'digu':
			$api_host = 'api.minicloud.com.cn';
			
			$curl = curl_init();

			$curl_auth = $sync['api']['username'] . ':' . $sync['api']['password'];

			$post_data = 'content=' . urlencode($message) . '&source=PageCookery';

			curl_setopt($curl, CURLOPT_URL, 'http://' . $api_host . '/statuses/update.json');
			curl_setopt($curl, CURLOPT_HEADER, false);

			curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
			curl_setopt($curl, CURLOPT_USERPWD, $curl_auth);

			curl_setopt($curl, CURLOPT_POST, true);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);

			$json = curl_exec($curl);

			curl_close($curl);
		break;
		
		case 'sina':
			$sina_client = new WeiboClient(WB_AKEY, WB_SKEY, $sync['api']['oauth_last_key']['oauth_token'], $sync['api']['oauth_last_key']['oauth_token_secret']);
			
			if ($picture)
			{
				$sina_client->upload($message, $picture);
			}
			else
			{
				$sina_client->update($message);
			}
		break;
	}
}

function api_get_status($since = 0)
{
	global $sync;
	
	switch ($sync['api']['type'])
	{
		case 'digu':
			$api_host = 'api.minicloud.com.cn';
			
			$curl = curl_init();
	
			$curl_auth = $sync['api']['username'] . ':' . $sync['api']['password'];
	
			if ($since == 0)
			{
				$since = $sync['api']['since'];
			}
	
			curl_setopt($curl, CURLOPT_URL, 'http://' . $api_host . '/statuses/user_timeline.json?userIdOrName=' . urlencode($sync['api']['username']));
	
			curl_setopt($curl, CURLOPT_HEADER, false);
	
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
			curl_setopt($curl, CURLOPT_USERPWD, $curl_auth);
	
			$json = curl_exec($curl);
	
			curl_close($curl);
		break;
		
		case 'sina':
			$sina_client = new WeiboClient(WB_AKEY, WB_SKEY, $sync['api']['oauth_last_key']['oauth_token'], $sync['api']['oauth_last_key']['oauth_token_secret']);
			
			$json = $sina_client->user_timeline(1, 200);
		break;
	}
	
	return $json;
}

function api_test()
{
	$json = api_get_status(1);
	
	if (!$json)
	{
		return false;
	}
	
	return true;
}

function api_import()
{
	global $sync, $db, $Own;
	
	$json = api_get_status();
	
	if (!is_array($json))
	{
		$messages = json_decode($json, true);
	}
	else
	{
		$messages = $json;
	}
	
	$i = 1;
	
	foreach ($messages AS $key => $message)
	{
		if ($i == 1)
		{
			$sync['api']['since'] = strtotime($message['created_at']);

			$db->update('user', array('sync' => Format::Safe(serialize($sync))), array('id' => $Own['id']));
		}
		
		switch ($sync['api']['type'])
		{
			case 'digu':
				if (strip_tags($message['source']) != 'API' AND strip_tags($message['source']) != 'PageCookery')
				{				
					if ($message['source'] != '网站')
					{
						$message['source'] = strtoupper($message['source']);
					}
					else
					{
						$message['source'] = 'Digu.Com';
					}
					
					$created_at = strtotime($message['created_at']) - 100;
					
					unset($check);
					
					$check = $db->query("SELECT id FROM entry WHERE content = '" . nl2br(Format::Safe($message['text'], true)) . "' LIMIT 1")->row_array();
					
					if (!$check['id'] AND $created_at > 0 AND substr($message['text'], 0, 1) != '@')
					{
						$db->insert('entry', array(
							'prefix' => 1,
							'content' => nl2br(Format::Safe($message['text'], true)),
							'time' => $created_at,
							'from' => Format::Safe($message['source'], ture)
						));
					}
				}
			break;
			
			case 'sina':
				if (!strstr(strtolower($message['source']), 'pagecookery') AND !strstr($message['text'], '@'))
				{
					$created_at = strtotime($message['created_at']);
					
					$content = nl2br(Format::Safe($message['text'], true));
					
					if ($message['thumbnail_pic'])
					{
						$content .= "\r\n<br />[url=" . $message['original_pic'] . '][img]' . $message['thumbnail_pic'] . '[/img][/url]';
					}
					
					$check = $db->query("SELECT id FROM entry WHERE content = '" . $content . "' LIMIT 1")->row_array();
					
					if (!$check['id'] AND $created_at > 0)
					{						
						$db->insert('entry', array(
							'prefix' => 1,
							'content' => $content,
							'time' => $created_at,
							'from' => '[Sina]' . Format::Safe(strip_tags($message['source']), ture)
						));
					}
				}
			break;
		}
		
		$i++;
	}
}

function get_flickr_feed_url($url)
{
	$data = file_get_contents($url);
	
	preg_match_all('#data-photo-owner="(.*)"#siU', $data, $matchs);
	
	if ($matchs[1][0])
	{
		return 'http://api.flickr.com/services/feeds/photos_public.gne?id=' . $matchs[1][0] . '&lang=zh-hk&format=json';
	}
	
	return false;
}

function get_twitter_feed_url($url)
{
	$data = file_get_contents($url);
	
	preg_match_all('/\<link rel="alternate" href="(.+?).rss"/i', $data, $matchs);
	
	if ($matchs[1][0])
	{
		return $matchs[1][0] . '.rss';
	}
	
	return false;
}

function get_picture_url($pictureid, $size = 'm', $location = false)
{
	global $db;
	
	$picture = $db->query("SELECT * FROM picture WHERE id = " . intval($pictureid))->row_array();
	
	if ($picture['id'])
	{
		return BASE_URL . 'uploads/' . gmdate('Y/m/d/', $picture['time']) . $size . '_' . $picture['location'];
	}
	
	return false;
}

function upload_picture($file = array(), $entryid)
{
	global $db;
	
	$upload_dir = 'uploads/' . gmdate('Y/m/d/', time());
	
	$return = Upload::Save($file, $upload_dir, 'jpg,gif,png');
	
	switch ($return)
	{
		case -1:
			Helper::PrintJavaScript("alert('只接受下列文件类型: jpg,gif,png, 请返回重新上传.'); window.history.go(-1);");
		break;
		
		case -2:
			Helper::PrintJavaScript("alert('文件上传失败,这是服务器的原因,请与管理员联系.'); window.history.go(-1);");
		break;
		
		default:
			rename($upload_dir . $return, $upload_dir . 'o_' . $return);
			
			$imageinfo = @getimagesize($upload_dir . 'o_' . $return);
			
			if ($imageinfo[0] <= 640)
			{
				copy($upload_dir . 'o_' . $return, $upload_dir . 'm_' . $return);
			}
			else
			{
				Image::Resize($upload_dir . 'o_' . $return, $upload_dir . 'm_' . $return, 640, $imageinfo[1] * 640 / $imageinfo[0], 90);
			}
			
			$db->insert('picture', array(
				'filename' => Format::Safe($file['name']),
				'location' => $return,
				'entryid' =>  intval($entryid),
				'time' => time()
			));
			
			return $db->insert_id();
		break;
	}
}

function fetch_follow($blogurl, $followid)
{
	global $db;
	
	$entrys = @json_decode(file_get_contents($blogurl . 'httprequest.php?act=following'), TRUE);
	
	if (!is_array($entrys))
	{
		return false;
	}
	
	foreach ($entrys AS $key => $entry)
	{
		$check = $db->query("SELECT * FROM followlog WHERE followid = " . intval($followid) . " AND time = " . intval($entry['time']))->row_array();
		
		if (!$check['id'])
		{
			$message = strip_tags(Format::Safe(str_ireplace(array('<br />', '<br/>', '<br>'), "\n", str_replace(array("\r", "\n"), '', $entry['message']))));
			
			if (trim($message) != '')
			{
				$db->insert('followlog', array(
					'followid' => intval($followid),
					'entryid' => intval($entry['entryid']),
					'message' => $message,
					'from' => strip_tags($entry['from']),
					'time' => intval($entry['time']),
					'picture' => $entry['picture']
				));

				$db->update('follow', array('lastupdate' => intval($entry['time'])), array('id' => intval($followid)));
			}
		}
	}
}

function get_recent_tracks()
{
	$recent_tracks = json_decode(trim(str_replace("\'", "'", file_get_contents('music.json'))), true);
	
	if (is_array($recent_tracks['recenttracks']['track']))
	{
		if ($recent_tracks['recenttracks']['track'][0]['@attr']['nowplaying'] == 'true')
		{
			return array(
				//'url' => $track['url'],
				'url' => 'http://cn.last.fm/user/' . urlencode($Own['lastfm']),
				'music' => $recent_tracks['recenttracks']['track'][0]['name'] . ' - ' . $recent_tracks['recenttracks']['track'][0]['artist']['#text']
			);
		}
	}
	else
	{
		@unlink(str_replace(basename($_SERVER['PHP_SELF']), '', __FILE__) . 'cache/last_fm_update_tag.db');
		
		return array();
	}
}

function http_post($url, $post = null, $cookie_string = '')  
{ 	
    $context = array();  

    if (is_array($post))  
    {  
        ksort($post);  

        $context['http'] = array  
        (  
            'method' => 'POST',  
			'header' => "User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; zh-cn) AppleWebKit/531.22.7 (KHTML, like Gecko) Version/4.0.5 Safari/531.22.7\r\nAccept:*/*\r\nCookie: " . $cookie_string . "\r\nConnection: keep-alive\r\n\r\n",
            'content' => http_build_query($post, '', '&'),  
        );  
    }  

    return file_get_contents($url, false, stream_context_create($context));  
}

function wp_post($wp_url, $username, $password, $title, $content, $categoryid)
{
	if (substr($wp_url, 0, 7) != 'http://')
	{
		$wp_url = 'http://' . $wp_url;
	}
	
	$context['http'] = array  
	(  
	    'method' => 'POST',  
		'header' => "User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; zh-cn) AppleWebKit/531.22.7 (KHTML, like Gecko) Version/4.0.5 Safari/531.22.7\r\nAccept: */*\r\nConnection: keep-alive\r\n\r\n",
	    'content' => http_build_query(array(
			'log' => $username,
			'pwd' => $password,
			'testcookie' => 1
		), '', '&')
	);

	file_get_contents($wp_url . 'wp-login.php', false, stream_context_create($context));

	preg_match_all("/Set-Cookie:(.*?)\r\n/", implode("\r\n", $http_response_header), $cookies);
	
	foreach ($cookies[1] AS $key => $cookie)
	{
		$_cookie = explode(';', $cookie);

		$cookie_string .= trim(str_replace(array("\r", "\n"), '', $_cookie[0])) . '; ';
	}

	$cookie_string = substr($cookie_string, 0, -2);

	$post = array
	(
		'_wpnonce' => md5(time()),
	    'user_ID' => '1',
	    'action' => 'post',
	    'originalaction' => 'post',
	    'post_type' => 'post',
	    'original_post_status' => 'draft',
	    'hidden_post_status' => 'draft',
	    'post_status' => 'draft',
	    'hidden_post_visibility' => 'public',
	    'visibility' => 'public',
	    'mm' => gmdate('m', time() + 8 * 3600),
	    'jj' => gmdate('d', time() + 8 * 3600),
	    'aa' => gmdate('Y', time() + 8 * 3600),
	    'hh' => gmdate('H', time() + 8 * 3600),
	    'mn' => gmdate('i', time() + 8 * 3600),
	    'ss' => gmdate('s', time() + 8 * 3600),
	    'hidden_mm' => gmdate('m', time() + 8 * 3600),
	    'cur_mm' => gmdate('m', time() + 8 * 3600),
	    'hidden_jj' => gmdate('d', time() + 8 * 3600),
	    'cur_jj' => gmdate('d', time() + 8 * 3600),
	    'hidden_aa' => gmdate('Y', time() + 8 * 3600),
	    'cur_aa' => gmdate('Y', time() + 8 * 3600),
	    'hidden_hh' => gmdate('d', time() + 8 * 3600),
	    'cur_hh' => gmdate('H', time() + 8 * 3600),
	    'hidden_mn' => gmdate('i', time() + 8 * 3600),
	    'cur_mn' => gmdate('i', time() + 8 * 3600),
	    'original_publish' => 'Publish',
	    'publish' => 'Publish',

	    'post_category' => array
	     (
	        '0' => $categoryid,
	     ),

	    'post_title' => $title,
	    'content' => $content,
	    'advanced_view' => '1',
	    'comment_status' => 'open',
		'_wp_http_referer' => $wp_url . 'post-new.php'
	);

	http_post($wp_url . 'wp-admin/post.php', $post, $cookie_string);
}

function _t($lang_string)
{
	global $PG_LANG;
	
	if (isset($PG_LANG[$lang_string]))
	{
		return $PG_LANG[$lang_string];
	}
	
	return $lang_string;
}