Ostatus_profile.php 80 KB

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