Ostatus_profile.php 70 KB

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