OStatusPlugin.php 53 KB

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