OStatusPlugin.php 60 KB

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