OStatusPlugin.php 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617
  1. <?php
  2. /*
  3. * StatusNet - the distributed open-source microblogging tool
  4. * Copyright (C) 2009-2010, 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. /**
  20. * OStatusPlugin implementation for GNU Social
  21. *
  22. * Depends on: WebFinger plugin
  23. *
  24. * @package OStatusPlugin
  25. * @maintainer Brion Vibber <brion@status.net>
  26. */
  27. if (!defined('GNUSOCIAL')) { exit(1); }
  28. require_once __DIR__ . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'util.php';
  29. class OStatusPlugin extends Plugin
  30. {
  31. const PLUGIN_VERSION = '2.1.0';
  32. /**
  33. * Hook for RouterInitialized event.
  34. *
  35. * @param URLMapper $m path-to-action mapper
  36. * @return boolean hook return
  37. */
  38. public function onRouterInitialized(URLMapper $m)
  39. {
  40. // Discovery actions
  41. $m->connect('main/ostatustag',
  42. ['action' => 'ostatustag']);
  43. $m->connect('main/ostatustag?nickname=:nickname',
  44. ['action' => 'ostatustag'],
  45. ['nickname' => '[A-Za-z0-9_-]+']);
  46. $m->connect('main/ostatus/group/:group',
  47. ['action' => 'ostatusinit'],
  48. ['group' => '[A-Za-z0-9_-]+']);
  49. $m->connect('main/ostatus/peopletag/:peopletag/tagger/:tagger',
  50. ['action' => 'ostatusinit'],
  51. ['tagger' => '[A-Za-z0-9_-]+',
  52. 'peopletag' => '[A-Za-z0-9_-]+']);
  53. $m->connect('main/ostatus',
  54. ['action' => 'ostatusinit']);
  55. // Remote subscription actions
  56. $m->connect('main/ostatusgroup',
  57. ['action' => 'ostatusgroup']);
  58. $m->connect('main/ostatuspeopletag',
  59. ['action' => 'ostatuspeopletag']);
  60. // WebSub actions
  61. $m->connect('main/push/hub', ['action' => 'pushhub']);
  62. $m->connect('main/push/callback/:feed',
  63. ['action' => 'pushcallback'],
  64. ['feed' => '[0-9]+']);
  65. // Salmon endpoint
  66. $m->connect('main/salmon/user/:id',
  67. ['action' => 'usersalmon'],
  68. ['id' => '[0-9]+']);
  69. $m->connect('main/salmon/group/:id',
  70. ['action' => 'groupsalmon'],
  71. ['id' => '[0-9]+']);
  72. $m->connect('main/salmon/peopletag/:id',
  73. ['action' => 'peopletagsalmon'],
  74. ['id' => '[0-9]+']);
  75. return true;
  76. }
  77. /**
  78. * Set up queue handlers for outgoing hub pushes
  79. * @param QueueManager $qm
  80. * @return boolean hook return
  81. */
  82. function onEndInitializeQueueManager(QueueManager $qm)
  83. {
  84. // Prepare outgoing distributions after notice save.
  85. $qm->connect('ostatus', 'OStatusQueueHandler');
  86. // Outgoing from our internal WebSub hub
  87. $qm->connect('hubconf', 'HubConfQueueHandler');
  88. $qm->connect('hubprep', 'HubPrepQueueHandler');
  89. $qm->connect('hubout', 'HubOutQueueHandler');
  90. // Outgoing Salmon replies (when we don't need a return value)
  91. $qm->connect('salmon', 'SalmonQueueHandler');
  92. // Incoming from a foreign WebSub hub
  93. $qm->connect('pushin', 'PushInQueueHandler');
  94. // Re-subscribe feeds that need renewal
  95. $qm->connect('pushrenew', 'PushRenewQueueHandler');
  96. return true;
  97. }
  98. /**
  99. * Put saved notices into the queue for pubsub distribution.
  100. */
  101. function onStartEnqueueNotice($notice, &$transports)
  102. {
  103. if ($notice->inScope(null) && $notice->getProfile()->hasRight(Right::PUBLICNOTICE)) {
  104. $transports[] = 'ostatus';
  105. $this->log(LOG_INFO, "OSTATUS [{$notice->getID()}]: queued for OStatus processing");
  106. } else {
  107. // FIXME: we don't do privacy-controlled OStatus updates yet.
  108. // once that happens, finer grain of control here.
  109. $this->log(LOG_NOTICE, "OSTATUS [{$notice->getID()}]: Not queueing because of privacy; scope = {$notice->scope}");
  110. }
  111. return true;
  112. }
  113. /**
  114. * Set up a WebSub hub link to our internal link for canonical timeline
  115. * Atom feeds for users and groups.
  116. */
  117. function onStartApiAtom($feed)
  118. {
  119. $id = null;
  120. if ($feed instanceof AtomUserNoticeFeed) {
  121. $salmonAction = 'usersalmon';
  122. $user = $feed->getUser();
  123. $id = $user->id;
  124. $profile = $user->getProfile();
  125. } else if ($feed instanceof AtomGroupNoticeFeed) {
  126. $salmonAction = 'groupsalmon';
  127. $group = $feed->getGroup();
  128. $id = $group->id;
  129. } else if ($feed instanceof AtomListNoticeFeed) {
  130. $salmonAction = 'peopletagsalmon';
  131. $peopletag = $feed->getList();
  132. $id = $peopletag->id;
  133. } else {
  134. return true;
  135. }
  136. if (!empty($id)) {
  137. $hub = common_config('ostatus', 'hub');
  138. if (empty($hub)) {
  139. // Updates will be handled through our internal WebSub hub.
  140. $hub = common_local_url('pushhub');
  141. }
  142. $feed->addLink($hub, array('rel' => 'hub'));
  143. // Also, we'll add in the salmon link
  144. $salmon = common_local_url($salmonAction, array('id' => $id));
  145. $feed->addLink($salmon, array('rel' => Salmon::REL_SALMON));
  146. // XXX: these are deprecated, but StatusNet only looks for NS_REPLIES
  147. $feed->addLink($salmon, array('rel' => Salmon::NS_REPLIES));
  148. $feed->addLink($salmon, array('rel' => Salmon::NS_MENTIONS));
  149. }
  150. return true;
  151. }
  152. /**
  153. * Add in an OStatus list button
  154. *
  155. * @param HTMLOutputter $output
  156. * @param Profile $profile
  157. * @return bool hook return value
  158. */
  159. function onStartProfileRemoteSubscribe(HTMLOutputter $output, Profile $profile): bool
  160. {
  161. $this->onStartProfileListItemActionElements($output);
  162. return true;
  163. }
  164. function onStartGroupSubscribe($widget, $group)
  165. {
  166. $cur = common_current_user();
  167. if (empty($cur)) {
  168. $widget->out->elementStart('li', 'entity_subscribe');
  169. $url = common_local_url('ostatusinit',
  170. array('group' => $group->nickname));
  171. $widget->out->element('a', array('href' => $url,
  172. 'class' => 'entity_remote_subscribe'),
  173. // TRANS: Link to subscribe to a remote entity.
  174. _m('Subscribe'));
  175. $widget->out->elementEnd('li');
  176. return false;
  177. }
  178. return true;
  179. }
  180. function onStartSubscribePeopletagForm($output, $peopletag)
  181. {
  182. $cur = common_current_user();
  183. if (empty($cur)) {
  184. $output->elementStart('li', 'entity_subscribe');
  185. $profile = $peopletag->getTagger();
  186. $url = common_local_url('ostatusinit',
  187. array('tagger' => $profile->nickname, 'peopletag' => $peopletag->tag));
  188. $output->element('a', array('href' => $url,
  189. 'class' => 'entity_remote_subscribe'),
  190. // TRANS: Link to subscribe to a remote entity.
  191. _m('Subscribe'));
  192. $output->elementEnd('li');
  193. return false;
  194. }
  195. return true;
  196. }
  197. /*
  198. * If the field being looked for is URI look for the profile
  199. */
  200. function onStartProfileCompletionSearch($action, $profile, $search_engine) {
  201. if ($action->field == 'uri') {
  202. $profile->joinAdd(array('id', 'user:id'));
  203. $profile->whereAdd('uri LIKE "%' . $profile->escape($q) . '%"');
  204. $profile->query();
  205. $validate = new Validate();
  206. if ($profile->N == 0) {
  207. try {
  208. if ($validate->email($q)) {
  209. $oprofile = Ostatus_profile::ensureWebfinger($q);
  210. } else if ($validate->uri($q)) {
  211. $oprofile = Ostatus_profile::ensureProfileURL($q);
  212. } else {
  213. // TRANS: Exception in OStatus when invalid URI was entered.
  214. throw new Exception(_m('Invalid URI.'));
  215. }
  216. return $this->filter(array($oprofile->localProfile()));
  217. } catch (Exception $e) {
  218. // TRANS: Error message in OStatus plugin. Do not translate the domain names example.com
  219. // TRANS: and example.net, as these are official standard domain names for use in examples.
  220. $this->msg = _m("Sorry, we could not reach that address. Please make sure that the OStatus address is like nickname@example.com or http://example.net/nickname.");
  221. return array();
  222. }
  223. }
  224. return false;
  225. }
  226. return true;
  227. }
  228. /**
  229. * Webfinger matches: @user@example.com or even @user--one.george_orwell@1984.biz
  230. * @param string $text The text from which to extract webfinger IDs
  231. * @param string $preMention Character(s) that signals a mention ('@', '!'...)
  232. *
  233. * @return array The matching IDs (without $preMention) and each respective position in the given string.
  234. */
  235. static function extractWebfingerIds($text, $preMention='@')
  236. {
  237. $wmatches = array();
  238. $result = preg_match_all('/(?<!\S)'.preg_quote($preMention, '/').'('.Nickname::WEBFINGER_FMT.')/',
  239. $text,
  240. $wmatches,
  241. PREG_OFFSET_CAPTURE);
  242. if ($result === false) {
  243. common_log(LOG_ERR, __METHOD__ . ': Error parsing webfinger IDs from text (preg_last_error=='.preg_last_error().').');
  244. return [];
  245. } elseif (count($wmatches)) {
  246. common_debug(sprintf('Found %d matches for WebFinger IDs: %s', count($wmatches), _ve($wmatches)));
  247. }
  248. return $wmatches[1];
  249. }
  250. /**
  251. * Profile URL matches: @example.com/mublog/user
  252. * @param string $text The text from which to extract URL mentions
  253. * @param string $preMention Character(s) that signals a mention ('@', '!'...)
  254. *
  255. * @return array The matching URLs (without @ or acct:) and each respective position in the given string.
  256. */
  257. static function extractUrlMentions($text, $preMention='@')
  258. {
  259. $wmatches = array();
  260. // In the regexp below we need to match / _before_ URL_REGEX_VALID_PATH_CHARS because it otherwise gets merged
  261. // with the TLD before (but / is in URL_REGEX_VALID_PATH_CHARS anyway, it's just its positioning that is important)
  262. $result = preg_match_all('/(?:^|\s+)'.preg_quote($preMention, '/').'('.URL_REGEX_DOMAIN_NAME.'(?:\/['.URL_REGEX_VALID_PATH_CHARS.']*)*)/',
  263. $text,
  264. $wmatches,
  265. PREG_OFFSET_CAPTURE);
  266. if ($result === false) {
  267. common_log(LOG_ERR, __METHOD__ . ': Error parsing profile URL mentions from text (preg_last_error=='.preg_last_error().').');
  268. return [];
  269. } elseif (count($wmatches)) {
  270. common_debug(sprintf('Found %d matches for profile URL mentions: %s', count($wmatches), _ve($wmatches)));
  271. }
  272. return $wmatches[1];
  273. }
  274. /**
  275. * Find any explicit remote mentions. Accepted forms:
  276. * Webfinger: @user@example.com
  277. * Profile link: @example.com/mublog/user
  278. * @param Profile $sender
  279. * @param string $text input markup text
  280. * @param array &$mention in/out param: set of found mentions
  281. * @return boolean hook return value
  282. */
  283. function onEndFindMentions(Profile $sender, $text, &$mentions)
  284. {
  285. $matches = array();
  286. foreach (self::extractWebfingerIds($text, '@') as $wmatch) {
  287. list($target, $pos) = $wmatch;
  288. $this->log(LOG_INFO, "Checking webfinger person '$target'");
  289. $profile = null;
  290. try {
  291. $oprofile = Ostatus_profile::ensureWebfinger($target);
  292. if (!$oprofile instanceof Ostatus_profile || !$oprofile->isPerson()) {
  293. continue;
  294. }
  295. $profile = $oprofile->localProfile();
  296. } catch (OStatusShadowException $e) {
  297. // This means we got a local user in the webfinger lookup
  298. $profile = $e->profile;
  299. } catch (Exception $e) {
  300. $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
  301. continue;
  302. }
  303. assert($profile instanceof Profile);
  304. $displayName = !empty($profile->nickname) && mb_strlen($profile->nickname) < mb_strlen($target)
  305. ? $profile->getNickname() // TODO: we could do getBestName() or getFullname() here
  306. : $target;
  307. $url = $profile->getUri();
  308. if (!common_valid_http_url($url)) {
  309. $url = $profile->getUrl();
  310. }
  311. $matches[$pos] = array('mentioned' => array($profile),
  312. 'type' => 'mention',
  313. 'text' => $displayName,
  314. 'position' => $pos,
  315. 'length' => mb_strlen($target),
  316. 'url' => $url);
  317. }
  318. // Doing groups in a separate routine because webfinger lookups don't work
  319. // remotely until everyone updates etc. etc.
  320. foreach (self::extractWebfingerIds($text, '!') as $wmatch) {
  321. list($target, $pos) = $wmatch;
  322. list($target_nickname, $target_hostname) = explode('@', parse_url($target, PHP_URL_PATH));
  323. $this->log(LOG_INFO, sprintf('Checking webfinger group %s as user %s on server %s', $target, $target_nickname, $target_hostname));
  324. $profile = null;
  325. if ($target_hostname === mb_strtolower(common_config('site', 'server'))) {
  326. try {
  327. $profile = Local_group::getKV('nickname', $target_nickname)->getProfile();
  328. } catch (NoSuchGroupException $e) {
  329. // referenced a local group which does not exist, so not returning it as a mention
  330. $this->log(LOG_ERR, "Local group lookup failed: " . _ve($e->getMessage()));
  331. continue;
  332. }
  333. } else {
  334. // XXX: Superhacky. Domain name can be incorrectly matched
  335. // here. But since users are only members of groups
  336. // they trust (of course they are!), the likelihood of
  337. // a mention-hijacking is very very low... for now.
  338. $possible_groups = new User_group();
  339. $possible_groups->nickname = $target_nickname;
  340. if (!$possible_groups->find()) {
  341. common_debug('No groups at all found with nickname: '._ve($target_nickname));
  342. continue;
  343. }
  344. while ($possible_groups->fetch()) {
  345. if (!$sender->isMember($possible_groups)) {
  346. continue;
  347. }
  348. $group_hostname = mb_strtolower(parse_url($possible_groups->mainpage, PHP_URL_HOST));
  349. if ($target_hostname === $group_hostname) {
  350. common_debug(sprintf('Found group with nick@host (%s@%s) matching %s', _ve($possible_groups->nickname), _ve($group_hostname), _ve($target)));
  351. $profile = $possible_groups->getProfile();
  352. break;
  353. }
  354. }
  355. $possible_groups->free();
  356. if (!$profile instanceof Profile) {
  357. common_debug('Found groups with correct nickname but not hostname for: '._ve($target));
  358. continue;
  359. }
  360. }
  361. assert($profile instanceof Profile);
  362. $displayName = !empty($profile->nickname) && mb_strlen($profile->nickname) < mb_strlen($target)
  363. ? $profile->getNickname() // TODO: we could do getBestName() or getFullname() here
  364. : $target;
  365. $url = $profile->getUri();
  366. if (!common_valid_http_url($url)) {
  367. $url = $profile->getUrl();
  368. }
  369. $matches[$pos] = array('mentioned' => array($profile),
  370. 'type' => 'group',
  371. 'text' => $displayName,
  372. 'position' => $pos,
  373. 'length' => mb_strlen($target),
  374. 'url' => $url);
  375. }
  376. foreach (self::extractUrlMentions($text) as $wmatch) {
  377. list($target, $pos) = $wmatch;
  378. $schemes = array('https', 'http');
  379. foreach ($schemes as $scheme) {
  380. $url = "$scheme://$target";
  381. $this->log(LOG_INFO, "Checking profile address '$url'");
  382. try {
  383. $oprofile = Ostatus_profile::ensureProfileURL($url);
  384. if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
  385. $profile = $oprofile->localProfile();
  386. $displayName = !empty($profile->nickname) && mb_strlen($profile->nickname) < mb_strlen($target) ?
  387. $profile->nickname : $target;
  388. $matches[$pos] = array('mentioned' => array($profile),
  389. 'type' => 'mention',
  390. 'text' => $displayName,
  391. 'position' => $pos,
  392. 'length' => mb_strlen($target),
  393. 'url' => $profile->getUrl());
  394. break;
  395. }
  396. } catch (Exception $e) {
  397. $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
  398. }
  399. }
  400. }
  401. foreach ($mentions as $i => $other) {
  402. // If we share a common prefix with a local user, override it!
  403. $pos = $other['position'];
  404. if (isset($matches[$pos])) {
  405. $mentions[$i] = $matches[$pos];
  406. unset($matches[$pos]);
  407. }
  408. }
  409. foreach ($matches as $mention) {
  410. $mentions[] = $mention;
  411. }
  412. return true;
  413. }
  414. /**
  415. * Allow remote profile references to be used in commands:
  416. * sub update@status.net
  417. * whois evan@identi.ca
  418. * reply http://identi.ca/evan hey what's up
  419. *
  420. * @param Command $command
  421. * @param string $arg
  422. * @param Profile &$profile
  423. * @return hook return code
  424. */
  425. function onStartCommandGetProfile($command, $arg, &$profile)
  426. {
  427. $oprofile = $this->pullRemoteProfile($arg);
  428. if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
  429. try {
  430. $profile = $oprofile->localProfile();
  431. } catch (NoProfileException $e) {
  432. // No locally stored profile found for remote profile
  433. return true;
  434. }
  435. return false;
  436. } else {
  437. return true;
  438. }
  439. }
  440. /**
  441. * Allow remote group references to be used in commands:
  442. * join group+statusnet@identi.ca
  443. * join http://identi.ca/group/statusnet
  444. * drop identi.ca/group/statusnet
  445. *
  446. * @param Command $command
  447. * @param string $arg
  448. * @param User_group &$group
  449. * @return hook return code
  450. */
  451. function onStartCommandGetGroup($command, $arg, &$group)
  452. {
  453. $oprofile = $this->pullRemoteProfile($arg);
  454. if ($oprofile instanceof Ostatus_profile && $oprofile->isGroup()) {
  455. $group = $oprofile->localGroup();
  456. return false;
  457. } else {
  458. return true;
  459. }
  460. }
  461. protected function pullRemoteProfile($arg)
  462. {
  463. $oprofile = null;
  464. if (preg_match('!^((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)$!', $arg)) {
  465. // webfinger lookup
  466. try {
  467. return Ostatus_profile::ensureWebfinger($arg);
  468. } catch (Exception $e) {
  469. common_log(LOG_ERR, 'Webfinger lookup failed for ' .
  470. $arg . ': ' . $e->getMessage());
  471. }
  472. }
  473. // Look for profile URLs, with or without scheme:
  474. $urls = array();
  475. if (preg_match('!^https?://((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
  476. $urls[] = $arg;
  477. }
  478. if (preg_match('!^((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
  479. $schemes = array('http', 'https');
  480. foreach ($schemes as $scheme) {
  481. $urls[] = "$scheme://$arg";
  482. }
  483. }
  484. foreach ($urls as $url) {
  485. try {
  486. return Ostatus_profile::ensureProfileURL($url);
  487. } catch (Exception $e) {
  488. common_log(LOG_ERR, 'Profile lookup failed for ' .
  489. $arg . ': ' . $e->getMessage());
  490. }
  491. }
  492. return null;
  493. }
  494. function onEndProfileSettingsActions($out) {
  495. $siteName = common_config('site', 'name');
  496. $js = 'navigator.registerContentHandler("application/vnd.mozilla.maybe.feed", "'.addslashes(common_local_url('RemoteFollowSub', null, array('profile' => '%s'))).'", "'.addslashes($siteName).'")';
  497. $out->elementStart('li');
  498. $out->element('a',
  499. array('href' => 'javascript:'.$js),
  500. // TRANS: Option in profile settings to add this instance to Firefox as a feedreader
  501. _('Add to Firefox as feedreader'));
  502. $out->elementEnd('li');
  503. }
  504. /**
  505. * Make sure necessary tables are filled out.
  506. */
  507. function onCheckSchema() {
  508. $schema = Schema::get();
  509. $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
  510. $schema->ensureTable('feedsub', FeedSub::schemaDef());
  511. $schema->ensureTable('hubsub', HubSub::schemaDef());
  512. $schema->ensureTable('magicsig', Magicsig::schemaDef());
  513. return true;
  514. }
  515. public function onEndShowStylesheets(Action $action) {
  516. $action->cssLink($this->path('theme/base/css/ostatus.css'));
  517. return true;
  518. }
  519. function onEndShowStatusNetScripts($action) {
  520. $action->script($this->path('js/ostatus.js'));
  521. return true;
  522. }
  523. /**
  524. * Override the "from ostatus" bit in notice lists to link to the
  525. * original post and show the domain it came from.
  526. *
  527. * @param Notice in $notice
  528. * @param string out &$name
  529. * @param string out &$url
  530. * @param string out &$title
  531. * @return mixed hook return code
  532. */
  533. function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
  534. {
  535. // If we don't handle this, keep the event handler going
  536. if (!in_array($notice->source, array('ostatus', 'share'))) {
  537. return true;
  538. }
  539. try {
  540. $url = $notice->getUrl();
  541. // If getUrl() throws exception, $url is never set
  542. $bits = parse_url($url);
  543. $domain = $bits['host'];
  544. if (substr($domain, 0, 4) == 'www.') {
  545. $name = substr($domain, 4);
  546. } else {
  547. $name = $domain;
  548. }
  549. // TRANS: Title. %s is a domain name.
  550. $title = sprintf(_m('Sent from %s via OStatus'), $domain);
  551. // Abort event handler, we have a name and URL!
  552. return false;
  553. } catch (InvalidUrlException $e) {
  554. // This just means we don't have the notice source data
  555. return true;
  556. }
  557. }
  558. /**
  559. * Send incoming WebSub feeds for OStatus endpoints in for processing.
  560. *
  561. * @param FeedSub $feedsub
  562. * @param DOMDocument $feed
  563. * @return mixed hook return code
  564. */
  565. function onStartFeedSubReceive($feedsub, $feed)
  566. {
  567. $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
  568. if ($oprofile instanceof Ostatus_profile) {
  569. $oprofile->processFeed($feed, 'push');
  570. } else {
  571. common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
  572. }
  573. }
  574. /**
  575. * Tell the FeedSub infrastructure whether we have any active OStatus
  576. * usage for the feed; if not it'll be able to garbage-collect the
  577. * feed subscription.
  578. *
  579. * @param FeedSub $feedsub
  580. * @param integer $count in/out
  581. * @return mixed hook return code
  582. */
  583. function onFeedSubSubscriberCount($feedsub, &$count)
  584. {
  585. $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
  586. if ($oprofile instanceof Ostatus_profile) {
  587. $count += $oprofile->subscriberCount();
  588. }
  589. return true;
  590. }
  591. /**
  592. * When about to subscribe to a remote user, start a server-to-server
  593. * WebSub subscription if needed. If we can't establish that, abort.
  594. *
  595. * @fixme If something else aborts later, we could end up with a stray
  596. * WebSub subscription. This is relatively harmless, though.
  597. *
  598. * @param Profile $profile subscriber
  599. * @param Profile $other subscribee
  600. *
  601. * @return hook return code
  602. *
  603. * @throws Exception
  604. */
  605. function onStartSubscribe(Profile $profile, Profile $other)
  606. {
  607. if (!$profile->isLocal()) {
  608. return true;
  609. }
  610. $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
  611. if (!$oprofile instanceof Ostatus_profile) {
  612. return true;
  613. }
  614. $oprofile->subscribe();
  615. }
  616. /**
  617. * Having established a remote subscription, send a notification to the
  618. * remote OStatus profile's endpoint.
  619. *
  620. * @param Profile $profile subscriber
  621. * @param Profile $other subscribee
  622. *
  623. * @return hook return code
  624. *
  625. * @throws Exception
  626. */
  627. function onEndSubscribe(Profile $profile, Profile $other)
  628. {
  629. if (!$profile->isLocal()) {
  630. return true;
  631. }
  632. $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
  633. if (!$oprofile instanceof Ostatus_profile) {
  634. return true;
  635. }
  636. $sub = Subscription::pkeyGet(array('subscriber' => $profile->id,
  637. 'subscribed' => $other->id));
  638. $act = $sub->asActivity();
  639. $oprofile->notifyActivity($act, $profile);
  640. return true;
  641. }
  642. /**
  643. * Notify remote server and garbage collect unused feeds on unsubscribe.
  644. * @todo FIXME: Send these operations to background queues
  645. *
  646. * @param User $user
  647. * @param Profile $other
  648. * @return hook return value
  649. */
  650. function onEndUnsubscribe(Profile $profile, Profile $other)
  651. {
  652. if (!$profile->isLocal()) {
  653. return true;
  654. }
  655. $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
  656. if (!$oprofile instanceof Ostatus_profile) {
  657. return true;
  658. }
  659. // Drop the WebSub subscription if there are no other subscribers.
  660. $oprofile->garbageCollect();
  661. $act = new Activity();
  662. $act->verb = ActivityVerb::UNFOLLOW;
  663. $act->id = TagURI::mint('unfollow:%d:%d:%s',
  664. $profile->id,
  665. $other->id,
  666. common_date_iso8601(time()));
  667. $act->time = time();
  668. // TRANS: Title for unfollowing a remote profile.
  669. $act->title = _m('TITLE','Unfollow');
  670. // TRANS: Success message for unsubscribe from user attempt through OStatus.
  671. // TRANS: %1$s is the unsubscriber's name, %2$s is the unsubscribed user's name.
  672. $act->content = sprintf(_m('%1$s stopped following %2$s.'),
  673. $profile->getBestName(),
  674. $other->getBestName());
  675. $act->actor = $profile->asActivityObject();
  676. $act->objects[] = $other->asActivityObject();
  677. $oprofile->notifyActivity($act, $profile);
  678. return true;
  679. }
  680. /**
  681. * When one of our local users tries to join a remote group,
  682. * notify the remote server. If the notification is rejected,
  683. * deny the join.
  684. *
  685. * @param User_group $group
  686. * @param Profile $profile
  687. *
  688. * @return mixed hook return value
  689. * @throws Exception of various kinds, some from $oprofile->subscribe();
  690. */
  691. function onStartJoinGroup($group, $profile)
  692. {
  693. $oprofile = Ostatus_profile::getKV('group_id', $group->id);
  694. if (!$oprofile instanceof Ostatus_profile) {
  695. return true;
  696. }
  697. $oprofile->subscribe();
  698. // NOTE: we don't use Group_member::asActivity() since that record
  699. // has not yet been created.
  700. $act = new Activity();
  701. $act->id = TagURI::mint('join:%d:%d:%s',
  702. $profile->id,
  703. $group->id,
  704. common_date_iso8601(time()));
  705. $act->actor = $profile->asActivityObject();
  706. $act->verb = ActivityVerb::JOIN;
  707. $act->objects[] = $oprofile->asActivityObject();
  708. $act->time = time();
  709. // TRANS: Title for joining a remote groep.
  710. $act->title = _m('TITLE','Join');
  711. // TRANS: Success message for subscribe to group attempt through OStatus.
  712. // TRANS: %1$s is the member name, %2$s is the subscribed group's name.
  713. $act->content = sprintf(_m('%1$s has joined group %2$s.'),
  714. $profile->getBestName(),
  715. $oprofile->getBestName());
  716. if ($oprofile->notifyActivity($act, $profile)) {
  717. return true;
  718. } else {
  719. $oprofile->garbageCollect();
  720. // TRANS: Exception thrown when joining a remote group fails.
  721. throw new Exception(_m('Failed joining remote group.'));
  722. }
  723. }
  724. /**
  725. * When one of our local users leaves a remote group, notify the remote
  726. * server.
  727. *
  728. * @fixme Might be good to schedule a resend of the leave notification
  729. * if it failed due to a transitory error. We've canceled the local
  730. * membership already anyway, but if the remote server comes back up
  731. * it'll be left with a stray membership record.
  732. *
  733. * @param User_group $group
  734. * @param Profile $profile
  735. *
  736. * @return mixed hook return value
  737. */
  738. function onEndLeaveGroup($group, $profile)
  739. {
  740. $oprofile = Ostatus_profile::getKV('group_id', $group->id);
  741. if (!$oprofile instanceof Ostatus_profile) {
  742. return true;
  743. }
  744. // Drop the WebSub subscription if there are no other subscribers.
  745. $oprofile->garbageCollect();
  746. $member = $profile;
  747. $act = new Activity();
  748. $act->id = TagURI::mint('leave:%d:%d:%s',
  749. $member->id,
  750. $group->id,
  751. common_date_iso8601(time()));
  752. $act->actor = $member->asActivityObject();
  753. $act->verb = ActivityVerb::LEAVE;
  754. $act->objects[] = $oprofile->asActivityObject();
  755. $act->time = time();
  756. // TRANS: Title for leaving a remote group.
  757. $act->title = _m('TITLE','Leave');
  758. // TRANS: Success message for unsubscribe from group attempt through OStatus.
  759. // TRANS: %1$s is the member name, %2$s is the unsubscribed group's name.
  760. $act->content = sprintf(_m('%1$s has left group %2$s.'),
  761. $member->getBestName(),
  762. $oprofile->getBestName());
  763. $oprofile->notifyActivity($act, $member);
  764. }
  765. /**
  766. * When one of our local users tries to subscribe to a remote peopletag,
  767. * notify the remote server. If the notification is rejected,
  768. * deny the subscription.
  769. *
  770. * @param Profile_list $peopletag
  771. * @param User $user
  772. *
  773. * @return mixed hook return value
  774. * @throws Exception of various kinds, some from $oprofile->subscribe();
  775. */
  776. function onStartSubscribePeopletag($peopletag, $user)
  777. {
  778. $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
  779. if (!$oprofile instanceof Ostatus_profile) {
  780. return true;
  781. }
  782. $oprofile->subscribe();
  783. $sub = $user->getProfile();
  784. $tagger = Profile::getKV($peopletag->tagger);
  785. $act = new Activity();
  786. $act->id = TagURI::mint('subscribe_peopletag:%d:%d:%s',
  787. $sub->id,
  788. $peopletag->id,
  789. common_date_iso8601(time()));
  790. $act->actor = $sub->asActivityObject();
  791. $act->verb = ActivityVerb::FOLLOW;
  792. $act->objects[] = $oprofile->asActivityObject();
  793. $act->time = time();
  794. // TRANS: Title for following a remote list.
  795. $act->title = _m('TITLE','Follow list');
  796. // TRANS: Success message for remote list follow through OStatus.
  797. // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
  798. $act->content = sprintf(_m('%1$s is now following people listed in %2$s by %3$s.'),
  799. $sub->getBestName(),
  800. $oprofile->getBestName(),
  801. $tagger->getBestName());
  802. if ($oprofile->notifyActivity($act, $sub)) {
  803. return true;
  804. } else {
  805. $oprofile->garbageCollect();
  806. // TRANS: Exception thrown when subscription to remote list fails.
  807. throw new Exception(_m('Failed subscribing to remote list.'));
  808. }
  809. }
  810. /**
  811. * When one of our local users unsubscribes to a remote peopletag, notify the remote
  812. * server.
  813. *
  814. * @param Profile_list $peopletag
  815. * @param User $user
  816. *
  817. * @return mixed hook return value
  818. */
  819. function onEndUnsubscribePeopletag($peopletag, $user)
  820. {
  821. $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
  822. if (!$oprofile instanceof Ostatus_profile) {
  823. return true;
  824. }
  825. // Drop the WebSub subscription if there are no other subscribers.
  826. $oprofile->garbageCollect();
  827. $sub = Profile::getKV($user->id);
  828. $tagger = Profile::getKV($peopletag->tagger);
  829. $act = new Activity();
  830. $act->id = TagURI::mint('unsubscribe_peopletag:%d:%d:%s',
  831. $sub->id,
  832. $peopletag->id,
  833. common_date_iso8601(time()));
  834. $act->actor = $member->asActivityObject();
  835. $act->verb = ActivityVerb::UNFOLLOW;
  836. $act->objects[] = $oprofile->asActivityObject();
  837. $act->time = time();
  838. // TRANS: Title for unfollowing a remote list.
  839. $act->title = _m('Unfollow list');
  840. // TRANS: Success message for remote list unfollow through OStatus.
  841. // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
  842. $act->content = sprintf(_m('%1$s stopped following the list %2$s by %3$s.'),
  843. $sub->getBestName(),
  844. $oprofile->getBestName(),
  845. $tagger->getBestName());
  846. $oprofile->notifyActivity($act, $user);
  847. }
  848. /**
  849. * Notify remote users when their notices get favorited.
  850. *
  851. * @param Profile or User $profile of local user doing the faving
  852. * @param Notice $notice being favored
  853. * @return hook return value
  854. */
  855. function onEndFavorNotice(Profile $profile, Notice $notice)
  856. {
  857. // Only distribute local users' favor actions, remote users
  858. // will have already distributed theirs.
  859. if (!$profile->isLocal()) {
  860. return true;
  861. }
  862. $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
  863. if (!$oprofile instanceof Ostatus_profile) {
  864. return true;
  865. }
  866. $fav = Fave::pkeyGet(array('user_id' => $profile->id,
  867. 'notice_id' => $notice->id));
  868. if (!$fav instanceof Fave) {
  869. // That's weird.
  870. // TODO: Make pkeyGet throw exception, since this is a critical failure.
  871. return true;
  872. }
  873. $act = $fav->asActivity();
  874. $oprofile->notifyActivity($act, $profile);
  875. return true;
  876. }
  877. /**
  878. * Notify remote user it has got a new people tag
  879. * - tag verb is queued
  880. * - the subscription is done immediately if not present
  881. *
  882. * @param Profile_tag $ptag the people tag that was created
  883. * @return hook return value
  884. * @throws Exception of various kinds, some from $oprofile->subscribe();
  885. */
  886. function onEndTagProfile($ptag)
  887. {
  888. $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
  889. if (!$oprofile instanceof Ostatus_profile) {
  890. return true;
  891. }
  892. $plist = $ptag->getMeta();
  893. if ($plist->private) {
  894. return true;
  895. }
  896. $act = new Activity();
  897. $tagger = $plist->getTagger();
  898. $tagged = Profile::getKV('id', $ptag->tagged);
  899. $act->verb = ActivityVerb::TAG;
  900. $act->id = TagURI::mint('tag_profile:%d:%d:%s',
  901. $plist->tagger, $plist->id,
  902. common_date_iso8601(time()));
  903. $act->time = time();
  904. // TRANS: Title for listing a remote profile.
  905. $act->title = _m('TITLE','List');
  906. // TRANS: Success message for remote list addition through OStatus.
  907. // TRANS: %1$s is the list creator's name, %2$s is the added list member, %3$s is the list name.
  908. $act->content = sprintf(_m('%1$s listed %2$s in the list %3$s.'),
  909. $tagger->getBestName(),
  910. $tagged->getBestName(),
  911. $plist->getBestName());
  912. $act->actor = $tagger->asActivityObject();
  913. $act->objects = array($tagged->asActivityObject());
  914. $act->target = ActivityObject::fromPeopletag($plist);
  915. $oprofile->notifyDeferred($act, $tagger);
  916. // initiate a WebSub subscription for the person being tagged
  917. $oprofile->subscribe();
  918. return true;
  919. }
  920. /**
  921. * Notify remote user that a people tag has been removed
  922. * - untag verb is queued
  923. * - the subscription is undone immediately if not required
  924. * i.e garbageCollect()'d
  925. *
  926. * @param Profile_tag $ptag the people tag that was deleted
  927. * @return hook return value
  928. */
  929. function onEndUntagProfile($ptag)
  930. {
  931. $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
  932. if (!$oprofile instanceof Ostatus_profile) {
  933. return true;
  934. }
  935. $plist = $ptag->getMeta();
  936. if ($plist->private) {
  937. return true;
  938. }
  939. $act = new Activity();
  940. $tagger = $plist->getTagger();
  941. $tagged = Profile::getKV('id', $ptag->tagged);
  942. $act->verb = ActivityVerb::UNTAG;
  943. $act->id = TagURI::mint('untag_profile:%d:%d:%s',
  944. $plist->tagger, $plist->id,
  945. common_date_iso8601(time()));
  946. $act->time = time();
  947. // TRANS: Title for unlisting a remote profile.
  948. $act->title = _m('TITLE','Unlist');
  949. // TRANS: Success message for remote list removal through OStatus.
  950. // TRANS: %1$s is the list creator's name, %2$s is the removed list member, %3$s is the list name.
  951. $act->content = sprintf(_m('%1$s removed %2$s from the list %3$s.'),
  952. $tagger->getBestName(),
  953. $tagged->getBestName(),
  954. $plist->getBestName());
  955. $act->actor = $tagger->asActivityObject();
  956. $act->objects = array($tagged->asActivityObject());
  957. $act->target = ActivityObject::fromPeopletag($plist);
  958. $oprofile->notifyDeferred($act, $tagger);
  959. // unsubscribe to WebSub feed if no more required
  960. $oprofile->garbageCollect();
  961. return true;
  962. }
  963. /**
  964. * Notify remote users when their notices get de-favorited.
  965. *
  966. * @param Profile $profile Profile person doing the de-faving
  967. * @param Notice $notice Notice being favored
  968. *
  969. * @return hook return value
  970. */
  971. function onEndDisfavorNotice(Profile $profile, Notice $notice)
  972. {
  973. // Only distribute local users' disfavor actions, remote users
  974. // will have already distributed theirs.
  975. if (!$profile->isLocal()) {
  976. return true;
  977. }
  978. $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
  979. if (!$oprofile instanceof Ostatus_profile) {
  980. return true;
  981. }
  982. $act = new Activity();
  983. $act->verb = ActivityVerb::UNFAVORITE;
  984. $act->id = TagURI::mint('disfavor:%d:%d:%s',
  985. $profile->id,
  986. $notice->id,
  987. common_date_iso8601(time()));
  988. $act->time = time();
  989. // TRANS: Title for unliking a remote notice.
  990. $act->title = _m('Unlike');
  991. // TRANS: Success message for remove a favorite notice through OStatus.
  992. // TRANS: %1$s is the unfavoring user's name, %2$s is URI to the no longer favored notice.
  993. $act->content = sprintf(_m('%1$s no longer likes %2$s.'),
  994. $profile->getBestName(),
  995. $notice->getUrl());
  996. $act->actor = $profile->asActivityObject();
  997. $act->objects[] = $notice->asActivityObject();
  998. $oprofile->notifyActivity($act, $profile);
  999. return true;
  1000. }
  1001. function onStartGetProfileUri($profile, &$uri)
  1002. {
  1003. $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
  1004. if ($oprofile instanceof Ostatus_profile) {
  1005. $uri = $oprofile->uri;
  1006. return false;
  1007. }
  1008. return true;
  1009. }
  1010. function onStartUserGroupHomeUrl($group, &$url)
  1011. {
  1012. return $this->onStartUserGroupPermalink($group, $url);
  1013. }
  1014. function onStartUserGroupPermalink($group, &$url)
  1015. {
  1016. $oprofile = Ostatus_profile::getKV('group_id', $group->id);
  1017. if ($oprofile instanceof Ostatus_profile) {
  1018. // @fixme this should probably be in the user_group table
  1019. // @fixme this uri not guaranteed to be a profile page
  1020. $url = $oprofile->uri;
  1021. return false;
  1022. }
  1023. }
  1024. function onStartShowUserGroupsContent($action)
  1025. {
  1026. $this->showEntityRemoteSubscribe($action);
  1027. return true;
  1028. }
  1029. function onEndShowGroupsMiniList($action)
  1030. {
  1031. $this->showEntityRemoteSubscribe($action);
  1032. return true;
  1033. }
  1034. function showEntityRemoteSubscribe($action)
  1035. {
  1036. if (!$action->getScoped() instanceof Profile) {
  1037. // early return if we're not logged in
  1038. return true;
  1039. }
  1040. if ($action->getScoped()->sameAs($action->getTarget())) {
  1041. $action->elementStart('div', 'entity_actions');
  1042. $action->elementStart('p', array('id' => 'entity_remote_subscribe',
  1043. 'class' => 'entity_subscribe'));
  1044. $action->element('a', array('href' => common_local_url('ostatusgroup'),
  1045. 'class' => 'entity_remote_subscribe'),
  1046. // TRANS: Link text for link to remote subscribe.
  1047. _m('Remote'));
  1048. $action->elementEnd('p');
  1049. $action->elementEnd('div');
  1050. }
  1051. }
  1052. /**
  1053. * Ping remote profiles with updates to this profile.
  1054. * Salmon pings are queued for background processing.
  1055. */
  1056. function onEndBroadcastProfile(Profile $profile)
  1057. {
  1058. $user = User::getKV('id', $profile->id);
  1059. // Find foreign accounts I'm subscribed to that support Salmon pings.
  1060. //
  1061. // @fixme we could run updates through the WebSub feed too,
  1062. // in which case we can skip Salmon pings to folks who
  1063. // are also subscribed to me.
  1064. $sql = "SELECT * FROM ostatus_profile " .
  1065. "WHERE profile_id IN " .
  1066. "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
  1067. "OR group_id IN " .
  1068. "(SELECT group_id FROM group_member WHERE profile_id=%d)";
  1069. $oprofile = new Ostatus_profile();
  1070. $oprofile->query(sprintf($sql, $profile->id, $profile->id));
  1071. if ($oprofile->N == 0) {
  1072. common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
  1073. return true;
  1074. }
  1075. $act = new Activity();
  1076. $act->verb = ActivityVerb::UPDATE_PROFILE;
  1077. $act->id = TagURI::mint('update-profile:%d:%s',
  1078. $profile->id,
  1079. common_date_iso8601(time()));
  1080. $act->time = time();
  1081. // TRANS: Title for activity.
  1082. $act->title = _m('Profile update');
  1083. // TRANS: Ping text for remote profile update through OStatus.
  1084. // TRANS: %s is user that updated their profile.
  1085. $act->content = sprintf(_m('%s has updated their profile page.'),
  1086. $profile->getBestName());
  1087. $act->actor = $profile->asActivityObject();
  1088. $act->objects[] = $act->actor;
  1089. while ($oprofile->fetch()) {
  1090. $oprofile->notifyDeferred($act, $profile);
  1091. }
  1092. return true;
  1093. }
  1094. function onEndShowAccountProfileBlock(HTMLOutputter $out, Profile $profile)
  1095. {
  1096. if ($profile->isLocal()) {
  1097. return true;
  1098. }
  1099. try {
  1100. $oprofile = Ostatus_profile::fromProfile($profile);
  1101. } catch (Exception $e) {
  1102. // Not a remote Ostatus_profile! Maybe some other network
  1103. // that has imported a non-local user?
  1104. return true;
  1105. }
  1106. try {
  1107. $feedsub = $oprofile->getFeedSub();
  1108. } catch (NoResultException $e) {
  1109. // No WebSub subscription has been attempted or exists for this profile
  1110. // which is the case, say for remote profiles that are only included
  1111. // via mentions or repeat/share.
  1112. return true;
  1113. }
  1114. $websub_states = [
  1115. 'subscribe' => _m('Pending'),
  1116. 'active' => _m('Active'),
  1117. 'nohub' => _m('Polling'),
  1118. 'inactive' => _m('Inactive'),
  1119. ];
  1120. $out->elementStart('dl', 'entity_tags ostatus_profile');
  1121. $out->element('dt', null, _m('WebSub'));
  1122. $out->element('dd', null, $websub_states[$feedsub->sub_state]);
  1123. $out->elementEnd('dl');
  1124. }
  1125. // FIXME: This one can accept both an Action and a Widget. Confusing! Refactor to (HTMLOutputter $out, Profile $target)!
  1126. function onStartProfileListItemActionElements($item)
  1127. {
  1128. if (common_logged_in()) {
  1129. // only non-logged in users get to see the "remote subscribe" form
  1130. return true;
  1131. }
  1132. $target = $item->getTarget();
  1133. if (!$target->isLocal()) {
  1134. // we can (for now) only provide remote subscribe forms for local users
  1135. return true;
  1136. }
  1137. if ($item instanceof ProfileAction) {
  1138. $output = $item;
  1139. } elseif ($item instanceof Widget) {
  1140. $output = $item->out;
  1141. } else {
  1142. // Bad $item class, don't know how to use this for outputting!
  1143. throw new ServerException('Bad item type for onStartProfileListItemActionElements');
  1144. }
  1145. $output->elementStart('li', 'entity_tag');
  1146. $url = common_local_url('ostatustag', ['nickname' => $target->getNickname()]);
  1147. $output->element('a',
  1148. ['href' => $url,
  1149. 'class' => 'entity_remote_tag'],
  1150. // TRANS: Link text for a user to list an OStatus user.
  1151. _m('List'));
  1152. $output->elementEnd('li');
  1153. return true;
  1154. }
  1155. /**
  1156. * Plugin Nodeinfo information
  1157. *
  1158. * @param array $protocols
  1159. * @return bool hook true
  1160. */
  1161. public function onNodeInfoProtocols(array &$protocols)
  1162. {
  1163. $protocols[] = "ostatus";
  1164. return true;
  1165. }
  1166. public function onPluginVersion(array &$versions): bool
  1167. {
  1168. $versions[] = array('name' => 'OStatus',
  1169. 'version' => self::PLUGIN_VERSION,
  1170. 'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
  1171. 'homepage' => 'https://git.gnu.io/gnu/gnu-social/tree/master/plugins/OStatus',
  1172. // TRANS: Plugin description.
  1173. 'rawdescription' => _m('Follow people across social networks that implement '.
  1174. '<a href="http://ostatus.org/">OStatus</a>.'));
  1175. return true;
  1176. }
  1177. /**
  1178. * Utility function to check if the given URI is a canonical group profile
  1179. * page, and if so return the ID number.
  1180. *
  1181. * @param string $url
  1182. * @return mixed int or false
  1183. */
  1184. public static function localGroupFromUrl($url)
  1185. {
  1186. $group = User_group::getKV('uri', $url);
  1187. if ($group instanceof User_group) {
  1188. if ($group->isLocal()) {
  1189. return $group->id;
  1190. }
  1191. } else {
  1192. // To find local groups which haven't had their uri fields filled out...
  1193. // If the domain has changed since a subscriber got the URI, it'll
  1194. // be broken.
  1195. $template = common_local_url('groupbyid', array('id' => '31337'));
  1196. $template = preg_quote($template, '/');
  1197. $template = str_replace('31337', '(\d+)', $template);
  1198. if (preg_match("/$template/", $url, $matches)) {
  1199. return intval($matches[1]);
  1200. }
  1201. }
  1202. return false;
  1203. }
  1204. public function onStartProfileGetAtomFeed($profile, &$feed)
  1205. {
  1206. $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
  1207. if (!$oprofile instanceof Ostatus_profile) {
  1208. return true;
  1209. }
  1210. $feed = $oprofile->feeduri;
  1211. return false;
  1212. }
  1213. function onStartGetProfileFromURI($uri, &$profile)
  1214. {
  1215. // Don't want to do Web-based discovery on our own server,
  1216. // so we check locally first. This duplicates the functionality
  1217. // in the Profile class, since the plugin always runs before
  1218. // that local lookup, but since we return false it won't run double.
  1219. $user = User::getKV('uri', $uri);
  1220. if ($user instanceof User) {
  1221. $profile = $user->getProfile();
  1222. return false;
  1223. } else {
  1224. $group = User_group::getKV('uri', $uri);
  1225. if ($group instanceof User_group) {
  1226. $profile = $group->getProfile();
  1227. return false;
  1228. }
  1229. }
  1230. // Now, check remotely
  1231. try {
  1232. $oprofile = Ostatus_profile::ensureProfileURI($uri);
  1233. $profile = $oprofile->localProfile();
  1234. return !($profile instanceof Profile); // localProfile won't throw exception but can return null
  1235. } catch (Exception $e) {
  1236. return true; // It's not an OStatus profile as far as we know, continue event handling
  1237. }
  1238. }
  1239. function onEndWebFingerNoticeLinks(XML_XRD $xrd, Notice $target)
  1240. {
  1241. $salmon_url = null;
  1242. $actor = $target->getProfile();
  1243. if ($actor->isLocal()) {
  1244. $profiletype = $this->profileTypeString($actor);
  1245. $salmon_url = common_local_url("{$profiletype}salmon", array('id' => $actor->getID()));
  1246. } else {
  1247. try {
  1248. $oprofile = Ostatus_profile::fromProfile($actor);
  1249. $salmon_url = $oprofile->salmonuri;
  1250. } catch (Exception $e) {
  1251. // Even though it's not a local user, we couldn't get an Ostatus_profile?!
  1252. }
  1253. }
  1254. // Ostatus_profile salmon URL may be empty
  1255. if (!empty($salmon_url)) {
  1256. $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
  1257. }
  1258. return true;
  1259. }
  1260. function onEndWebFingerProfileLinks(XML_XRD $xrd, Profile $target)
  1261. {
  1262. if ($target->getObjectType() === ActivityObject::PERSON) {
  1263. $this->addWebFingerPersonLinks($xrd, $target);
  1264. } elseif ($target->getObjectType() === ActivityObject::GROUP) {
  1265. $xrd->links[] = new XML_XRD_Element_Link(Discovery::UPDATESFROM,
  1266. common_local_url('ApiTimelineGroup',
  1267. array('id' => $target->getGroup()->getID(), 'format' => 'atom')),
  1268. 'application/atom+xml');
  1269. }
  1270. // Salmon
  1271. $profiletype = $this->profileTypeString($target);
  1272. $salmon_url = common_local_url("{$profiletype}salmon", array('id' => $target->id));
  1273. $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
  1274. // XXX: these are deprecated, but StatusNet only looks for NS_REPLIES
  1275. $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_REPLIES, $salmon_url);
  1276. $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_MENTIONS, $salmon_url);
  1277. return true;
  1278. }
  1279. protected function profileTypeString(Profile $target)
  1280. {
  1281. // This is just used to have a definitive string response to "USERsalmon" or "GROUPsalmon"
  1282. switch ($target->getObjectType()) {
  1283. case ActivityObject::PERSON:
  1284. return 'user';
  1285. case ActivityObject::GROUP:
  1286. return 'group';
  1287. default:
  1288. throw new ServerException('Unknown profile type for WebFinger profile links');
  1289. }
  1290. }
  1291. protected function addWebFingerPersonLinks(XML_XRD $xrd, Profile $target)
  1292. {
  1293. $xrd->links[] = new XML_XRD_Element_Link(Discovery::UPDATESFROM,
  1294. common_local_url('ApiTimelineUser',
  1295. array('id' => $target->id, 'format' => 'atom')),
  1296. 'application/atom+xml');
  1297. // Get this profile's keypair
  1298. $magicsig = Magicsig::getKV('user_id', $target->id);
  1299. if (!$magicsig instanceof Magicsig && $target->isLocal()) {
  1300. $magicsig = Magicsig::generate($target->getUser());
  1301. }
  1302. if (!$magicsig instanceof Magicsig) {
  1303. return false; // value doesn't mean anything, just figured I'd indicate this function didn't do anything
  1304. }
  1305. if (Event::handle('StartAttachPubkeyToUserXRD', array($magicsig, $xrd, $target))) {
  1306. $xrd->links[] = new XML_XRD_Element_Link(Magicsig::PUBLICKEYREL,
  1307. 'data:application/magic-public-key,'. $magicsig->toString());
  1308. // The following event handles plugins like Diaspora which add their own version of the Magicsig pubkey
  1309. Event::handle('EndAttachPubkeyToUserXRD', array($magicsig, $xrd, $target));
  1310. }
  1311. }
  1312. public function onGetLocalAttentions(Profile $actor, array $attention_uris, array &$mentions, array &$groups)
  1313. {
  1314. list($groups, $mentions) = Ostatus_profile::filterAttention($actor, $attention_uris);
  1315. }
  1316. // FIXME: Maybe this shouldn't be so authoritative that it breaks other remote profile lookups?
  1317. static public function onCheckActivityAuthorship(Activity $activity, Profile &$profile)
  1318. {
  1319. try {
  1320. $oprofile = Ostatus_profile::ensureProfileURL($profile->getUrl());
  1321. $profile = $oprofile->checkAuthorship($activity);
  1322. } catch (Exception $e) {
  1323. common_log(LOG_ERR, 'Could not get a profile or check authorship ('.get_class($e).': "'.$e->getMessage().'") for activity ID: '.$activity->id);
  1324. $profile = null;
  1325. return false;
  1326. }
  1327. return true;
  1328. }
  1329. public function onProfileDeleteRelated($profile, &$related)
  1330. {
  1331. // Ostatus_profile has a 'profile_id' property, which will be used to find the object
  1332. $related[] = 'Ostatus_profile';
  1333. // Magicsig has a "user_id" column instead, so we have to delete it more manually:
  1334. $magicsig = Magicsig::getKV('user_id', $profile->id);
  1335. if ($magicsig instanceof Magicsig) {
  1336. $magicsig->delete();
  1337. }
  1338. return true;
  1339. }
  1340. public function onSalmonSlap($endpoint_uri, MagicEnvelope $magic_env, Profile $target=null)
  1341. {
  1342. try {
  1343. $envxml = $magic_env->toXML($target);
  1344. } catch (Exception $e) {
  1345. common_log(LOG_ERR, sprintf('Could not generate Magic Envelope XML for profile id=='.$target->getID().': '.$e->getMessage()));
  1346. return false;
  1347. }
  1348. $headers = array('Content-Type: application/magic-envelope+xml');
  1349. try {
  1350. $client = new HTTPClient();
  1351. $client->setBody($envxml);
  1352. $response = $client->post($endpoint_uri, $headers);
  1353. } catch (Exception $e) {
  1354. common_log(LOG_ERR, "Salmon post to $endpoint_uri failed: " . $e->getMessage());
  1355. return false;
  1356. }
  1357. if ($response->getStatus() === 422) {
  1358. common_debug(sprintf('Salmon (from profile %d) endpoint %s returned status %s. We assume it is a Diaspora seed; will adapt and try again if that plugin is enabled!', $magic_env->getActor()->getID(), $endpoint_uri, $response->getStatus()));
  1359. return true;
  1360. }
  1361. // The different kinds of accepted responses...
  1362. // 200 OK means it's all ok
  1363. // 201 Created is what Mastodon returns when it's ok
  1364. // 202 Accepted is what we get from Diaspora, also good
  1365. if (!in_array($response->getStatus(), array(200, 201, 202))) {
  1366. common_log(LOG_ERR, sprintf('Salmon (from profile %d) endpoint %s returned status %s: %s',
  1367. $magic_env->getActor()->getID(), $endpoint_uri, $response->getStatus(), $response->getBody()));
  1368. return true;
  1369. }
  1370. // Since we completed the salmon slap, we discontinue the event
  1371. return false;
  1372. }
  1373. public function onCronDaily()
  1374. {
  1375. try {
  1376. $sub = FeedSub::renewalCheck();
  1377. } catch (NoResultException $e) {
  1378. common_log(LOG_INFO, "There were no expiring feeds.");
  1379. return;
  1380. }
  1381. $qm = QueueManager::get();
  1382. while ($sub->fetch()) {
  1383. $item = array('feedsub_id' => $sub->id);
  1384. $qm->enqueue($item, 'pushrenew');
  1385. }
  1386. }
  1387. /**
  1388. * Try to grab and store the remote profile by the given uri
  1389. *
  1390. * @param string $uri
  1391. * @param Profile &$profile
  1392. * @return bool
  1393. */
  1394. public function onRemoteFollowPullProfile(string $uri, ?Profile &$profile): bool
  1395. {
  1396. $oprofile = pullRemoteProfile($uri);
  1397. if ($oprofile instanceof Ostatus_profile) {
  1398. // validation
  1399. if ($oprofile->isGroup()) {
  1400. $target = common_local_url('ostatusgroup', [], ['profile' => $uri]);
  1401. common_redirect($target, 303);
  1402. } else if ($oprofile->isPeopletag()) {
  1403. $target = common_local_url('ostatuspeopletag', [], ['profile' => $uri]);
  1404. common_redirect($target, 303);
  1405. }
  1406. $profile = $oprofile->localProfile();
  1407. }
  1408. return is_null($profile);
  1409. }
  1410. }