<?php
// $Id: sina_open.pages.inc,v 1.5 2011/02/11 03:52:44 eastcn Exp $

/**
 * 获取授权令牌并在 dd 可登录
 */
function sina_open_page_t_login() {
  global $user;
  
  if ($user->uid) {
    if ($tok = sina_open_get_access_token($user->uid)){
      
      if ($result = sina_open_t_set_request('http://api.t.sina.com.cn/account/verify_credentials.json')) {
        if ($result->code == 200) {
          dd_set_message('授权成功');
          dd_goto('user/'.$user->uid);
        }
      }
      
    }
  }
  
  if ($_GET['op'] == 'validate') {
		
    if ($tok = sina_open_t_access_token()) {
      
      _sina_open_t_login($tok);
      
    } else {
      
      dd_set_message('授权未通过验证', 'error');
      dd_goto('user/login');
      
    }
    
    exit;
  }
  
  if ($to_url = sina_open_t_login_url()) {
    dd_goto($to_url);
  } else {
    dd_set_message('新浪服务器未响应，无法验证', 'error');
    dd_goto('user/login');
  }
}

/**
 * 让用户登录，若用户不存在，则创建新用户并登录.
 * 若用户已登录，则将新浪微博帐号绑定
 * 必须先获取访问令牌
 * @param (object) $tok
 *  访问令牌
 */
function _sina_open_t_login($tok = NULL) {
  global $user;
	
  $values = array();
  if (isset($tok)) {
    $values['oauth_access_token_key'] = $tok->key;
    $values['oauth_access_token_secret'] = $tok->secret;
    if ($tok->verifier) {
      $values['oauth_verifier'] = $tok->verifier;
    }
  }
  
  if ($result = sina_open_t_set_request('http://api.t.sina.com.cn/account/verify_credentials.json', $values)) {
    if ($result->code == 200) {
      if ($json = json_decode($result->data)) {
        $authname = $json->name;
        $sina_uid = $json->id;
        $uid = db_query("SELECT uid FROM {sina_open_user} WHERE sina_name = ?", array($authname), array('return' => 'column'));
        if ($ac = $uid) {
          $account = user_load($ac);
        }
        
        if (isset($account->uid)) {
          // 该微博帐号已经存在
          if ($user->uid) {
            
            if ($user->uid != $account->uid) {
              dd_set_message('该帐号已与其它用户绑定', 'error');
              dd_goto('user/'.$user->uid);
            }
            
          } else {
            user_login($account, 'sina_open');
          }
          
          if (isset($tok)) {
            db_query("UPDATE {sina_open_user} SET sina_uid = ?, token = ? WHERE uid = ?",
            array($sina_uid, serialize($tok), $account->uid));
          }
          
        } else if ($user->uid > 0) {
          // 绑定到当前用户
          if (db_query('SELECT uid FROM {sina_open_user} WHERE uid = ?', array($user->uid), array('return' => 'column'))) {
            dd_set_message('您已经绑定了一个新浪微博帐号', 'error');
            dd_goto('user/'.$user->uid);
          } else {
            $account = $user;
            db_query("INSERT INTO {sina_open_user} (uid, sina_uid, sina_name, token, config) VALUES (?, ?, ?, ?, '')",
            array($user->uid, $sina_uid, $authname, serialize($tok)));
          }
          
        } else {
          // 新注册一个用户
          
          // 检查用户名是否存在，若存在，则选择一个新的用户名。
          $new_name = $authname;
          $i = 1;
          while ($uid = db_query("SELECT uid FROM {users} WHERE name = ?", array($new_name), array('return' => 'column'))) {
            $new_name = $authname.'_'.$i;
            ++$i;
          }
          
          $pass = user_password();
					$ac = new stdClass;
				  $ac->name = $new_name;
				  $ac->mail = $pass.'@sina.cn';// 默认使用新浪微博的域名做为邮件
				  $ac->pass  = $pass;

          if (!$account = user_save($ac)) {
            dd_set_message('无法注册帐号', 'error');
            dd_goto('user/register');
          }
          
          db_query("INSERT INTO {sina_open_user} (uid, sina_uid, sina_name, token, config) VALUES (?, ?, ?, ?, '')",
          array($account->uid, $sina_uid, $authname, serialize($tok)));
          dd_set_message('已为你成功创建帐号，随机密码：'.$pass.'，如果你需要从本站直接登录，请记住此密码或'.l('立即修改', 'user/'.$account->uid.'/edit'));
          user_login($account);
        }
        
        if (isset($_REQUEST['redirect']) && $_REQUEST['redirect']) {
          dd_goto($_REQUEST['redirect']);
        } else {
         dd_goto('user/'.$account->uid);
        }
      }
    }
  }
  
  dd_set_message('无法登录，请重试', 'error');
  dd_goto('user/login');
}
/**
 * Generate a random alphanumeric password.
 */
function user_password($length = 10) {
  // This variable contains the list of allowable characters for the
  // password. Note that the number 0 and the letter 'O' have been
  // removed to avoid confusion between the two. The same is true
  // of 'I', 1, and 'l'.
  $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';

  // Zero-based count of characters in the allowable list:
  $len = strlen($allowable_characters) - 1;

  // Declare the password as a blank string.
  $pass = '';

  // Loop the number of times specified by $length.
  for ($i = 0; $i < $length; $i++) {

    // Each iteration, pick a random character from the
    // allowable string and append it to the password:
    $pass .= $allowable_characters[mt_rand(0, $len)];
  }

  return $pass;
}
/**
 * 微博相关设置
 * @param (object) $ac
 */
function sina_open_page_config($uid) {
  $output = '';
	
  $data = db_query('SELECT uid, token, sina_name FROM {sina_open_user} WHERE uid = ?', array($uid), array('return' => 'one'));
  if ($data->uid) {
    $items[] = '您绑定的帐号：'. $data->sina_name
    . l('解除绑定', 'user/'.$uid.'/sina_open/remove', array('attributes' => array('class' => 'sina_open_user_remove confirm')));
    
    if ($GLOBALS['user']->uid == $uid) {
      $items[] = dd_get_form('sina_open_set_tweet_form', $uid);
    }
  } else {
    $items[] = '您还没有绑定帐号，' . l('立即绑定', 'sina_open/t_login');
  }
  
  $output = theme('item_list', $items, '新浪微博', 'ul', array('id' => 'sina_open_page_config'));
  
  return $output;
  
  if ($data = sina_open_t_get_info($ac)) {
    
    if ($data->screen_name) {
      $items[] = '您绑定的帐号：'. $data->screen_name;
      $output = theme('item_list', $items);
    }
    
  } else {
    
  }
  
  return $output;
}

/**
 * 解除新浪微博帐号绑定
 * @param (array) $form_state
 * @param (object) $ac
 */
function sina_open_remove_confirm($uid) {
  if ($data = db_query('SELECT uid, token, sina_name FROM {sina_open_user} WHERE uid = ?', array($uid), array('return' => 'one'))) {
    db_query('DELETE FROM {sina_open_user} WHERE uid = ?', array($uid));
		dd_set_message('成功解除绑定');
		$form_state['redirect'] = 'user/'.$uid.'/sina_open/config';
		return;
  } else {
    dd_get_access();
    exit;
  }
}

function sina_open_my_tweets(){
  $content = sina_open_t_set_request('http://api.t.sina.com.cn/statuses/user_timeline.json',
  array('page'=>$_GET['page']));
  $data = json_decode($content->data);
  print_r($data);exit();
  return 'sina_open_my_tweets';
}