OStatusPlugin.php 60 KB

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