Ostatus_profile.php 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949
  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 bool 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());
  800. return $avatar;
  801. }
  802. } catch (NoAvatarException $e) {
  803. // No avatar available, let's fetch it.
  804. }
  805. // ImageFile throws exception if something goes wrong, which we'll let go on its merry way
  806. $imagefile = ImageFile::fromUrl($url);
  807. $self = $this->localProfile();
  808. $id = $self->getID();
  809. $type = $imagefile->preferredType();
  810. $filename = Avatar::filename(
  811. $id,
  812. image_type_to_extension($type),
  813. null,
  814. 'tmp' . common_timestamp()
  815. );
  816. $filepath = Avatar::path($filename);
  817. /*$imagefile = */$imagefile->copyTo($filepath);
  818. // @todo FIXME: Hardcoded chmod is lame, but seems to be necessary to
  819. // keep from accidentally saving images from command-line (queues)
  820. // that can't be read from web server, which causes hard-to-notice
  821. // problems later on:
  822. //
  823. // http://status.net/open-source/issues/2663
  824. chmod($filepath, 0644);
  825. $self->setOriginal($filename);
  826. $orig = clone($this);
  827. $this->avatar = $url;
  828. $this->update($orig);
  829. return Avatar::getUploaded($self);
  830. }
  831. /**
  832. * Pull avatar URL from ActivityObject or profile hints
  833. *
  834. * @param ActivityObject $object
  835. * @param array $hints
  836. * @return mixed URL string or false
  837. */
  838. public static function getActivityObjectAvatar(ActivityObject $object, array $hints = [])
  839. {
  840. if ($object->avatarLinks) {
  841. $best = false;
  842. // Take the exact-size avatar, or the largest avatar, or the first avatar if all sizeless
  843. foreach ($object->avatarLinks as $avatar) {
  844. if (
  845. $avatar->width === AVATAR_PROFILE_SIZE
  846. && $avatar->height === AVATAR_PROFILE_SIZE
  847. ) {
  848. // Exact match!
  849. $best = $avatar;
  850. break;
  851. }
  852. if (!$best || $avatar->width > $best->width) {
  853. $best = $avatar;
  854. }
  855. }
  856. return $best->url;
  857. } elseif (array_key_exists('avatar', $hints)) {
  858. return $hints['avatar'];
  859. }
  860. return false;
  861. }
  862. /**
  863. * Get an appropriate avatar image source URL, if available.
  864. *
  865. * @param ActivityObject $actor
  866. * @param DOMElement $feed
  867. * @return string
  868. */
  869. protected static function getAvatar(ActivityObject $actor, DOMElement $feed)
  870. {
  871. $url = '';
  872. $icon = '';
  873. if ($actor->avatar) {
  874. $url = trim($actor->avatar);
  875. }
  876. if (!$url) {
  877. // Check <atom:logo> and <atom:icon> on the feed
  878. $els = $feed->childNodes();
  879. if ($els && $els->length) {
  880. for ($i = 0; $i < $els->length; $i++) {
  881. $el = $els->item($i);
  882. if ($el->namespaceURI == Activity::ATOM) {
  883. if (empty($url) && $el->localName == 'logo') {
  884. $url = trim($el->textContent);
  885. break;
  886. }
  887. if (empty($icon) && $el->localName == 'icon') {
  888. // Use as a fallback
  889. $icon = trim($el->textContent);
  890. }
  891. }
  892. }
  893. }
  894. if ($icon && !$url) {
  895. $url = $icon;
  896. }
  897. }
  898. if ($url) {
  899. $opts = array('allowed_schemes' => array('http', 'https'));
  900. if (common_valid_http_url($url)) {
  901. return $url;
  902. }
  903. }
  904. return Plugin::staticPath('OStatus', 'images/96px-Feed-icon.svg.png');
  905. }
  906. /**
  907. * Fetch, or build if necessary, an Ostatus_profile for the actor
  908. * in a given Activity Streams activity.
  909. * This should never return null -- you will either get an object or
  910. * an exception will be thrown.
  911. *
  912. * @param Activity $activity
  913. * @param string $feeduri if we already know the canonical feed URI!
  914. * @param string $salmonuri if we already know the salmon return channel URI
  915. * @return Ostatus_profile
  916. * @throws Exception
  917. */
  918. public static function ensureActorProfile(Activity $activity, array $hints=array())
  919. {
  920. return self::ensureActivityObjectProfile($activity->actor, $hints);
  921. }
  922. /**
  923. * Fetch, or build if necessary, an Ostatus_profile for the profile
  924. * in a given Activity Streams object (can be subject, actor, or object).
  925. * This should never return null -- you will either get an object or
  926. * an exception will be thrown.
  927. *
  928. * @param ActivityObject $object
  929. * @param array $hints additional discovery information passed from higher levels
  930. * @return Ostatus_profile
  931. * @throws Exception
  932. */
  933. public static function ensureActivityObjectProfile(ActivityObject $object, array $hints=array())
  934. {
  935. $profile = self::getActivityObjectProfile($object);
  936. if ($profile instanceof Ostatus_profile) {
  937. $profile->updateFromActivityObject($object, $hints);
  938. } else {
  939. $profile = self::createActivityObjectProfile($object, $hints);
  940. }
  941. return $profile;
  942. }
  943. /**
  944. * @param Activity $activity
  945. * @return mixed matching Ostatus_profile or false if none known
  946. * @throws ServerException if feed info invalid
  947. */
  948. public static function getActorProfile(Activity $activity)
  949. {
  950. return self::getActivityObjectProfile($activity->actor);
  951. }
  952. /**
  953. * @param ActivityObject $activity
  954. * @return mixed matching Ostatus_profile or false if none known
  955. * @throws ServerException if feed info invalid
  956. */
  957. protected static function getActivityObjectProfile(ActivityObject $object)
  958. {
  959. $uri = self::getActivityObjectProfileURI($object);
  960. return Ostatus_profile::getKV('uri', $uri);
  961. }
  962. /**
  963. * Get the identifier URI for the remote entity described
  964. * by this ActivityObject. This URI is *not* guaranteed to be
  965. * a resolvable HTTP/HTTPS URL.
  966. *
  967. * @param ActivityObject $object
  968. * @return string
  969. * @throws ServerException if feed info invalid
  970. */
  971. protected static function getActivityObjectProfileURI(ActivityObject $object)
  972. {
  973. if ($object->id) {
  974. if (ActivityUtils::validateUri($object->id)) {
  975. return $object->id;
  976. }
  977. }
  978. // If the id is missing or invalid (we've seen feeds mistakenly listing
  979. // things like local usernames in that field) then we'll use the profile
  980. // page link, if valid.
  981. if ($object->link && common_valid_http_url($object->link)) {
  982. return $object->link;
  983. }
  984. // TRANS: Server exception.
  985. throw new ServerException(_m('No author ID URI found.'));
  986. }
  987. /**
  988. * @todo FIXME: Validate stuff somewhere.
  989. */
  990. /**
  991. * Create local ostatus_profile and profile/user_group entries for
  992. * the provided remote user or group.
  993. * This should never return null -- you will either get an object or
  994. * an exception will be thrown.
  995. *
  996. * @param ActivityObject $object
  997. * @param array $hints
  998. *
  999. * @return Ostatus_profile
  1000. */
  1001. protected static function createActivityObjectProfile(ActivityObject $object, array $hints=array())
  1002. {
  1003. common_debug('Attempting to create an Ostatus_profile from an ActivityObject with ID: '._ve($object->id));
  1004. $homeuri = $object->id;
  1005. $discover = false;
  1006. if (!$homeuri) {
  1007. common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
  1008. // TRANS: Exception.
  1009. throw new Exception(_m('No profile URI.'));
  1010. }
  1011. $user = User::getKV('uri', $homeuri);
  1012. if ($user instanceof User) {
  1013. // TRANS: Exception.
  1014. throw new Exception(_m('Local user cannot be referenced as remote.'));
  1015. }
  1016. if (OStatusPlugin::localGroupFromUrl($homeuri)) {
  1017. // TRANS: Exception.
  1018. throw new Exception(_m('Local group cannot be referenced as remote.'));
  1019. }
  1020. $ptag = Profile_list::getKV('uri', $homeuri);
  1021. if ($ptag instanceof Profile_list) {
  1022. $local_user = User::getKV('id', $ptag->tagger);
  1023. if ($local_user instanceof User) {
  1024. // TRANS: Exception.
  1025. throw new Exception(_m('Local list cannot be referenced as remote.'));
  1026. }
  1027. }
  1028. if (!array_key_exists('feedurl', $hints)) {
  1029. $discover = new FeedDiscovery();
  1030. $hints['feedurl'] = $discover->discoverFromURL($homeuri);
  1031. common_debug(__METHOD__.' did not have a "feedurl" hint, FeedDiscovery found '._ve($hints['feedurl']));
  1032. }
  1033. $feeduri = $hints['feedurl'];
  1034. if (array_key_exists('salmon', $hints)) {
  1035. $salmonuri = $hints['salmon'];
  1036. } else {
  1037. if (!$discover) {
  1038. $discover = new FeedDiscovery();
  1039. $discover->discoverFromFeedURL($hints['feedurl']);
  1040. }
  1041. // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
  1042. $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
  1043. ?: $discover->getAtomLink(Salmon::NS_REPLIES);
  1044. }
  1045. if (array_key_exists('hub', $hints)) {
  1046. $huburi = $hints['hub'];
  1047. } else {
  1048. if (!$discover) {
  1049. $discover = new FeedDiscovery();
  1050. $discover->discoverFromFeedURL($hints['feedurl']);
  1051. }
  1052. $huburi = $discover->getHubLink();
  1053. }
  1054. if (!$huburi && !common_config('feedsub', 'fallback_hub') && !common_config('feedsub', 'nohub')) {
  1055. // We can only deal with folks with a WebSub hub
  1056. throw new FeedSubNoHubException();
  1057. }
  1058. $oprofile = new Ostatus_profile();
  1059. $oprofile->uri = $homeuri;
  1060. $oprofile->feeduri = $feeduri;
  1061. $oprofile->salmonuri = $salmonuri;
  1062. $oprofile->created = common_sql_now();
  1063. $oprofile->modified = common_sql_now();
  1064. $tfn = false;
  1065. if ($object->type == ActivityObject::PERSON) {
  1066. // Does any other protocol have this remote entity we're about to add ?
  1067. Event::handle('StartTFNLookup', [$oprofile->uri, get_called_class(), &$profile_id]);
  1068. if (!is_null($profile_id)) {
  1069. $tfn = true; // been here!
  1070. // Yes! Avoid creating a new profile
  1071. $oprofile->profile_id = $profile_id;
  1072. if ($oprofile->insert() === false) {
  1073. // TRANS: Server exception.
  1074. throw new ServerException(_m('Cannot save OStatus profile.'));
  1075. }
  1076. // Update existing profile with received data
  1077. $profile = Profile::getKV('id', $profile_id);
  1078. $profile->modified = common_sql_now();
  1079. self::updateProfile($profile, $object, $hints);
  1080. // Ask TFN to handle profile duplication
  1081. Event::handle('EndTFNLookup', [get_called_class(), $profile_id]);
  1082. } else {
  1083. // No, create both a new profile and remote profile
  1084. $profile = new Profile();
  1085. $profile->created = common_sql_now();
  1086. self::updateProfile($profile, $object, $hints);
  1087. $oprofile->profile_id = $profile->insert();
  1088. if ($oprofile->profile_id === false) {
  1089. // TRANS: Server exception.
  1090. throw new ServerException(_m('Cannot save local profile.'));
  1091. }
  1092. }
  1093. } elseif ($object->type == ActivityObject::GROUP) {
  1094. $profile = new Profile();
  1095. $profile->query('START TRANSACTION');
  1096. $group = new User_group();
  1097. $group->uri = $homeuri;
  1098. $group->created = common_sql_now();
  1099. self::updateGroup($group, $object, $hints);
  1100. // TODO: We should do this directly in User_group->insert()!
  1101. // currently it's duplicated in User_group->update()
  1102. // AND User_group->register()!!!
  1103. $fields = array(/*group field => profile field*/
  1104. 'nickname' => 'nickname',
  1105. 'fullname' => 'fullname',
  1106. 'mainpage' => 'profileurl',
  1107. 'homepage' => 'homepage',
  1108. 'description' => 'bio',
  1109. 'location' => 'location',
  1110. 'created' => 'created',
  1111. 'modified' => 'modified',
  1112. );
  1113. foreach ($fields as $gf=>$pf) {
  1114. $profile->$pf = $group->$gf;
  1115. }
  1116. $profile_id = $profile->insert();
  1117. if ($profile_id === false) {
  1118. $profile->query('ROLLBACK');
  1119. throw new ServerException(_('Profile insertion failed.'));
  1120. }
  1121. $group->profile_id = $profile_id;
  1122. $oprofile->group_id = $group->insert();
  1123. if ($oprofile->group_id === false) {
  1124. $profile->query('ROLLBACK');
  1125. // TRANS: Server exception.
  1126. throw new ServerException(_m('Cannot save local profile.'));
  1127. }
  1128. $profile->query('COMMIT');
  1129. } elseif ($object->type == ActivityObject::_LIST) {
  1130. $ptag = new Profile_list();
  1131. $ptag->uri = $homeuri;
  1132. $ptag->created = common_sql_now();
  1133. self::updatePeopletag($ptag, $object, $hints);
  1134. $oprofile->peopletag_id = $ptag->insert();
  1135. if ($oprofile->peopletag_id === false) {
  1136. // TRANS: Server exception.
  1137. throw new ServerException(_m('Cannot save local list.'));
  1138. }
  1139. }
  1140. if (!$tfn) {
  1141. $ok = $oprofile->insert();
  1142. if ($ok === false) {
  1143. // TRANS: Server exception.
  1144. throw new ServerException(_m('Cannot save OStatus profile.'));
  1145. }
  1146. }
  1147. $avatar = self::getActivityObjectAvatar($object, $hints);
  1148. if ($avatar) {
  1149. try {
  1150. $oprofile->updateAvatar($avatar);
  1151. } catch (Exception $ex) {
  1152. // Profile is saved, but Avatar is messed up. We're
  1153. // just going to continue.
  1154. common_log(LOG_WARNING, "Exception saving OStatus profile avatar: ". $ex->getMessage());
  1155. }
  1156. }
  1157. return $oprofile;
  1158. }
  1159. /**
  1160. * Save any updated profile information to our local copy.
  1161. * @param ActivityObject $object
  1162. * @param array $hints
  1163. */
  1164. public function updateFromActivityObject(ActivityObject $object, array $hints=array())
  1165. {
  1166. if (self::getActivityObjectProfileURI($object) !== $this->getUri()) {
  1167. common_log(LOG_ERR, 'Trying to update profile with URI '._ve($this->getUri()).' from ActivityObject with URI: '._ve(self::getActivityObjectProfileURI($object)));
  1168. // FIXME: Maybe not AuthorizationException?
  1169. throw new AuthorizationException('Trying to update profile from ActivityObject with different URI.');
  1170. }
  1171. common_debug('Updating Ostatus_profile with URI '._ve($this->getUri()).' from ActivityObject');
  1172. if ($this->isGroup()) {
  1173. $group = $this->localGroup();
  1174. self::updateGroup($group, $object, $hints);
  1175. } elseif ($this->isPeopletag()) {
  1176. $ptag = $this->localPeopletag();
  1177. self::updatePeopletag($ptag, $object, $hints);
  1178. } else {
  1179. $profile = $this->localProfile();
  1180. self::updateProfile($profile, $object, $hints);
  1181. }
  1182. $avatar = self::getActivityObjectAvatar($object, $hints);
  1183. if ($avatar && !isset($ptag)) {
  1184. try {
  1185. $this->updateAvatar($avatar);
  1186. } catch (Exception $e) {
  1187. common_log(LOG_WARNING, 'Exception ('.get_class($e).') updating OStatus profile avatar: ' . $e->getMessage());
  1188. }
  1189. }
  1190. }
  1191. public static function updateProfile(Profile $profile, ActivityObject $object, array $hints=array())
  1192. {
  1193. $orig = clone($profile);
  1194. // Existing nickname is better than nothing.
  1195. if (!array_key_exists('nickname', $hints)) {
  1196. $hints['nickname'] = $profile->nickname;
  1197. }
  1198. $nickname = self::getActivityObjectNickname($object, $hints);
  1199. if (!empty($nickname)) {
  1200. $profile->nickname = $nickname;
  1201. }
  1202. if (!empty($object->title)) {
  1203. $profile->fullname = $object->title;
  1204. } elseif (array_key_exists('fullname', $hints)) {
  1205. $profile->fullname = $hints['fullname'];
  1206. }
  1207. if (!empty($object->link)) {
  1208. $profile->profileurl = $object->link;
  1209. } elseif (array_key_exists('profileurl', $hints)) {
  1210. $profile->profileurl = $hints['profileurl'];
  1211. } elseif (common_valid_http_url($object->id)) {
  1212. $profile->profileurl = $object->id;
  1213. }
  1214. $bio = self::getActivityObjectBio($object, $hints);
  1215. if (!empty($bio)) {
  1216. $profile->bio = $bio;
  1217. }
  1218. $location = self::getActivityObjectLocation($object, $hints);
  1219. if (!empty($location)) {
  1220. $profile->location = $location;
  1221. }
  1222. $homepage = self::getActivityObjectHomepage($object, $hints);
  1223. if (!empty($homepage)) {
  1224. $profile->homepage = $homepage;
  1225. }
  1226. if (!empty($object->geopoint)) {
  1227. $location = ActivityContext::locationFromPoint($object->geopoint);
  1228. if (!empty($location)) {
  1229. $profile->lat = $location->lat;
  1230. $profile->lon = $location->lon;
  1231. }
  1232. }
  1233. // @todo FIXME: tags/categories
  1234. // @todo tags from categories
  1235. if ($profile->id) {
  1236. //common_debug('Updating OStatus profile '._ve($profile->getID().' from remote info '._ve($object->id).': ' . _ve($object) . _ve($hints));
  1237. common_debug('Updating OStatus profile '._ve($profile->getID()).' from remote info '._ve($object->id).' gathered from hints: '._ve($hints));
  1238. $profile->update($orig);
  1239. }
  1240. }
  1241. protected static function updateGroup(User_group $group, ActivityObject $object, array $hints=array())
  1242. {
  1243. $orig = clone($group);
  1244. $group->nickname = self::getActivityObjectNickname($object, $hints);
  1245. $group->fullname = $object->title;
  1246. if (!empty($object->link)) {
  1247. $group->mainpage = $object->link;
  1248. } elseif (array_key_exists('profileurl', $hints)) {
  1249. $group->mainpage = $hints['profileurl'];
  1250. }
  1251. // @todo tags from categories
  1252. $group->description = self::getActivityObjectBio($object, $hints);
  1253. $group->location = self::getActivityObjectLocation($object, $hints);
  1254. $group->homepage = self::getActivityObjectHomepage($object, $hints);
  1255. if ($group->id) { // If no id, we haven't called insert() yet, so don't run update()
  1256. //common_debug('Updating OStatus group '._ve($group->getID().' from remote info '._ve($object->id).': ' . _ve($object) . _ve($hints));
  1257. common_debug('Updating OStatus group '._ve($group->getID()).' from remote info '._ve($object->id).' gathered from hints: '._ve($hints));
  1258. $group->update($orig);
  1259. }
  1260. }
  1261. protected static function updatePeopletag($tag, ActivityObject $object, array $hints=array())
  1262. {
  1263. $orig = clone($tag);
  1264. $tag->tag = $object->title;
  1265. if (!empty($object->link)) {
  1266. $tag->mainpage = $object->link;
  1267. } elseif (array_key_exists('profileurl', $hints)) {
  1268. $tag->mainpage = $hints['profileurl'];
  1269. }
  1270. $tag->description = $object->summary;
  1271. $tagger = self::ensureActivityObjectProfile($object->owner);
  1272. $tag->tagger = $tagger->profile_id;
  1273. if ($tag->id) {
  1274. //common_debug('Updating OStatus peopletag '._ve($tag->getID().' from remote info '._ve($object->id).': ' . _ve($object) . _ve($hints));
  1275. common_debug('Updating OStatus peopletag '._ve($tag->getID()).' from remote info '._ve($object->id).' gathered from hints: '._ve($hints));
  1276. $tag->update($orig);
  1277. }
  1278. }
  1279. protected static function getActivityObjectHomepage(ActivityObject $object, array $hints=array())
  1280. {
  1281. $homepage = null;
  1282. $poco = $object->poco;
  1283. if (!empty($poco)) {
  1284. $url = $poco->getPrimaryURL();
  1285. if ($url && $url->type == 'homepage') {
  1286. $homepage = $url->value;
  1287. }
  1288. }
  1289. // @todo Try for a another PoCo URL?
  1290. return $homepage;
  1291. }
  1292. protected static function getActivityObjectLocation(ActivityObject $object, array $hints=array())
  1293. {
  1294. $location = null;
  1295. if (!empty($object->poco) &&
  1296. isset($object->poco->address->formatted)) {
  1297. $location = $object->poco->address->formatted;
  1298. } elseif (array_key_exists('location', $hints)) {
  1299. $location = $hints['location'];
  1300. }
  1301. if (!empty($location)) {
  1302. if (mb_strlen($location) > 191) { // not 255 because utf8mb4 takes more space
  1303. $location = mb_substr($note, 0, 191 - 3) . ' … ';
  1304. }
  1305. }
  1306. // @todo Try to find location some othe way? Via goerss point?
  1307. return $location;
  1308. }
  1309. protected static function getActivityObjectBio(ActivityObject $object, array $hints=array())
  1310. {
  1311. $bio = null;
  1312. if (!empty($object->poco)) {
  1313. $note = $object->poco->note;
  1314. } elseif (array_key_exists('bio', $hints)) {
  1315. $note = $hints['bio'];
  1316. }
  1317. if (!empty($note)) {
  1318. if (Profile::bioTooLong($note)) {
  1319. // XXX: truncate ok?
  1320. $bio = mb_substr($note, 0, Profile::maxBio() - 3) . ' … ';
  1321. } else {
  1322. $bio = $note;
  1323. }
  1324. }
  1325. // @todo Try to get bio info some other way?
  1326. return $bio;
  1327. }
  1328. public static function getActivityObjectNickname(ActivityObject $object, array $hints=array())
  1329. {
  1330. if ($object->poco) {
  1331. if (!empty($object->poco->preferredUsername)) {
  1332. return common_nicknamize($object->poco->preferredUsername);
  1333. }
  1334. }
  1335. if (!empty($object->nickname)) {
  1336. return common_nicknamize($object->nickname);
  1337. }
  1338. if (array_key_exists('nickname', $hints)) {
  1339. return $hints['nickname'];
  1340. }
  1341. // Try the profile url (like foo.example.com or example.com/user/foo)
  1342. if (!empty($object->link)) {
  1343. $profileUrl = $object->link;
  1344. } elseif (!empty($hints['profileurl'])) {
  1345. $profileUrl = $hints['profileurl'];
  1346. }
  1347. if (!empty($profileUrl)) {
  1348. $nickname = self::nicknameFromURI($profileUrl);
  1349. }
  1350. // Try the URI (may be a tag:, http:, acct:, ...
  1351. if (empty($nickname)) {
  1352. $nickname = self::nicknameFromURI($object->id);
  1353. }
  1354. // Try a Webfinger if one was passed (way) down
  1355. if (empty($nickname)) {
  1356. if (array_key_exists('webfinger', $hints)) {
  1357. $nickname = self::nicknameFromURI($hints['webfinger']);
  1358. }
  1359. }
  1360. // Try the name
  1361. if (empty($nickname)) {
  1362. $nickname = common_nicknamize($object->title);
  1363. }
  1364. return $nickname;
  1365. }
  1366. protected static function nicknameFromURI($uri)
  1367. {
  1368. if (preg_match('/(\w+):/', $uri, $matches)) {
  1369. $protocol = $matches[1];
  1370. } else {
  1371. return null;
  1372. }
  1373. switch ($protocol) {
  1374. case 'acct':
  1375. case 'mailto':
  1376. if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
  1377. return common_canonical_nickname($matches[1]);
  1378. }
  1379. return null;
  1380. case 'http':
  1381. return common_url_to_nickname($uri);
  1382. break;
  1383. default:
  1384. return null;
  1385. }
  1386. }
  1387. /**
  1388. * Look up, and if necessary create, an Ostatus_profile for the remote
  1389. * entity with the given webfinger address.
  1390. * This should never return null -- you will either get an object or
  1391. * an exception will be thrown.
  1392. *
  1393. * @param string $addr webfinger address
  1394. * @return Ostatus_profile
  1395. * @throws Exception on error conditions
  1396. * @throws OStatusShadowException if this reference would obscure a local user/group
  1397. */
  1398. public static function ensureWebfinger($addr)
  1399. {
  1400. // Normalize $addr, i.e. add 'acct:' if missing
  1401. $addr = Discovery::normalize($addr);
  1402. // Try the cache
  1403. $uri = self::cacheGet(sprintf('ostatus_profile:webfinger:%s', $addr));
  1404. if ($uri !== false) {
  1405. if (is_null($uri)) {
  1406. // Negative cache entry
  1407. // TRANS: Exception.
  1408. throw new Exception(_m('Not a valid webfinger address (via cache).'));
  1409. }
  1410. $oprofile = Ostatus_profile::getKV('uri', $uri);
  1411. if ($oprofile instanceof Ostatus_profile) {
  1412. return $oprofile;
  1413. }
  1414. common_log(LOG_ERR, sprintf(__METHOD__ . ': Webfinger address cache inconsistent with database, did not find Ostatus_profile uri==%s', $uri));
  1415. self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), false);
  1416. }
  1417. // Try looking it up
  1418. $oprofile = Ostatus_profile::getKV('uri', $addr);
  1419. if ($oprofile instanceof Ostatus_profile) {
  1420. self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
  1421. return $oprofile;
  1422. }
  1423. // Now, try some discovery
  1424. $disco = new Discovery();
  1425. try {
  1426. $xrd = $disco->lookup($addr);
  1427. } catch (Exception $e) {
  1428. // Save negative cache entry so we don't waste time looking it up again.
  1429. // @todo FIXME: Distinguish temporary failures?
  1430. self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null);
  1431. // TRANS: Exception.
  1432. throw new Exception(_m('Not a valid webfinger address.'));
  1433. }
  1434. $hints = array_merge(
  1435. ['webfinger' => $addr],
  1436. DiscoveryHints::fromXRD($xrd)
  1437. );
  1438. // If there's an Hcard, let's grab its info
  1439. if (array_key_exists('hcard', $hints)) {
  1440. if (!array_key_exists('profileurl', $hints) ||
  1441. $hints['hcard'] != $hints['profileurl']) {
  1442. $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
  1443. $hints = array_merge($hcardHints, $hints);
  1444. }
  1445. }
  1446. // If we got a feed URL, try that
  1447. $feedUrl = null;
  1448. if (array_key_exists('feedurl', $hints)) {
  1449. $feedUrl = $hints['feedurl'];
  1450. try {
  1451. common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
  1452. $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
  1453. self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
  1454. return $oprofile;
  1455. } catch (Exception $e) {
  1456. common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
  1457. // keep looking
  1458. }
  1459. }
  1460. // If we got a profile page, try that!
  1461. $profileUrl = null;
  1462. if (array_key_exists('profileurl', $hints)) {
  1463. $profileUrl = $hints['profileurl'];
  1464. try {
  1465. common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
  1466. $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
  1467. self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
  1468. return $oprofile;
  1469. } catch (OStatusShadowException $e) {
  1470. // We've ended up with a remote reference to a local user or group.
  1471. // @todo FIXME: Ideally we should be able to say who it was so we can
  1472. // go back and refer to it the regular way
  1473. throw $e;
  1474. } catch (Exception $e) {
  1475. common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
  1476. // keep looking
  1477. //
  1478. // @todo FIXME: This means an error discovering from profile page
  1479. // may give us a corrupt entry using the webfinger URI, which
  1480. // will obscure the correct page-keyed profile later on.
  1481. }
  1482. }
  1483. // XXX: try hcard
  1484. // XXX: try FOAF
  1485. if (array_key_exists('salmon', $hints)) {
  1486. $salmonEndpoint = $hints['salmon'];
  1487. // An account URL, a salmon endpoint, and a dream? Not much to go
  1488. // on, but let's give it a try
  1489. $uri = 'acct:'.$addr;
  1490. $profile = new Profile();
  1491. $profile->nickname = self::nicknameFromUri($uri);
  1492. $profile->created = common_sql_now();
  1493. if (!is_null($profileUrl)) {
  1494. $profile->profileurl = $profileUrl;
  1495. }
  1496. $profile_id = $profile->insert();
  1497. if ($profile_id === false) {
  1498. common_log_db_error($profile, 'INSERT', __FILE__);
  1499. // TRANS: Exception. %s is a webfinger address.
  1500. throw new Exception(sprintf(_m('Could not save profile for "%s".'), $addr));
  1501. }
  1502. $oprofile = new Ostatus_profile();
  1503. $oprofile->uri = $uri;
  1504. $oprofile->salmonuri = $salmonEndpoint;
  1505. $oprofile->profile_id = $profile_id;
  1506. $oprofile->created = common_sql_now();
  1507. if (!is_null($feedUrl)) {
  1508. $oprofile->feeduri = $feedUrl;
  1509. }
  1510. $result = $oprofile->insert();
  1511. if ($result === false) {
  1512. $profile->delete();
  1513. common_log_db_error($oprofile, 'INSERT', __FILE__);
  1514. // TRANS: Exception. %s is a webfinger address.
  1515. throw new Exception(sprintf(_m('Could not save OStatus profile for "%s".'), $addr));
  1516. }
  1517. self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
  1518. return $oprofile;
  1519. }
  1520. // TRANS: Exception. %s is a webfinger address.
  1521. throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'), $addr));
  1522. }
  1523. /**
  1524. * Store the full-length scrubbed HTML of a remote notice to an attachment
  1525. * file on our server. We'll link to this at the end of the cropped version.
  1526. *
  1527. * @param string $title plaintext for HTML page's title
  1528. * @param string $rendered HTML fragment for HTML page's body
  1529. * @return File
  1530. */
  1531. public function saveHTMLFile($title, $rendered)
  1532. {
  1533. $final = sprintf(
  1534. <<<'END'
  1535. <!DOCTYPE html>
  1536. <html><head>
  1537. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  1538. <title>%s</title>
  1539. </head>
  1540. <body>%s</body></html>
  1541. END,
  1542. htmlspecialchars($title),
  1543. $rendered
  1544. );
  1545. $filename = File::filename(
  1546. $this->localProfile(),
  1547. 'ostatus', // ignored?
  1548. 'text/html'
  1549. );
  1550. $filepath = File::path($filename);
  1551. $fileurl = File::url($filename);
  1552. file_put_contents($filepath, $final);
  1553. $file = new File;
  1554. $file->filename = $filename;
  1555. $file->urlhash = File::hashurl($fileurl);
  1556. $file->url = $fileurl;
  1557. $file->size = filesize($filepath);
  1558. $file->date = time();
  1559. $file->mimetype = 'text/html';
  1560. $file_id = $file->insert();
  1561. if ($file_id === false) {
  1562. common_log_db_error($file, "INSERT", __FILE__);
  1563. // TRANS: Server exception.
  1564. throw new ServerException(_m('Could not store HTML content of long post as file.'));
  1565. }
  1566. return $file;
  1567. }
  1568. public static function ensureProfileURI($uri)
  1569. {
  1570. $oprofile = null;
  1571. // First, try to query it
  1572. $oprofile = Ostatus_profile::getKV('uri', $uri);
  1573. if ($oprofile instanceof Ostatus_profile) {
  1574. return $oprofile;
  1575. }
  1576. // If unfound, do discovery stuff
  1577. if (preg_match("/^(\w+)\:(.*)/", $uri, $match)) {
  1578. $protocol = $match[1];
  1579. switch ($protocol) {
  1580. case 'http':
  1581. case 'https':
  1582. $oprofile = self::ensureProfileURL($uri);
  1583. break;
  1584. case 'acct':
  1585. case 'mailto':
  1586. $rest = $match[2];
  1587. $oprofile = self::ensureWebfinger($rest);
  1588. break;
  1589. default:
  1590. // TRANS: Server exception.
  1591. // TRANS: %1$s is a protocol, %2$s is a URI.
  1592. throw new ServerException(sprintf(
  1593. _m('Unrecognized URI protocol for profile: %1$s (%2$s).'),
  1594. $protocol,
  1595. $uri
  1596. ));
  1597. }
  1598. } else {
  1599. // TRANS: Server exception. %s is a URI.
  1600. throw new ServerException(sprintf(_m('No URI protocol for profile: %s.'), $uri));
  1601. }
  1602. return $oprofile;
  1603. }
  1604. public function checkAuthorship(Activity $activity)
  1605. {
  1606. if ($this->isGroup() || $this->isPeopletag()) {
  1607. // A group or propletag feed will contain posts from multiple authors.
  1608. $oprofile = self::ensureActorProfile($activity);
  1609. if ($oprofile->isGroup() || $oprofile->isPeopletag()) {
  1610. // Groups can't post notices in StatusNet.
  1611. common_log(
  1612. LOG_WARNING,
  1613. 'OStatus: skipping post with group listed as author: '
  1614. . "{$oprofile->getUri()} in feed from {$this->getUri()}"
  1615. );
  1616. throw new ServerException('Activity author is a non-actor');
  1617. }
  1618. } else {
  1619. $actor = $activity->actor;
  1620. if (empty($actor)) {
  1621. // OK here! assume the default
  1622. } elseif ($actor->id == $this->getUri()
  1623. || $actor->link == $this->getUri()) {
  1624. $this->updateFromActivityObject($actor);
  1625. } elseif ($actor->id) {
  1626. // We have an ActivityStreams actor with an explicit ID that doesn't match the feed owner.
  1627. // This isn't what we expect from mainline OStatus person feeds!
  1628. // Group feeds go down another path, with different validation...
  1629. // Most likely this is a plain ol' blog feed of some kind which
  1630. // doesn't match our expectations. We'll take the entry, but ignore
  1631. // the <author> info.
  1632. common_log(LOG_WARNING, "Got an actor '{$actor->title}' ({$actor->id}) on single-user feed for " . $this->getUri());
  1633. } else {
  1634. // Plain <author> without ActivityStreams actor info.
  1635. // We'll just ignore this info for now and save the update under the feed's identity.
  1636. }
  1637. $oprofile = $this;
  1638. }
  1639. return $oprofile->localProfile();
  1640. }
  1641. public function updateUriKeys($profile_uri, array $hints=array())
  1642. {
  1643. $orig = clone($this);
  1644. common_debug('URIFIX These identities both say they are each other: '._ve($orig->uri).' and '._ve($profile_uri));
  1645. $this->uri = $profile_uri;
  1646. if (array_key_exists('feedurl', $hints) && common_valid_http_url($hints['feedurl'])) {
  1647. try {
  1648. $feedsub = $this->getFeedSub();
  1649. common_debug('URIFIX Changing FeedSub id==['._ve($feedsub->id).'] feeduri '._ve($feedsub->uri).' to '._ve($hints['feedurl']));
  1650. $feedorig = clone($feedsub);
  1651. $feedsub->uri = $hints['feedurl'];
  1652. $feedsub->updateWithKeys($feedorig);
  1653. } catch (EmptyPkeyValueException $e) {
  1654. common_debug('URIFIX Old Ostatus_profile did not have feedurl set, ensuring new feedurl: '._ve($hints['feedurl']));
  1655. FeedSub::ensureFeed($hints['feedurl']);
  1656. } catch (NoResultException $e) {
  1657. common_debug('URIFIX Missing FeedSub entry for the Ostatus_profile, ensuring new feedurl: '._ve($hints['feedurl']));
  1658. FeedSub::ensureFeed($hints['feedurl']);
  1659. }
  1660. $this->feeduri = $hints['feedurl'];
  1661. } elseif (array_key_exists('feedurl')) {
  1662. common_log(LOG_WARN, 'The feedurl hint we got was not a valid HTTP URL: '._ve($hints['feedurl']));
  1663. }
  1664. if (array_key_exists('salmon', $hints)) {
  1665. common_debug('URIFIX Changing Ostatus_profile salmonuri from "'.$this->salmonuri.'" to "'.$hints['salmon'].'"');
  1666. $this->salmonuri = $hints['salmon'];
  1667. }
  1668. common_debug('URIFIX Updating Ostatus_profile URI for '.$orig->uri.' to '.$this->uri);
  1669. $this->updateWithKeys($orig); // Will use the PID column(s) in the 'UPDATE ... WHERE [unique selector]'
  1670. common_debug('URIFIX Subscribing/renewing feedsub for Ostatus_profile '.$this->uri);
  1671. $this->subscribe();
  1672. }
  1673. }