twitter.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. <?php
  2. /*
  3. * StatusNet - the distributed open-source microblogging tool
  4. * Copyright (C) 2008-2011 StatusNet, Inc.
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. if (!defined('STATUSNET') && !defined('LACONICA')) {
  20. exit(1);
  21. }
  22. define('TWITTER_SERVICE', 1); // Twitter is foreign_service ID 1
  23. function add_twitter_user($twitter_id, $screen_name)
  24. {
  25. // Clear out any bad old foreign_users with the new user's legit URL
  26. // This can happen when users move around or fakester accounts get
  27. // repoed, and things like that.
  28. $luser = Foreign_user::getForeignUser($twitter_id, TWITTER_SERVICE);
  29. if (!empty($luser)) {
  30. $result = $luser->delete();
  31. if ($result != false) {
  32. common_log(
  33. LOG_INFO,
  34. "Twitter bridge - removed old Twitter user: $screen_name ($twitter_id)."
  35. );
  36. }
  37. }
  38. $fuser = new Foreign_user();
  39. $fuser->nickname = $screen_name;
  40. $fuser->uri = 'http://twitter.com/' . $screen_name;
  41. $fuser->id = $twitter_id;
  42. $fuser->service = TWITTER_SERVICE;
  43. $fuser->created = common_sql_now();
  44. $result = $fuser->insert();
  45. if (empty($result)) {
  46. common_log(LOG_WARNING,
  47. "Twitter bridge - failed to add new Twitter user: $twitter_id - $screen_name.");
  48. common_log_db_error($fuser, 'INSERT', __FILE__);
  49. } else {
  50. common_log(LOG_INFO,
  51. "Twitter bridge - Added new Twitter user: $screen_name ($twitter_id).");
  52. }
  53. return $result;
  54. }
  55. // Creates or Updates a Twitter user
  56. function save_twitter_user($twitter_id, $screen_name)
  57. {
  58. // Check to see whether the Twitter user is already in the system,
  59. // and update its screen name and uri if so.
  60. $fuser = Foreign_user::getForeignUser($twitter_id, TWITTER_SERVICE);
  61. if (!empty($fuser)) {
  62. // Delete old record if Twitter user changed screen name
  63. if ($fuser->nickname != $screen_name) {
  64. $oldname = $fuser->nickname;
  65. $fuser->delete();
  66. common_log(LOG_INFO, sprintf('Twitter bridge - Updated nickname (and URI) ' .
  67. 'for Twitter user %1$d - %2$s, was %3$s.',
  68. $fuser->id,
  69. $screen_name,
  70. $oldname));
  71. }
  72. } else {
  73. // Kill any old, invalid records for this screen name
  74. $fuser = Foreign_user::getByNickname($screen_name, TWITTER_SERVICE);
  75. if (!empty($fuser)) {
  76. $fuser->delete();
  77. common_log(
  78. LOG_INFO,
  79. sprintf(
  80. 'Twitter bridge - deteted old record for Twitter ' .
  81. 'screen name "%s" belonging to Twitter ID %d.',
  82. $screen_name,
  83. $fuser->id
  84. )
  85. );
  86. }
  87. }
  88. return add_twitter_user($twitter_id, $screen_name);
  89. }
  90. function is_twitter_bound($notice, $flink) {
  91. // Don't send activity activities (at least for now)
  92. if ($notice->object_type == ActivityObject::ACTIVITY) {
  93. return false;
  94. }
  95. $allowedVerbs = array(ActivityVerb::POST, ActivityVerb::SHARE);
  96. // Don't send things that aren't posts or repeats (at least for now)
  97. if (!in_array($notice->verb, $allowedVerbs)) {
  98. return false;
  99. }
  100. // Check to see if notice should go to Twitter
  101. if (!empty($flink) && (($flink->noticesync & FOREIGN_NOTICE_SEND) == FOREIGN_NOTICE_SEND)) {
  102. // If it's not a Twitter-style reply, or if the user WANTS to send replies,
  103. // or if it's in reply to a twitter notice
  104. if ( (($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) == FOREIGN_NOTICE_SEND_REPLY) ||
  105. ((is_twitter_notice($notice->reply_to) || is_twitter_notice($notice->repeat_of))
  106. && (($flink->noticesync & FOREIGN_NOTICE_RECV) == FOREIGN_NOTICE_RECV)) ||
  107. (empty($notice->reply_to) && !preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content)) ){
  108. return true;
  109. }
  110. }
  111. return false;
  112. }
  113. function is_twitter_notice($id)
  114. {
  115. $n2s = Notice_to_status::getKV('notice_id', $id);
  116. return (!empty($n2s));
  117. }
  118. /**
  119. * Pull the formatted status ID number from a Twitter status object
  120. * returned via JSON from Twitter API.
  121. *
  122. * Encapsulates checking for the id_str attribute, which is required
  123. * to read 64-bit "Snowflake" ID numbers on a 32-bit system -- the
  124. * integer id attribute gets corrupted into a double-precision float,
  125. * losing a few digits of precision.
  126. *
  127. * Warning: avoid performing arithmetic or direct comparisons with
  128. * this number, as it may get coerced back to a double on 32-bit.
  129. *
  130. * @param object $status
  131. * @param string $field base field name if not 'id'
  132. * @return mixed id number as int or string
  133. */
  134. function twitter_id($status, $field='id')
  135. {
  136. $field_str = "{$field}_str";
  137. if (isset($status->$field_str)) {
  138. // String version of the id -- required on 32-bit systems
  139. // since the 64-bit numbers get corrupted as ints.
  140. return $status->$field_str;
  141. } else {
  142. return $status->$field;
  143. }
  144. }
  145. /**
  146. * Check if we need to broadcast a notice over the Twitter bridge, and
  147. * do so if necessary. Will determine whether to do a straight post or
  148. * a repeat/retweet
  149. *
  150. * This function is meant to be called directly from TwitterQueueHandler.
  151. *
  152. * @param Notice $notice
  153. * @return boolean true if complete or successful, false if we should retry
  154. */
  155. function broadcast_twitter($notice)
  156. {
  157. $flink = Foreign_link::getByUserID($notice->profile_id,
  158. TWITTER_SERVICE);
  159. // Don't bother with basic auth, since it's no longer allowed
  160. if (!empty($flink) && TwitterOAuthClient::isPackedToken($flink->credentials)) {
  161. if (is_twitter_bound($notice, $flink)) {
  162. if (!empty($notice->repeat_of) && is_twitter_notice($notice->repeat_of)) {
  163. $retweet = retweet_notice($flink, Notice::getKV('id', $notice->repeat_of));
  164. if (is_object($retweet)) {
  165. Notice_to_status::saveNew($notice->id, twitter_id($retweet));
  166. return true;
  167. } else {
  168. // Our error processing will have decided if we need to requeue
  169. // this or can discard safely.
  170. return $retweet;
  171. }
  172. } else {
  173. return broadcast_oauth($notice, $flink);
  174. }
  175. }
  176. }
  177. return true;
  178. }
  179. /**
  180. * Send a retweet to Twitter for a notice that has been previously bridged
  181. * in or out.
  182. *
  183. * Warning: the return value is not guaranteed to be an object; some error
  184. * conditions will return a 'true' which should be passed on to a calling
  185. * queue handler.
  186. *
  187. * No local information about the resulting retweet is saved: it's up to
  188. * caller to save new mappings etc if appropriate.
  189. *
  190. * @param Foreign_link $flink
  191. * @param Notice $notice
  192. * @return mixed object with resulting Twitter status data on success, or true/false/null on error conditions.
  193. */
  194. function retweet_notice($flink, $notice)
  195. {
  196. $token = TwitterOAuthClient::unpackToken($flink->credentials);
  197. $client = new TwitterOAuthClient($token->key, $token->secret);
  198. $id = twitter_status_id($notice);
  199. if (empty($id)) {
  200. common_log(LOG_WARNING, "Trying to retweet notice {$notice->id} with no known status id.");
  201. return null;
  202. }
  203. try {
  204. $status = $client->statusesRetweet($id);
  205. return $status;
  206. } catch (OAuthClientException $e) {
  207. return process_error($e, $flink, $notice);
  208. }
  209. }
  210. function twitter_status_id($notice)
  211. {
  212. $n2s = Notice_to_status::getKV('notice_id', $notice->id);
  213. if (empty($n2s)) {
  214. return null;
  215. } else {
  216. return $n2s->status_id;
  217. }
  218. }
  219. /**
  220. * Pull any extra information from a notice that we should transfer over
  221. * to Twitter beyond the notice text itself.
  222. *
  223. * @param Notice $notice
  224. * @return array of key-value pairs for Twitter update submission
  225. * @access private
  226. */
  227. function twitter_update_params($notice)
  228. {
  229. $params = array();
  230. if ($notice->lat || $notice->lon) {
  231. $params['lat'] = $notice->lat;
  232. $params['long'] = $notice->lon;
  233. }
  234. if (!empty($notice->reply_to) && is_twitter_notice($notice->reply_to)) {
  235. $reply = Notice::getKV('id', $notice->reply_to);
  236. $params['in_reply_to_status_id'] = twitter_status_id($reply);
  237. }
  238. return $params;
  239. }
  240. function broadcast_oauth($notice, $flink) {
  241. $user = $flink->getUser();
  242. $statustxt = format_status($notice);
  243. $params = twitter_update_params($notice);
  244. $token = TwitterOAuthClient::unpackToken($flink->credentials);
  245. $client = new TwitterOAuthClient($token->key, $token->secret);
  246. $status = null;
  247. try {
  248. $status = $client->statusesUpdate($statustxt, $params);
  249. if (!empty($status)) {
  250. Notice_to_status::saveNew($notice->id, twitter_id($status));
  251. }
  252. } catch (OAuthClientException $e) {
  253. return process_error($e, $flink, $notice);
  254. }
  255. if (empty($status)) {
  256. // This could represent a failure posting,
  257. // or the Twitter API might just be behaving flakey.
  258. $errmsg = sprintf('Twitter bridge - No data returned by Twitter API when ' .
  259. 'trying to post notice %d for User %s (user id %d).',
  260. $notice->id,
  261. $user->nickname,
  262. $user->id);
  263. common_log(LOG_WARNING, $errmsg);
  264. return false;
  265. }
  266. // Notice crossed the great divide
  267. $msg = sprintf('Twitter bridge - posted notice %d to Twitter using ' .
  268. 'OAuth for User %s (user id %d).',
  269. $notice->id,
  270. $user->nickname,
  271. $user->id);
  272. common_log(LOG_INFO, $msg);
  273. return true;
  274. }
  275. function process_error($e, $flink, $notice)
  276. {
  277. $user = $flink->getUser();
  278. $code = $e->getCode();
  279. $logmsg = sprintf('Twitter bridge - %d posting notice %d for ' .
  280. 'User %s (user id: %d): %s.',
  281. $code,
  282. $notice->id,
  283. $user->nickname,
  284. $user->id,
  285. $e->getMessage());
  286. common_log(LOG_WARNING, $logmsg);
  287. // http://dev.twitter.com/pages/responses_errors
  288. switch($code) {
  289. case 400:
  290. // Probably invalid data (bad Unicode chars or coords) that
  291. // cannot be resolved by just sending again.
  292. //
  293. // It could also be rate limiting, but retrying immediately
  294. // won't help much with that, so we'll discard for now.
  295. // If a facility for retrying things later comes up in future,
  296. // we can detect the rate-limiting headers and use that.
  297. //
  298. // Discard the message permanently.
  299. return true;
  300. break;
  301. case 401:
  302. // Probably a revoked or otherwise bad access token - nuke!
  303. remove_twitter_link($flink);
  304. return true;
  305. break;
  306. case 403:
  307. // User has exceeder her rate limit -- toss the notice
  308. return true;
  309. break;
  310. case 404:
  311. // Resource not found. Shouldn't happen much on posting,
  312. // but just in case!
  313. //
  314. // Consider it a matter for tossing the notice.
  315. return true;
  316. break;
  317. default:
  318. // For every other case, it's probably some flakiness so try
  319. // sending the notice again later (requeue).
  320. return false;
  321. break;
  322. }
  323. }
  324. function format_status($notice)
  325. {
  326. // Start with the plaintext source of this notice...
  327. $statustxt = $notice->content;
  328. // Convert !groups to #hashes
  329. // XXX: Make this an optional setting?
  330. $statustxt = preg_replace('/(^|\s)!([A-Za-z0-9]{1,64})/', "\\1#\\2", $statustxt);
  331. // Twitter still has a 140-char hardcoded max.
  332. if (mb_strlen($statustxt) > 140) {
  333. $noticeUrl = common_shorten_url($notice->getUrl());
  334. $urlLen = mb_strlen($noticeUrl);
  335. $statustxt = mb_substr($statustxt, 0, 140 - ($urlLen + 3)) . ' … ' . $noticeUrl;
  336. }
  337. return $statustxt;
  338. }
  339. function remove_twitter_link($flink)
  340. {
  341. $user = $flink->getUser();
  342. common_log(LOG_INFO, 'Removing Twitter bridge Foreign link for ' .
  343. "user $user->nickname (user id: $user->id).");
  344. $result = $flink->safeDelete();
  345. if (empty($result)) {
  346. common_log(LOG_ERR, 'Could not remove Twitter bridge ' .
  347. "Foreign_link for $user->nickname (user id: $user->id)!");
  348. common_log_db_error($flink, 'DELETE', __FILE__);
  349. }
  350. // Notify the user that her Twitter bridge is down
  351. if (isset($user->email)) {
  352. $result = mail_twitter_bridge_removed($user);
  353. if (!$result) {
  354. $msg = 'Unable to send email to notify ' .
  355. "$user->nickname (user id: $user->id) " .
  356. 'that their Twitter bridge link was ' .
  357. 'removed!';
  358. common_log(LOG_WARNING, $msg);
  359. }
  360. }
  361. }
  362. /**
  363. * Send a mail message to notify a user that her Twitter bridge link
  364. * has stopped working, and therefore has been removed. This can
  365. * happen when the user changes her Twitter password, or otherwise
  366. * revokes access.
  367. *
  368. * @param User $user user whose Twitter bridge link has been removed
  369. *
  370. * @return boolean success flag
  371. */
  372. function mail_twitter_bridge_removed($user)
  373. {
  374. $profile = $user->getProfile();
  375. common_switch_locale($user->language);
  376. // TRANS: Mail subject after forwarding notices to Twitter has stopped working.
  377. $subject = sprintf(_m('Your Twitter bridge has been disabled'));
  378. $site_name = common_config('site', 'name');
  379. // TRANS: Mail body after forwarding notices to Twitter has stopped working.
  380. // TRANS: %1$ is the name of the user the mail is sent to, %2$s is a URL to the
  381. // TRANS: Twitter settings, %3$s is the StatusNet sitename.
  382. $body = sprintf(_m('Hi, %1$s. We\'re sorry to inform you that your ' .
  383. 'link to Twitter has been disabled. We no longer seem to have ' .
  384. 'permission to update your Twitter status. Did you maybe revoke ' .
  385. '%3$s\'s access?' . "\n\n" .
  386. 'You can re-enable your Twitter bridge by visiting your ' .
  387. "Twitter settings page:\n\n\t%2\$s\n\n" .
  388. "Regards,\n%3\$s"),
  389. $profile->getBestName(),
  390. common_local_url('twittersettings'),
  391. common_config('site', 'name'));
  392. common_switch_locale();
  393. return mail_to_user($user, $subject, $body);
  394. }