00001 <?php
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013 class FetchTweetsCommand extends CommandChain {
00014 protected function do_execute() {
00015 $ret = new Status();
00016 $params = $this->get_params();
00017 $twitter_user = Arr::get_item($params, 'user', false);
00018 $policy = Arr::get_item($params, 'html_policy', 0);
00019 $data = $this->fetch_tweets($twitter_user, $ret);
00020 if ($ret->is_ok()) {
00021 $ret->merge($this->insert_tweets($data, $policy));
00022 if ($ret->is_error()) {
00023 $ret->append('Inserting tweets of "' . $twitter_user . '" failed');
00024 }
00025 }
00026 return $ret;
00027 }
00028
00029
00030
00031
00032 protected function fetch_tweets($twitter_user, Status $err) {
00033 $data = array();
00034 if (empty($twitter_user)) {
00035 $ret->merge('Empty twitter user when fetching tweets');
00036 }
00037 else {
00038 $url = 'http://twitter.com/statuses/user_timeline/' . String::plain_ascii($twitter_user) . '.json';
00039
00040 Load::components('httprequest');
00041 $json = HttpRequest::get_content($url, $err);
00042 if ($err->is_ok()) {
00043 $data = ConverterFactory::decode($json, CONVERTER_JSON);
00044 }
00045 }
00046 return $data;
00047 }
00048
00049
00050
00051
00052 protected function insert_tweets($data, $policy) {
00053 $ret = new Status();
00054 if (is_array($data)) {
00055 Load::models('tweets');
00056 foreach ($data as $s) {
00057 $ret->merge($this->insert_tweet($s, $policy));
00058 if ($ret->is_error()) {
00059 break;
00060 }
00061 }
00062 }
00063 else {
00064 $ret->merge('Twitter Fetch returned no valid data!');
00065 }
00066 return $ret;
00067 }
00068
00069
00070
00071
00072 protected function insert_tweet($s, $policy) {
00073 $ret = new Status();
00074 $tweet = new DAOTweets();
00075 $tweet->id_twitter = $s->id;
00076
00077 $tweet->find(DataObjectBase::AUTOFETCH);
00078
00079 $message = ConverterFactory::decode($s->text, CONVERTER_TWITTER);
00080 $tweet->message = $message;
00081 $tweet->message_html = ConverterFactory::encode($message, CONVERTER_TWITTER, $policy);
00082 $title = String::substr_word($message, 0, 120);
00083 if ($title == '') {
00084 $title = String::substr($message, 0, 120);
00085 }
00086 $tweet->title = $title;
00087
00088 $tweet->username = $s->user->screen_name;
00089 $tweet->creationdate = GyroDate::datetime($s->created_at);
00090
00091 $ret->merge($tweet->validate());
00092 if ($ret->is_ok()) {
00093 if ($tweet->id) {
00094 $ret->merge($tweet->update());
00095 }
00096 else {
00097 $ret->merge($tweet->insert());
00098 }
00099 }
00100 return $ret;
00101 }
00102 }