Ostatus_profile.php 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867
  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. if (!defined('GNUSOCIAL')) { exit(1); }
  20. /**
  21. * @package OStatusPlugin
  22. * @author Brion Vibber <brion@status.net>
  23. * @maintainer Mikael Nordfeldth <mmn@hethane.se>
  24. */
  25. class Ostatus_profile extends Managed_DataObject
  26. {
  27. public $__table = 'ostatus_profile';
  28. public $uri;
  29. public $profile_id;
  30. public $group_id;
  31. public $peopletag_id;
  32. public $feeduri;
  33. public $salmonuri;
  34. public $avatar; // remote URL of the last avatar we saved
  35. public $created;
  36. public $modified;
  37. /**
  38. * Return table definition for Schema setup and DB_DataObject usage.
  39. *
  40. * @return array array of column definitions
  41. */
  42. static function schemaDef()
  43. {
  44. return array(
  45. 'fields' => array(
  46. 'uri' => array('type' => 'varchar', 'length' => 191, 'not null' => true),
  47. 'profile_id' => array('type' => 'integer'),
  48. 'group_id' => array('type' => 'integer'),
  49. 'peopletag_id' => array('type' => 'integer'),
  50. 'feeduri' => array('type' => 'varchar', 'length' => 191),
  51. 'salmonuri' => array('type' => 'varchar', 'length' => 191),
  52. 'avatar' => array('type' => 'text'),
  53. 'created' => array('type' => 'datetime', 'not null' => true),
  54. 'modified' => array('type' => 'datetime', 'not null' => true),
  55. ),
  56. 'primary key' => array('uri'),
  57. 'unique keys' => array(
  58. 'ostatus_profile_profile_id_key' => array('profile_id'),
  59. 'ostatus_profile_group_id_key' => array('group_id'),
  60. 'ostatus_profile_peopletag_id_key' => array('peopletag_id'),
  61. 'ostatus_profile_feeduri_key' => array('feeduri'),
  62. ),
  63. 'foreign keys' => array(
  64. 'ostatus_profile_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
  65. 'ostatus_profile_group_id_fkey' => array('user_group', array('group_id' => 'id')),
  66. 'ostatus_profile_peopletag_id_fkey' => array('profile_list', array('peopletag_id' => 'id')),
  67. ),
  68. );
  69. }
  70. public function getUri()
  71. {
  72. return $this->uri;
  73. }
  74. public function fromProfile(Profile $profile)
  75. {
  76. $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
  77. if (!$oprofile instanceof Ostatus_profile) {
  78. throw new Exception('No Ostatus_profile for Profile ID: '.$profile->id);
  79. }
  80. }
  81. /**
  82. * Fetch the locally stored profile for this feed
  83. * @return Profile
  84. * @throws NoProfileException if it was not found
  85. */
  86. public function localProfile()
  87. {
  88. if ($this->isGroup()) {
  89. return $this->localGroup()->getProfile();
  90. }
  91. $profile = Profile::getKV('id', $this->profile_id);
  92. if (!$profile instanceof Profile) {
  93. throw new NoProfileException($this->profile_id);
  94. }
  95. return $profile;
  96. }
  97. /**
  98. * Fetch the StatusNet-side profile for this feed
  99. * @return Profile
  100. */
  101. public function localGroup()
  102. {
  103. $group = User_group::getKV('id', $this->group_id);
  104. if (!$group instanceof User_group) {
  105. throw new NoSuchGroupException(array('id'=>$this->group_id));
  106. }
  107. return $group;
  108. }
  109. /**
  110. * Fetch the StatusNet-side peopletag for this feed
  111. * @return Profile
  112. */
  113. public function localPeopletag()
  114. {
  115. if ($this->peopletag_id) {
  116. return Profile_list::getKV('id', $this->peopletag_id);
  117. }
  118. return null;
  119. }
  120. /**
  121. * Returns an ActivityObject describing this remote user or group profile.
  122. * Can then be used to generate Atom chunks.
  123. *
  124. * @return ActivityObject
  125. */
  126. function asActivityObject()
  127. {
  128. if ($this->isGroup()) {
  129. return ActivityObject::fromGroup($this->localGroup());
  130. } else if ($this->isPeopletag()) {
  131. return ActivityObject::fromPeopletag($this->localPeopletag());
  132. } else {
  133. return $this->localProfile()->asActivityObject();
  134. }
  135. }
  136. /**
  137. * Returns an XML string fragment with profile information as an
  138. * Activity Streams noun object with the given element type.
  139. *
  140. * Assumes that 'activity' namespace has been previously defined.
  141. *
  142. * @todo FIXME: Replace with wrappers on asActivityObject when it's got everything.
  143. *
  144. * @param string $element one of 'actor', 'subject', 'object', 'target'
  145. * @return string
  146. */
  147. function asActivityNoun($element)
  148. {
  149. if ($this->isGroup()) {
  150. $noun = ActivityObject::fromGroup($this->localGroup());
  151. return $noun->asString('activity:' . $element);
  152. } else if ($this->isPeopletag()) {
  153. $noun = ActivityObject::fromPeopletag($this->localPeopletag());
  154. return $noun->asString('activity:' . $element);
  155. } else {
  156. $noun = $this->localProfile()->asActivityObject();
  157. return $noun->asString('activity:' . $element);
  158. }
  159. }
  160. /**
  161. * @return boolean true if this is a remote group
  162. */
  163. function isGroup()
  164. {
  165. if ($this->profile_id || $this->peopletag_id && !$this->group_id) {
  166. return false;
  167. } else if ($this->group_id && !$this->profile_id && !$this->peopletag_id) {
  168. return true;
  169. } else if ($this->group_id && ($this->profile_id || $this->peopletag_id)) {
  170. // TRANS: Server exception. %s is a URI
  171. throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->getUri()));
  172. } else {
  173. // TRANS: Server exception. %s is a URI
  174. throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->getUri()));
  175. }
  176. }
  177. public function isPerson()
  178. {
  179. return $this->localProfile()->isPerson();
  180. }
  181. /**
  182. * @return boolean true if this is a remote peopletag
  183. */
  184. function isPeopletag()
  185. {
  186. if ($this->profile_id || $this->group_id && !$this->peopletag_id) {
  187. return false;
  188. } else if ($this->peopletag_id && !$this->profile_id && !$this->group_id) {
  189. return true;
  190. } else if ($this->peopletag_id && ($this->profile_id || $this->group_id)) {
  191. // TRANS: Server exception. %s is a URI
  192. throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->getUri()));
  193. } else {
  194. // TRANS: Server exception. %s is a URI
  195. throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->getUri()));
  196. }
  197. }
  198. /**
  199. * Send a subscription request to the hub for this feed.
  200. * The hub will later send us a confirmation POST to /main/push/callback.
  201. *
  202. * @return void
  203. * @throws ServerException if feed state is not valid or subscription fails.
  204. */
  205. public function subscribe()
  206. {
  207. $feedsub = FeedSub::ensureFeed($this->feeduri);
  208. if ($feedsub->sub_state == 'active') {
  209. // Active subscription, we don't need to do anything.
  210. return;
  211. }
  212. // Inactive or we got left in an inconsistent state.
  213. // Run a subscription request to make sure we're current!
  214. return $feedsub->subscribe();
  215. }
  216. /**
  217. * Check if this remote profile has any active local subscriptions, and
  218. * if not drop the PuSH subscription feed.
  219. *
  220. * @return boolean true if subscription is removed, false if there are still subscribers to the feed
  221. * @throws Exception of various kinds on failure.
  222. */
  223. public function unsubscribe() {
  224. return $this->garbageCollect();
  225. }
  226. /**
  227. * Check if this remote profile has any active local subscriptions, and
  228. * if not drop the PuSH subscription feed.
  229. *
  230. * @return boolean true if subscription is removed, false if there are still subscribers to the feed
  231. * @throws Exception of various kinds on failure.
  232. */
  233. public function garbageCollect()
  234. {
  235. $feedsub = FeedSub::getKV('uri', $this->feeduri);
  236. if ($feedsub instanceof FeedSub) {
  237. return $feedsub->garbageCollect();
  238. }
  239. // Since there's no FeedSub we can assume it's already garbage collected
  240. return true;
  241. }
  242. /**
  243. * Check if this remote profile has any active local subscriptions, so the
  244. * PuSH subscription layer can decide if it can drop the feed.
  245. *
  246. * This gets called via the FeedSubSubscriberCount event when running
  247. * FeedSub::garbageCollect().
  248. *
  249. * @return int
  250. * @throws NoProfileException if there is no local profile for the object
  251. */
  252. public function subscriberCount()
  253. {
  254. if ($this->isGroup()) {
  255. $members = $this->localGroup()->getMembers(0, 1);
  256. $count = $members->N;
  257. } else if ($this->isPeopletag()) {
  258. $subscribers = $this->localPeopletag()->getSubscribers(0, 1);
  259. $count = $subscribers->N;
  260. } else {
  261. $profile = $this->localProfile();
  262. if ($profile->hasLocalTags()) {
  263. $count = 1;
  264. } else {
  265. $count = $profile->subscriberCount();
  266. }
  267. }
  268. common_log(LOG_INFO, __METHOD__ . " SUB COUNT BEFORE: $count");
  269. // Other plugins may be piggybacking on OStatus without having
  270. // an active group or user-to-user subscription we know about.
  271. Event::handle('Ostatus_profileSubscriberCount', array($this, &$count));
  272. common_log(LOG_INFO, __METHOD__ . " SUB COUNT AFTER: $count");
  273. return $count;
  274. }
  275. /**
  276. * Send an Activity Streams notification to the remote Salmon endpoint,
  277. * if so configured.
  278. *
  279. * @param Profile $actor Actor who did the activity
  280. * @param string $verb Activity::SUBSCRIBE or Activity::JOIN
  281. * @param Object $object object of the action; must define asActivityNoun($tag)
  282. */
  283. public function notify(Profile $actor, $verb, $object=null, $target=null)
  284. {
  285. if ($object == null) {
  286. $object = $this;
  287. }
  288. if (empty($this->salmonuri)) {
  289. return false;
  290. }
  291. $text = 'update';
  292. $id = TagURI::mint('%s:%s:%s',
  293. $verb,
  294. $actor->getURI(),
  295. common_date_iso8601(time()));
  296. // @todo FIXME: Consolidate all these NS settings somewhere.
  297. $attributes = array('xmlns' => Activity::ATOM,
  298. 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
  299. 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
  300. 'xmlns:georss' => 'http://www.georss.org/georss',
  301. 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
  302. 'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
  303. 'xmlns:media' => 'http://purl.org/syndication/atommedia');
  304. $entry = new XMLStringer();
  305. $entry->elementStart('entry', $attributes);
  306. $entry->element('id', null, $id);
  307. $entry->element('title', null, $text);
  308. $entry->element('summary', null, $text);
  309. $entry->element('published', null, common_date_w3dtf(common_sql_now()));
  310. $entry->element('activity:verb', null, $verb);
  311. $entry->raw($actor->asAtomAuthor());
  312. $entry->raw($actor->asActivityActor());
  313. $entry->raw($object->asActivityNoun('object'));
  314. if ($target != null) {
  315. $entry->raw($target->asActivityNoun('target'));
  316. }
  317. $entry->elementEnd('entry');
  318. $xml = $entry->getString();
  319. common_log(LOG_INFO, "Posting to Salmon endpoint $this->salmonuri: $xml");
  320. Salmon::post($this->salmonuri, $xml, $actor);
  321. }
  322. /**
  323. * Send a Salmon notification ping immediately, and confirm that we got
  324. * an acceptable response from the remote site.
  325. *
  326. * @param mixed $entry XML string, Notice, or Activity
  327. * @param Profile $actor
  328. * @return boolean success
  329. */
  330. public function notifyActivity($entry, Profile $actor)
  331. {
  332. if ($this->salmonuri) {
  333. return Salmon::post($this->salmonuri, $this->notifyPrepXml($entry), $actor, $this->localProfile());
  334. }
  335. common_debug(__CLASS__.' error: No salmonuri for Ostatus_profile uri: '.$this->uri);
  336. return false;
  337. }
  338. /**
  339. * Queue a Salmon notification for later. If queues are disabled we'll
  340. * send immediately but won't get the return value.
  341. *
  342. * @param mixed $entry XML string, Notice, or Activity
  343. * @return boolean success
  344. */
  345. public function notifyDeferred($entry, $actor)
  346. {
  347. if ($this->salmonuri) {
  348. try {
  349. common_debug("OSTATUS: user {$actor->getNickname()} ({$actor->getID()}) wants to ping {$this->localProfile()->getNickname()} on {$this->salmonuri}");
  350. $data = array('salmonuri' => $this->salmonuri,
  351. 'entry' => $this->notifyPrepXml($entry),
  352. 'actor' => $actor->getID(),
  353. 'target' => $this->localProfile()->getID());
  354. $qm = QueueManager::get();
  355. return $qm->enqueue($data, 'salmon');
  356. } catch (Exception $e) {
  357. common_log(LOG_ERR, 'OSTATUS: Something went wrong when creating a Salmon slap: '._ve($e->getMessage()));
  358. return false;
  359. }
  360. }
  361. return false;
  362. }
  363. protected function notifyPrepXml($entry)
  364. {
  365. $preamble = '<?xml version="1.0" encoding="UTF-8" ?' . '>';
  366. if (is_string($entry)) {
  367. return $entry;
  368. } else if ($entry instanceof Activity) {
  369. return $preamble . $entry->asString(true);
  370. } else if ($entry instanceof Notice) {
  371. return $preamble . $entry->asAtomEntry(true, true);
  372. } else {
  373. // TRANS: Server exception.
  374. throw new ServerException(_m('Invalid type passed to Ostatus_profile::notify. It must be XML string or Activity entry.'));
  375. }
  376. }
  377. function getBestName()
  378. {
  379. if ($this->isGroup()) {
  380. return $this->localGroup()->getBestName();
  381. } else if ($this->isPeopletag()) {
  382. return $this->localPeopletag()->getBestName();
  383. } else {
  384. return $this->localProfile()->getBestName();
  385. }
  386. }
  387. /**
  388. * Read and post notices for updates from the feed.
  389. * Currently assumes that all items in the feed are new,
  390. * coming from a PuSH hub.
  391. *
  392. * @param DOMDocument $doc
  393. * @param string $source identifier ("push")
  394. */
  395. public function processFeed(DOMDocument $doc, $source)
  396. {
  397. $feed = $doc->documentElement;
  398. if ($feed->localName == 'feed' && $feed->namespaceURI == Activity::ATOM) {
  399. $this->processAtomFeed($feed, $source);
  400. } else if ($feed->localName == 'rss') { // @todo FIXME: Check namespace.
  401. $this->processRssFeed($feed, $source);
  402. } else {
  403. // TRANS: Exception.
  404. throw new Exception(_m('Unknown feed format.'));
  405. }
  406. }
  407. public function processAtomFeed(DOMElement $feed, $source)
  408. {
  409. $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
  410. if ($entries->length == 0) {
  411. common_log(LOG_ERR, __METHOD__ . ": no entries in feed update, ignoring");
  412. return;
  413. }
  414. $this->processEntries($entries, $feed, $source);
  415. }
  416. public function processRssFeed(DOMElement $rss, $source)
  417. {
  418. $channels = $rss->getElementsByTagName('channel');
  419. if ($channels->length == 0) {
  420. // TRANS: Exception.
  421. throw new Exception(_m('RSS feed without a channel.'));
  422. } else if ($channels->length > 1) {
  423. common_log(LOG_WARNING, __METHOD__ . ": more than one channel in an RSS feed");
  424. }
  425. $channel = $channels->item(0);
  426. $items = $channel->getElementsByTagName('item');
  427. $this->processEntries($items, $channel, $source);
  428. }
  429. public function processEntries(DOMNodeList $entries, DOMElement $feed, $source)
  430. {
  431. for ($i = 0; $i < $entries->length; $i++) {
  432. $entry = $entries->item($i);
  433. try {
  434. $this->processEntry($entry, $feed, $source);
  435. } catch (AlreadyFulfilledException $e) {
  436. common_debug('We already had this entry: '.$e->getMessage());
  437. } catch (ServerException $e) {
  438. // FIXME: This should be UnknownUriException and the ActivityUtils:: findLocalObject should only test one URI
  439. common_log(LOG_ERR, 'Entry threw exception while processing a feed from '.$source.': '.$e->getMessage());
  440. }
  441. }
  442. }
  443. /**
  444. * Process a posted entry from this feed source.
  445. *
  446. * @param DOMElement $entry
  447. * @param DOMElement $feed for context
  448. * @param string $source identifier ("push" or "salmon")
  449. *
  450. * @return Notice Notice representing the new (or existing) activity
  451. */
  452. public function processEntry(DOMElement $entry, DOMElement $feed, $source)
  453. {
  454. $activity = new Activity($entry, $feed);
  455. return $this->processActivity($activity, $source);
  456. }
  457. // TODO: Make this throw an exception
  458. public function processActivity(Activity $activity, $source)
  459. {
  460. $notice = null;
  461. // The "WithProfile" events were added later.
  462. if (Event::handle('StartHandleFeedEntryWithProfile', array($activity, $this->localProfile(), &$notice)) &&
  463. Event::handle('StartHandleFeedEntry', array($activity))) {
  464. common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
  465. Event::handle('EndHandleFeedEntry', array($activity));
  466. Event::handle('EndHandleFeedEntryWithProfile', array($activity, $this, $notice));
  467. }
  468. return $notice;
  469. }
  470. /**
  471. * Process an incoming post activity from this remote feed.
  472. * @param Activity $activity
  473. * @param string $method 'push' or 'salmon'
  474. * @return mixed saved Notice or false
  475. */
  476. public function processPost($activity, $method)
  477. {
  478. $actor = ActivityUtils::checkAuthorship($activity, $this->localProfile());
  479. $options = array('is_local' => Notice::REMOTE);
  480. try {
  481. $stored = Notice::saveActivity($activity, $actor, $options);
  482. Ostatus_source::saveNew($stored, $this, $method);
  483. } catch (Exception $e) {
  484. common_log(LOG_ERR, "OStatus save of remote message $sourceUri failed: " . $e->getMessage());
  485. throw $e;
  486. }
  487. return $stored;
  488. }
  489. /**
  490. * Filters a list of recipient ID URIs to just those for local delivery.
  491. * @param Profile local profile of sender
  492. * @param array in/out &$attention_uris set of URIs, will be pruned on output
  493. * @return array of group IDs
  494. */
  495. static public function filterAttention(Profile $sender, array $attention)
  496. {
  497. common_log(LOG_DEBUG, "Original reply recipients: " . implode(', ', array_keys($attention)));
  498. $groups = array();
  499. $replies = array();
  500. foreach ($attention as $recipient=>$type) {
  501. // Is the recipient a local user?
  502. $user = User::getKV('uri', $recipient);
  503. if ($user instanceof User) {
  504. // @todo FIXME: Sender verification, spam etc?
  505. $replies[] = $recipient;
  506. continue;
  507. }
  508. // Is the recipient a local group?
  509. // TODO: $group = User_group::getKV('uri', $recipient);
  510. $id = OStatusPlugin::localGroupFromUrl($recipient);
  511. if ($id) {
  512. $group = User_group::getKV('id', $id);
  513. if ($group instanceof User_group) {
  514. // Deliver to all members of this local group if allowed.
  515. if ($sender->isMember($group)) {
  516. $groups[] = $group->id;
  517. } else {
  518. common_log(LOG_DEBUG, sprintf('Skipping reply to local group %s as sender %d is not a member', $group->getNickname(), $sender->id));
  519. }
  520. continue;
  521. } else {
  522. common_log(LOG_DEBUG, "Skipping reply to bogus group $recipient");
  523. }
  524. }
  525. // Is the recipient a remote user or group?
  526. try {
  527. $oprofile = self::ensureProfileURI($recipient);
  528. if ($oprofile->isGroup()) {
  529. // Deliver to local members of this remote group.
  530. // @todo FIXME: Sender verification?
  531. $groups[] = $oprofile->group_id;
  532. } else {
  533. // may be canonicalized or something
  534. $replies[] = $oprofile->getUri();
  535. }
  536. continue;
  537. } catch (Exception $e) {
  538. // Neither a recognizable local nor remote user!
  539. common_log(LOG_DEBUG, "Skipping reply to unrecognized profile $recipient: " . $e->getMessage());
  540. }
  541. }
  542. common_log(LOG_DEBUG, "Local reply recipients: " . implode(', ', $replies));
  543. common_log(LOG_DEBUG, "Local group recipients: " . implode(', ', $groups));
  544. return array($groups, $replies);
  545. }
  546. /**
  547. * Look up and if necessary create an Ostatus_profile for the remote entity
  548. * with the given profile page URL. This should never return null -- you
  549. * will either get an object or an exception will be thrown.
  550. *
  551. * @param string $profile_url
  552. * @return Ostatus_profile
  553. * @throws Exception on various error conditions
  554. * @throws OStatusShadowException if this reference would obscure a local user/group
  555. */
  556. public static function ensureProfileURL($profile_url, array $hints=array())
  557. {
  558. $oprofile = self::getFromProfileURL($profile_url);
  559. if ($oprofile instanceof Ostatus_profile) {
  560. return $oprofile;
  561. }
  562. $hints['profileurl'] = $profile_url;
  563. // Fetch the URL
  564. // XXX: HTTP caching
  565. $client = new HTTPClient();
  566. $client->setHeader('Accept', 'text/html,application/xhtml+xml');
  567. $response = $client->get($profile_url);
  568. if (!$response->isOk()) {
  569. // TRANS: Exception. %s is a profile URL.
  570. throw new Exception(sprintf(_m('Could not reach profile page %s.'),$profile_url));
  571. }
  572. // Check if we have a non-canonical URL
  573. $finalUrl = $response->getEffectiveUrl();
  574. if ($finalUrl != $profile_url) {
  575. $hints['profileurl'] = $finalUrl;
  576. $oprofile = self::getFromProfileURL($finalUrl);
  577. if ($oprofile instanceof Ostatus_profile) {
  578. return $oprofile;
  579. }
  580. }
  581. if (in_array(
  582. preg_replace('/\s*;.*$/', '', $response->getHeader('Content-Type')),
  583. array('application/rss+xml', 'application/atom+xml', 'application/xml', 'text/xml'))
  584. ) {
  585. $hints['feedurl'] = $response->getEffectiveUrl();
  586. } else {
  587. // Try to get some hCard data
  588. $body = $response->getBody();
  589. $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl);
  590. if (!empty($hcardHints)) {
  591. $hints = array_merge($hints, $hcardHints);
  592. }
  593. }
  594. // Check if they've got an LRDD header
  595. $lrdd = LinkHeader::getLink($response, 'lrdd');
  596. try {
  597. $xrd = new XML_XRD();
  598. $xrd->loadFile($lrdd);
  599. $xrdHints = DiscoveryHints::fromXRD($xrd);
  600. $hints = array_merge($hints, $xrdHints);
  601. } catch (Exception $e) {
  602. // No hints available from XRD
  603. }
  604. // If discovery found a feedurl (probably from LRDD), use it.
  605. if (array_key_exists('feedurl', $hints)) {
  606. return self::ensureFeedURL($hints['feedurl'], $hints);
  607. }
  608. // Get the feed URL from HTML
  609. $discover = new FeedDiscovery();
  610. $feedurl = $discover->discoverFromHTML($finalUrl, $body);
  611. if (!empty($feedurl)) {
  612. $hints['feedurl'] = $feedurl;
  613. return self::ensureFeedURL($feedurl, $hints);
  614. }
  615. // TRANS: Exception. %s is a URL.
  616. throw new Exception(sprintf(_m('Could not find a feed URL for profile page %s.'),$finalUrl));
  617. }
  618. /**
  619. * Look up the Ostatus_profile, if present, for a remote entity with the
  620. * given profile page URL. Will return null for both unknown and invalid
  621. * remote profiles.
  622. *
  623. * @return mixed Ostatus_profile or null
  624. * @throws OStatusShadowException for local profiles
  625. */
  626. static function getFromProfileURL($profile_url)
  627. {
  628. $profile = Profile::getKV('profileurl', $profile_url);
  629. if (!$profile instanceof Profile) {
  630. return null;
  631. }
  632. try {
  633. $oprofile = self::getFromProfile($profile);
  634. // We found the profile, return it!
  635. return $oprofile;
  636. } catch (NoResultException $e) {
  637. // Could not find an OStatus profile, is it instead a local user?
  638. $user = User::getKV('id', $profile->id);
  639. if ($user instanceof User) {
  640. // @todo i18n FIXME: use sprintf and add i18n (?)
  641. throw new OStatusShadowException($profile, "'$profile_url' is the profile for local user '{$user->nickname}'.");
  642. }
  643. }
  644. // Continue discovery; it's a remote profile
  645. // for OMB or some other protocol, may also
  646. // support OStatus
  647. return null;
  648. }
  649. static function getFromProfile(Profile $profile)
  650. {
  651. $oprofile = new Ostatus_profile();
  652. $oprofile->profile_id = $profile->id;
  653. if (!$oprofile->find(true)) {
  654. throw new NoResultException($oprofile);
  655. }
  656. return $oprofile;
  657. }
  658. /**
  659. * Look up and if necessary create an Ostatus_profile for remote entity
  660. * with the given update feed. This should never return null -- you will
  661. * either get an object or an exception will be thrown.
  662. *
  663. * @return Ostatus_profile
  664. * @throws Exception
  665. */
  666. public static function ensureFeedURL($feed_url, array $hints=array())
  667. {
  668. $oprofile = Ostatus_profile::getKV('feeduri', $feed_url);
  669. if ($oprofile instanceof Ostatus_profile) {
  670. return $oprofile;
  671. }
  672. $discover = new FeedDiscovery();
  673. $feeduri = $discover->discoverFromFeedURL($feed_url);
  674. $hints['feedurl'] = $feeduri;
  675. $huburi = $discover->getHubLink();
  676. $hints['hub'] = $huburi;
  677. // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
  678. $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
  679. ?: $discover->getAtomLink(Salmon::NS_REPLIES);
  680. $hints['salmon'] = $salmonuri;
  681. if (!$huburi && !common_config('feedsub', 'fallback_hub') && !common_config('feedsub', 'nohub')) {
  682. // We can only deal with folks with a PuSH hub
  683. // unless we have something similar available locally.
  684. throw new FeedSubNoHubException();
  685. }
  686. $feedEl = $discover->root;
  687. if ($feedEl->tagName == 'feed') {
  688. return self::ensureAtomFeed($feedEl, $hints);
  689. } else if ($feedEl->tagName == 'channel') {
  690. return self::ensureRssChannel($feedEl, $hints);
  691. } else {
  692. throw new FeedSubBadXmlException($feeduri);
  693. }
  694. }
  695. /**
  696. * Look up and, if necessary, create an Ostatus_profile for the remote
  697. * profile with the given Atom feed - actually loaded from the feed.
  698. * This should never return null -- you will either get an object or
  699. * an exception will be thrown.
  700. *
  701. * @param DOMElement $feedEl root element of a loaded Atom feed
  702. * @param array $hints additional discovery information passed from higher levels
  703. * @todo FIXME: Should this be marked public?
  704. * @return Ostatus_profile
  705. * @throws Exception
  706. */
  707. public static function ensureAtomFeed(DOMElement $feedEl, array $hints)
  708. {
  709. $author = ActivityUtils::getFeedAuthor($feedEl);
  710. if (empty($author)) {
  711. // XXX: make some educated guesses here
  712. // TRANS: Feed sub exception.
  713. throw new FeedSubException(_m('Cannot find enough profile '.
  714. 'information to make a feed.'));
  715. }
  716. return self::ensureActivityObjectProfile($author, $hints);
  717. }
  718. /**
  719. * Look up and, if necessary, create an Ostatus_profile for the remote
  720. * profile with the given RSS feed - actually loaded from the feed.
  721. * This should never return null -- you will either get an object or
  722. * an exception will be thrown.
  723. *
  724. * @param DOMElement $feedEl root element of a loaded RSS feed
  725. * @param array $hints additional discovery information passed from higher levels
  726. * @todo FIXME: Should this be marked public?
  727. * @return Ostatus_profile
  728. * @throws Exception
  729. */
  730. public static function ensureRssChannel(DOMElement $feedEl, array $hints)
  731. {
  732. // Special-case for Posterous. They have some nice metadata in their
  733. // posterous:author elements. We should use them instead of the channel.
  734. $items = $feedEl->getElementsByTagName('item');
  735. if ($items->length > 0) {
  736. $item = $items->item(0);
  737. $authorEl = ActivityUtils::child($item, ActivityObject::AUTHOR, ActivityObject::POSTEROUS);
  738. if (!empty($authorEl)) {
  739. $obj = ActivityObject::fromPosterousAuthor($authorEl);
  740. // Posterous has multiple authors per feed, and multiple feeds
  741. // per author. We check if this is the "main" feed for this author.
  742. if (array_key_exists('profileurl', $hints) &&
  743. !empty($obj->poco) &&
  744. common_url_to_nickname($hints['profileurl']) == $obj->poco->preferredUsername) {
  745. return self::ensureActivityObjectProfile($obj, $hints);
  746. }
  747. }
  748. }
  749. $obj = ActivityUtils::getFeedAuthor($feedEl);
  750. // @todo FIXME: We should check whether this feed has elements
  751. // with different <author> or <dc:creator> elements, and... I dunno.
  752. // Do something about that.
  753. if(empty($obj)) { $obj = ActivityObject::fromRssChannel($feedEl); }
  754. return self::ensureActivityObjectProfile($obj, $hints);
  755. }
  756. /**
  757. * Download and update given avatar image
  758. *
  759. * @param string $url
  760. * @return Avatar The Avatar we have on disk. (seldom used)
  761. * @throws Exception in various failure cases
  762. */
  763. public function updateAvatar($url, $force=false)
  764. {
  765. try {
  766. // If avatar URL differs: update. If URLs were identical but we're forced: update.
  767. if ($url == $this->avatar && !$force) {
  768. // If there's no locally stored avatar, throw an exception and continue fetching below.
  769. $avatar = Avatar::getUploaded($this->localProfile()) instanceof Avatar;
  770. return $avatar;
  771. }
  772. } catch (NoAvatarException $e) {
  773. // No avatar available, let's fetch it.
  774. }
  775. if (!common_valid_http_url($url)) {
  776. // TRANS: Server exception. %s is a URL.
  777. throw new ServerException(sprintf(_m('Invalid avatar URL %s.'), $url));
  778. }
  779. $self = $this->localProfile();
  780. // @todo FIXME: This should be better encapsulated
  781. // ripped from oauthstore.php (for old OMB client)
  782. $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
  783. try {
  784. $imgData = HTTPClient::quickGet($url);
  785. // Make sure it's at least an image file. ImageFile can do the rest.
  786. if (false === getimagesizefromstring($imgData)) {
  787. throw new UnsupportedMediaException(_('Downloaded group avatar was not an image.'));
  788. }
  789. file_put_contents($temp_filename, $imgData);
  790. unset($imgData); // No need to carry this in memory.
  791. if ($this->isGroup()) {
  792. $id = $this->group_id;
  793. } else {
  794. $id = $this->profile_id;
  795. }
  796. $imagefile = new ImageFile(null, $temp_filename);
  797. $filename = Avatar::filename($id,
  798. image_type_to_extension($imagefile->type),
  799. null,
  800. common_timestamp());
  801. rename($temp_filename, Avatar::path($filename));
  802. } catch (Exception $e) {
  803. unlink($temp_filename);
  804. throw $e;
  805. }
  806. // @todo FIXME: Hardcoded chmod is lame, but seems to be necessary to
  807. // keep from accidentally saving images from command-line (queues)
  808. // that can't be read from web server, which causes hard-to-notice
  809. // problems later on:
  810. //
  811. // http://status.net/open-source/issues/2663
  812. chmod(Avatar::path($filename), 0644);
  813. $self->setOriginal($filename);
  814. $orig = clone($this);
  815. $this->avatar = $url;
  816. $this->update($orig);
  817. return Avatar::getUploaded($self);
  818. }
  819. /**
  820. * Pull avatar URL from ActivityObject or profile hints
  821. *
  822. * @param ActivityObject $object
  823. * @param array $hints
  824. * @return mixed URL string or false
  825. */
  826. public static function getActivityObjectAvatar(ActivityObject $object, array $hints=array())
  827. {
  828. if ($object->avatarLinks) {
  829. $best = false;
  830. // Take the exact-size avatar, or the largest avatar, or the first avatar if all sizeless
  831. foreach ($object->avatarLinks as $avatar) {
  832. if ($avatar->width == AVATAR_PROFILE_SIZE && $avatar->height = AVATAR_PROFILE_SIZE) {
  833. // Exact match!
  834. $best = $avatar;
  835. break;
  836. }
  837. if (!$best || $avatar->width > $best->width) {
  838. $best = $avatar;
  839. }
  840. }
  841. return $best->url;
  842. } else if (array_key_exists('avatar', $hints)) {
  843. return $hints['avatar'];
  844. }
  845. return false;
  846. }
  847. /**
  848. * Get an appropriate avatar image source URL, if available.
  849. *
  850. * @param ActivityObject $actor
  851. * @param DOMElement $feed
  852. * @return string
  853. */
  854. protected static function getAvatar(ActivityObject $actor, DOMElement $feed)
  855. {
  856. $url = '';
  857. $icon = '';
  858. if ($actor->avatar) {
  859. $url = trim($actor->avatar);
  860. }
  861. if (!$url) {
  862. // Check <atom:logo> and <atom:icon> on the feed
  863. $els = $feed->childNodes();
  864. if ($els && $els->length) {
  865. for ($i = 0; $i < $els->length; $i++) {
  866. $el = $els->item($i);
  867. if ($el->namespaceURI == Activity::ATOM) {
  868. if (empty($url) && $el->localName == 'logo') {
  869. $url = trim($el->textContent);
  870. break;
  871. }
  872. if (empty($icon) && $el->localName == 'icon') {
  873. // Use as a fallback
  874. $icon = trim($el->textContent);
  875. }
  876. }
  877. }
  878. }
  879. if ($icon && !$url) {
  880. $url = $icon;
  881. }
  882. }
  883. if ($url) {
  884. $opts = array('allowed_schemes' => array('http', 'https'));
  885. if (common_valid_http_url($url)) {
  886. return $url;
  887. }
  888. }
  889. return Plugin::staticPath('OStatus', 'images/96px-Feed-icon.svg.png');
  890. }
  891. /**
  892. * Fetch, or build if necessary, an Ostatus_profile for the actor
  893. * in a given Activity Streams activity.
  894. * This should never return null -- you will either get an object or
  895. * an exception will be thrown.
  896. *
  897. * @param Activity $activity
  898. * @param string $feeduri if we already know the canonical feed URI!
  899. * @param string $salmonuri if we already know the salmon return channel URI
  900. * @return Ostatus_profile
  901. * @throws Exception
  902. */
  903. public static function ensureActorProfile(Activity $activity, array $hints=array())
  904. {
  905. return self::ensureActivityObjectProfile($activity->actor, $hints);
  906. }
  907. /**
  908. * Fetch, or build if necessary, an Ostatus_profile for the profile
  909. * in a given Activity Streams object (can be subject, actor, or object).
  910. * This should never return null -- you will either get an object or
  911. * an exception will be thrown.
  912. *
  913. * @param ActivityObject $object
  914. * @param array $hints additional discovery information passed from higher levels
  915. * @return Ostatus_profile
  916. * @throws Exception
  917. */
  918. public static function ensureActivityObjectProfile(ActivityObject $object, array $hints=array())
  919. {
  920. $profile = self::getActivityObjectProfile($object);
  921. if ($profile instanceof Ostatus_profile) {
  922. $profile->updateFromActivityObject($object, $hints);
  923. } else {
  924. $profile = self::createActivityObjectProfile($object, $hints);
  925. }
  926. return $profile;
  927. }
  928. /**
  929. * @param Activity $activity
  930. * @return mixed matching Ostatus_profile or false if none known
  931. * @throws ServerException if feed info invalid
  932. */
  933. public static function getActorProfile(Activity $activity)
  934. {
  935. return self::getActivityObjectProfile($activity->actor);
  936. }
  937. /**
  938. * @param ActivityObject $activity
  939. * @return mixed matching Ostatus_profile or false if none known
  940. * @throws ServerException if feed info invalid
  941. */
  942. protected static function getActivityObjectProfile(ActivityObject $object)
  943. {
  944. $uri = self::getActivityObjectProfileURI($object);
  945. return Ostatus_profile::getKV('uri', $uri);
  946. }
  947. /**
  948. * Get the identifier URI for the remote entity described
  949. * by this ActivityObject. This URI is *not* guaranteed to be
  950. * a resolvable HTTP/HTTPS URL.
  951. *
  952. * @param ActivityObject $object
  953. * @return string
  954. * @throws ServerException if feed info invalid
  955. */
  956. protected static function getActivityObjectProfileURI(ActivityObject $object)
  957. {
  958. if ($object->id) {
  959. if (ActivityUtils::validateUri($object->id)) {
  960. return $object->id;
  961. }
  962. }
  963. // If the id is missing or invalid (we've seen feeds mistakenly listing
  964. // things like local usernames in that field) then we'll use the profile
  965. // page link, if valid.
  966. if ($object->link && common_valid_http_url($object->link)) {
  967. return $object->link;
  968. }
  969. // TRANS: Server exception.
  970. throw new ServerException(_m('No author ID URI found.'));
  971. }
  972. /**
  973. * @todo FIXME: Validate stuff somewhere.
  974. */
  975. /**
  976. * Create local ostatus_profile and profile/user_group entries for
  977. * the provided remote user or group.
  978. * This should never return null -- you will either get an object or
  979. * an exception will be thrown.
  980. *
  981. * @param ActivityObject $object
  982. * @param array $hints
  983. *
  984. * @return Ostatus_profile
  985. */
  986. protected static function createActivityObjectProfile(ActivityObject $object, array $hints=array())
  987. {
  988. $homeuri = $object->id;
  989. $discover = false;
  990. if (!$homeuri) {
  991. common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
  992. // TRANS: Exception.
  993. throw new Exception(_m('No profile URI.'));
  994. }
  995. $user = User::getKV('uri', $homeuri);
  996. if ($user instanceof User) {
  997. // TRANS: Exception.
  998. throw new Exception(_m('Local user cannot be referenced as remote.'));
  999. }
  1000. if (OStatusPlugin::localGroupFromUrl($homeuri)) {
  1001. // TRANS: Exception.
  1002. throw new Exception(_m('Local group cannot be referenced as remote.'));
  1003. }
  1004. $ptag = Profile_list::getKV('uri', $homeuri);
  1005. if ($ptag instanceof Profile_list) {
  1006. $local_user = User::getKV('id', $ptag->tagger);
  1007. if ($local_user instanceof User) {
  1008. // TRANS: Exception.
  1009. throw new Exception(_m('Local list cannot be referenced as remote.'));
  1010. }
  1011. }
  1012. if (array_key_exists('feedurl', $hints)) {
  1013. $feeduri = $hints['feedurl'];
  1014. } else {
  1015. $discover = new FeedDiscovery();
  1016. $feeduri = $discover->discoverFromURL($homeuri);
  1017. }
  1018. if (array_key_exists('salmon', $hints)) {
  1019. $salmonuri = $hints['salmon'];
  1020. } else {
  1021. if (!$discover) {
  1022. $discover = new FeedDiscovery();
  1023. $discover->discoverFromFeedURL($hints['feedurl']);
  1024. }
  1025. // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
  1026. $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
  1027. ?: $discover->getAtomLink(Salmon::NS_REPLIES);
  1028. }
  1029. if (array_key_exists('hub', $hints)) {
  1030. $huburi = $hints['hub'];
  1031. } else {
  1032. if (!$discover) {
  1033. $discover = new FeedDiscovery();
  1034. $discover->discoverFromFeedURL($hints['feedurl']);
  1035. }
  1036. $huburi = $discover->getHubLink();
  1037. }
  1038. if (!$huburi && !common_config('feedsub', 'fallback_hub') && !common_config('feedsub', 'nohub')) {
  1039. // We can only deal with folks with a PuSH hub
  1040. throw new FeedSubNoHubException();
  1041. }
  1042. $oprofile = new Ostatus_profile();
  1043. $oprofile->uri = $homeuri;
  1044. $oprofile->feeduri = $feeduri;
  1045. $oprofile->salmonuri = $salmonuri;
  1046. $oprofile->created = common_sql_now();
  1047. $oprofile->modified = common_sql_now();
  1048. if ($object->type == ActivityObject::PERSON) {
  1049. $profile = new Profile();
  1050. $profile->created = common_sql_now();
  1051. self::updateProfile($profile, $object, $hints);
  1052. $oprofile->profile_id = $profile->insert();
  1053. if ($oprofile->profile_id === false) {
  1054. // TRANS: Server exception.
  1055. throw new ServerException(_m('Cannot save local profile.'));
  1056. }
  1057. } else if ($object->type == ActivityObject::GROUP) {
  1058. $profile = new Profile();
  1059. $profile->query('BEGIN');
  1060. $group = new User_group();
  1061. $group->uri = $homeuri;
  1062. $group->created = common_sql_now();
  1063. self::updateGroup($group, $object, $hints);
  1064. // TODO: We should do this directly in User_group->insert()!
  1065. // currently it's duplicated in User_group->update()
  1066. // AND User_group->register()!!!
  1067. $fields = array(/*group field => profile field*/
  1068. 'nickname' => 'nickname',
  1069. 'fullname' => 'fullname',
  1070. 'mainpage' => 'profileurl',
  1071. 'homepage' => 'homepage',
  1072. 'description' => 'bio',
  1073. 'location' => 'location',
  1074. 'created' => 'created',
  1075. 'modified' => 'modified',
  1076. );
  1077. foreach ($fields as $gf=>$pf) {
  1078. $profile->$pf = $group->$gf;
  1079. }
  1080. $profile_id = $profile->insert();
  1081. if ($profile_id === false) {
  1082. $profile->query('ROLLBACK');
  1083. throw new ServerException(_('Profile insertion failed.'));
  1084. }
  1085. $group->profile_id = $profile_id;
  1086. $oprofile->group_id = $group->insert();
  1087. if ($oprofile->group_id === false) {
  1088. $profile->query('ROLLBACK');
  1089. // TRANS: Server exception.
  1090. throw new ServerException(_m('Cannot save local profile.'));
  1091. }
  1092. $profile->query('COMMIT');
  1093. } else if ($object->type == ActivityObject::_LIST) {
  1094. $ptag = new Profile_list();
  1095. $ptag->uri = $homeuri;
  1096. $ptag->created = common_sql_now();
  1097. self::updatePeopletag($ptag, $object, $hints);
  1098. $oprofile->peopletag_id = $ptag->insert();
  1099. if ($oprofile->peopletag_id === false) {
  1100. // TRANS: Server exception.
  1101. throw new ServerException(_m('Cannot save local list.'));
  1102. }
  1103. }
  1104. $ok = $oprofile->insert();
  1105. if ($ok === false) {
  1106. // TRANS: Server exception.
  1107. throw new ServerException(_m('Cannot save OStatus profile.'));
  1108. }
  1109. $avatar = self::getActivityObjectAvatar($object, $hints);
  1110. if ($avatar) {
  1111. try {
  1112. $oprofile->updateAvatar($avatar);
  1113. } catch (Exception $ex) {
  1114. // Profile is saved, but Avatar is messed up. We're
  1115. // just going to continue.
  1116. common_log(LOG_WARNING, "Exception saving OStatus profile avatar: ". $ex->getMessage());
  1117. }
  1118. }
  1119. return $oprofile;
  1120. }
  1121. /**
  1122. * Save any updated profile information to our local copy.
  1123. * @param ActivityObject $object
  1124. * @param array $hints
  1125. */
  1126. public function updateFromActivityObject(ActivityObject $object, array $hints=array())
  1127. {
  1128. if ($this->isGroup()) {
  1129. $group = $this->localGroup();
  1130. self::updateGroup($group, $object, $hints);
  1131. } else if ($this->isPeopletag()) {
  1132. $ptag = $this->localPeopletag();
  1133. self::updatePeopletag($ptag, $object, $hints);
  1134. } else {
  1135. $profile = $this->localProfile();
  1136. self::updateProfile($profile, $object, $hints);
  1137. }
  1138. $avatar = self::getActivityObjectAvatar($object, $hints);
  1139. if ($avatar && !isset($ptag)) {
  1140. try {
  1141. $this->updateAvatar($avatar);
  1142. } catch (Exception $ex) {
  1143. common_log(LOG_WARNING, "Exception updating OStatus profile avatar: " . $ex->getMessage());
  1144. }
  1145. }
  1146. }
  1147. public static function updateProfile(Profile $profile, ActivityObject $object, array $hints=array())
  1148. {
  1149. $orig = clone($profile);
  1150. // Existing nickname is better than nothing.
  1151. if (!array_key_exists('nickname', $hints)) {
  1152. $hints['nickname'] = $profile->nickname;
  1153. }
  1154. $nickname = self::getActivityObjectNickname($object, $hints);
  1155. if (!empty($nickname)) {
  1156. $profile->nickname = $nickname;
  1157. }
  1158. if (!empty($object->title)) {
  1159. $profile->fullname = $object->title;
  1160. } else if (array_key_exists('fullname', $hints)) {
  1161. $profile->fullname = $hints['fullname'];
  1162. }
  1163. if (!empty($object->link)) {
  1164. $profile->profileurl = $object->link;
  1165. } else if (array_key_exists('profileurl', $hints)) {
  1166. $profile->profileurl = $hints['profileurl'];
  1167. } else if (common_valid_http_url($object->id)) {
  1168. $profile->profileurl = $object->id;
  1169. }
  1170. $bio = self::getActivityObjectBio($object, $hints);
  1171. if (!empty($bio)) {
  1172. $profile->bio = $bio;
  1173. }
  1174. $location = self::getActivityObjectLocation($object, $hints);
  1175. if (!empty($location)) {
  1176. $profile->location = $location;
  1177. }
  1178. $homepage = self::getActivityObjectHomepage($object, $hints);
  1179. if (!empty($homepage)) {
  1180. $profile->homepage = $homepage;
  1181. }
  1182. if (!empty($object->geopoint)) {
  1183. $location = ActivityContext::locationFromPoint($object->geopoint);
  1184. if (!empty($location)) {
  1185. $profile->lat = $location->lat;
  1186. $profile->lon = $location->lon;
  1187. }
  1188. }
  1189. // @todo FIXME: tags/categories
  1190. // @todo tags from categories
  1191. if ($profile->id) {
  1192. common_log(LOG_DEBUG, "Updating OStatus profile $profile->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
  1193. $profile->update($orig);
  1194. }
  1195. }
  1196. protected static function updateGroup(User_group $group, ActivityObject $object, array $hints=array())
  1197. {
  1198. $orig = clone($group);
  1199. $group->nickname = self::getActivityObjectNickname($object, $hints);
  1200. $group->fullname = $object->title;
  1201. if (!empty($object->link)) {
  1202. $group->mainpage = $object->link;
  1203. } else if (array_key_exists('profileurl', $hints)) {
  1204. $group->mainpage = $hints['profileurl'];
  1205. }
  1206. // @todo tags from categories
  1207. $group->description = self::getActivityObjectBio($object, $hints);
  1208. $group->location = self::getActivityObjectLocation($object, $hints);
  1209. $group->homepage = self::getActivityObjectHomepage($object, $hints);
  1210. if ($group->id) { // If no id, we haven't called insert() yet, so don't run update()
  1211. common_log(LOG_DEBUG, "Updating OStatus group $group->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
  1212. $group->update($orig);
  1213. }
  1214. }
  1215. protected static function updatePeopletag($tag, ActivityObject $object, array $hints=array()) {
  1216. $orig = clone($tag);
  1217. $tag->tag = $object->title;
  1218. if (!empty($object->link)) {
  1219. $tag->mainpage = $object->link;
  1220. } else if (array_key_exists('profileurl', $hints)) {
  1221. $tag->mainpage = $hints['profileurl'];
  1222. }
  1223. $tag->description = $object->summary;
  1224. $tagger = self::ensureActivityObjectProfile($object->owner);
  1225. $tag->tagger = $tagger->profile_id;
  1226. if ($tag->id) {
  1227. common_log(LOG_DEBUG, "Updating OStatus peopletag $tag->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
  1228. $tag->update($orig);
  1229. }
  1230. }
  1231. protected static function getActivityObjectHomepage(ActivityObject $object, array $hints=array())
  1232. {
  1233. $homepage = null;
  1234. $poco = $object->poco;
  1235. if (!empty($poco)) {
  1236. $url = $poco->getPrimaryURL();
  1237. if ($url && $url->type == 'homepage') {
  1238. $homepage = $url->value;
  1239. }
  1240. }
  1241. // @todo Try for a another PoCo URL?
  1242. return $homepage;
  1243. }
  1244. protected static function getActivityObjectLocation(ActivityObject $object, array $hints=array())
  1245. {
  1246. $location = null;
  1247. if (!empty($object->poco) &&
  1248. isset($object->poco->address->formatted)) {
  1249. $location = $object->poco->address->formatted;
  1250. } else if (array_key_exists('location', $hints)) {
  1251. $location = $hints['location'];
  1252. }
  1253. if (!empty($location)) {
  1254. if (mb_strlen($location) > 191) { // not 255 because utf8mb4 takes more space
  1255. $location = mb_substr($note, 0, 191 - 3) . ' … ';
  1256. }
  1257. }
  1258. // @todo Try to find location some othe way? Via goerss point?
  1259. return $location;
  1260. }
  1261. protected static function getActivityObjectBio(ActivityObject $object, array $hints=array())
  1262. {
  1263. $bio = null;
  1264. if (!empty($object->poco)) {
  1265. $note = $object->poco->note;
  1266. } else if (array_key_exists('bio', $hints)) {
  1267. $note = $hints['bio'];
  1268. }
  1269. if (!empty($note)) {
  1270. if (Profile::bioTooLong($note)) {
  1271. // XXX: truncate ok?
  1272. $bio = mb_substr($note, 0, Profile::maxBio() - 3) . ' … ';
  1273. } else {
  1274. $bio = $note;
  1275. }
  1276. }
  1277. // @todo Try to get bio info some other way?
  1278. return $bio;
  1279. }
  1280. public static function getActivityObjectNickname(ActivityObject $object, array $hints=array())
  1281. {
  1282. if ($object->poco) {
  1283. if (!empty($object->poco->preferredUsername)) {
  1284. return common_nicknamize($object->poco->preferredUsername);
  1285. }
  1286. }
  1287. if (!empty($object->nickname)) {
  1288. return common_nicknamize($object->nickname);
  1289. }
  1290. if (array_key_exists('nickname', $hints)) {
  1291. return $hints['nickname'];
  1292. }
  1293. // Try the profile url (like foo.example.com or example.com/user/foo)
  1294. if (!empty($object->link)) {
  1295. $profileUrl = $object->link;
  1296. } else if (!empty($hints['profileurl'])) {
  1297. $profileUrl = $hints['profileurl'];
  1298. }
  1299. if (!empty($profileUrl)) {
  1300. $nickname = self::nicknameFromURI($profileUrl);
  1301. }
  1302. // Try the URI (may be a tag:, http:, acct:, ...
  1303. if (empty($nickname)) {
  1304. $nickname = self::nicknameFromURI($object->id);
  1305. }
  1306. // Try a Webfinger if one was passed (way) down
  1307. if (empty($nickname)) {
  1308. if (array_key_exists('webfinger', $hints)) {
  1309. $nickname = self::nicknameFromURI($hints['webfinger']);
  1310. }
  1311. }
  1312. // Try the name
  1313. if (empty($nickname)) {
  1314. $nickname = common_nicknamize($object->title);
  1315. }
  1316. return $nickname;
  1317. }
  1318. protected static function nicknameFromURI($uri)
  1319. {
  1320. if (preg_match('/(\w+):/', $uri, $matches)) {
  1321. $protocol = $matches[1];
  1322. } else {
  1323. return null;
  1324. }
  1325. switch ($protocol) {
  1326. case 'acct':
  1327. case 'mailto':
  1328. if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
  1329. return common_canonical_nickname($matches[1]);
  1330. }
  1331. return null;
  1332. case 'http':
  1333. return common_url_to_nickname($uri);
  1334. break;
  1335. default:
  1336. return null;
  1337. }
  1338. }
  1339. /**
  1340. * Look up, and if necessary create, an Ostatus_profile for the remote
  1341. * entity with the given webfinger address.
  1342. * This should never return null -- you will either get an object or
  1343. * an exception will be thrown.
  1344. *
  1345. * @param string $addr webfinger address
  1346. * @return Ostatus_profile
  1347. * @throws Exception on error conditions
  1348. * @throws OStatusShadowException if this reference would obscure a local user/group
  1349. */
  1350. public static function ensureWebfinger($addr)
  1351. {
  1352. // First, try the cache
  1353. $uri = self::cacheGet(sprintf('ostatus_profile:webfinger:%s', $addr));
  1354. if ($uri !== false) {
  1355. if (is_null($uri)) {
  1356. // Negative cache entry
  1357. // TRANS: Exception.
  1358. throw new Exception(_m('Not a valid webfinger address.'));
  1359. }
  1360. $oprofile = Ostatus_profile::getKV('uri', $uri);
  1361. if ($oprofile instanceof Ostatus_profile) {
  1362. return $oprofile;
  1363. }
  1364. }
  1365. // Try looking it up
  1366. $oprofile = Ostatus_profile::getKV('uri', Discovery::normalize($addr));
  1367. if ($oprofile instanceof Ostatus_profile) {
  1368. self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
  1369. return $oprofile;
  1370. }
  1371. // Now, try some discovery
  1372. $disco = new Discovery();
  1373. try {
  1374. $xrd = $disco->lookup($addr);
  1375. } catch (Exception $e) {
  1376. // Save negative cache entry so we don't waste time looking it up again.
  1377. // @todo FIXME: Distinguish temporary failures?
  1378. self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null);
  1379. // TRANS: Exception.
  1380. throw new Exception(_m('Not a valid webfinger address.'));
  1381. }
  1382. $hints = array_merge(array('webfinger' => $addr),
  1383. DiscoveryHints::fromXRD($xrd));
  1384. // If there's an Hcard, let's grab its info
  1385. if (array_key_exists('hcard', $hints)) {
  1386. if (!array_key_exists('profileurl', $hints) ||
  1387. $hints['hcard'] != $hints['profileurl']) {
  1388. $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
  1389. $hints = array_merge($hcardHints, $hints);
  1390. }
  1391. }
  1392. // If we got a feed URL, try that
  1393. $feedUrl = null;
  1394. if (array_key_exists('feedurl', $hints)) {
  1395. $feedUrl = $hints['feedurl'];
  1396. try {
  1397. common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
  1398. $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
  1399. self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
  1400. return $oprofile;
  1401. } catch (Exception $e) {
  1402. common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
  1403. // keep looking
  1404. }
  1405. }
  1406. // If we got a profile page, try that!
  1407. $profileUrl = null;
  1408. if (array_key_exists('profileurl', $hints)) {
  1409. $profileUrl = $hints['profileurl'];
  1410. try {
  1411. common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
  1412. $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
  1413. self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
  1414. return $oprofile;
  1415. } catch (OStatusShadowException $e) {
  1416. // We've ended up with a remote reference to a local user or group.
  1417. // @todo FIXME: Ideally we should be able to say who it was so we can
  1418. // go back and refer to it the regular way
  1419. throw $e;
  1420. } catch (Exception $e) {
  1421. common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
  1422. // keep looking
  1423. //
  1424. // @todo FIXME: This means an error discovering from profile page
  1425. // may give us a corrupt entry using the webfinger URI, which
  1426. // will obscure the correct page-keyed profile later on.
  1427. }
  1428. }
  1429. // XXX: try hcard
  1430. // XXX: try FOAF
  1431. if (array_key_exists('salmon', $hints)) {
  1432. $salmonEndpoint = $hints['salmon'];
  1433. // An account URL, a salmon endpoint, and a dream? Not much to go
  1434. // on, but let's give it a try
  1435. $uri = 'acct:'.$addr;
  1436. $profile = new Profile();
  1437. $profile->nickname = self::nicknameFromUri($uri);
  1438. $profile->created = common_sql_now();
  1439. if (!is_null($profileUrl)) {
  1440. $profile->profileurl = $profileUrl;
  1441. }
  1442. $profile_id = $profile->insert();
  1443. if ($profile_id === false) {
  1444. common_log_db_error($profile, 'INSERT', __FILE__);
  1445. // TRANS: Exception. %s is a webfinger address.
  1446. throw new Exception(sprintf(_m('Could not save profile for "%s".'),$addr));
  1447. }
  1448. $oprofile = new Ostatus_profile();
  1449. $oprofile->uri = $uri;
  1450. $oprofile->salmonuri = $salmonEndpoint;
  1451. $oprofile->profile_id = $profile_id;
  1452. $oprofile->created = common_sql_now();
  1453. if (!is_null($feedUrl)) {
  1454. $oprofile->feeduri = $feedUrl;
  1455. }
  1456. $result = $oprofile->insert();
  1457. if ($result === false) {
  1458. $profile->delete();
  1459. common_log_db_error($oprofile, 'INSERT', __FILE__);
  1460. // TRANS: Exception. %s is a webfinger address.
  1461. throw new Exception(sprintf(_m('Could not save OStatus profile for "%s".'),$addr));
  1462. }
  1463. self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
  1464. return $oprofile;
  1465. }
  1466. // TRANS: Exception. %s is a webfinger address.
  1467. throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'),$addr));
  1468. }
  1469. /**
  1470. * Store the full-length scrubbed HTML of a remote notice to an attachment
  1471. * file on our server. We'll link to this at the end of the cropped version.
  1472. *
  1473. * @param string $title plaintext for HTML page's title
  1474. * @param string $rendered HTML fragment for HTML page's body
  1475. * @return File
  1476. */
  1477. function saveHTMLFile($title, $rendered)
  1478. {
  1479. $final = sprintf("<!DOCTYPE html>\n" .
  1480. '<html><head>' .
  1481. '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' .
  1482. '<title>%s</title>' .
  1483. '</head>' .
  1484. '<body>%s</body></html>',
  1485. htmlspecialchars($title),
  1486. $rendered);
  1487. $filename = File::filename($this->localProfile(),
  1488. 'ostatus', // ignored?
  1489. 'text/html');
  1490. $filepath = File::path($filename);
  1491. $fileurl = File::url($filename);
  1492. file_put_contents($filepath, $final);
  1493. $file = new File;
  1494. $file->filename = $filename;
  1495. $file->urlhash = File::hashurl($fileurl);
  1496. $file->url = $fileurl;
  1497. $file->size = filesize($filepath);
  1498. $file->date = time();
  1499. $file->mimetype = 'text/html';
  1500. $file_id = $file->insert();
  1501. if ($file_id === false) {
  1502. common_log_db_error($file, "INSERT", __FILE__);
  1503. // TRANS: Server exception.
  1504. throw new ServerException(_m('Could not store HTML content of long post as file.'));
  1505. }
  1506. return $file;
  1507. }
  1508. static function ensureProfileURI($uri)
  1509. {
  1510. $oprofile = null;
  1511. // First, try to query it
  1512. $oprofile = Ostatus_profile::getKV('uri', $uri);
  1513. if ($oprofile instanceof Ostatus_profile) {
  1514. return $oprofile;
  1515. }
  1516. // If unfound, do discovery stuff
  1517. if (preg_match("/^(\w+)\:(.*)/", $uri, $match)) {
  1518. $protocol = $match[1];
  1519. switch ($protocol) {
  1520. case 'http':
  1521. case 'https':
  1522. $oprofile = self::ensureProfileURL($uri);
  1523. break;
  1524. case 'acct':
  1525. case 'mailto':
  1526. $rest = $match[2];
  1527. $oprofile = self::ensureWebfinger($rest);
  1528. break;
  1529. default:
  1530. // TRANS: Server exception.
  1531. // TRANS: %1$s is a protocol, %2$s is a URI.
  1532. throw new ServerException(sprintf(_m('Unrecognized URI protocol for profile: %1$s (%2$s).'),
  1533. $protocol,
  1534. $uri));
  1535. }
  1536. } else {
  1537. // TRANS: Server exception. %s is a URI.
  1538. throw new ServerException(sprintf(_m('No URI protocol for profile: %s.'),$uri));
  1539. }
  1540. return $oprofile;
  1541. }
  1542. public function checkAuthorship(Activity $activity)
  1543. {
  1544. if ($this->isGroup() || $this->isPeopletag()) {
  1545. // A group or propletag feed will contain posts from multiple authors.
  1546. $oprofile = self::ensureActorProfile($activity);
  1547. if ($oprofile->isGroup() || $oprofile->isPeopletag()) {
  1548. // Groups can't post notices in StatusNet.
  1549. common_log(LOG_WARNING,
  1550. "OStatus: skipping post with group listed ".
  1551. "as author: " . $oprofile->getUri() . " in feed from " . $this->getUri());
  1552. throw new ServerException('Activity author is a non-actor');
  1553. }
  1554. } else {
  1555. $actor = $activity->actor;
  1556. if (empty($actor)) {
  1557. // OK here! assume the default
  1558. } else if ($actor->id == $this->getUri() || $actor->link == $this->getUri()) {
  1559. $this->updateFromActivityObject($actor);
  1560. } else if ($actor->id) {
  1561. // We have an ActivityStreams actor with an explicit ID that doesn't match the feed owner.
  1562. // This isn't what we expect from mainline OStatus person feeds!
  1563. // Group feeds go down another path, with different validation...
  1564. // Most likely this is a plain ol' blog feed of some kind which
  1565. // doesn't match our expectations. We'll take the entry, but ignore
  1566. // the <author> info.
  1567. common_log(LOG_WARNING, "Got an actor '{$actor->title}' ({$actor->id}) on single-user feed for " . $this->getUri());
  1568. } else {
  1569. // Plain <author> without ActivityStreams actor info.
  1570. // We'll just ignore this info for now and save the update under the feed's identity.
  1571. }
  1572. $oprofile = $this;
  1573. }
  1574. return $oprofile->localProfile();
  1575. }
  1576. public function updateUriKeys($profile_uri, array $hints=array())
  1577. {
  1578. $orig = clone($this);
  1579. common_debug('URIFIX These identities both say they are each other: "'.$orig->uri.'" and "'.$profile_uri.'"');
  1580. $this->uri = $profile_uri;
  1581. if (array_key_exists('feedurl', $hints)) {
  1582. if (!empty($this->feeduri)) {
  1583. common_debug('URIFIX Changing FeedSub ['.$feedsub->id.'] feeduri "'.$feedsub->uri.'" to "'.$hints['feedurl']);
  1584. $feedsub = FeedSub::getKV('uri', $this->feeduri);
  1585. $feedorig = clone($feedsub);
  1586. $feedsub->uri = $hints['feedurl'];
  1587. $feedsub->updateWithKeys($feedorig);
  1588. } else {
  1589. common_debug('URIFIX Old Ostatus_profile did not have feedurl set, ensuring feed: '.$hints['feedurl']);
  1590. FeedSub::ensureFeed($hints['feedurl']);
  1591. }
  1592. $this->feeduri = $hints['feedurl'];
  1593. }
  1594. if (array_key_exists('salmon', $hints)) {
  1595. common_debug('URIFIX Changing Ostatus_profile salmonuri from "'.$this->salmonuri.'" to "'.$hints['salmon'].'"');
  1596. $this->salmonuri = $hints['salmon'];
  1597. }
  1598. common_debug('URIFIX Updating Ostatus_profile URI for '.$orig->uri.' to '.$this->uri);
  1599. $this->updateWithKeys($orig); // Will use the PID column(s) in the 'UPDATE ... WHERE [unique selector]'
  1600. common_debug('URIFIX Subscribing/renewing feedsub for Ostatus_profile '.$this->uri);
  1601. $this->subscribe();
  1602. }
  1603. }