OStatusPlugin.php 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615
  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. class OStatusPlugin extends Plugin
  29. {
  30. const PLUGIN_VERSION = '2.0.3';
  31. /**
  32. * Hook for RouterInitialized event.
  33. *
  34. * @param URLMapper $m path-to-action mapper
  35. * @return boolean hook return
  36. */
  37. public function onRouterInitialized(URLMapper $m)
  38. {
  39. // Discovery actions
  40. $m->connect('main/ostatustag',
  41. ['action' => 'ostatustag']);
  42. $m->connect('main/ostatustag?nickname=:nickname',
  43. ['action' => 'ostatustag'],
  44. ['nickname' => '[A-Za-z0-9_-]+']);
  45. $m->connect('main/ostatus/nickname/:nickname',
  46. ['action' => 'ostatusinit'],
  47. ['nickname' => '[A-Za-z0-9_-]+']);
  48. $m->connect('main/ostatus/group/:group',
  49. ['action' => 'ostatusinit'],
  50. ['group' => '[A-Za-z0-9_-]+']);
  51. $m->connect('main/ostatus/peopletag/:peopletag/tagger/:tagger',
  52. ['action' => 'ostatusinit'],
  53. ['tagger' => '[A-Za-z0-9_-]+',
  54. 'peopletag' => '[A-Za-z0-9_-]+']);
  55. $m->connect('main/ostatus',
  56. ['action' => 'ostatusinit']);
  57. // Remote subscription actions
  58. $m->connect('main/ostatussub',
  59. ['action' => 'ostatussub']);
  60. $m->connect('main/ostatusgroup',
  61. ['action' => 'ostatusgroup']);
  62. $m->connect('main/ostatuspeopletag',
  63. ['action' => 'ostatuspeopletag']);
  64. // WebSub actions
  65. $m->connect('main/push/hub', ['action' => 'pushhub']);
  66. $m->connect('main/push/callback/:feed',
  67. ['action' => 'pushcallback'],
  68. ['feed' => '[0-9]+']);
  69. // Salmon endpoint
  70. $m->connect('main/salmon/user/:id',
  71. ['action' => 'usersalmon'],
  72. ['id' => '[0-9]+']);
  73. $m->connect('main/salmon/group/:id',
  74. ['action' => 'groupsalmon'],
  75. ['id' => '[0-9]+']);
  76. $m->connect('main/salmon/peopletag/:id',
  77. ['action' => 'peopletagsalmon'],
  78. ['id' => '[0-9]+']);
  79. return true;
  80. }
  81. /**
  82. * Set up queue handlers for outgoing hub pushes
  83. * @param QueueManager $qm
  84. * @return boolean hook return
  85. */
  86. function onEndInitializeQueueManager(QueueManager $qm)
  87. {
  88. // Prepare outgoing distributions after notice save.
  89. $qm->connect('ostatus', 'OStatusQueueHandler');
  90. // Outgoing from our internal WebSub hub
  91. $qm->connect('hubconf', 'HubConfQueueHandler');
  92. $qm->connect('hubprep', 'HubPrepQueueHandler');
  93. $qm->connect('hubout', 'HubOutQueueHandler');
  94. // Outgoing Salmon replies (when we don't need a return value)
  95. $qm->connect('salmon', 'SalmonQueueHandler');
  96. // Incoming from a foreign WebSub hub
  97. $qm->connect('pushin', 'PushInQueueHandler');
  98. // Re-subscribe feeds that need renewal
  99. $qm->connect('pushrenew', 'PushRenewQueueHandler');
  100. return true;
  101. }
  102. /**
  103. * Put saved notices into the queue for pubsub distribution.
  104. */
  105. function onStartEnqueueNotice($notice, &$transports)
  106. {
  107. if ($notice->inScope(null) && $notice->getProfile()->hasRight(Right::PUBLICNOTICE)) {
  108. $transports[] = 'ostatus';
  109. $this->log(LOG_INFO, "OSTATUS [{$notice->getID()}]: queued for OStatus processing");
  110. } else {
  111. // FIXME: we don't do privacy-controlled OStatus updates yet.
  112. // once that happens, finer grain of control here.
  113. $this->log(LOG_NOTICE, "OSTATUS [{$notice->getID()}]: Not queueing because of privacy; scope = {$notice->scope}");
  114. }
  115. return true;
  116. }
  117. /**
  118. * Set up a WebSub hub link to our internal link for canonical timeline
  119. * Atom feeds for users and groups.
  120. */
  121. function onStartApiAtom($feed)
  122. {
  123. $id = null;
  124. if ($feed instanceof AtomUserNoticeFeed) {
  125. $salmonAction = 'usersalmon';
  126. $user = $feed->getUser();
  127. $id = $user->id;
  128. $profile = $user->getProfile();
  129. } else if ($feed instanceof AtomGroupNoticeFeed) {
  130. $salmonAction = 'groupsalmon';
  131. $group = $feed->getGroup();
  132. $id = $group->id;
  133. } else if ($feed instanceof AtomListNoticeFeed) {
  134. $salmonAction = 'peopletagsalmon';
  135. $peopletag = $feed->getList();
  136. $id = $peopletag->id;
  137. } else {
  138. return true;
  139. }
  140. if (!empty($id)) {
  141. $hub = common_config('ostatus', 'hub');
  142. if (empty($hub)) {
  143. // Updates will be handled through our internal WebSub hub.
  144. $hub = common_local_url('pushhub');
  145. }
  146. $feed->addLink($hub, array('rel' => 'hub'));
  147. // Also, we'll add in the salmon link
  148. $salmon = common_local_url($salmonAction, array('id' => $id));
  149. $feed->addLink($salmon, array('rel' => Salmon::REL_SALMON));
  150. // XXX: these are deprecated, but StatusNet only looks for NS_REPLIES
  151. $feed->addLink($salmon, array('rel' => Salmon::NS_REPLIES));
  152. $feed->addLink($salmon, array('rel' => Salmon::NS_MENTIONS));
  153. }
  154. return true;
  155. }
  156. /**
  157. * Add in an OStatus subscribe button
  158. */
  159. function onStartProfileRemoteSubscribe($output, $profile)
  160. {
  161. $this->onStartProfileListItemActionElements($output, $profile);
  162. return false;
  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('ostatussub', 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 onStartShowSubscriptionsContent($action)
  1025. {
  1026. $this->showEntityRemoteSubscribe($action);
  1027. return true;
  1028. }
  1029. function onStartShowUserGroupsContent($action)
  1030. {
  1031. $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
  1032. return true;
  1033. }
  1034. function onEndShowSubscriptionsMiniList($action)
  1035. {
  1036. $this->showEntityRemoteSubscribe($action);
  1037. return true;
  1038. }
  1039. function onEndShowGroupsMiniList($action)
  1040. {
  1041. $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
  1042. return true;
  1043. }
  1044. function showEntityRemoteSubscribe($action, $target='ostatussub')
  1045. {
  1046. if (!$action->getScoped() instanceof Profile) {
  1047. // early return if we're not logged in
  1048. return true;
  1049. }
  1050. if ($action->getScoped()->sameAs($action->getTarget())) {
  1051. $action->elementStart('div', 'entity_actions');
  1052. $action->elementStart('p', array('id' => 'entity_remote_subscribe',
  1053. 'class' => 'entity_subscribe'));
  1054. $action->element('a', array('href' => common_local_url($target),
  1055. 'class' => 'entity_remote_subscribe'),
  1056. // TRANS: Link text for link to remote subscribe.
  1057. _m('Remote'));
  1058. $action->elementEnd('p');
  1059. $action->elementEnd('div');
  1060. }
  1061. }
  1062. /**
  1063. * Ping remote profiles with updates to this profile.
  1064. * Salmon pings are queued for background processing.
  1065. */
  1066. function onEndBroadcastProfile(Profile $profile)
  1067. {
  1068. $user = User::getKV('id', $profile->id);
  1069. // Find foreign accounts I'm subscribed to that support Salmon pings.
  1070. //
  1071. // @fixme we could run updates through the WebSub feed too,
  1072. // in which case we can skip Salmon pings to folks who
  1073. // are also subscribed to me.
  1074. $sql = "SELECT * FROM ostatus_profile " .
  1075. "WHERE profile_id IN " .
  1076. "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
  1077. "OR group_id IN " .
  1078. "(SELECT group_id FROM group_member WHERE profile_id=%d)";
  1079. $oprofile = new Ostatus_profile();
  1080. $oprofile->query(sprintf($sql, $profile->id, $profile->id));
  1081. if ($oprofile->N == 0) {
  1082. common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
  1083. return true;
  1084. }
  1085. $act = new Activity();
  1086. $act->verb = ActivityVerb::UPDATE_PROFILE;
  1087. $act->id = TagURI::mint('update-profile:%d:%s',
  1088. $profile->id,
  1089. common_date_iso8601(time()));
  1090. $act->time = time();
  1091. // TRANS: Title for activity.
  1092. $act->title = _m('Profile update');
  1093. // TRANS: Ping text for remote profile update through OStatus.
  1094. // TRANS: %s is user that updated their profile.
  1095. $act->content = sprintf(_m('%s has updated their profile page.'),
  1096. $profile->getBestName());
  1097. $act->actor = $profile->asActivityObject();
  1098. $act->objects[] = $act->actor;
  1099. while ($oprofile->fetch()) {
  1100. $oprofile->notifyDeferred($act, $profile);
  1101. }
  1102. return true;
  1103. }
  1104. function onEndShowAccountProfileBlock(HTMLOutputter $out, Profile $profile)
  1105. {
  1106. if ($profile->isLocal()) {
  1107. return true;
  1108. }
  1109. try {
  1110. $oprofile = Ostatus_profile::fromProfile($profile);
  1111. } catch (Exception $e) {
  1112. // Not a remote Ostatus_profile! Maybe some other network
  1113. // that has imported a non-local user?
  1114. return true;
  1115. }
  1116. try {
  1117. $feedsub = $oprofile->getFeedSub();
  1118. } catch (NoResultException $e) {
  1119. // No WebSub subscription has been attempted or exists for this profile
  1120. // which is the case, say for remote profiles that are only included
  1121. // via mentions or repeat/share.
  1122. return true;
  1123. }
  1124. $websub_states = [
  1125. 'subscribe' => _m('Pending'),
  1126. 'active' => _m('Active'),
  1127. 'nohub' => _m('Polling'),
  1128. 'inactive' => _m('Inactive'),
  1129. ];
  1130. $out->elementStart('dl', 'entity_tags ostatus_profile');
  1131. $out->element('dt', null, _m('WebSub'));
  1132. $out->element('dd', null, $websub_states[$feedsub->sub_state]);
  1133. $out->elementEnd('dl');
  1134. }
  1135. // FIXME: This one can accept both an Action and a Widget. Confusing! Refactor to (HTMLOutputter $out, Profile $target)!
  1136. function onStartProfileListItemActionElements($item)
  1137. {
  1138. if (common_logged_in()) {
  1139. // only non-logged in users get to see the "remote subscribe" form
  1140. return true;
  1141. } elseif (!$item->getTarget()->isLocal()) {
  1142. // we can (for now) only provide remote subscribe forms for local users
  1143. return true;
  1144. }
  1145. if ($item instanceof ProfileAction) {
  1146. $output = $item;
  1147. } elseif ($item instanceof Widget) {
  1148. $output = $item->out;
  1149. } else {
  1150. // Bad $item class, don't know how to use this for outputting!
  1151. throw new ServerException('Bad item type for onStartProfileListItemActionElements');
  1152. }
  1153. // Add an OStatus subscribe
  1154. $output->elementStart('li', 'entity_subscribe');
  1155. $url = common_local_url('ostatusinit',
  1156. array('nickname' => $item->getTarget()->getNickname()));
  1157. $output->element('a', array('href' => $url,
  1158. 'class' => 'entity_remote_subscribe'),
  1159. // TRANS: Link text for a user to subscribe to an OStatus user.
  1160. _m('Subscribe'));
  1161. $output->elementEnd('li');
  1162. $output->elementStart('li', 'entity_tag');
  1163. $url = common_local_url('ostatustag',
  1164. array('nickname' => $item->getTarget()->getNickname()));
  1165. $output->element('a', array('href' => $url,
  1166. 'class' => 'entity_remote_tag'),
  1167. // TRANS: Link text for a user to list an OStatus user.
  1168. _m('List'));
  1169. $output->elementEnd('li');
  1170. return true;
  1171. }
  1172. /**
  1173. * Plugin Nodeinfo information
  1174. *
  1175. * @param array $protocols
  1176. * @return bool hook true
  1177. */
  1178. public function onNodeInfoProtocols(array &$protocols)
  1179. {
  1180. $protocols[] = "ostatus";
  1181. return true;
  1182. }
  1183. function onPluginVersion(array &$versions)
  1184. {
  1185. $versions[] = array('name' => 'OStatus',
  1186. 'version' => self::PLUGIN_VERSION,
  1187. 'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
  1188. 'homepage' => 'https://git.gnu.io/gnu/gnu-social/tree/master/plugins/OStatus',
  1189. // TRANS: Plugin description.
  1190. 'rawdescription' => _m('Follow people across social networks that implement '.
  1191. '<a href="http://ostatus.org/">OStatus</a>.'));
  1192. return true;
  1193. }
  1194. /**
  1195. * Utility function to check if the given URI is a canonical group profile
  1196. * page, and if so return the ID number.
  1197. *
  1198. * @param string $url
  1199. * @return mixed int or false
  1200. */
  1201. public static function localGroupFromUrl($url)
  1202. {
  1203. $group = User_group::getKV('uri', $url);
  1204. if ($group instanceof User_group) {
  1205. if ($group->isLocal()) {
  1206. return $group->id;
  1207. }
  1208. } else {
  1209. // To find local groups which haven't had their uri fields filled out...
  1210. // If the domain has changed since a subscriber got the URI, it'll
  1211. // be broken.
  1212. $template = common_local_url('groupbyid', array('id' => '31337'));
  1213. $template = preg_quote($template, '/');
  1214. $template = str_replace('31337', '(\d+)', $template);
  1215. if (preg_match("/$template/", $url, $matches)) {
  1216. return intval($matches[1]);
  1217. }
  1218. }
  1219. return false;
  1220. }
  1221. public function onStartProfileGetAtomFeed($profile, &$feed)
  1222. {
  1223. $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
  1224. if (!$oprofile instanceof Ostatus_profile) {
  1225. return true;
  1226. }
  1227. $feed = $oprofile->feeduri;
  1228. return false;
  1229. }
  1230. function onStartGetProfileFromURI($uri, &$profile)
  1231. {
  1232. // Don't want to do Web-based discovery on our own server,
  1233. // so we check locally first. This duplicates the functionality
  1234. // in the Profile class, since the plugin always runs before
  1235. // that local lookup, but since we return false it won't run double.
  1236. $user = User::getKV('uri', $uri);
  1237. if ($user instanceof User) {
  1238. $profile = $user->getProfile();
  1239. return false;
  1240. } else {
  1241. $group = User_group::getKV('uri', $uri);
  1242. if ($group instanceof User_group) {
  1243. $profile = $group->getProfile();
  1244. return false;
  1245. }
  1246. }
  1247. // Now, check remotely
  1248. try {
  1249. $oprofile = Ostatus_profile::ensureProfileURI($uri);
  1250. $profile = $oprofile->localProfile();
  1251. return !($profile instanceof Profile); // localProfile won't throw exception but can return null
  1252. } catch (Exception $e) {
  1253. return true; // It's not an OStatus profile as far as we know, continue event handling
  1254. }
  1255. }
  1256. function onEndWebFingerNoticeLinks(XML_XRD $xrd, Notice $target)
  1257. {
  1258. $salmon_url = null;
  1259. $actor = $target->getProfile();
  1260. if ($actor->isLocal()) {
  1261. $profiletype = $this->profileTypeString($actor);
  1262. $salmon_url = common_local_url("{$profiletype}salmon", array('id' => $actor->getID()));
  1263. } else {
  1264. try {
  1265. $oprofile = Ostatus_profile::fromProfile($actor);
  1266. $salmon_url = $oprofile->salmonuri;
  1267. } catch (Exception $e) {
  1268. // Even though it's not a local user, we couldn't get an Ostatus_profile?!
  1269. }
  1270. }
  1271. // Ostatus_profile salmon URL may be empty
  1272. if (!empty($salmon_url)) {
  1273. $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
  1274. }
  1275. return true;
  1276. }
  1277. function onEndWebFingerProfileLinks(XML_XRD $xrd, Profile $target)
  1278. {
  1279. if ($target->getObjectType() === ActivityObject::PERSON) {
  1280. $this->addWebFingerPersonLinks($xrd, $target);
  1281. } elseif ($target->getObjectType() === ActivityObject::GROUP) {
  1282. $xrd->links[] = new XML_XRD_Element_Link(Discovery::UPDATESFROM,
  1283. common_local_url('ApiTimelineGroup',
  1284. array('id' => $target->getGroup()->getID(), 'format' => 'atom')),
  1285. 'application/atom+xml');
  1286. }
  1287. // Salmon
  1288. $profiletype = $this->profileTypeString($target);
  1289. $salmon_url = common_local_url("{$profiletype}salmon", array('id' => $target->id));
  1290. $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
  1291. // XXX: these are deprecated, but StatusNet only looks for NS_REPLIES
  1292. $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_REPLIES, $salmon_url);
  1293. $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_MENTIONS, $salmon_url);
  1294. // TODO - finalize where the redirect should go on the publisher
  1295. $xrd->links[] = new XML_XRD_Element_Link('http://ostatus.org/schema/1.0/subscribe',
  1296. common_local_url('ostatussub') . '?profile={uri}',
  1297. null, // type not set
  1298. true); // isTemplate
  1299. return true;
  1300. }
  1301. protected function profileTypeString(Profile $target)
  1302. {
  1303. // This is just used to have a definitive string response to "USERsalmon" or "GROUPsalmon"
  1304. switch ($target->getObjectType()) {
  1305. case ActivityObject::PERSON:
  1306. return 'user';
  1307. case ActivityObject::GROUP:
  1308. return 'group';
  1309. default:
  1310. throw new ServerException('Unknown profile type for WebFinger profile links');
  1311. }
  1312. }
  1313. protected function addWebFingerPersonLinks(XML_XRD $xrd, Profile $target)
  1314. {
  1315. $xrd->links[] = new XML_XRD_Element_Link(Discovery::UPDATESFROM,
  1316. common_local_url('ApiTimelineUser',
  1317. array('id' => $target->id, 'format' => 'atom')),
  1318. 'application/atom+xml');
  1319. // Get this profile's keypair
  1320. $magicsig = Magicsig::getKV('user_id', $target->id);
  1321. if (!$magicsig instanceof Magicsig && $target->isLocal()) {
  1322. $magicsig = Magicsig::generate($target->getUser());
  1323. }
  1324. if (!$magicsig instanceof Magicsig) {
  1325. return false; // value doesn't mean anything, just figured I'd indicate this function didn't do anything
  1326. }
  1327. if (Event::handle('StartAttachPubkeyToUserXRD', array($magicsig, $xrd, $target))) {
  1328. $xrd->links[] = new XML_XRD_Element_Link(Magicsig::PUBLICKEYREL,
  1329. 'data:application/magic-public-key,'. $magicsig->toString());
  1330. // The following event handles plugins like Diaspora which add their own version of the Magicsig pubkey
  1331. Event::handle('EndAttachPubkeyToUserXRD', array($magicsig, $xrd, $target));
  1332. }
  1333. }
  1334. public function onGetLocalAttentions(Profile $actor, array $attention_uris, array &$mentions, array &$groups)
  1335. {
  1336. list($groups, $mentions) = Ostatus_profile::filterAttention($actor, $attention_uris);
  1337. }
  1338. // FIXME: Maybe this shouldn't be so authoritative that it breaks other remote profile lookups?
  1339. static public function onCheckActivityAuthorship(Activity $activity, Profile &$profile)
  1340. {
  1341. try {
  1342. $oprofile = Ostatus_profile::ensureProfileURL($profile->getUrl());
  1343. $profile = $oprofile->checkAuthorship($activity);
  1344. } catch (Exception $e) {
  1345. common_log(LOG_ERR, 'Could not get a profile or check authorship ('.get_class($e).': "'.$e->getMessage().'") for activity ID: '.$activity->id);
  1346. $profile = null;
  1347. return false;
  1348. }
  1349. return true;
  1350. }
  1351. public function onProfileDeleteRelated($profile, &$related)
  1352. {
  1353. // Ostatus_profile has a 'profile_id' property, which will be used to find the object
  1354. $related[] = 'Ostatus_profile';
  1355. // Magicsig has a "user_id" column instead, so we have to delete it more manually:
  1356. $magicsig = Magicsig::getKV('user_id', $profile->id);
  1357. if ($magicsig instanceof Magicsig) {
  1358. $magicsig->delete();
  1359. }
  1360. return true;
  1361. }
  1362. public function onSalmonSlap($endpoint_uri, MagicEnvelope $magic_env, Profile $target=null)
  1363. {
  1364. try {
  1365. $envxml = $magic_env->toXML($target);
  1366. } catch (Exception $e) {
  1367. common_log(LOG_ERR, sprintf('Could not generate Magic Envelope XML for profile id=='.$target->getID().': '.$e->getMessage()));
  1368. return false;
  1369. }
  1370. $headers = array('Content-Type: application/magic-envelope+xml');
  1371. try {
  1372. $client = new HTTPClient();
  1373. $client->setBody($envxml);
  1374. $response = $client->post($endpoint_uri, $headers);
  1375. } catch (Exception $e) {
  1376. common_log(LOG_ERR, "Salmon post to $endpoint_uri failed: " . $e->getMessage());
  1377. return false;
  1378. }
  1379. if ($response->getStatus() === 422) {
  1380. 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()));
  1381. return true;
  1382. }
  1383. // The different kinds of accepted responses...
  1384. // 200 OK means it's all ok
  1385. // 201 Created is what Mastodon returns when it's ok
  1386. // 202 Accepted is what we get from Diaspora, also good
  1387. if (!in_array($response->getStatus(), array(200, 201, 202))) {
  1388. common_log(LOG_ERR, sprintf('Salmon (from profile %d) endpoint %s returned status %s: %s',
  1389. $magic_env->getActor()->getID(), $endpoint_uri, $response->getStatus(), $response->getBody()));
  1390. return true;
  1391. }
  1392. // Since we completed the salmon slap, we discontinue the event
  1393. return false;
  1394. }
  1395. public function onCronDaily()
  1396. {
  1397. try {
  1398. $sub = FeedSub::renewalCheck();
  1399. } catch (NoResultException $e) {
  1400. common_log(LOG_INFO, "There were no expiring feeds.");
  1401. return;
  1402. }
  1403. $qm = QueueManager::get();
  1404. while ($sub->fetch()) {
  1405. $item = array('feedsub_id' => $sub->id);
  1406. $qm->enqueue($item, 'pushrenew');
  1407. }
  1408. }
  1409. }