OStatusPlugin.php 60 KB

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