]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/classes/Ostatus_profile.php
b14b4c9a376ccca3a38979a8acac8b9a8095dbfd
[quix0rs-gnu-social.git] / plugins / OStatus / classes / Ostatus_profile.php
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
20 /**
21  * @package OStatusPlugin
22  * @maintainer Brion Vibber <brion@status.net>
23  */
24
25 class Ostatus_profile extends Memcached_DataObject
26 {
27     public $__table = 'ostatus_profile';
28
29     public $uri;
30
31     public $profile_id;
32     public $group_id;
33
34     public $feeduri;
35     public $salmonuri;
36
37     public $created;
38     public $modified;
39
40     public /*static*/ function staticGet($k, $v=null)
41     {
42         return parent::staticGet(__CLASS__, $k, $v);
43     }
44
45     /**
46      * return table definition for DB_DataObject
47      *
48      * DB_DataObject needs to know something about the table to manipulate
49      * instances. This method provides all the DB_DataObject needs to know.
50      *
51      * @return array array of column definitions
52      */
53
54     function table()
55     {
56         return array('uri' => DB_DATAOBJECT_STR + DB_DATAOBJECT_NOTNULL,
57                      'profile_id' => DB_DATAOBJECT_INT,
58                      'group_id' => DB_DATAOBJECT_INT,
59                      'feeduri' => DB_DATAOBJECT_STR,
60                      'salmonuri' =>  DB_DATAOBJECT_STR,
61                      'created' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME + DB_DATAOBJECT_NOTNULL,
62                      'modified' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME + DB_DATAOBJECT_NOTNULL);
63     }
64
65     static function schemaDef()
66     {
67         return array(new ColumnDef('uri', 'varchar',
68                                    255, false, 'PRI'),
69                      new ColumnDef('profile_id', 'integer',
70                                    null, true, 'UNI'),
71                      new ColumnDef('group_id', 'integer',
72                                    null, true, 'UNI'),
73                      new ColumnDef('feeduri', 'varchar',
74                                    255, true, 'UNI'),
75                      new ColumnDef('salmonuri', 'text',
76                                    null, true),
77                      new ColumnDef('created', 'datetime',
78                                    null, false),
79                      new ColumnDef('modified', 'datetime',
80                                    null, false));
81     }
82
83     /**
84      * return key definitions for DB_DataObject
85      *
86      * DB_DataObject needs to know about keys that the table has; this function
87      * defines them.
88      *
89      * @return array key definitions
90      */
91
92     function keys()
93     {
94         return array_keys($this->keyTypes());
95     }
96
97     /**
98      * return key definitions for Memcached_DataObject
99      *
100      * Our caching system uses the same key definitions, but uses a different
101      * method to get them.
102      *
103      * @return array key definitions
104      */
105
106     function keyTypes()
107     {
108         return array('uri' => 'K', 'profile_id' => 'U', 'group_id' => 'U', 'feeduri' => 'U');
109     }
110
111     function sequenceKey()
112     {
113         return array(false, false, false);
114     }
115
116     /**
117      * Fetch the StatusNet-side profile for this feed
118      * @return Profile
119      */
120     public function localProfile()
121     {
122         if ($this->profile_id) {
123             return Profile::staticGet('id', $this->profile_id);
124         }
125         return null;
126     }
127
128     /**
129      * Fetch the StatusNet-side profile for this feed
130      * @return Profile
131      */
132     public function localGroup()
133     {
134         if ($this->group_id) {
135             return User_group::staticGet('id', $this->group_id);
136         }
137         return null;
138     }
139
140     /**
141      * Returns an XML string fragment with profile information as an
142      * Activity Streams noun object with the given element type.
143      *
144      * Assumes that 'activity' namespace has been previously defined.
145      *
146      * @param string $element one of 'actor', 'subject', 'object', 'target'
147      * @return string
148      */
149     function asActivityNoun($element)
150     {
151         $xs = new XMLStringer(true);
152
153         $avatarHref = Avatar::defaultImage(AVATAR_PROFILE_SIZE);
154         $avatarType = 'image/png';
155         if ($this->isGroup()) {
156             $type = 'http://activitystrea.ms/schema/1.0/group';
157             $self = $this->localGroup();
158
159             // @fixme put a standard getAvatar() interface on groups too
160             if ($self->homepage_logo) {
161                 $avatarHref = $self->homepage_logo;
162                 $map = array('png' => 'image/png',
163                              'jpg' => 'image/jpeg',
164                              'jpeg' => 'image/jpeg',
165                              'gif' => 'image/gif');
166                 $extension = pathinfo(parse_url($avatarHref, PHP_URL_PATH), PATHINFO_EXTENSION);
167                 if (isset($map[$extension])) {
168                     $avatarType = $map[$extension];
169                 }
170             }
171         } else {
172             $type = 'http://activitystrea.ms/schema/1.0/person';
173             $self = $this->localProfile();
174             $avatar = $self->getAvatar(AVATAR_PROFILE_SIZE);
175             if ($avatar) {
176                 $avatarHref = $avatar->
177                 $avatarType = $avatar->mediatype;
178             }
179         }
180         $xs->elementStart('activity:' . $element);
181         $xs->element(
182             'activity:object-type',
183             null,
184             $type
185         );
186         $xs->element(
187             'id',
188             null,
189             $this->uri); // ?
190         $xs->element('title', null, $self->getBestName());
191
192         $xs->element(
193             'link', array(
194                 'type' => $avatarType,
195                 'href' => $avatarHref
196             ),
197             ''
198         );
199
200         $xs->elementEnd('activity:' . $element);
201
202         return $xs->getString();
203     }
204
205     /**
206      * Damn dirty hack!
207      */
208     function isGroup()
209     {
210         return (strpos($this->feeduri, '/groups/') !== false);
211     }
212
213     /**
214      * Subscribe a local user to this remote user.
215      * PuSH subscription will be started if necessary, and we'll
216      * send a Salmon notification to the remote server if available
217      * notifying them of the sub.
218      *
219      * @param User $user
220      * @return boolean success
221      * @throws FeedException
222      */
223     public function subscribeLocalToRemote(User $user)
224     {
225         if ($this->isGroup()) {
226             throw new ServerException("Can't subscribe to a remote group");
227         }
228
229         if ($this->subscribe()) {
230             if ($user->subscribeTo($this->localProfile())) {
231                 $this->notify($user->getProfile(), ActivityVerb::FOLLOW, $this);
232                 return true;
233             }
234         }
235         return false;
236     }
237
238     /**
239      * Mark this remote profile as subscribing to the given local user,
240      * and send appropriate notifications to the user.
241      *
242      * This will generally be in response to a subscription notification
243      * from a foreign site to our local Salmon response channel.
244      *
245      * @param User $user
246      * @return boolean success
247      */
248     public function subscribeRemoteToLocal(User $user)
249     {
250         if ($this->isGroup()) {
251             throw new ServerException("Remote groups can't subscribe to local users");
252         }
253
254         // @fixme use regular channels for subbing, once they accept remote profiles
255         $sub = new Subscription();
256         $sub->subscriber = $this->profile_id;
257         $sub->subscribed = $user->id;
258         $sub->created = common_sql_now(); // current time
259
260         if ($sub->insert()) {
261             // @fixme use subs_notify() if refactored to take profiles?
262             mail_subscribe_notify_profile($user, $this->localProfile());
263             return true;
264         }
265         return false;
266     }
267
268     /**
269      * Send a subscription request to the hub for this feed.
270      * The hub will later send us a confirmation POST to /main/push/callback.
271      *
272      * @return bool true on success, false on failure
273      * @throws ServerException if feed state is not valid
274      */
275     public function subscribe()
276     {
277         $feedsub = FeedSub::ensureFeed($this->feeduri);
278         if ($feedsub->sub_state == 'active' || $feedsub->sub_state == 'subscribe') {
279             return true;
280         } else if ($feedsub->sub_state == '' || $feedsub->sub_state == 'inactive') {
281             return $feedsub->subscribe();
282         } else if ('unsubscribe') {
283             throw new FeedSubException("Unsub is pending, can't subscribe...");
284         }
285     }
286
287     /**
288      * Send a PuSH unsubscription request to the hub for this feed.
289      * The hub will later send us a confirmation POST to /main/push/callback.
290      *
291      * @return bool true on success, false on failure
292      * @throws ServerException if feed state is not valid
293      */
294     public function unsubscribe() {
295         $feedsub = FeedSub::staticGet('uri', $this->feeduri);
296         if ($feedsub->sub_state == 'active') {
297             return $feedsub->unsubscribe();
298         } else if ($feedsub->sub_state == '' || $feedsub->sub_state == 'inactive' || $feedsub->sub_state == 'unsubscribe') {
299             return true;
300         } else if ($feedsub->sub_state == 'subscribe') {
301             throw new FeedSubException("Feed is awaiting subscription, can't unsub...");
302         }
303     }
304
305     /**
306      * Send an Activity Streams notification to the remote Salmon endpoint,
307      * if so configured.
308      *
309      * @param Profile $actor
310      * @param $verb eg Activity::SUBSCRIBE or Activity::JOIN
311      * @param $object object of the action; if null, the remote entity itself is assumed
312      */
313     public function notify($actor, $verb, $object=null)
314     {
315         if (!($actor instanceof Profile)) {
316             $type = gettype($actor);
317             if ($type == 'object') {
318                 $type = get_class($actor);
319             }
320             throw new ServerException("Invalid actor passed to " . __METHOD__ . ": " . $type);
321         }
322         if ($object == null) {
323             $object = $this;
324         }
325         if ($this->salmonuri) {
326             $text = 'update'; // @fixme
327             $id = 'tag:' . common_config('site', 'server') .
328                 ':' . $verb .
329                 ':' . $actor->id .
330                 ':' . time(); // @fixme
331
332             // @fixme consolidate all these NS settings somewhere
333             $attributes = array('xmlns' => Activity::ATOM,
334                                 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
335                                 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
336                                 'xmlns:georss' => 'http://www.georss.org/georss',
337                                 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0');
338
339             $entry = new XMLStringer();
340             $entry->elementStart('entry', $attributes);
341             $entry->element('id', null, $id);
342             $entry->element('title', null, $text);
343             $entry->element('summary', null, $text);
344             $entry->element('published', null, common_date_w3dtf(common_sql_now()));
345
346             $entry->element('activity:verb', null, $verb);
347             $entry->raw($actor->asAtomAuthor());
348             $entry->raw($actor->asActivityActor());
349             $entry->raw($object->asActivityNoun('object'));
350             $entry->elementEnd('entry');
351
352             $xml = $entry->getString();
353             common_log(LOG_INFO, "Posting to Salmon endpoint $this->salmonuri: $xml");
354
355             $salmon = new Salmon(); // ?
356             $salmon->post($this->salmonuri, $xml);
357         }
358     }
359
360     function getBestName()
361     {
362         if ($this->isGroup()) {
363             return $this->localGroup()->getBestName();
364         } else {
365             return $this->localProfile()->getBestName();
366         }
367     }
368
369     function atomFeed($actor)
370     {
371         $feed = new Atom10Feed();
372         // @fixme should these be set up somewhere else?
373         $feed->addNamespace('activity', 'http://activitystrea.ms/spec/1.0/');
374         $feed->addNamespace('thr', 'http://purl.org/syndication/thread/1.0');
375         $feed->addNamespace('georss', 'http://www.georss.org/georss');
376         $feed->addNamespace('ostatus', 'http://ostatus.org/schema/1.0');
377
378         $taguribase = common_config('integration', 'taguri');
379         $feed->setId("tag:{$taguribase}:UserTimeline:{$actor->id}"); // ???
380
381         $feed->setTitle($actor->getBestName() . ' timeline'); // @fixme
382         $feed->setUpdated(time());
383         $feed->setPublished(time());
384
385         $feed->addLink(common_local_url('ApiTimelineUser',
386                                         array('id' => $actor->id,
387                                               'type' => 'atom')),
388                        array('rel' => 'self',
389                              'type' => 'application/atom+xml'));
390
391         $feed->addLink(common_local_url('userbyid',
392                                         array('id' => $actor->id)),
393                        array('rel' => 'alternate',
394                              'type' => 'text/html'));
395
396         return $feed;
397     }
398
399     /**
400      * Read and post notices for updates from the feed.
401      * Currently assumes that all items in the feed are new,
402      * coming from a PuSH hub.
403      *
404      * @param DOMDocument $feed
405      */
406     public function processFeed($feed)
407     {
408         $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
409         if ($entries->length == 0) {
410             common_log(LOG_ERR, __METHOD__ . ": no entries in feed update, ignoring");
411             return;
412         }
413
414         for ($i = 0; $i < $entries->length; $i++) {
415             $entry = $entries->item($i);
416             $this->processEntry($entry, $feed);
417         }
418     }
419
420     /**
421      * Process a posted entry from this feed source.
422      *
423      * @param DOMElement $entry
424      * @param DOMElement $feed for context
425      */
426     protected function processEntry($entry, $feed)
427     {
428         $activity = new Activity($entry, $feed);
429
430         $debug = var_export($activity, true);
431         common_log(LOG_DEBUG, $debug);
432
433         if ($activity->verb == ActivityVerb::POST) {
434             $this->processPost($activity);
435         } else {
436             common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
437         }
438     }
439
440     /**
441      * Process an incoming post activity from this remote feed.
442      * @param Activity $activity
443      */
444     protected function processPost($activity)
445     {
446         if ($this->isGroup()) {
447             // @fixme validate these profiles in some way!
448             $oprofile = self::ensureActorProfile($activity);
449         } else {
450             $actorUri = self::getActorProfileURI($activity);
451             if ($actorUri == $this->uri) {
452                 // @fixme check if profile info has changed and update it
453             } else {
454                 // @fixme drop or reject the messages once we've got the canonical profile URI recorded sanely
455                 common_log(LOG_INFO, "OStatus: Warning: non-group post with unexpected author: $actorUri expected $this->uri");
456                 //return;
457             }
458             $oprofile = $this;
459         }
460
461         if ($activity->object->link) {
462             $sourceUri = $activity->object->link;
463         } else if (preg_match('!^https?://!', $activity->object->id)) {
464             $sourceUri = $activity->object->id;
465         } else {
466             common_log(LOG_INFO, "OStatus: ignoring post with no source link: id $activity->object->id");
467             return;
468         }
469
470         $dupe = Notice::staticGet('uri', $sourceUri);
471         if ($dupe) {
472             common_log(LOG_INFO, "OStatus: ignoring duplicate post: $noticeLink");
473             return;
474         }
475
476         // @fixme sanitize and save HTML content if available
477         $content = $activity->object->title;
478
479         $params = array('is_local' => Notice::REMOTE_OMB,
480                         'uri' => $sourceUri);
481
482         $location = $this->getEntryLocation($activity->entry);
483         if ($location) {
484             $params['lat'] = $location->lat;
485             $params['lon'] = $location->lon;
486             if ($location->location_id) {
487                 $params['location_ns'] = $location->location_ns;
488                 $params['location_id'] = $location->location_id;
489             }
490         }
491
492         // @fixme save detailed ostatus source info
493         // @fixme ensure that groups get handled correctly
494
495         $saved = Notice::saveNew($oprofile->localProfile()->id,
496                                  $content,
497                                  'ostatus',
498                                  $params);
499     }
500
501     /**
502      * @param string $profile_url
503      * @return Ostatus_profile
504      * @throws FeedSubException
505      */
506     public static function ensureProfile($profile_uri)
507     {
508         // Get the canonical feed URI and check it
509         $discover = new FeedDiscovery();
510         $feeduri = $discover->discoverFromURL($profile_uri);
511
512         //$feedsub = FeedSub::ensureFeed($feeduri, $discover->feed);
513         $huburi = $discover->getAtomLink('hub');
514         $salmonuri = $discover->getAtomLink('salmon');
515
516         if (!$huburi) {
517             // We can only deal with folks with a PuSH hub
518             throw new FeedSubNoHubException();
519         }
520
521         // Ok this is going to be a terrible hack!
522         // Won't be suitable for groups, empty feeds, or getting
523         // info that's only available on the profile page.
524         $entries = $discover->feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
525         if (!$entries || $entries->length == 0) {
526             throw new FeedSubException('empty feed');
527         }
528         $first = new Activity($entries->item(0), $discover->feed);
529         return self::ensureActorProfile($first, $feeduri, $salmonuri);
530     }
531
532     /**
533      * Download and update given avatar image
534      * @param string $url
535      * @throws Exception in various failure cases
536      */
537     protected function updateAvatar($url)
538     {
539         // @fixme this should be better encapsulated
540         // ripped from oauthstore.php (for old OMB client)
541         $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
542         copy($url, $temp_filename);
543
544         if ($this->isGroup()) {
545             $id = $this->group_id;
546         } else {
547             $id = $this->profile_id;
548         }
549         // @fixme should we be using different ids?
550         $imagefile = new ImageFile($id, $temp_filename);
551         $filename = Avatar::filename($id,
552                                      image_type_to_extension($imagefile->type),
553                                      null,
554                                      common_timestamp());
555         rename($temp_filename, Avatar::path($filename));
556         if ($this->isGroup()) {
557             $group = $this->localGroup();
558             $group->setOriginal($filename);
559         } else {
560             $profile = $this->localProfile();
561             $profile->setOriginal($filename);
562         }
563     }
564
565     /**
566      * Get an appropriate avatar image source URL, if available.
567      *
568      * @param ActivityObject $actor
569      * @param DOMElement $feed
570      * @return string
571      */
572     protected static function getAvatar($actor, $feed)
573     {
574         $url = '';
575         $icon = '';
576         if ($actor->avatar) {
577             $url = trim($actor->avatar);
578         }
579         if (!$url) {
580             // Check <atom:logo> and <atom:icon> on the feed
581             $els = $feed->childNodes();
582             if ($els && $els->length) {
583                 for ($i = 0; $i < $els->length; $i++) {
584                     $el = $els->item($i);
585                     if ($el->namespaceURI == Activity::ATOM) {
586                         if (empty($url) && $el->localName == 'logo') {
587                             $url = trim($el->textContent);
588                             break;
589                         }
590                         if (empty($icon) && $el->localName == 'icon') {
591                             // Use as a fallback
592                             $icon = trim($el->textContent);
593                         }
594                     }
595                 }
596             }
597             if ($icon && !$url) {
598                 $url = $icon;
599             }
600         }
601         if ($url) {
602             $opts = array('allowed_schemes' => array('http', 'https'));
603             if (Validate::uri($url, $opts)) {
604                 return $url;
605             }
606         }
607         return common_path('plugins/OStatus/images/96px-Feed-icon.svg.png');
608     }
609
610     /**
611      * Fetch, or build if necessary, an Ostatus_profile for the actor
612      * in a given Activity Streams activity.
613      *
614      * @param Activity $activity
615      * @param string $feeduri if we already know the canonical feed URI!
616      * @param string $salmonuri if we already know the salmon return channel URI
617      * @return Ostatus_profile
618      */
619     public static function ensureActorProfile($activity, $feeduri=null, $salmonuri=null)
620     {
621         $profile = self::getActorProfile($activity);
622         if (!$profile) {
623             $profile = self::createActorProfile($activity, $feeduri, $salmonuri);
624         }
625         return $profile;
626     }
627
628     /**
629      * @param Activity $activity
630      * @return mixed matching Ostatus_profile or false if none known
631      */
632     protected static function getActorProfile($activity)
633     {
634         $homeuri = self::getActorProfileURI($activity);
635         return self::staticGet('uri', $homeuri);
636     }
637
638     /**
639      * @param Activity $activity
640      * @return string
641      * @throws ServerException
642      */
643     protected static function getActorProfileURI($activity)
644     {
645         $opts = array('allowed_schemes' => array('http', 'https'));
646         $actor = $activity->actor;
647         if ($actor->id && Validate::uri($actor->id, $opts)) {
648             return $actor->id;
649         }
650         if ($actor->link && Validate::uri($actor->link, $opts)) {
651             return $actor->link;
652         }
653         throw new ServerException("No author ID URI found");
654     }
655
656     /**
657      * @fixme validate stuff somewhere
658      */
659     protected static function createActorProfile($activity, $feeduri=null, $salmonuri=null)
660     {
661         $actor = $activity->actor;
662         $homeuri = self::getActorProfileURI($activity);
663         $nickname = self::getAuthorNick($activity);
664         $avatar = self::getAvatar($actor, $activity->feed);
665
666         if (!$homeuri) {
667             common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
668             throw new ServerException("No profile URI");
669         }
670
671         if (!$feeduri || !$salmonuri) {
672             // Get the canonical feed URI and check it
673             $discover = new FeedDiscovery();
674             $feeduri = $discover->discoverFromURL($homeuri);
675     
676             $huburi = $discover->getAtomLink('hub');
677             $salmonuri = $discover->getAtomLink('salmon');
678     
679             if (!$huburi) {
680                 // We can only deal with folks with a PuSH hub
681                 throw new FeedSubNoHubException();
682             }
683         }
684
685         $profile = new Profile();
686         $profile->nickname   = $nickname;
687         $profile->fullname   = $actor->displayName;
688         $profile->homepage   = $actor->link; // @fixme
689         $profile->profileurl = $homeuri;
690         // @fixme bio
691         // @fixme tags/categories
692         // @fixme location?
693         // @todo tags from categories
694         // @todo lat/lon/location?
695
696         $ok = $profile->insert();
697         if (!$ok) {
698             throw new ServerException("Can't save local profile");
699         }
700
701         // @fixme either need to do feed discovery here
702         // or need to split out some of the feed stuff
703         // so we can leave it empty until later.
704         $oprofile = new Ostatus_profile();
705         $oprofile->uri = $homeuri;
706         $oprofile->feeduri = $feeduri;
707         $oprofile->salmonuri = $salmonuri;
708         $oprofile->profile_id = $profile->id;
709
710         $oprofile->created = common_sql_now();
711         $oprofile->modified = common_sql_now();
712
713         $ok = $oprofile->insert();
714         if ($ok) {
715             $oprofile->updateAvatar($avatar);
716             return $oprofile;
717         } else {
718             throw new ServerException("Can't save OStatus profile");
719         }
720     }
721
722     /**
723      * @fixme move this into Activity?
724      * @param Activity $activity
725      * @return string
726      */
727     protected static function getAuthorNick($activity)
728     {
729         // @fixme not technically part of the actor?
730         foreach (array($activity->entry, $activity->feed) as $source) {
731             $author = ActivityUtils::child($source, 'author', Activity::ATOM);
732             if ($author) {
733                 $name = ActivityUtils::child($author, 'name', Activity::ATOM);
734                 if ($name) {
735                     return trim($name->textContent);
736                 }
737             }
738         }
739         return false;
740     }
741
742 }