3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2009-2010, StatusNet, Inc.
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.
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.
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/>.
21 * @package OStatusPlugin
22 * @maintainer Brion Vibber <brion@status.net>
25 class Ostatus_profile extends Memcached_DataObject
27 public $__table = 'ostatus_profile';
36 public $avatar; // remote URL of the last avatar we saved
41 public /*static*/ function staticGet($k, $v=null)
43 return parent::staticGet(__CLASS__, $k, $v);
47 * return table definition for DB_DataObject
49 * DB_DataObject needs to know something about the table to manipulate
50 * instances. This method provides all the DB_DataObject needs to know.
52 * @return array array of column definitions
57 return array('uri' => DB_DATAOBJECT_STR + DB_DATAOBJECT_NOTNULL,
58 'profile_id' => DB_DATAOBJECT_INT,
59 'group_id' => DB_DATAOBJECT_INT,
60 'feeduri' => DB_DATAOBJECT_STR,
61 'salmonuri' => DB_DATAOBJECT_STR,
62 'avatar' => DB_DATAOBJECT_STR,
63 'created' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME + DB_DATAOBJECT_NOTNULL,
64 'modified' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME + DB_DATAOBJECT_NOTNULL);
67 static function schemaDef()
69 return array(new ColumnDef('uri', 'varchar',
71 new ColumnDef('profile_id', 'integer',
73 new ColumnDef('group_id', 'integer',
75 new ColumnDef('feeduri', 'varchar',
77 new ColumnDef('salmonuri', 'text',
79 new ColumnDef('avatar', 'text',
81 new ColumnDef('created', 'datetime',
83 new ColumnDef('modified', 'datetime',
88 * return key definitions for DB_DataObject
90 * DB_DataObject needs to know about keys that the table has; this function
93 * @return array key definitions
98 return array_keys($this->keyTypes());
102 * return key definitions for Memcached_DataObject
104 * Our caching system uses the same key definitions, but uses a different
105 * method to get them.
107 * @return array key definitions
112 return array('uri' => 'K', 'profile_id' => 'U', 'group_id' => 'U', 'feeduri' => 'U');
115 function sequenceKey()
117 return array(false, false, false);
121 * Fetch the StatusNet-side profile for this feed
124 public function localProfile()
126 if ($this->profile_id) {
127 return Profile::staticGet('id', $this->profile_id);
133 * Fetch the StatusNet-side profile for this feed
136 public function localGroup()
138 if ($this->group_id) {
139 return User_group::staticGet('id', $this->group_id);
145 * Returns an ActivityObject describing this remote user or group profile.
146 * Can then be used to generate Atom chunks.
148 * @return ActivityObject
150 function asActivityObject()
152 if ($this->isGroup()) {
153 return ActivityObject::fromGroup($this->localGroup());
155 return ActivityObject::fromProfile($this->localProfile());
160 * Returns an XML string fragment with profile information as an
161 * Activity Streams noun object with the given element type.
163 * Assumes that 'activity' namespace has been previously defined.
165 * @fixme replace with wrappers on asActivityObject when it's got everything.
167 * @param string $element one of 'actor', 'subject', 'object', 'target'
170 function asActivityNoun($element)
172 if ($this->isGroup()) {
173 $noun = ActivityObject::fromGroup($this->localGroup());
174 return $noun->asString('activity:' . $element);
176 $noun = ActivityObject::fromProfile($this->localProfile());
177 return $noun->asString('activity:' . $element);
182 * @return boolean true if this is a remote group
186 if ($this->profile_id && !$this->group_id) {
188 } else if ($this->group_id && !$this->profile_id) {
190 } else if ($this->group_id && $this->profile_id) {
191 throw new ServerException("Invalid ostatus_profile state: both group and profile IDs set for $this->uri");
193 throw new ServerException("Invalid ostatus_profile state: both group and profile IDs empty for $this->uri");
198 * Send a subscription request to the hub for this feed.
199 * The hub will later send us a confirmation POST to /main/push/callback.
201 * @return bool true on success, false on failure
202 * @throws ServerException if feed state is not valid
204 public function subscribe()
206 $feedsub = FeedSub::ensureFeed($this->feeduri);
207 if ($feedsub->sub_state == 'active') {
208 // Active subscription, we don't need to do anything.
211 // Inactive or we got left in an inconsistent state.
212 // Run a subscription request to make sure we're current!
213 return $feedsub->subscribe();
218 * Send a PuSH unsubscription request to the hub for this feed.
219 * The hub will later send us a confirmation POST to /main/push/callback.
221 * @return bool true on success, false on failure
222 * @throws ServerException if feed state is not valid
224 public function unsubscribe() {
225 $feedsub = FeedSub::staticGet('uri', $this->feeduri);
226 if (!$feedsub || $feedsub->sub_state == '' || $feedsub->sub_state == 'inactive') {
227 // No active PuSH subscription, we can just leave it be.
230 // PuSH subscription is either active or in an indeterminate state.
231 // Send an unsubscribe.
232 return $feedsub->unsubscribe();
237 * Check if this remote profile has any active local subscriptions, and
238 * if not drop the PuSH subscription feed.
242 public function garbageCollect()
244 if ($this->isGroup()) {
245 $members = $this->localGroup()->getMembers(0, 1);
246 $count = $members->N;
248 $count = $this->localProfile()->subscriberCount();
251 common_log(LOG_INFO, "Unsubscribing from now-unused remote feed $this->feeduri");
252 $this->unsubscribe();
260 * Send an Activity Streams notification to the remote Salmon endpoint,
263 * @param Profile $actor Actor who did the activity
264 * @param string $verb Activity::SUBSCRIBE or Activity::JOIN
265 * @param Object $object object of the action; must define asActivityNoun($tag)
267 public function notify($actor, $verb, $object=null)
269 if (!($actor instanceof Profile)) {
270 $type = gettype($actor);
271 if ($type == 'object') {
272 $type = get_class($actor);
274 throw new ServerException("Invalid actor passed to " . __METHOD__ . ": " . $type);
276 if ($object == null) {
279 if ($this->salmonuri) {
282 $id = TagURI::mint('%s:%s:%s',
285 common_date_iso8601(time()));
287 // @fixme consolidate all these NS settings somewhere
288 $attributes = array('xmlns' => Activity::ATOM,
289 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
290 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
291 'xmlns:georss' => 'http://www.georss.org/georss',
292 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
293 'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
294 'xmlns:media' => 'http://purl.org/syndication/atommedia');
296 $entry = new XMLStringer();
297 $entry->elementStart('entry', $attributes);
298 $entry->element('id', null, $id);
299 $entry->element('title', null, $text);
300 $entry->element('summary', null, $text);
301 $entry->element('published', null, common_date_w3dtf(common_sql_now()));
303 $entry->element('activity:verb', null, $verb);
304 $entry->raw($actor->asAtomAuthor());
305 $entry->raw($actor->asActivityActor());
306 $entry->raw($object->asActivityNoun('object'));
307 $entry->elementEnd('entry');
309 $xml = $entry->getString();
310 common_log(LOG_INFO, "Posting to Salmon endpoint $this->salmonuri: $xml");
312 $salmon = new Salmon(); // ?
313 return $salmon->post($this->salmonuri, $xml, $actor);
319 * Send a Salmon notification ping immediately, and confirm that we got
320 * an acceptable response from the remote site.
322 * @param mixed $entry XML string, Notice, or Activity
323 * @return boolean success
325 public function notifyActivity($entry, $actor)
327 if ($this->salmonuri) {
328 $salmon = new Salmon();
329 return $salmon->post($this->salmonuri, $this->notifyPrepXml($entry), $actor);
336 * Queue a Salmon notification for later. If queues are disabled we'll
337 * send immediately but won't get the return value.
339 * @param mixed $entry XML string, Notice, or Activity
340 * @return boolean success
342 public function notifyDeferred($entry, $actor)
344 if ($this->salmonuri) {
345 $data = array('salmonuri' => $this->salmonuri,
346 'entry' => $this->notifyPrepXml($entry),
347 'actor' => $actor->id);
349 $qm = QueueManager::get();
350 return $qm->enqueue($data, 'salmon');
356 protected function notifyPrepXml($entry)
358 $preamble = '<?xml version="1.0" encoding="UTF-8" ?' . '>';
359 if (is_string($entry)) {
361 } else if ($entry instanceof Activity) {
362 return $preamble . $entry->asString(true);
363 } else if ($entry instanceof Notice) {
364 return $preamble . $entry->asAtomEntry(true, true);
366 throw new ServerException("Invalid type passed to Ostatus_profile::notify; must be XML string or Activity entry");
370 function getBestName()
372 if ($this->isGroup()) {
373 return $this->localGroup()->getBestName();
375 return $this->localProfile()->getBestName();
380 * Read and post notices for updates from the feed.
381 * Currently assumes that all items in the feed are new,
382 * coming from a PuSH hub.
384 * @param DOMDocument $doc
385 * @param string $source identifier ("push")
387 public function processFeed(DOMDocument $doc, $source)
389 $feed = $doc->documentElement;
391 if ($feed->localName != 'feed' || $feed->namespaceURI != Activity::ATOM) {
392 common_log(LOG_ERR, __METHOD__ . ": not an Atom feed, ignoring");
396 $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
397 if ($entries->length == 0) {
398 common_log(LOG_ERR, __METHOD__ . ": no entries in feed update, ignoring");
402 for ($i = 0; $i < $entries->length; $i++) {
403 $entry = $entries->item($i);
404 $this->processEntry($entry, $feed, $source);
409 * Process a posted entry from this feed source.
411 * @param DOMElement $entry
412 * @param DOMElement $feed for context
413 * @param string $source identifier ("push" or "salmon")
415 public function processEntry($entry, $feed, $source)
417 $activity = new Activity($entry, $feed);
419 if ($activity->verb == ActivityVerb::POST) {
420 $this->processPost($activity, $source);
422 common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
427 * Process an incoming post activity from this remote feed.
428 * @param Activity $activity
429 * @param string $method 'push' or 'salmon'
430 * @return mixed saved Notice or false
431 * @fixme break up this function, it's getting nasty long
433 public function processPost($activity, $method)
435 if ($this->isGroup()) {
436 // A group feed will contain posts from multiple authors.
437 // @fixme validate these profiles in some way!
438 $oprofile = self::ensureActorProfile($activity);
439 if ($oprofile->isGroup()) {
440 // Groups can't post notices in StatusNet.
441 common_log(LOG_WARNING, "OStatus: skipping post with group listed as author: $oprofile->uri in feed from $this->uri");
445 // Individual user feeds may contain only posts from themselves.
446 // Authorship is validated against the profile URI on upper layers,
447 // through PuSH setup or Salmon signature checks.
448 $actorUri = self::getActorProfileURI($activity);
449 if ($actorUri == $this->uri) {
450 // Check if profile info has changed and update it
451 $this->updateFromActivityObject($activity->actor);
453 common_log(LOG_WARNING, "OStatus: skipping post with bad author: got $actorUri expected $this->uri");
459 // The id URI will be used as a unique identifier for for the notice,
460 // protecting against duplicate saves. It isn't required to be a URL;
461 // tag: URIs for instance are found in Google Buzz feeds.
462 $sourceUri = $activity->object->id;
463 $dupe = Notice::staticGet('uri', $sourceUri);
465 common_log(LOG_INFO, "OStatus: ignoring duplicate post: $sourceUri");
469 // We'll also want to save a web link to the original notice, if provided.
471 if ($activity->object->link) {
472 $sourceUrl = $activity->object->link;
473 } else if ($activity->link) {
474 $sourceUrl = $activity->link;
475 } else if (preg_match('!^https?://!', $activity->object->id)) {
476 $sourceUrl = $activity->object->id;
479 // Get (safe!) HTML and text versions of the content
480 $rendered = $this->purify($activity->object->content);
481 $content = html_entity_decode(strip_tags($rendered));
483 $shortened = common_shorten_links($content);
485 // If it's too long, try using the summary, and make the
486 // HTML an attachment.
490 if (Notice::contentTooLong($shortened)) {
491 $attachment = $this->saveHTMLFile($activity->object->title, $rendered);
492 $summary = $activity->object->summary;
493 if (empty($summary)) {
496 $shortSummary = common_shorten_links($summary);
497 if (Notice::contentTooLong($shortSummary)) {
498 $url = common_shorten_url($sourceUrl);
499 $shortSummary = substr($shortSummary,
501 Notice::maxContent() - (mb_strlen($url) + 2));
502 $content = $shortSummary . ' ' . $url;
504 // We mark up the attachment link specially for the HTML output
505 // so we can fold-out the full version inline.
506 $attachUrl = common_local_url('attachment',
507 array('attachment' => $attachment->id));
508 $rendered = common_render_text($shortSummary) .
509 '<a href="' . htmlspecialchars($attachUrl) .'"'.
510 ' class="attachment more"' .
511 ' title="'. htmlspecialchars(_m('Show more')) . '">' .
517 $options = array('is_local' => Notice::REMOTE_OMB,
520 'rendered' => $rendered,
521 'replies' => array(),
526 // Check for optional attributes...
528 if (!empty($activity->time)) {
529 $options['created'] = common_sql_date($activity->time);
532 if ($activity->context) {
533 // Any individual or group attn: targets?
534 $replies = $activity->context->attention;
535 $options['groups'] = $this->filterReplies($oprofile, $replies);
536 $options['replies'] = $replies;
538 // Maintain direct reply associations
539 // @fixme what about conversation ID?
540 if (!empty($activity->context->replyToID)) {
541 $orig = Notice::staticGet('uri',
542 $activity->context->replyToID);
544 $options['reply_to'] = $orig->id;
548 $location = $activity->context->location;
550 $options['lat'] = $location->lat;
551 $options['lon'] = $location->lon;
552 if ($location->location_id) {
553 $options['location_ns'] = $location->location_ns;
554 $options['location_id'] = $location->location_id;
559 // Atom categories <-> hashtags
560 foreach ($activity->categories as $cat) {
562 $term = common_canonical_tag($cat->term);
564 $options['tags'][] = $term;
569 // Atom enclosures -> attachment URLs
570 foreach ($activity->enclosures as $href) {
571 // @fixme save these locally or....?
572 $options['urls'][] = $href;
576 $saved = Notice::saveNew($oprofile->profile_id,
581 Ostatus_source::saveNew($saved, $this, $method);
582 if (!empty($attachment)) {
583 File_to_post::processNew($attachment->id, $saved->id);
586 } catch (Exception $e) {
587 common_log(LOG_ERR, "OStatus save of remote message $sourceUri failed: " . $e->getMessage());
590 common_log(LOG_INFO, "OStatus saved remote message $sourceUri as notice id $saved->id");
597 protected function purify($html)
599 require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';
600 $config = array('safe' => 1,
601 'deny_attribute' => 'id,style,on*');
602 return htmLawed($html, $config);
606 * Filters a list of recipient ID URIs to just those for local delivery.
607 * @param Ostatus_profile local profile of sender
608 * @param array in/out &$attention_uris set of URIs, will be pruned on output
609 * @return array of group IDs
611 protected function filterReplies($sender, &$attention_uris)
613 common_log(LOG_DEBUG, "Original reply recipients: " . implode(', ', $attention_uris));
616 foreach ($attention_uris as $recipient) {
617 // Is the recipient a local user?
618 $user = User::staticGet('uri', $recipient);
620 // @fixme sender verification, spam etc?
621 $replies[] = $recipient;
625 // Is the recipient a remote group?
626 $oprofile = Ostatus_profile::staticGet('uri', $recipient);
628 if ($oprofile->isGroup()) {
629 // Deliver to local members of this remote group.
630 // @fixme sender verification?
631 $groups[] = $oprofile->group_id;
633 common_log(LOG_DEBUG, "Skipping reply to remote profile $recipient");
638 // Is the recipient a local group?
639 // @fixme uri on user_group isn't reliable yet
640 // $group = User_group::staticGet('uri', $recipient);
641 $id = OStatusPlugin::localGroupFromUrl($recipient);
643 $group = User_group::staticGet('id', $id);
645 // Deliver to all members of this local group if allowed.
646 $profile = $sender->localProfile();
647 if ($profile->isMember($group)) {
648 $groups[] = $group->id;
650 common_log(LOG_DEBUG, "Skipping reply to local group $group->nickname as sender $profile->id is not a member");
654 common_log(LOG_DEBUG, "Skipping reply to bogus group $recipient");
658 common_log(LOG_DEBUG, "Skipping reply to unrecognized profile $recipient");
661 $attention_uris = $replies;
662 common_log(LOG_DEBUG, "Local reply recipients: " . implode(', ', $replies));
663 common_log(LOG_DEBUG, "Local group recipients: " . implode(', ', $groups));
668 * @param string $profile_url
669 * @return Ostatus_profile
670 * @throws FeedSubException
673 public static function ensureProfileURL($profile_url, $hints=array())
675 $oprofile = self::getFromProfileURL($profile_url);
677 if (!empty($oprofile)) {
681 $hints['profileurl'] = $profile_url;
686 $client = new HTTPClient();
687 $client->setHeader('Accept', 'text/html,application/xhtml+xml');
688 $response = $client->get($profile_url);
690 if (!$response->isOk()) {
694 // Check if we have a non-canonical URL
696 $finalUrl = $response->getUrl();
698 if ($finalUrl != $profile_url) {
700 $hints['profileurl'] = $finalUrl;
702 $oprofile = self::getFromProfileURL($finalUrl);
704 if (!empty($oprofile)) {
709 // Try to get some hCard data
711 $body = $response->getBody();
713 $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl);
715 if (!empty($hcardHints)) {
716 $hints = array_merge($hints, $hcardHints);
719 // Check if they've got an LRDD header
721 $lrdd = LinkHeader::getLink($response, 'lrdd', 'application/xrd+xml');
725 $xrd = Discovery::fetchXrd($lrdd);
726 $xrdHints = DiscoveryHints::fromXRD($xrd);
728 $hints = array_merge($hints, $xrdHints);
731 // If discovery found a feedurl (probably from LRDD), use it.
733 if (array_key_exists('feedurl', $hints)) {
734 return self::ensureFeedURL($hints['feedurl'], $hints);
737 // Get the feed URL from HTML
739 $discover = new FeedDiscovery();
741 $feedurl = $discover->discoverFromHTML($finalUrl, $body);
743 if (!empty($feedurl)) {
744 $hints['feedurl'] = $feedurl;
746 return self::ensureFeedURL($feedurl, $hints);
750 static function getFromProfileURL($profile_url)
752 $profile = Profile::staticGet('profileurl', $profile_url);
754 if (empty($profile)) {
758 // Is it a known Ostatus profile?
760 $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
762 if (!empty($oprofile)) {
766 // Is it a local user?
768 $user = User::staticGet('id', $profile->id);
771 throw new Exception("'$profile_url' is the profile for local user '{$user->nickname}'.");
774 // Continue discovery; it's a remote profile
775 // for OMB or some other protocol, may also
781 public static function ensureFeedURL($feed_url, $hints=array())
783 $discover = new FeedDiscovery();
785 $feeduri = $discover->discoverFromFeedURL($feed_url);
786 $hints['feedurl'] = $feeduri;
788 $huburi = $discover->getAtomLink('hub');
789 $hints['hub'] = $huburi;
790 $salmonuri = $discover->getAtomLink(Salmon::NS_REPLIES);
791 $hints['salmon'] = $salmonuri;
794 // We can only deal with folks with a PuSH hub
795 throw new FeedSubNoHubException();
798 // Try to get a profile from the feed activity:subject
800 $feedEl = $discover->feed->documentElement;
802 $subject = ActivityUtils::child($feedEl, Activity::SUBJECT, Activity::SPEC);
804 if (!empty($subject)) {
805 $subjObject = new ActivityObject($subject);
806 return self::ensureActivityObjectProfile($subjObject, $hints);
809 // Otherwise, try the feed author
811 $author = ActivityUtils::child($feedEl, Activity::AUTHOR, Activity::ATOM);
813 if (!empty($author)) {
814 $authorObject = new ActivityObject($author);
815 return self::ensureActivityObjectProfile($authorObject, $hints);
818 // Sheesh. Not a very nice feed! Let's try fingerpoken in the
821 $entries = $discover->feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
823 if (!empty($entries) && $entries->length > 0) {
825 $entry = $entries->item(0);
827 $actor = ActivityUtils::child($entry, Activity::ACTOR, Activity::SPEC);
829 if (!empty($actor)) {
830 $actorObject = new ActivityObject($actor);
831 return self::ensureActivityObjectProfile($actorObject, $hints);
835 $author = ActivityUtils::child($entry, Activity::AUTHOR, Activity::ATOM);
837 if (!empty($author)) {
838 $authorObject = new ActivityObject($author);
839 return self::ensureActivityObjectProfile($authorObject, $hints);
843 // XXX: make some educated guesses here
845 throw new FeedSubException("Can't find enough profile information to make a feed.");
849 * Download and update given avatar image
852 * @throws Exception in various failure cases
854 protected function updateAvatar($url)
856 if ($url == $this->avatar) {
857 // We've already got this one.
860 if (!common_valid_http_url($url)) {
861 throw new ServerException(_m("Invalid avatar URL %s"), $url);
864 if ($this->isGroup()) {
865 $self = $this->localGroup();
867 $self = $this->localProfile();
870 throw new ServerException(sprintf(
871 _m("Tried to update avatar for unsaved remote profile %s"),
875 // @fixme this should be better encapsulated
876 // ripped from oauthstore.php (for old OMB client)
877 $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
878 if (!copy($url, $temp_filename)) {
879 throw new ServerException(sprintf(_m("Unable to fetch avatar from %s"), $url));
882 if ($this->isGroup()) {
883 $id = $this->group_id;
885 $id = $this->profile_id;
887 // @fixme should we be using different ids?
888 $imagefile = new ImageFile($id, $temp_filename);
889 $filename = Avatar::filename($id,
890 image_type_to_extension($imagefile->type),
893 rename($temp_filename, Avatar::path($filename));
894 $self->setOriginal($filename);
896 $orig = clone($this);
897 $this->avatar = $url;
898 $this->update($orig);
902 * Pull avatar URL from ActivityObject or profile hints
904 * @param ActivityObject $object
905 * @param array $hints
906 * @return mixed URL string or false
909 protected static function getActivityObjectAvatar($object, $hints=array())
911 if ($object->avatarLinks) {
913 // Take the exact-size avatar, or the largest avatar, or the first avatar if all sizeless
914 foreach ($object->avatarLinks as $avatar) {
915 if ($avatar->width == AVATAR_PROFILE_SIZE && $avatar->height = AVATAR_PROFILE_SIZE) {
920 if (!$best || $avatar->width > $best->width) {
925 } else if (array_key_exists('avatar', $hints)) {
926 return $hints['avatar'];
932 * Get an appropriate avatar image source URL, if available.
934 * @param ActivityObject $actor
935 * @param DOMElement $feed
939 protected static function getAvatar($actor, $feed)
943 if ($actor->avatar) {
944 $url = trim($actor->avatar);
947 // Check <atom:logo> and <atom:icon> on the feed
948 $els = $feed->childNodes();
949 if ($els && $els->length) {
950 for ($i = 0; $i < $els->length; $i++) {
951 $el = $els->item($i);
952 if ($el->namespaceURI == Activity::ATOM) {
953 if (empty($url) && $el->localName == 'logo') {
954 $url = trim($el->textContent);
957 if (empty($icon) && $el->localName == 'icon') {
959 $icon = trim($el->textContent);
964 if ($icon && !$url) {
969 $opts = array('allowed_schemes' => array('http', 'https'));
970 if (Validate::uri($url, $opts)) {
974 return common_path('plugins/OStatus/images/96px-Feed-icon.svg.png');
978 * Fetch, or build if necessary, an Ostatus_profile for the actor
979 * in a given Activity Streams activity.
981 * @param Activity $activity
982 * @param string $feeduri if we already know the canonical feed URI!
983 * @param string $salmonuri if we already know the salmon return channel URI
984 * @return Ostatus_profile
987 public static function ensureActorProfile($activity, $hints=array())
989 return self::ensureActivityObjectProfile($activity->actor, $hints);
992 public static function ensureActivityObjectProfile($object, $hints=array())
994 $profile = self::getActivityObjectProfile($object);
996 $profile->updateFromActivityObject($object, $hints);
998 $profile = self::createActivityObjectProfile($object, $hints);
1004 * @param Activity $activity
1005 * @return mixed matching Ostatus_profile or false if none known
1007 public static function getActorProfile($activity)
1009 return self::getActivityObjectProfile($activity->actor);
1012 protected static function getActivityObjectProfile($object)
1014 $uri = self::getActivityObjectProfileURI($object);
1015 return Ostatus_profile::staticGet('uri', $uri);
1018 protected static function getActorProfileURI($activity)
1020 return self::getActivityObjectProfileURI($activity->actor);
1024 * @param Activity $activity
1026 * @throws ServerException
1028 protected static function getActivityObjectProfileURI($object)
1030 $opts = array('allowed_schemes' => array('http', 'https'));
1031 if ($object->id && Validate::uri($object->id, $opts)) {
1034 if ($object->link && Validate::uri($object->link, $opts)) {
1035 return $object->link;
1037 throw new ServerException("No author ID URI found");
1041 * @fixme validate stuff somewhere
1045 * Create local ostatus_profile and profile/user_group entries for
1046 * the provided remote user or group.
1048 * @param ActivityObject $object
1049 * @param array $hints
1051 * @return Ostatus_profile
1053 protected static function createActivityObjectProfile($object, $hints=array())
1055 $homeuri = $object->id;
1059 common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
1060 throw new Exception("No profile URI");
1063 if (OStatusPlugin::localProfileFromUrl($homeuri)) {
1064 throw new Exception("Local user can't be referenced as remote.");
1067 if (OStatusPlugin::localGroupFromUrl($homeuri)) {
1068 throw new Exception("Local group can't be referenced as remote.");
1071 if (array_key_exists('feedurl', $hints)) {
1072 $feeduri = $hints['feedurl'];
1074 $discover = new FeedDiscovery();
1075 $feeduri = $discover->discoverFromURL($homeuri);
1078 if (array_key_exists('salmon', $hints)) {
1079 $salmonuri = $hints['salmon'];
1082 $discover = new FeedDiscovery();
1083 $discover->discoverFromFeedURL($hints['feedurl']);
1085 $salmonuri = $discover->getAtomLink(Salmon::NS_REPLIES);
1088 if (array_key_exists('hub', $hints)) {
1089 $huburi = $hints['hub'];
1092 $discover = new FeedDiscovery();
1093 $discover->discoverFromFeedURL($hints['feedurl']);
1095 $huburi = $discover->getAtomLink('hub');
1099 // We can only deal with folks with a PuSH hub
1100 throw new FeedSubNoHubException();
1103 $oprofile = new Ostatus_profile();
1105 $oprofile->uri = $homeuri;
1106 $oprofile->feeduri = $feeduri;
1107 $oprofile->salmonuri = $salmonuri;
1109 $oprofile->created = common_sql_now();
1110 $oprofile->modified = common_sql_now();
1112 if ($object->type == ActivityObject::PERSON) {
1113 $profile = new Profile();
1114 $profile->created = common_sql_now();
1115 self::updateProfile($profile, $object, $hints);
1117 $oprofile->profile_id = $profile->insert();
1118 if (!$oprofile->profile_id) {
1119 throw new ServerException("Can't save local profile");
1122 $group = new User_group();
1123 $group->uri = $homeuri;
1124 $group->created = common_sql_now();
1125 self::updateGroup($group, $object, $hints);
1127 $oprofile->group_id = $group->insert();
1128 if (!$oprofile->group_id) {
1129 throw new ServerException("Can't save local profile");
1133 $ok = $oprofile->insert();
1136 $avatar = self::getActivityObjectAvatar($object, $hints);
1138 $oprofile->updateAvatar($avatar);
1142 throw new ServerException("Can't save OStatus profile");
1147 * Save any updated profile information to our local copy.
1148 * @param ActivityObject $object
1149 * @param array $hints
1151 public function updateFromActivityObject($object, $hints=array())
1153 if ($this->isGroup()) {
1154 $group = $this->localGroup();
1155 self::updateGroup($group, $object, $hints);
1157 $profile = $this->localProfile();
1158 self::updateProfile($profile, $object, $hints);
1160 $avatar = self::getActivityObjectAvatar($object, $hints);
1162 $this->updateAvatar($avatar);
1166 protected static function updateProfile($profile, $object, $hints=array())
1168 $orig = clone($profile);
1170 $profile->nickname = self::getActivityObjectNickname($object, $hints);
1172 if (!empty($object->title)) {
1173 $profile->fullname = $object->title;
1174 } else if (array_key_exists('fullname', $hints)) {
1175 $profile->fullname = $hints['fullname'];
1178 if (!empty($object->link)) {
1179 $profile->profileurl = $object->link;
1180 } else if (array_key_exists('profileurl', $hints)) {
1181 $profile->profileurl = $hints['profileurl'];
1182 } else if (Validate::uri($object->id, array('allowed_schemes' => array('http', 'https')))) {
1183 $profile->profileurl = $object->id;
1186 $profile->bio = self::getActivityObjectBio($object, $hints);
1187 $profile->location = self::getActivityObjectLocation($object, $hints);
1188 $profile->homepage = self::getActivityObjectHomepage($object, $hints);
1190 if (!empty($object->geopoint)) {
1191 $location = ActivityContext::locationFromPoint($object->geopoint);
1192 if (!empty($location)) {
1193 $profile->lat = $location->lat;
1194 $profile->lon = $location->lon;
1198 // @fixme tags/categories
1199 // @todo tags from categories
1202 common_log(LOG_DEBUG, "Updating OStatus profile $profile->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1203 $profile->update($orig);
1207 protected static function updateGroup($group, $object, $hints=array())
1209 $orig = clone($group);
1211 $group->nickname = self::getActivityObjectNickname($object, $hints);
1212 $group->fullname = $object->title;
1214 if (!empty($object->link)) {
1215 $group->mainpage = $object->link;
1216 } else if (array_key_exists('profileurl', $hints)) {
1217 $group->mainpage = $hints['profileurl'];
1220 // @todo tags from categories
1221 $group->description = self::getActivityObjectBio($object, $hints);
1222 $group->location = self::getActivityObjectLocation($object, $hints);
1223 $group->homepage = self::getActivityObjectHomepage($object, $hints);
1226 common_log(LOG_DEBUG, "Updating OStatus group $group->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1227 $group->update($orig);
1231 protected static function getActivityObjectHomepage($object, $hints=array())
1234 $poco = $object->poco;
1236 if (!empty($poco)) {
1237 $url = $poco->getPrimaryURL();
1238 if ($url && $url->type == 'homepage') {
1239 $homepage = $url->value;
1243 // @todo Try for a another PoCo URL?
1248 protected static function getActivityObjectLocation($object, $hints=array())
1252 if (!empty($object->poco) &&
1253 isset($object->poco->address->formatted)) {
1254 $location = $object->poco->address->formatted;
1255 } else if (array_key_exists('location', $hints)) {
1256 $location = $hints['location'];
1259 if (!empty($location)) {
1260 if (mb_strlen($location) > 255) {
1261 $location = mb_substr($note, 0, 255 - 3) . ' … ';
1265 // @todo Try to find location some othe way? Via goerss point?
1270 protected static function getActivityObjectBio($object, $hints=array())
1274 if (!empty($object->poco)) {
1275 $note = $object->poco->note;
1276 } else if (array_key_exists('bio', $hints)) {
1277 $note = $hints['bio'];
1280 if (!empty($note)) {
1281 if (Profile::bioTooLong($note)) {
1282 // XXX: truncate ok?
1283 $bio = mb_substr($note, 0, Profile::maxBio() - 3) . ' … ';
1289 // @todo Try to get bio info some other way?
1294 protected static function getActivityObjectNickname($object, $hints=array())
1296 if ($object->poco) {
1297 if (!empty($object->poco->preferredUsername)) {
1298 return common_nicknamize($object->poco->preferredUsername);
1302 if (!empty($object->nickname)) {
1303 return common_nicknamize($object->nickname);
1306 if (array_key_exists('nickname', $hints)) {
1307 return $hints['nickname'];
1310 // Try the definitive ID
1312 $nickname = self::nicknameFromURI($object->id);
1314 // Try a Webfinger if one was passed (way) down
1316 if (empty($nickname)) {
1317 if (array_key_exists('webfinger', $hints)) {
1318 $nickname = self::nicknameFromURI($hints['webfinger']);
1324 if (empty($nickname)) {
1325 $nickname = common_nicknamize($object->title);
1331 protected static function nicknameFromURI($uri)
1333 preg_match('/(\w+):/', $uri, $matches);
1335 $protocol = $matches[1];
1337 switch ($protocol) {
1340 if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
1341 return common_canonical_nickname($matches[1]);
1345 return common_url_to_nickname($uri);
1353 * @param string $addr webfinger address
1354 * @return Ostatus_profile
1355 * @throws Exception on error conditions
1357 public static function ensureWebfinger($addr)
1359 // First, try the cache
1361 $uri = self::cacheGet(sprintf('ostatus_profile:webfinger:%s', $addr));
1363 if ($uri !== false) {
1364 if (is_null($uri)) {
1365 // Negative cache entry
1366 throw new Exception('Not a valid webfinger address.');
1368 $oprofile = Ostatus_profile::staticGet('uri', $uri);
1369 if (!empty($oprofile)) {
1374 // Try looking it up
1376 $oprofile = Ostatus_profile::staticGet('uri', 'acct:'.$addr);
1378 if (!empty($oprofile)) {
1379 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1383 // Now, try some discovery
1385 $disco = new Discovery();
1388 $xrd = $disco->lookup($addr);
1389 } catch (Exception $e) {
1390 // Save negative cache entry so we don't waste time looking it up again.
1391 // @fixme distinguish temporary failures?
1392 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null);
1393 throw new Exception('Not a valid webfinger address.');
1396 $hints = array('webfinger' => $addr);
1398 $dhints = DiscoveryHints::fromXRD($xrd);
1400 $hints = array_merge($hints, $dhints);
1402 // If there's an Hcard, let's grab its info
1404 if (array_key_exists('hcard', $hints)) {
1405 if (!array_key_exists('profileurl', $hints) ||
1406 $hints['hcard'] != $hints['profileurl']) {
1407 $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
1408 $hints = array_merge($hcardHints, $hints);
1412 // If we got a feed URL, try that
1414 if (array_key_exists('feedurl', $hints)) {
1416 common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
1417 $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
1418 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1420 } catch (Exception $e) {
1421 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
1426 // If we got a profile page, try that!
1428 if (array_key_exists('profileurl', $hints)) {
1430 common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
1431 $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
1432 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1434 } catch (Exception $e) {
1435 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
1443 if (array_key_exists('salmon', $hints)) {
1445 $salmonEndpoint = $hints['salmon'];
1447 // An account URL, a salmon endpoint, and a dream? Not much to go
1448 // on, but let's give it a try
1450 $uri = 'acct:'.$addr;
1452 $profile = new Profile();
1454 $profile->nickname = self::nicknameFromUri($uri);
1455 $profile->created = common_sql_now();
1457 if (isset($profileUrl)) {
1458 $profile->profileurl = $profileUrl;
1461 $profile_id = $profile->insert();
1464 common_log_db_error($profile, 'INSERT', __FILE__);
1465 throw new Exception("Couldn't save profile for '$addr'");
1468 $oprofile = new Ostatus_profile();
1470 $oprofile->uri = $uri;
1471 $oprofile->salmonuri = $salmonEndpoint;
1472 $oprofile->profile_id = $profile_id;
1473 $oprofile->created = common_sql_now();
1475 if (isset($feedUrl)) {
1476 $profile->feeduri = $feedUrl;
1479 $result = $oprofile->insert();
1482 common_log_db_error($oprofile, 'INSERT', __FILE__);
1483 throw new Exception("Couldn't save ostatus_profile for '$addr'");
1486 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1490 throw new Exception("Couldn't find a valid profile for '$addr'");
1494 * Store the full-length scrubbed HTML of a remote notice to an attachment
1495 * file on our server. We'll link to this at the end of the cropped version.
1497 * @param string $title plaintext for HTML page's title
1498 * @param string $rendered HTML fragment for HTML page's body
1501 function saveHTMLFile($title, $rendered)
1503 $final = sprintf("<!DOCTYPE html>\n<html><head><title>%s</title></head>".
1504 '<body>%s</body></html>',
1505 htmlspecialchars($title),
1508 $filename = File::filename($this->localProfile(),
1509 'ostatus', // ignored?
1512 $filepath = File::path($filename);
1514 file_put_contents($filepath, $final);
1518 $file->filename = $filename;
1519 $file->url = File::url($filename);
1520 $file->size = filesize($filepath);
1521 $file->date = time();
1522 $file->mimetype = 'text/html';
1524 $file_id = $file->insert();
1526 if ($file_id === false) {
1527 common_log_db_error($file, "INSERT", __FILE__);
1528 throw new ServerException(_('Could not store HTML content of long post as file.'));