OStatusPlugin.php 60 KB

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