OStatusPlugin.php 60 KB

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