Ostatus_profile.php 69 KB

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