apiaction.php 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563
  1. <?php
  2. // This file is part of GNU social - https://www.gnu.org/software/social
  3. //
  4. // GNU social is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // GNU social is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * Base API action
  18. *
  19. * @category API
  20. * @package GNUsocial
  21. * @author Craig Andrews <candrews@integralblue.com>
  22. * @author Dan Moore <dan@moore.cx>
  23. * @author Evan Prodromou <evan@status.net>
  24. * @author Jeffery To <jeffery.to@gmail.com>
  25. * @author Toby Inkster <mail@tobyinkster.co.uk>
  26. * @author Zach Copley <zach@status.net>
  27. * @copyright 2009-2010 StatusNet, Inc.
  28. * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
  29. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  30. */
  31. /* External API usage documentation. Please update when you change how the API works. */
  32. /*! @mainpage StatusNet REST API
  33. @section Introduction
  34. Some explanatory text about the API would be nice.
  35. @section API Methods
  36. @subsection timelinesmethods_sec Timeline Methods
  37. @li @ref publictimeline
  38. @li @ref friendstimeline
  39. @subsection statusmethods_sec Status Methods
  40. @li @ref statusesupdate
  41. @subsection usermethods_sec User Methods
  42. @subsection directmessagemethods_sec Direct Message Methods (now a plugin)
  43. @subsection friendshipmethods_sec Friendship Methods
  44. @subsection socialgraphmethods_sec Social Graph Methods
  45. @subsection accountmethods_sec Account Methods
  46. @subsection favoritesmethods_sec Favorites Methods
  47. @subsection blockmethods_sec Block Methods
  48. @subsection oauthmethods_sec OAuth Methods
  49. @subsection helpmethods_sec Help Methods
  50. @subsection groupmethods_sec Group Methods
  51. @page apiroot API Root
  52. The URLs for methods referred to in this API documentation are
  53. relative to the StatusNet API root. The API root is determined by the
  54. site's @b server and @b path variables, which are generally specified
  55. in config.php. For example:
  56. @code
  57. $config['site']['server'] = 'example.org';
  58. $config['site']['path'] = 'statusnet'
  59. @endcode
  60. The pattern for a site's API root is: @c protocol://server/path/api E.g:
  61. @c http://example.org/statusnet/api
  62. The @b path can be empty. In that case the API root would simply be:
  63. @c http://example.org/api
  64. */
  65. defined('GNUSOCIAL') || die();
  66. class ApiValidationException extends Exception
  67. {
  68. }
  69. /**
  70. * Contains most of the Twitter-compatible API output functions.
  71. *
  72. * @category API
  73. * @package GNUsocial
  74. * @author Craig Andrews <candrews@integralblue.com>
  75. * @author Dan Moore <dan@moore.cx>
  76. * @author Evan Prodromou <evan@status.net>
  77. * @author Jeffery To <jeffery.to@gmail.com>
  78. * @author Toby Inkster <mail@tobyinkster.co.uk>
  79. * @author Zach Copley <zach@status.net>
  80. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  81. */
  82. class ApiAction extends Action
  83. {
  84. const READ_ONLY = 1;
  85. const READ_WRITE = 2;
  86. public static $reserved_sources = ['web', 'omb', 'ostatus', 'mail', 'xmpp', 'api'];
  87. public $user = null;
  88. public $auth_user = null;
  89. public $page = null;
  90. public $count = null;
  91. public $offset = null;
  92. public $limit = null;
  93. public $max_id = null;
  94. public $since_id = null;
  95. public $source = null;
  96. public $callback = null;
  97. public $format = null; // read (default) or read-write
  98. public $access = self::READ_ONLY;
  99. public function twitterRelationshipArray($source, $target)
  100. {
  101. $relationship = [];
  102. $relationship['source'] =
  103. $this->relationshipDetailsArray($source->getProfile(), $target->getProfile());
  104. $relationship['target'] =
  105. $this->relationshipDetailsArray($target->getProfile(), $source->getProfile());
  106. return ['relationship' => $relationship];
  107. }
  108. public function relationshipDetailsArray(Profile $source, Profile $target)
  109. {
  110. $details = [];
  111. $details['screen_name'] = $source->getNickname();
  112. $details['followed_by'] = $target->isSubscribed($source);
  113. try {
  114. $sub = Subscription::getSubscription($source, $target);
  115. $details['following'] = true;
  116. $details['notifications_enabled'] = ($sub->jabber || $sub->sms);
  117. } catch (NoResultException $e) {
  118. $details['following'] = false;
  119. $details['notifications_enabled'] = false;
  120. }
  121. $details['blocking'] = $source->hasBlocked($target);
  122. $details['id'] = intval($source->id);
  123. return $details;
  124. }
  125. public function showTwitterXmlRelationship($relationship)
  126. {
  127. $this->elementStart('relationship');
  128. foreach ($relationship as $element => $value) {
  129. if ($element == 'source' || $element == 'target') {
  130. $this->elementStart($element);
  131. $this->showXmlRelationshipDetails($value);
  132. $this->elementEnd($element);
  133. }
  134. }
  135. $this->elementEnd('relationship');
  136. }
  137. public function showXmlRelationshipDetails($details)
  138. {
  139. foreach ($details as $element => $value) {
  140. $this->element($element, null, $value);
  141. }
  142. }
  143. /**
  144. * Overrides XMLOutputter::element to write booleans as strings (true|false).
  145. * See that method's documentation for more info.
  146. *
  147. * @param string $tag Element type or tagname
  148. * @param array|string|null $attrs Array of element attributes, as key-value pairs
  149. * @param string|null $content string content of the element
  150. *
  151. * @return void
  152. */
  153. public function element(string $tag, $attrs = null, ?string $content = null): void
  154. {
  155. if (is_bool($content)) {
  156. $content = ($content ? "true" : "false");
  157. }
  158. parent::element($tag, $attrs, $content);
  159. }
  160. public function showSingleXmlStatus($notice)
  161. {
  162. $this->initDocument('xml');
  163. $twitter_status = $this->twitterStatusArray($notice);
  164. $this->showTwitterXmlStatus($twitter_status, 'status', true);
  165. $this->endDocument('xml');
  166. }
  167. public function initDocument($type = 'xml')
  168. {
  169. switch ($type) {
  170. case 'xml':
  171. header('Content-Type: application/xml; charset=utf-8');
  172. $this->startXML();
  173. break;
  174. case 'json':
  175. header('Content-Type: application/json; charset=utf-8');
  176. // Check for JSONP callback
  177. if (isset($this->callback)) {
  178. print $this->callback . '(';
  179. }
  180. break;
  181. case 'rss':
  182. header("Content-Type: application/rss+xml; charset=utf-8");
  183. $this->initTwitterRss();
  184. break;
  185. case 'atom':
  186. header('Content-Type: application/atom+xml; charset=utf-8');
  187. $this->initTwitterAtom();
  188. break;
  189. default:
  190. // TRANS: Client error on an API request with an unsupported data format.
  191. $this->clientError(_('Not a supported data format.'));
  192. }
  193. return;
  194. }
  195. public function initTwitterRss()
  196. {
  197. $this->startXML();
  198. $this->elementStart(
  199. 'rss',
  200. [
  201. 'version' => '2.0',
  202. 'xmlns:atom' => 'http://www.w3.org/2005/Atom',
  203. 'xmlns:georss' => 'http://www.georss.org/georss'
  204. ]
  205. );
  206. $this->elementStart('channel');
  207. Event::handle('StartApiRss', [$this]);
  208. }
  209. public function initTwitterAtom()
  210. {
  211. $this->startXML();
  212. // FIXME: don't hardcode the language here!
  213. $this->elementStart('feed', ['xmlns' => 'http://www.w3.org/2005/Atom',
  214. 'xml:lang' => 'en-US',
  215. 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0']);
  216. }
  217. public function twitterStatusArray($notice, $include_user = true)
  218. {
  219. $base = $this->twitterSimpleStatusArray($notice, $include_user);
  220. // FIXME: MOVE TO SHARE PLUGIN
  221. if (!empty($notice->repeat_of)) {
  222. $original = Notice::getKV('id', $notice->repeat_of);
  223. if ($original instanceof Notice) {
  224. $orig_array = $this->twitterSimpleStatusArray($original, $include_user);
  225. $base['retweeted_status'] = $orig_array;
  226. }
  227. }
  228. return $base;
  229. }
  230. public function twitterSimpleStatusArray($notice, $include_user = true)
  231. {
  232. $profile = $notice->getProfile();
  233. $twitter_status = [];
  234. $twitter_status['text'] = $notice->content;
  235. $twitter_status['truncated'] = false; # Not possible on StatusNet
  236. $twitter_status['created_at'] = self::dateTwitter($notice->created);
  237. try {
  238. // We could just do $notice->reply_to but maybe the future holds a
  239. // different story for parenting.
  240. $parent = $notice->getParent();
  241. $in_reply_to = $parent->id;
  242. } catch (NoParentNoticeException $e) {
  243. $in_reply_to = null;
  244. } catch (NoResultException $e) {
  245. // the in_reply_to message has probably been deleted
  246. $in_reply_to = null;
  247. }
  248. $twitter_status['in_reply_to_status_id'] = $in_reply_to;
  249. $source = null;
  250. $source_link = null;
  251. $ns = $notice->getSource();
  252. if ($ns instanceof Notice_source) {
  253. $source = $ns->code;
  254. if (!empty($ns->url)) {
  255. $source_link = $ns->url;
  256. if (!empty($ns->name)) {
  257. $source = $ns->name;
  258. }
  259. }
  260. }
  261. $twitter_status['uri'] = $notice->getUri();
  262. $twitter_status['source'] = $source;
  263. $twitter_status['source_link'] = $source_link;
  264. $twitter_status['id'] = intval($notice->id);
  265. $replier_profile = null;
  266. if ($notice->reply_to) {
  267. $reply = Notice::getKV(intval($notice->reply_to));
  268. if ($reply) {
  269. $replier_profile = $reply->getProfile();
  270. }
  271. }
  272. $twitter_status['in_reply_to_user_id'] =
  273. ($replier_profile) ? intval($replier_profile->id) : null;
  274. $twitter_status['in_reply_to_screen_name'] =
  275. ($replier_profile) ? $replier_profile->nickname : null;
  276. try {
  277. $notloc = Notice_location::locFromStored($notice);
  278. // This is the format that GeoJSON expects stuff to be in
  279. $twitter_status['geo'] = ['type' => 'Point',
  280. 'coordinates' => [(float)$notloc->lat,
  281. (float)$notloc->lon]];
  282. } catch (ServerException $e) {
  283. $twitter_status['geo'] = null;
  284. }
  285. // Enclosures
  286. $attachments = $notice->attachments();
  287. if (!empty($attachments)) {
  288. $twitter_status['attachments'] = [];
  289. foreach ($attachments as $attachment) {
  290. try {
  291. $enclosure_o = $attachment->getEnclosure();
  292. $enclosure = [];
  293. $enclosure['url'] = $enclosure_o->url;
  294. $enclosure['mimetype'] = $enclosure_o->mimetype;
  295. $enclosure['size'] = $enclosure_o->size;
  296. $twitter_status['attachments'][] = $enclosure;
  297. } catch (ServerException $e) {
  298. // There was not enough metadata available
  299. }
  300. }
  301. }
  302. if ($include_user && $profile) {
  303. // Don't get notice (recursive!)
  304. $twitter_user = $this->twitterUserArray($profile, false);
  305. $twitter_status['user'] = $twitter_user;
  306. }
  307. // StatusNet-specific
  308. $twitter_status['statusnet_html'] = $notice->getRendered();
  309. $twitter_status['statusnet_conversation_id'] = intval($notice->conversation);
  310. // The event call to handle NoticeSimpleStatusArray lets plugins add data to the output array
  311. Event::handle('NoticeSimpleStatusArray', [$notice, &$twitter_status, $this->scoped,
  312. ['include_user' => $include_user]]);
  313. return $twitter_status;
  314. }
  315. public static function dateTwitter($dt)
  316. {
  317. $dateStr = date('d F Y H:i:s', strtotime($dt));
  318. $d = new DateTime($dateStr, new DateTimeZone('UTC'));
  319. $d->setTimezone(new DateTimeZone(common_timezone()));
  320. return $d->format('D M d H:i:s O Y');
  321. }
  322. public function twitterUserArray($profile, $get_notice = false)
  323. {
  324. $twitter_user = [];
  325. try {
  326. $user = $profile->getUser();
  327. } catch (NoSuchUserException $e) {
  328. $user = null;
  329. }
  330. $twitter_user['id'] = $profile->getID();
  331. $twitter_user['name'] = $profile->getBestName();
  332. $twitter_user['screen_name'] = $profile->getNickname();
  333. $twitter_user['location'] = $profile->location;
  334. $twitter_user['description'] = $profile->getDescription();
  335. // TODO: avatar url template (example.com/user/avatar?size={x}x{y})
  336. $twitter_user['profile_image_url'] = Avatar::urlByProfile($profile, AVATAR_STREAM_SIZE);
  337. $twitter_user['profile_image_url_https'] = $twitter_user['profile_image_url'];
  338. // START introduced by qvitter API, not necessary for StatusNet API
  339. $twitter_user['profile_image_url_profile_size'] = Avatar::urlByProfile($profile, AVATAR_PROFILE_SIZE);
  340. try {
  341. $avatar = Avatar::getUploaded($profile);
  342. $origurl = $avatar->displayUrl();
  343. } catch (Exception $e) {
  344. $origurl = $twitter_user['profile_image_url_profile_size'];
  345. }
  346. $twitter_user['profile_image_url_original'] = $origurl;
  347. $twitter_user['groups_count'] = $profile->getGroupCount();
  348. foreach (['linkcolor', 'backgroundcolor'] as $key) {
  349. $twitter_user[$key] = Profile_prefs::getConfigData($profile, 'theme', $key);
  350. }
  351. // END introduced by qvitter API, not necessary for StatusNet API
  352. $twitter_user['url'] = ($profile->homepage) ? $profile->homepage : null;
  353. $twitter_user['protected'] = (!empty($user) && $user->private_stream) ? true : false;
  354. $twitter_user['followers_count'] = $profile->subscriberCount();
  355. // Note: some profiles don't have an associated user
  356. $twitter_user['friends_count'] = $profile->subscriptionCount();
  357. $twitter_user['created_at'] = self::dateTwitter($profile->created);
  358. $timezone = 'UTC';
  359. if (!empty($user) && $user->timezone) {
  360. $timezone = $user->timezone;
  361. }
  362. $t = new DateTime;
  363. $t->setTimezone(new DateTimeZone($timezone));
  364. $twitter_user['utc_offset'] = $t->format('Z');
  365. $twitter_user['time_zone'] = $timezone;
  366. $twitter_user['statuses_count'] = $profile->noticeCount();
  367. // Is the requesting user following this user?
  368. // These values might actually also mean "unknown". Ambiguity issues?
  369. $twitter_user['following'] = false;
  370. $twitter_user['statusnet_blocking'] = false;
  371. $twitter_user['notifications'] = false;
  372. if ($this->scoped instanceof Profile) {
  373. try {
  374. $sub = Subscription::getSubscription($this->scoped, $profile);
  375. // Notifications on?
  376. $twitter_user['following'] = true;
  377. $twitter_user['notifications'] = ($sub->jabber || $sub->sms);
  378. } catch (NoResultException $e) {
  379. // well, the values are already false...
  380. }
  381. $twitter_user['statusnet_blocking'] = $this->scoped->hasBlocked($profile);
  382. }
  383. if ($get_notice) {
  384. $notice = $profile->getCurrentNotice();
  385. if ($notice instanceof Notice) {
  386. // don't get user!
  387. $twitter_user['status'] = $this->twitterStatusArray($notice, false);
  388. }
  389. }
  390. // StatusNet-specific
  391. $twitter_user['statusnet_profile_url'] = $profile->profileurl;
  392. // The event call to handle NoticeSimpleStatusArray lets plugins add data to the output array
  393. Event::handle('TwitterUserArray', [$profile, &$twitter_user, $this->scoped, []]);
  394. return $twitter_user;
  395. }
  396. public function showTwitterXmlStatus($twitter_status, $tag = 'status', $namespaces = false)
  397. {
  398. $attrs = [];
  399. if ($namespaces) {
  400. $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
  401. }
  402. $this->elementStart($tag, $attrs);
  403. foreach ($twitter_status as $element => $value) {
  404. switch ($element) {
  405. case 'user':
  406. $this->showTwitterXmlUser($twitter_status['user']);
  407. break;
  408. case 'text':
  409. $this->element($element, null, common_xml_safe_str($value));
  410. break;
  411. case 'attachments':
  412. $this->showXmlAttachments($twitter_status['attachments']);
  413. break;
  414. case 'geo':
  415. $this->showGeoXML($value);
  416. break;
  417. case 'retweeted_status':
  418. // FIXME: MOVE TO SHARE PLUGIN
  419. $this->showTwitterXmlStatus($value, 'retweeted_status');
  420. break;
  421. default:
  422. if (strncmp($element, 'statusnet_', 10) == 0) {
  423. if ($element === 'statusnet_in_groups' && is_array($value)) {
  424. // QVITTERFIX because it would cause an array to be sent as $value
  425. // THIS IS UNDOCUMENTED AND SHOULD NEVER BE RELIED UPON (qvitter uses json output)
  426. $value = json_encode($value);
  427. }
  428. $this->element('statusnet:' . substr($element, 10), null, $value);
  429. } else {
  430. $this->element($element, null, $value);
  431. }
  432. }
  433. }
  434. $this->elementEnd($tag);
  435. }
  436. public function showTwitterXmlUser($twitter_user, $role = 'user', $namespaces = false)
  437. {
  438. $attrs = [];
  439. if ($namespaces) {
  440. $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
  441. }
  442. $this->elementStart($role, $attrs);
  443. foreach ($twitter_user as $element => $value) {
  444. if ($element == 'status') {
  445. $this->showTwitterXmlStatus($twitter_user['status']);
  446. } elseif (strncmp($element, 'statusnet_', 10) == 0) {
  447. $this->element('statusnet:' . substr($element, 10), null, $value);
  448. } else {
  449. $this->element($element, null, $value);
  450. }
  451. }
  452. $this->elementEnd($role);
  453. }
  454. public function showXmlAttachments($attachments)
  455. {
  456. if (!empty($attachments)) {
  457. $this->elementStart('attachments', ['type' => 'array']);
  458. foreach ($attachments as $attachment) {
  459. $attrs = [];
  460. $attrs['url'] = $attachment['url'];
  461. $attrs['mimetype'] = $attachment['mimetype'];
  462. $attrs['size'] = $attachment['size'];
  463. $this->element('enclosure', $attrs, '');
  464. }
  465. $this->elementEnd('attachments');
  466. }
  467. }
  468. public function showGeoXML($geo)
  469. {
  470. if (empty($geo)) {
  471. // empty geo element
  472. $this->element('geo');
  473. } else {
  474. $this->elementStart('geo', ['xmlns:georss' => 'http://www.georss.org/georss']);
  475. $this->element('georss:point', null, $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]);
  476. $this->elementEnd('geo');
  477. }
  478. }
  479. public function endDocument($type = 'xml')
  480. {
  481. switch ($type) {
  482. case 'xml':
  483. $this->endXML();
  484. break;
  485. case 'json':
  486. // Check for JSONP callback
  487. if (isset($this->callback)) {
  488. print ')';
  489. }
  490. break;
  491. case 'rss':
  492. $this->endTwitterRss();
  493. break;
  494. case 'atom':
  495. $this->endTwitterRss();
  496. break;
  497. default:
  498. // TRANS: Client error on an API request with an unsupported data format.
  499. $this->clientError(_('Not a supported data format.'));
  500. }
  501. return;
  502. }
  503. public function endTwitterRss()
  504. {
  505. $this->elementEnd('channel');
  506. $this->elementEnd('rss');
  507. $this->endXML();
  508. }
  509. public function showSingleAtomStatus($notice)
  510. {
  511. header('Content-Type: application/atom+xml;type=entry;charset="utf-8"');
  512. print '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
  513. print $notice->asAtomEntry(true, true, true, $this->scoped);
  514. }
  515. public function show_single_json_status($notice)
  516. {
  517. $this->initDocument('json');
  518. $status = $this->twitterStatusArray($notice);
  519. $this->showJsonObjects($status);
  520. $this->endDocument('json');
  521. }
  522. public function showJsonObjects($objects)
  523. {
  524. $json_objects = json_encode($objects);
  525. if ($json_objects === false) {
  526. $this->clientError(_('JSON encoding failed. Error: ') . json_last_error_msg());
  527. } else {
  528. print $json_objects;
  529. }
  530. }
  531. public function showXmlTimeline($notice)
  532. {
  533. $this->initDocument('xml');
  534. $this->elementStart('statuses', ['type' => 'array',
  535. 'xmlns:statusnet' => 'http://status.net/schema/api/1/']);
  536. if (is_array($notice)) {
  537. //FIXME: make everything calling showJsonTimeline use only Notice objects
  538. $ids = [];
  539. foreach ($notice as $n) {
  540. $ids[] = $n->getID();
  541. }
  542. $notice = Notice::multiGet('id', $ids);
  543. }
  544. while ($notice->fetch()) {
  545. try {
  546. $twitter_status = $this->twitterStatusArray($notice);
  547. $this->showTwitterXmlStatus($twitter_status);
  548. } catch (Exception $e) {
  549. common_log(LOG_ERR, $e->getMessage());
  550. continue;
  551. }
  552. }
  553. $this->elementEnd('statuses');
  554. $this->endDocument('xml');
  555. }
  556. public function showRssTimeline($notice, $title, $link, $subtitle, $suplink = null, $logo = null, $self = null)
  557. {
  558. $this->initDocument('rss');
  559. $this->element('title', null, $title);
  560. $this->element('link', null, $link);
  561. if (!is_null($self)) {
  562. $this->element(
  563. 'atom:link',
  564. [
  565. 'type' => 'application/rss+xml',
  566. 'href' => $self,
  567. 'rel' => 'self'
  568. ]
  569. );
  570. }
  571. if (!is_null($suplink)) {
  572. // For FriendFeed's SUP protocol
  573. $this->element('link', ['xmlns' => 'http://www.w3.org/2005/Atom',
  574. 'rel' => 'http://api.friendfeed.com/2008/03#sup',
  575. 'href' => $suplink,
  576. 'type' => 'application/json']);
  577. }
  578. if (!is_null($logo)) {
  579. $this->elementStart('image');
  580. $this->element('link', null, $link);
  581. $this->element('title', null, $title);
  582. $this->element('url', null, $logo);
  583. $this->elementEnd('image');
  584. }
  585. $this->element('description', null, $subtitle);
  586. $this->element('language', null, 'en-us');
  587. $this->element('ttl', null, '40');
  588. if (is_array($notice)) {
  589. //FIXME: make everything calling showJsonTimeline use only Notice objects
  590. $ids = [];
  591. foreach ($notice as $n) {
  592. $ids[] = $n->getID();
  593. }
  594. $notice = Notice::multiGet('id', $ids);
  595. }
  596. while ($notice->fetch()) {
  597. try {
  598. $entry = $this->twitterRssEntryArray($notice);
  599. $this->showTwitterRssItem($entry);
  600. } catch (Exception $e) {
  601. common_log(LOG_ERR, $e->getMessage());
  602. // continue on exceptions
  603. }
  604. }
  605. $this->endTwitterRss();
  606. }
  607. public function twitterRssEntryArray($notice)
  608. {
  609. $entry = [];
  610. if (Event::handle('StartRssEntryArray', [$notice, &$entry])) {
  611. $profile = $notice->getProfile();
  612. // We trim() to avoid extraneous whitespace in the output
  613. $entry['content'] = common_xml_safe_str(trim($notice->getRendered()));
  614. $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
  615. $entry['link'] = common_local_url('shownotice', ['notice' => $notice->id]);
  616. $entry['published'] = common_date_iso8601($notice->created);
  617. $taguribase = TagURI::base();
  618. $entry['id'] = "tag:$taguribase:$entry[link]";
  619. $entry['updated'] = $entry['published'];
  620. $entry['author'] = $profile->getBestName();
  621. // Enclosures
  622. $attachments = $notice->attachments();
  623. $enclosures = [];
  624. foreach ($attachments as $attachment) {
  625. try {
  626. $enclosure_o = $attachment->getEnclosure();
  627. $enclosure = [];
  628. $enclosure['url'] = $enclosure_o->url;
  629. $enclosure['mimetype'] = $enclosure_o->mimetype;
  630. $enclosure['size'] = $enclosure_o->size;
  631. $enclosures[] = $enclosure;
  632. } catch (ServerException $e) {
  633. // There was not enough metadata available
  634. }
  635. }
  636. if (!empty($enclosures)) {
  637. $entry['enclosures'] = $enclosures;
  638. }
  639. // Tags/Categories
  640. $tag = new Notice_tag();
  641. $tag->notice_id = $notice->id;
  642. if ($tag->find()) {
  643. $entry['tags'] = [];
  644. while ($tag->fetch()) {
  645. $entry['tags'][] = $tag->tag;
  646. }
  647. }
  648. $tag->free();
  649. // RSS Item specific
  650. $entry['description'] = $entry['content'];
  651. $entry['pubDate'] = common_date_rfc2822($notice->created);
  652. $entry['guid'] = $entry['link'];
  653. try {
  654. $notloc = Notice_location::locFromStored($notice);
  655. // This is the format that GeoJSON expects stuff to be in.
  656. // showGeoRSS() below uses it for XML output, so we reuse it
  657. $entry['geo'] = ['type' => 'Point',
  658. 'coordinates' => [(float)$notloc->lat,
  659. (float)$notloc->lon]];
  660. } catch (ServerException $e) {
  661. $entry['geo'] = null;
  662. }
  663. Event::handle('EndRssEntryArray', [$notice, &$entry]);
  664. }
  665. return $entry;
  666. }
  667. public function showTwitterRssItem($entry)
  668. {
  669. $this->elementStart('item');
  670. $this->element('title', null, $entry['title']);
  671. $this->element('description', null, $entry['description']);
  672. $this->element('pubDate', null, $entry['pubDate']);
  673. $this->element('guid', null, $entry['guid']);
  674. $this->element('link', null, $entry['link']);
  675. // RSS only supports 1 enclosure per item
  676. if (array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])) {
  677. $enclosure = $entry['enclosures'][0];
  678. $this->element('enclosure', ['url' => $enclosure['url'], 'type' => $enclosure['mimetype'], 'length' => $enclosure['size']]);
  679. }
  680. if (array_key_exists('tags', $entry)) {
  681. foreach ($entry['tags'] as $tag) {
  682. $this->element('category', null, $tag);
  683. }
  684. }
  685. $this->showGeoRSS($entry['geo']);
  686. $this->elementEnd('item');
  687. }
  688. public function showGeoRSS($geo)
  689. {
  690. if (!empty($geo)) {
  691. $this->element(
  692. 'georss:point',
  693. null,
  694. $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]
  695. );
  696. }
  697. }
  698. public function showAtomTimeline($notice, $title, $id, $link, $subtitle = null, $suplink = null, $selfuri = null, $logo = null)
  699. {
  700. $this->initDocument('atom');
  701. $this->element('title', null, $title);
  702. $this->element('id', null, $id);
  703. $this->element('link', ['href' => $link, 'rel' => 'alternate', 'type' => 'text/html']);
  704. if (!is_null($logo)) {
  705. $this->element('logo', null, $logo);
  706. }
  707. if (!is_null($suplink)) {
  708. // For FriendFeed's SUP protocol
  709. $this->element('link', ['rel' => 'http://api.friendfeed.com/2008/03#sup',
  710. 'href' => $suplink,
  711. 'type' => 'application/json']);
  712. }
  713. if (!is_null($selfuri)) {
  714. $this->element('link', ['href' => $selfuri,
  715. 'rel' => 'self', 'type' => 'application/atom+xml']);
  716. }
  717. $this->element('updated', null, common_date_iso8601('now'));
  718. $this->element('subtitle', null, $subtitle);
  719. if (is_array($notice)) {
  720. //FIXME: make everything calling showJsonTimeline use only Notice objects
  721. $ids = [];
  722. foreach ($notice as $n) {
  723. $ids[] = $n->getID();
  724. }
  725. $notice = Notice::multiGet('id', $ids);
  726. }
  727. while ($notice->fetch()) {
  728. try {
  729. $this->raw($notice->asAtomEntry());
  730. } catch (Exception $e) {
  731. common_log(LOG_ERR, $e->getMessage());
  732. continue;
  733. }
  734. }
  735. $this->endDocument('atom');
  736. }
  737. public function showRssGroups($group, $title, $link, $subtitle)
  738. {
  739. $this->initDocument('rss');
  740. $this->element('title', null, $title);
  741. $this->element('link', null, $link);
  742. $this->element('description', null, $subtitle);
  743. $this->element('language', null, 'en-us');
  744. $this->element('ttl', null, '40');
  745. if (is_array($group)) {
  746. foreach ($group as $g) {
  747. $twitter_group = $this->twitterRssGroupArray($g);
  748. $this->showTwitterRssItem($twitter_group);
  749. }
  750. } else {
  751. while ($group->fetch()) {
  752. $twitter_group = $this->twitterRssGroupArray($group);
  753. $this->showTwitterRssItem($twitter_group);
  754. }
  755. }
  756. $this->endTwitterRss();
  757. }
  758. public function twitterRssGroupArray($group)
  759. {
  760. $entry = [];
  761. $entry['content'] = $group->description;
  762. $entry['title'] = $group->nickname;
  763. $entry['link'] = $group->permalink();
  764. $entry['published'] = common_date_iso8601($group->created);
  765. $entry['updated'] = common_date_iso8601($group->modified);
  766. $taguribase = common_config('integration', 'groupuri');
  767. $entry['id'] = "group:$taguribase:$entry[link]";
  768. $entry['description'] = $entry['content'];
  769. $entry['pubDate'] = common_date_rfc2822($group->created);
  770. $entry['guid'] = $entry['link'];
  771. return $entry;
  772. }
  773. public function showTwitterAtomEntry($entry)
  774. {
  775. $this->elementStart('entry');
  776. $this->element('title', null, common_xml_safe_str($entry['title']));
  777. $this->element(
  778. 'content',
  779. ['type' => 'html'],
  780. common_xml_safe_str($entry['content'])
  781. );
  782. $this->element('id', null, $entry['id']);
  783. $this->element('published', null, $entry['published']);
  784. $this->element('updated', null, $entry['updated']);
  785. $this->element('link', ['type' => 'text/html',
  786. 'href' => $entry['link'],
  787. 'rel' => 'alternate']);
  788. $this->element('link', ['type' => $entry['avatar-type'],
  789. 'href' => $entry['avatar'],
  790. 'rel' => 'image']);
  791. $this->elementStart('author');
  792. $this->element('name', null, $entry['author-name']);
  793. $this->element('uri', null, $entry['author-uri']);
  794. $this->elementEnd('author');
  795. $this->elementEnd('entry');
  796. }
  797. public function showAtomGroups($group, $title, $id, $link, $subtitle = null, $selfuri = null)
  798. {
  799. $this->initDocument('atom');
  800. $this->element('title', null, common_xml_safe_str($title));
  801. $this->element('id', null, $id);
  802. $this->element('link', ['href' => $link, 'rel' => 'alternate', 'type' => 'text/html']);
  803. if (!is_null($selfuri)) {
  804. $this->element('link', ['href' => $selfuri,
  805. 'rel' => 'self', 'type' => 'application/atom+xml']);
  806. }
  807. $this->element('updated', null, common_date_iso8601('now'));
  808. $this->element('subtitle', null, common_xml_safe_str($subtitle));
  809. if (is_array($group)) {
  810. foreach ($group as $g) {
  811. $this->raw($g->asAtomEntry());
  812. }
  813. } else {
  814. while ($group->fetch()) {
  815. $this->raw($group->asAtomEntry());
  816. }
  817. }
  818. $this->endDocument('atom');
  819. }
  820. public function showJsonTimeline($notice)
  821. {
  822. $this->initDocument('json');
  823. $statuses = [];
  824. if (is_array($notice)) {
  825. //FIXME: make everything calling showJsonTimeline use only Notice objects
  826. $ids = [];
  827. foreach ($notice as $n) {
  828. $ids[] = $n->getID();
  829. }
  830. $notice = Notice::multiGet('id', $ids);
  831. }
  832. while ($notice->fetch()) {
  833. try {
  834. $twitter_status = $this->twitterStatusArray($notice);
  835. array_push($statuses, $twitter_status);
  836. } catch (Exception $e) {
  837. common_log(LOG_ERR, $e->getMessage());
  838. continue;
  839. }
  840. }
  841. $this->showJsonObjects($statuses);
  842. $this->endDocument('json');
  843. }
  844. public function showJsonGroups($group)
  845. {
  846. $this->initDocument('json');
  847. $groups = [];
  848. if (is_array($group)) {
  849. foreach ($group as $g) {
  850. $twitter_group = $this->twitterGroupArray($g);
  851. array_push($groups, $twitter_group);
  852. }
  853. } else {
  854. while ($group->fetch()) {
  855. $twitter_group = $this->twitterGroupArray($group);
  856. array_push($groups, $twitter_group);
  857. }
  858. }
  859. $this->showJsonObjects($groups);
  860. $this->endDocument('json');
  861. }
  862. public function twitterGroupArray($group)
  863. {
  864. $twitter_group = [];
  865. $twitter_group['id'] = intval($group->id);
  866. $twitter_group['url'] = $group->permalink();
  867. $twitter_group['nickname'] = $group->nickname;
  868. $twitter_group['fullname'] = $group->fullname;
  869. if ($this->scoped instanceof Profile) {
  870. $twitter_group['member'] = $this->scoped->isMember($group);
  871. $twitter_group['blocked'] = Group_block::isBlocked(
  872. $group,
  873. $this->scoped
  874. );
  875. }
  876. $twitter_group['admin_count'] = $group->getAdminCount();
  877. $twitter_group['member_count'] = $group->getMemberCount();
  878. $twitter_group['original_logo'] = $group->original_logo;
  879. $twitter_group['homepage_logo'] = $group->homepage_logo;
  880. $twitter_group['stream_logo'] = $group->stream_logo;
  881. $twitter_group['mini_logo'] = $group->mini_logo;
  882. $twitter_group['homepage'] = $group->homepage;
  883. $twitter_group['description'] = $group->description;
  884. $twitter_group['location'] = $group->location;
  885. $twitter_group['created'] = self::dateTwitter($group->created);
  886. $twitter_group['modified'] = self::dateTwitter($group->modified);
  887. return $twitter_group;
  888. }
  889. public function showXmlGroups($group)
  890. {
  891. $this->initDocument('xml');
  892. $this->elementStart('groups', ['type' => 'array']);
  893. if (is_array($group)) {
  894. foreach ($group as $g) {
  895. $twitter_group = $this->twitterGroupArray($g);
  896. $this->showTwitterXmlGroup($twitter_group);
  897. }
  898. } else {
  899. while ($group->fetch()) {
  900. $twitter_group = $this->twitterGroupArray($group);
  901. $this->showTwitterXmlGroup($twitter_group);
  902. }
  903. }
  904. $this->elementEnd('groups');
  905. $this->endDocument('xml');
  906. }
  907. public function showTwitterXmlGroup($twitter_group)
  908. {
  909. $this->elementStart('group');
  910. foreach ($twitter_group as $element => $value) {
  911. $this->element($element, null, $value);
  912. }
  913. $this->elementEnd('group');
  914. }
  915. public function showXmlLists($list, $next_cursor = 0, $prev_cursor = 0)
  916. {
  917. $this->initDocument('xml');
  918. $this->elementStart('lists_list');
  919. $this->elementStart('lists', ['type' => 'array']);
  920. if (is_array($list)) {
  921. foreach ($list as $l) {
  922. $twitter_list = $this->twitterListArray($l);
  923. $this->showTwitterXmlList($twitter_list);
  924. }
  925. } else {
  926. while ($list->fetch()) {
  927. $twitter_list = $this->twitterListArray($list);
  928. $this->showTwitterXmlList($twitter_list);
  929. }
  930. }
  931. $this->elementEnd('lists');
  932. $this->element('next_cursor', null, $next_cursor);
  933. $this->element('previous_cursor', null, $prev_cursor);
  934. $this->elementEnd('lists_list');
  935. $this->endDocument('xml');
  936. }
  937. public function twitterListArray($list)
  938. {
  939. $profile = Profile::getKV('id', $list->tagger);
  940. $twitter_list = [];
  941. $twitter_list['id'] = $list->id;
  942. $twitter_list['name'] = $list->tag;
  943. $twitter_list['full_name'] = '@' . $profile->nickname . '/' . $list->tag;
  944. ;
  945. $twitter_list['slug'] = $list->tag;
  946. $twitter_list['description'] = $list->description;
  947. $twitter_list['subscriber_count'] = $list->subscriberCount();
  948. $twitter_list['member_count'] = $list->taggedCount();
  949. $twitter_list['uri'] = $list->getUri();
  950. if ($this->scoped instanceof Profile) {
  951. $twitter_list['following'] = $list->hasSubscriber($this->scoped);
  952. } else {
  953. $twitter_list['following'] = false;
  954. }
  955. $twitter_list['mode'] = ($list->private) ? 'private' : 'public';
  956. $twitter_list['user'] = $this->twitterUserArray($profile, false);
  957. return $twitter_list;
  958. }
  959. public function showTwitterXmlList($twitter_list)
  960. {
  961. $this->elementStart('list');
  962. foreach ($twitter_list as $element => $value) {
  963. if ($element == 'user') {
  964. $this->showTwitterXmlUser($value, 'user');
  965. } else {
  966. $this->element($element, null, $value);
  967. }
  968. }
  969. $this->elementEnd('list');
  970. }
  971. public function showJsonLists($list, $next_cursor = 0, $prev_cursor = 0)
  972. {
  973. $this->initDocument('json');
  974. $lists = [];
  975. if (is_array($list)) {
  976. foreach ($list as $l) {
  977. $twitter_list = $this->twitterListArray($l);
  978. array_push($lists, $twitter_list);
  979. }
  980. } else {
  981. while ($list->fetch()) {
  982. $twitter_list = $this->twitterListArray($list);
  983. array_push($lists, $twitter_list);
  984. }
  985. }
  986. $lists_list = [
  987. 'lists' => $lists,
  988. 'next_cursor' => $next_cursor,
  989. 'next_cursor_str' => strval($next_cursor),
  990. 'previous_cursor' => $prev_cursor,
  991. 'previous_cursor_str' => strval($prev_cursor)
  992. ];
  993. $this->showJsonObjects($lists_list);
  994. $this->endDocument('json');
  995. }
  996. public function showTwitterXmlUsers($user)
  997. {
  998. $this->initDocument('xml');
  999. $this->elementStart('users', ['type' => 'array',
  1000. 'xmlns:statusnet' => 'http://status.net/schema/api/1/']);
  1001. if (is_array($user)) {
  1002. foreach ($user as $u) {
  1003. $twitter_user = $this->twitterUserArray($u);
  1004. $this->showTwitterXmlUser($twitter_user);
  1005. }
  1006. } else {
  1007. while ($user->fetch()) {
  1008. $twitter_user = $this->twitterUserArray($user);
  1009. $this->showTwitterXmlUser($twitter_user);
  1010. }
  1011. }
  1012. $this->elementEnd('users');
  1013. $this->endDocument('xml');
  1014. }
  1015. public function showJsonUsers($user)
  1016. {
  1017. $this->initDocument('json');
  1018. $users = [];
  1019. if (is_array($user)) {
  1020. foreach ($user as $u) {
  1021. $twitter_user = $this->twitterUserArray($u);
  1022. array_push($users, $twitter_user);
  1023. }
  1024. } else {
  1025. while ($user->fetch()) {
  1026. $twitter_user = $this->twitterUserArray($user);
  1027. array_push($users, $twitter_user);
  1028. }
  1029. }
  1030. $this->showJsonObjects($users);
  1031. $this->endDocument('json');
  1032. }
  1033. public function showSingleJsonGroup($group)
  1034. {
  1035. $this->initDocument('json');
  1036. $twitter_group = $this->twitterGroupArray($group);
  1037. $this->showJsonObjects($twitter_group);
  1038. $this->endDocument('json');
  1039. }
  1040. public function showSingleXmlGroup($group)
  1041. {
  1042. $this->initDocument('xml');
  1043. $twitter_group = $this->twitterGroupArray($group);
  1044. $this->showTwitterXmlGroup($twitter_group);
  1045. $this->endDocument('xml');
  1046. }
  1047. public function showSingleJsonList($list)
  1048. {
  1049. $this->initDocument('json');
  1050. $twitter_list = $this->twitterListArray($list);
  1051. $this->showJsonObjects($twitter_list);
  1052. $this->endDocument('json');
  1053. }
  1054. public function showSingleXmlList($list)
  1055. {
  1056. $this->initDocument('xml');
  1057. $twitter_list = $this->twitterListArray($list);
  1058. $this->showTwitterXmlList($twitter_list);
  1059. $this->endDocument('xml');
  1060. }
  1061. public function endTwitterAtom()
  1062. {
  1063. $this->elementEnd('feed');
  1064. $this->endXML();
  1065. }
  1066. public function showProfile($profile, $content_type = 'xml', $notice = null, $includeStatuses = true)
  1067. {
  1068. $profile_array = $this->twitterUserArray($profile, $includeStatuses);
  1069. switch ($content_type) {
  1070. case 'xml':
  1071. $this->showTwitterXmlUser($profile_array);
  1072. break;
  1073. case 'json':
  1074. $this->showJsonObjects($profile_array);
  1075. break;
  1076. default:
  1077. // TRANS: Client error on an API request with an unsupported data format.
  1078. $this->clientError(_('Not a supported data format.'));
  1079. }
  1080. return;
  1081. }
  1082. public function getTargetProfile($id)
  1083. {
  1084. if (empty($id)) {
  1085. // Twitter supports these other ways of passing the user ID
  1086. if (self::is_decimal($this->arg('id'))) {
  1087. return Profile::getKV($this->arg('id'));
  1088. } elseif ($this->arg('id')) {
  1089. // Screen names currently can only uniquely identify a local user.
  1090. $nickname = common_canonical_nickname($this->arg('id'));
  1091. $user = User::getKV('nickname', $nickname);
  1092. return $user ? $user->getProfile() : null;
  1093. } elseif ($this->arg('user_id')) {
  1094. // This is to ensure that a non-numeric user_id still
  1095. // overrides screen_name even if it doesn't get used
  1096. if (self::is_decimal($this->arg('user_id'))) {
  1097. return Profile::getKV('id', $this->arg('user_id'));
  1098. }
  1099. } elseif (mb_strlen($this->arg('screen_name')) > 0) {
  1100. $nickname = common_canonical_nickname($this->arg('screen_name'));
  1101. $user = User::getByNickname($nickname);
  1102. return $user->getProfile();
  1103. } else {
  1104. // Fall back to trying the currently authenticated user
  1105. return $this->scoped;
  1106. }
  1107. }
  1108. if (self::is_decimal($id) && intval($id) > 0) {
  1109. return Profile::getByID($id);
  1110. }
  1111. // FIXME: check if isAcct to identify remote profiles and not just local nicknames
  1112. $nickname = common_canonical_nickname($id);
  1113. $user = User::getByNickname($nickname);
  1114. return $user->getProfile();
  1115. }
  1116. private static function is_decimal($str)
  1117. {
  1118. return preg_match('/^[0-9]+$/', $str);
  1119. }
  1120. /**
  1121. * Returns query argument or default value if not found. Certain
  1122. * parameters used throughout the API are lightly scrubbed and
  1123. * bounds checked. This overrides Action::arg().
  1124. *
  1125. * @param string $key requested argument
  1126. * @param string $def default value to return if $key is not provided
  1127. *
  1128. * @return var $var
  1129. */
  1130. public function arg($key, $def = null)
  1131. {
  1132. // XXX: Do even more input validation/scrubbing?
  1133. if (array_key_exists($key, $this->args)) {
  1134. switch ($key) {
  1135. case 'page':
  1136. $page = (int)$this->args['page'];
  1137. return ($page < 1) ? 1 : $page;
  1138. case 'count':
  1139. $count = (int)$this->args['count'];
  1140. if ($count < 1) {
  1141. return 20;
  1142. } elseif ($count > 200) {
  1143. return 200;
  1144. } else {
  1145. return $count;
  1146. }
  1147. // no break
  1148. case 'since_id':
  1149. $since_id = (int)$this->args['since_id'];
  1150. return ($since_id < 1) ? 0 : $since_id;
  1151. case 'max_id':
  1152. $max_id = (int)$this->args['max_id'];
  1153. return ($max_id < 1) ? 0 : $max_id;
  1154. default:
  1155. return parent::arg($key, $def);
  1156. }
  1157. } else {
  1158. return $def;
  1159. }
  1160. }
  1161. public function getTargetGroup($id)
  1162. {
  1163. if (empty($id)) {
  1164. if (self::is_decimal($this->arg('id'))) {
  1165. return User_group::getKV('id', $this->arg('id'));
  1166. } elseif ($this->arg('id')) {
  1167. return User_group::getForNickname($this->arg('id'));
  1168. } elseif ($this->arg('group_id')) {
  1169. // This is to ensure that a non-numeric group_id still
  1170. // overrides group_name even if it doesn't get used
  1171. if (self::is_decimal($this->arg('group_id'))) {
  1172. return User_group::getKV('id', $this->arg('group_id'));
  1173. }
  1174. } elseif ($this->arg('group_name')) {
  1175. return User_group::getForNickname($this->arg('group_name'));
  1176. }
  1177. }
  1178. if (self::is_decimal($id)) {
  1179. return User_group::getKV('id', $id);
  1180. } elseif ($this->arg('uri')) { // FIXME: move this into empty($id) check?
  1181. return User_group::getKV('uri', urldecode($this->arg('uri')));
  1182. }
  1183. return User_group::getForNickname($id);
  1184. }
  1185. public function getTargetList($user = null, $id = null)
  1186. {
  1187. $tagger = $this->getTargetUser($user);
  1188. $list = null;
  1189. if (empty($id)) {
  1190. $id = $this->arg('id');
  1191. }
  1192. if ($id) {
  1193. if (is_numeric($id)) {
  1194. $list = Profile_list::getKV('id', $id);
  1195. // only if the list with the id belongs to the tagger
  1196. if (empty($list) || $list->tagger != $tagger->id) {
  1197. $list = null;
  1198. }
  1199. }
  1200. if (empty($list)) {
  1201. $tag = common_canonical_tag($id);
  1202. $list = Profile_list::getByTaggerAndTag($tagger->id, $tag);
  1203. }
  1204. if (!empty($list) && $list->private) {
  1205. if ($this->scoped->id == $list->tagger) {
  1206. return $list;
  1207. }
  1208. } else {
  1209. return $list;
  1210. }
  1211. }
  1212. return null;
  1213. }
  1214. public function getTargetUser($id)
  1215. {
  1216. if (empty($id)) {
  1217. // Twitter supports these other ways of passing the user ID
  1218. if (self::is_decimal($this->arg('id'))) {
  1219. return User::getKV($this->arg('id'));
  1220. } elseif ($this->arg('id')) {
  1221. $nickname = common_canonical_nickname($this->arg('id'));
  1222. return User::getKV('nickname', $nickname);
  1223. } elseif ($this->arg('user_id')) {
  1224. // This is to ensure that a non-numeric user_id still
  1225. // overrides screen_name even if it doesn't get used
  1226. if (self::is_decimal($this->arg('user_id'))) {
  1227. return User::getKV('id', $this->arg('user_id'));
  1228. }
  1229. } elseif ($this->arg('screen_name')) {
  1230. $nickname = common_canonical_nickname($this->arg('screen_name'));
  1231. return User::getKV('nickname', $nickname);
  1232. } elseif ($this->scoped instanceof Profile) {
  1233. // Fall back to trying the currently authenticated user
  1234. return $this->scoped->getUser();
  1235. } else {
  1236. throw new ClientException(_('No such user.'));
  1237. }
  1238. }
  1239. if (self::is_decimal($id)) {
  1240. return User::getKV($id);
  1241. }
  1242. $nickname = common_canonical_nickname($id);
  1243. return User::getKV('nickname', $nickname);
  1244. }
  1245. /**
  1246. * Calculate the complete URI that called up this action. Used for
  1247. * Atom rel="self" links. Warning: this is funky.
  1248. *
  1249. * @return string URL a URL suitable for rel="self" Atom links
  1250. */
  1251. public function getSelfUri()
  1252. {
  1253. $action = mb_substr(get_class($this), 0, -6); // remove 'Action'
  1254. $id = $this->arg('id');
  1255. $aargs = ['format' => $this->format];
  1256. if (!empty($id)) {
  1257. $aargs['id'] = $id;
  1258. }
  1259. $user = $this->arg('user');
  1260. if (!empty($user)) {
  1261. $aargs['user'] = $user;
  1262. }
  1263. $tag = $this->arg('tag');
  1264. if (!empty($tag)) {
  1265. $aargs['tag'] = $tag;
  1266. }
  1267. parse_str($_SERVER['QUERY_STRING'], $params);
  1268. $pstring = '';
  1269. if (!empty($params)) {
  1270. unset($params['p']);
  1271. $pstring = http_build_query($params);
  1272. }
  1273. $uri = common_local_url($action, $aargs);
  1274. if (!empty($pstring)) {
  1275. $uri .= '?' . $pstring;
  1276. }
  1277. return $uri;
  1278. }
  1279. /**
  1280. * Initialization.
  1281. *
  1282. * @param array $args Web and URL arguments
  1283. *
  1284. * @return boolean false if user doesn't exist
  1285. * @throws ClientException
  1286. */
  1287. protected function prepare(array $args = [])
  1288. {
  1289. GNUsocial::setApi(true); // reduce exception reports to aid in debugging
  1290. parent::prepare($args);
  1291. $this->format = $this->arg('format');
  1292. $this->callback = $this->arg('callback');
  1293. $this->page = (int)$this->arg('page', 1);
  1294. $this->count = (int)$this->arg('count', 20);
  1295. $this->max_id = (int)$this->arg('max_id', 0);
  1296. $this->since_id = (int)$this->arg('since_id', 0);
  1297. // These two are not used everywhere, mainly just AtompubAction extensions
  1298. $this->offset = ($this->page - 1) * $this->count;
  1299. $this->limit = $this->count + 1;
  1300. if ($this->arg('since')) {
  1301. header('X-GNUsocial-Warning: since parameter is disabled; use since_id');
  1302. }
  1303. $this->source = $this->trimmed('source');
  1304. if (empty($this->source) || in_array($this->source, self::$reserved_sources)) {
  1305. $this->source = 'api';
  1306. }
  1307. return true;
  1308. }
  1309. /**
  1310. * Handle a request
  1311. *
  1312. * @return void
  1313. */
  1314. protected function handle()
  1315. {
  1316. header('Access-Control-Allow-Origin: *');
  1317. parent::handle();
  1318. }
  1319. }