]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/activity.php
Parse an hcard for hints, if available
[quix0rs-gnu-social.git] / lib / activity.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * An activity
6  *
7  * PHP version 5
8  *
9  * LICENCE: This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Affero General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Affero General Public License for more details.
18  *
19  * You should have received a copy of the GNU Affero General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  * @category  Feed
23  * @package   StatusNet
24  * @author    Evan Prodromou <evan@status.net>
25  * @author    Zach Copley <zach@status.net>
26  * @copyright 2010 StatusNet, Inc.
27  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
28  * @link      http://status.net/
29  */
30
31 if (!defined('STATUSNET')) {
32     exit(1);
33 }
34
35 class PoCoURL
36 {
37     const URLS      = 'urls';
38     const TYPE      = 'type';
39     const VALUE     = 'value';
40     const PRIMARY   = 'primary';
41
42     public $type;
43     public $value;
44     public $primary;
45
46     function __construct($type, $value, $primary = false)
47     {
48         $this->type    = $type;
49         $this->value   = $value;
50         $this->primary = $primary;
51     }
52
53     function asString()
54     {
55         $xs = new XMLStringer(true);
56         $xs->elementStart('poco:urls');
57         $xs->element('poco:type', null, $this->type);
58         $xs->element('poco:value', null, $this->value);
59         if (!empty($this->primary)) {
60             $xs->element('poco:primary', null, 'true');
61         }
62         $xs->elementEnd('poco:urls');
63         return $xs->getString();
64     }
65 }
66
67 class PoCoAddress
68 {
69     const ADDRESS   = 'address';
70     const FORMATTED = 'formatted';
71
72     public $formatted;
73
74     // @todo Other address fields
75
76     function asString()
77     {
78         if (!empty($this->formatted)) {
79             $xs = new XMLStringer(true);
80             $xs->elementStart('poco:address');
81             $xs->element('poco:formatted', null, $this->formatted);
82             $xs->elementEnd('poco:address');
83             return $xs->getString();
84         }
85
86         return null;
87     }
88 }
89
90 class PoCo
91 {
92     const NS = 'http://portablecontacts.net/spec/1.0';
93
94     const USERNAME     = 'preferredUsername';
95     const DISPLAYNAME  = 'displayName';
96     const NOTE         = 'note';
97
98     public $preferredUsername;
99     public $displayName;
100     public $note;
101     public $address;
102     public $urls = array();
103
104     function __construct($element = null)
105     {
106         if (empty($element)) {
107             return;
108         }
109
110         $this->preferredUsername = ActivityUtils::childContent(
111             $element,
112             self::USERNAME,
113             self::NS
114         );
115
116         $this->displayName = ActivityUtils::childContent(
117             $element,
118             self::DISPLAYNAME,
119             self::NS
120         );
121
122         $this->note = ActivityUtils::childContent(
123             $element,
124             self::NOTE,
125             self::NS
126         );
127
128         $this->address = $this->_getAddress($element);
129         $this->urls = $this->_getURLs($element);
130     }
131
132     private function _getURLs($element)
133     {
134         $urlEls = $element->getElementsByTagnameNS(self::NS, PoCoURL::URLS);
135         $urls = array();
136
137         foreach ($urlEls as $urlEl) {
138
139             $type = ActivityUtils::childContent(
140                 $urlEl,
141                 PoCoURL::TYPE,
142                 PoCo::NS
143             );
144
145             $value = ActivityUtils::childContent(
146                 $urlEl,
147                 PoCoURL::VALUE,
148                 PoCo::NS
149             );
150
151             $primary = ActivityUtils::childContent(
152                 $urlEl,
153                 PoCoURL::PRIMARY,
154                 PoCo::NS
155             );
156
157             $isPrimary = false;
158
159             if (isset($primary) && $primary == 'true') {
160                 $isPrimary = true;
161             }
162
163             // @todo check to make sure a primary hasn't already been added
164
165             array_push($urls, new PoCoURL($type, $value, $isPrimary));
166         }
167         return $urls;
168     }
169
170     private function _getAddress($element)
171     {
172         $addressEl = ActivityUtils::child(
173             $element,
174             PoCoAddress::ADDRESS,
175             PoCo::NS
176         );
177
178         if (!empty($addressEl)) {
179             $formatted = ActivityUtils::childContent(
180                 $addressEl,
181                 PoCoAddress::FORMATTED,
182                 self::NS
183             );
184
185             if (!empty($formatted)) {
186                 $address = new PoCoAddress();
187                 $address->formatted = $formatted;
188                 return $address;
189             }
190         }
191
192         return null;
193     }
194
195     function fromProfile($profile)
196     {
197         if (empty($profile)) {
198             return null;
199         }
200
201         $poco = new PoCo();
202
203         $poco->preferredUsername = $profile->nickname;
204         $poco->displayName       = $profile->getBestName();
205
206         $poco->note = $profile->bio;
207
208         $paddy = new PoCoAddress();
209         $paddy->formatted = $profile->location;
210         $poco->address = $paddy;
211
212         if (!empty($profile->homepage)) {
213             array_push(
214                 $poco->urls,
215                 new PoCoURL(
216                     'homepage',
217                     $profile->homepage,
218                     true
219                 )
220             );
221         }
222
223         return $poco;
224     }
225
226     function fromGroup($group)
227     {
228         if (empty($group)) {
229             return null;
230         }
231
232         $poco = new PoCo();
233
234         $poco->preferredUsername = $group->nickname;
235         $poco->displayName       = $group->getBestName();
236
237         $poco->note = $group->description;
238
239         $paddy = new PoCoAddress();
240         $paddy->formatted = $group->location;
241         $poco->address = $paddy;
242
243         if (!empty($group->homepage)) {
244             array_push(
245                 $poco->urls,
246                 new PoCoURL(
247                     'homepage',
248                     $group->homepage,
249                     true
250                 )
251             );
252         }
253
254         return $poco;
255     }
256
257     function getPrimaryURL()
258     {
259         foreach ($this->urls as $url) {
260             if ($url->primary) {
261                 return $url;
262             }
263         }
264     }
265
266     function asString()
267     {
268         $xs = new XMLStringer(true);
269         $xs->element(
270             'poco:preferredUsername',
271             null,
272             $this->preferredUsername
273         );
274
275         $xs->element(
276             'poco:displayName',
277             null,
278             $this->displayName
279         );
280
281         if (!empty($this->note)) {
282             $xs->element('poco:note', null, $this->note);
283         }
284
285         if (!empty($this->address)) {
286             $xs->raw($this->address->asString());
287         }
288
289         foreach ($this->urls as $url) {
290             $xs->raw($url->asString());
291         }
292
293         return $xs->getString();
294     }
295 }
296
297 /**
298  * Utilities for turning DOMish things into Activityish things
299  *
300  * Some common functions that I didn't have the bandwidth to try to factor
301  * into some kind of reasonable superclass, so just dumped here. Might
302  * be useful to have an ActivityObject parent class or something.
303  *
304  * @category  OStatus
305  * @package   StatusNet
306  * @author    Evan Prodromou <evan@status.net>
307  * @copyright 2010 StatusNet, Inc.
308  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
309  * @link      http://status.net/
310  */
311
312 class ActivityUtils
313 {
314     const ATOM = 'http://www.w3.org/2005/Atom';
315
316     const LINK = 'link';
317     const REL  = 'rel';
318     const TYPE = 'type';
319     const HREF = 'href';
320
321     const CONTENT = 'content';
322     const SRC     = 'src';
323
324     /**
325      * Get the permalink for an Activity object
326      *
327      * @param DOMElement $element A DOM element
328      *
329      * @return string related link, if any
330      */
331
332     static function getPermalink($element)
333     {
334         return self::getLink($element, 'alternate', 'text/html');
335     }
336
337     /**
338      * Get the permalink for an Activity object
339      *
340      * @param DOMElement $element A DOM element
341      *
342      * @return string related link, if any
343      */
344
345     static function getLink(DOMNode $element, $rel, $type=null)
346     {
347         $links = $element->getElementsByTagnameNS(self::ATOM, self::LINK);
348
349         foreach ($links as $link) {
350
351             $linkRel = $link->getAttribute(self::REL);
352             $linkType = $link->getAttribute(self::TYPE);
353
354             if ($linkRel == $rel &&
355                 (is_null($type) || $linkType == $type)) {
356                 return $link->getAttribute(self::HREF);
357             }
358         }
359
360         return null;
361     }
362
363     /**
364      * Gets the first child element with the given tag
365      *
366      * @param DOMElement $element   element to pick at
367      * @param string     $tag       tag to look for
368      * @param string     $namespace Namespace to look under
369      *
370      * @return DOMElement found element or null
371      */
372
373     static function child(DOMNode $element, $tag, $namespace=self::ATOM)
374     {
375         $els = $element->childNodes;
376         if (empty($els) || $els->length == 0) {
377             return null;
378         } else {
379             for ($i = 0; $i < $els->length; $i++) {
380                 $el = $els->item($i);
381                 if ($el->localName == $tag && $el->namespaceURI == $namespace) {
382                     return $el;
383                 }
384             }
385         }
386     }
387
388     /**
389      * Grab the text content of a DOM element child of the current element
390      *
391      * @param DOMElement $element   Element whose children we examine
392      * @param string     $tag       Tag to look up
393      * @param string     $namespace Namespace to use, defaults to Atom
394      *
395      * @return string content of the child
396      */
397
398     static function childContent(DOMNode $element, $tag, $namespace=self::ATOM)
399     {
400         $el = self::child($element, $tag, $namespace);
401
402         if (empty($el)) {
403             return null;
404         } else {
405             return $el->textContent;
406         }
407     }
408
409     /**
410      * Get the content of an atom:entry-like object
411      *
412      * @param DOMElement $element The element to examine.
413      *
414      * @return string unencoded HTML content of the element, like "This -&lt; is <b>HTML</b>."
415      *
416      * @todo handle remote content
417      * @todo handle embedded XML mime types
418      * @todo handle base64-encoded non-XML and non-text mime types
419      */
420
421     static function getContent($element)
422     {
423         $contentEl = ActivityUtils::child($element, self::CONTENT);
424
425         if (!empty($contentEl)) {
426
427             $src  = $contentEl->getAttribute(self::SRC);
428
429             if (!empty($src)) {
430                 throw new ClientException(_("Can't handle remote content yet."));
431             }
432
433             $type = $contentEl->getAttribute(self::TYPE);
434
435             // slavishly following http://atompub.org/rfc4287.html#rfc.section.4.1.3.3
436
437             if ($type == 'text') {
438                 return $contentEl->textContent;
439             } else if ($type == 'html') {
440                 $text = $contentEl->textContent;
441                 return htmlspecialchars_decode($text, ENT_QUOTES);
442             } else if ($type == 'xhtml') {
443                 $divEl = ActivityUtils::child($contentEl, 'div');
444                 if (empty($divEl)) {
445                     return null;
446                 }
447                 $doc = $divEl->ownerDocument;
448                 $text = '';
449                 $children = $divEl->childNodes;
450
451                 for ($i = 0; $i < $children->length; $i++) {
452                     $child = $children->item($i);
453                     $text .= $doc->saveXML($child);
454                 }
455                 return trim($text);
456             } else if (in_array(array('text/xml', 'application/xml'), $type) ||
457                        preg_match('#(+|/)xml$#', $type)) {
458                 throw new ClientException(_("Can't handle embedded XML content yet."));
459             } else if (strncasecmp($type, 'text/', 5)) {
460                 return $contentEl->textContent;
461             } else {
462                 throw new ClientException(_("Can't handle embedded Base64 content yet."));
463             }
464         }
465     }
466 }
467
468 /**
469  * A noun-ish thing in the activity universe
470  *
471  * The activity streams spec talks about activity objects, while also having
472  * a tag activity:object, which is in fact an activity object. Aaaaaah!
473  *
474  * This is just a thing in the activity universe. Can be the subject, object,
475  * or indirect object (target!) of an activity verb. Rotten name, and I'm
476  * propagating it. *sigh*
477  *
478  * @category  OStatus
479  * @package   StatusNet
480  * @author    Evan Prodromou <evan@status.net>
481  * @copyright 2010 StatusNet, Inc.
482  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
483  * @link      http://status.net/
484  */
485
486 class ActivityObject
487 {
488     const ARTICLE   = 'http://activitystrea.ms/schema/1.0/article';
489     const BLOGENTRY = 'http://activitystrea.ms/schema/1.0/blog-entry';
490     const NOTE      = 'http://activitystrea.ms/schema/1.0/note';
491     const STATUS    = 'http://activitystrea.ms/schema/1.0/status';
492     const FILE      = 'http://activitystrea.ms/schema/1.0/file';
493     const PHOTO     = 'http://activitystrea.ms/schema/1.0/photo';
494     const ALBUM     = 'http://activitystrea.ms/schema/1.0/photo-album';
495     const PLAYLIST  = 'http://activitystrea.ms/schema/1.0/playlist';
496     const VIDEO     = 'http://activitystrea.ms/schema/1.0/video';
497     const AUDIO     = 'http://activitystrea.ms/schema/1.0/audio';
498     const BOOKMARK  = 'http://activitystrea.ms/schema/1.0/bookmark';
499     const PERSON    = 'http://activitystrea.ms/schema/1.0/person';
500     const GROUP     = 'http://activitystrea.ms/schema/1.0/group';
501     const PLACE     = 'http://activitystrea.ms/schema/1.0/place';
502     const COMMENT   = 'http://activitystrea.ms/schema/1.0/comment';
503     // ^^^^^^^^^^ tea!
504
505     // Atom elements we snarf
506
507     const TITLE   = 'title';
508     const SUMMARY = 'summary';
509     const ID      = 'id';
510     const SOURCE  = 'source';
511
512     const NAME  = 'name';
513     const URI   = 'uri';
514     const EMAIL = 'email';
515
516     public $element;
517     public $type;
518     public $id;
519     public $title;
520     public $summary;
521     public $content;
522     public $link;
523     public $source;
524     public $avatar;
525     public $geopoint;
526     public $poco;
527     public $displayName;
528
529     /**
530      * Constructor
531      *
532      * This probably needs to be refactored
533      * to generate a local class (ActivityPerson, ActivityFile, ...)
534      * based on the object type.
535      *
536      * @param DOMElement $element DOM thing to turn into an Activity thing
537      */
538
539     function __construct($element = null)
540     {
541         if (empty($element)) {
542             return;
543         }
544
545         $this->element = $element;
546
547         $this->geopoint = $this->_childContent(
548             $element,
549             ActivityContext::POINT,
550             ActivityContext::GEORSS
551         );
552
553         if ($element->tagName == 'author') {
554
555             $this->type  = self::PERSON; // XXX: is this fair?
556             $this->title = $this->_childContent($element, self::NAME);
557             $this->id    = $this->_childContent($element, self::URI);
558
559             if (empty($this->id)) {
560                 $email = $this->_childContent($element, self::EMAIL);
561                 if (!empty($email)) {
562                     // XXX: acct: ?
563                     $this->id = 'mailto:'.$email;
564                 }
565             }
566
567         } else {
568
569             $this->type = $this->_childContent($element, Activity::OBJECTTYPE,
570                                                Activity::SPEC);
571
572             if (empty($this->type)) {
573                 $this->type = ActivityObject::NOTE;
574             }
575
576             $this->id      = $this->_childContent($element, self::ID);
577             $this->title   = $this->_childContent($element, self::TITLE);
578             $this->summary = $this->_childContent($element, self::SUMMARY);
579
580             $this->source  = $this->_getSource($element);
581
582             $this->content = ActivityUtils::getContent($element);
583
584             $this->link = ActivityUtils::getPermalink($element);
585
586         }
587
588         // Some per-type attributes...
589         if ($this->type == self::PERSON || $this->type == self::GROUP) {
590             $this->displayName = $this->title;
591
592             // @fixme we may have multiple avatars with different resolutions specified
593             $this->avatar = ActivityUtils::getLink($element, 'avatar');
594
595             $this->poco = new PoCo($element);
596         }
597     }
598
599     private function _childContent($element, $tag, $namespace=ActivityUtils::ATOM)
600     {
601         return ActivityUtils::childContent($element, $tag, $namespace);
602     }
603
604     // Try to get a unique id for the source feed
605
606     private function _getSource($element)
607     {
608         $sourceEl = ActivityUtils::child($element, 'source');
609
610         if (empty($sourceEl)) {
611             return null;
612         } else {
613             $href = ActivityUtils::getLink($sourceEl, 'self');
614             if (!empty($href)) {
615                 return $href;
616             } else {
617                 return ActivityUtils::childContent($sourceEl, 'id');
618             }
619         }
620     }
621
622     static function fromNotice($notice)
623     {
624         $object = new ActivityObject();
625
626         $object->type    = ActivityObject::NOTE;
627
628         $object->id      = $notice->uri;
629         $object->title   = $notice->content;
630         $object->content = $notice->rendered;
631         $object->link    = $notice->bestUrl();
632
633         return $object;
634     }
635
636     static function fromProfile($profile)
637     {
638         $object = new ActivityObject();
639
640         $object->type   = ActivityObject::PERSON;
641         $object->id     = $profile->getUri();
642         $object->title  = $profile->getBestName();
643         $object->link   = $profile->profileurl;
644         $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE);
645         if ($avatar) {
646             $object->avatar = $avatar->displayUrl();
647         }
648
649         if (isset($profile->lat) && isset($profile->lon)) {
650             $object->geopoint = (float)$profile->lat . ' ' . (float)$profile->lon;
651         }
652
653         $object->poco = PoCo::fromProfile($profile);
654
655         return $object;
656     }
657
658     static function fromGroup($group)
659     {
660         $object = new ActivityObject();
661
662         $object->type   = ActivityObject::GROUP;
663         $object->id     = $group->getUri();
664         $object->title  = $group->getBestName();
665         $object->link   = $group->getUri();
666         $object->avatar = $group->getAvatar();
667
668         $object->poco = PoCo::fromGroup($group);
669
670         return $object;
671     }
672
673     function asString($tag='activity:object')
674     {
675         $xs = new XMLStringer(true);
676
677         $xs->elementStart($tag);
678
679         $xs->element('activity:object-type', null, $this->type);
680
681         $xs->element(self::ID, null, $this->id);
682
683         if (!empty($this->title)) {
684             $xs->element(self::TITLE, null, $this->title);
685         }
686
687         if (!empty($this->summary)) {
688             $xs->element(self::SUMMARY, null, $this->summary);
689         }
690
691         if (!empty($this->content)) {
692             // XXX: assuming HTML content here
693             $xs->element(ActivityUtils::CONTENT, array('type' => 'html'), $this->content);
694         }
695
696         if (!empty($this->link)) {
697             $xs->element(
698                 'link',
699                 array(
700                     'rel' => 'alternate',
701                     'type' => 'text/html',
702                     'href' => $this->link
703                 ),
704                 null
705             );
706         }
707
708         if ($this->type == ActivityObject::PERSON) {
709             $xs->element(
710                 'link', array(
711                     'type' => empty($this->avatar) ? 'image/png' : $this->avatar->mediatype,
712                     'rel'  => 'avatar',
713                     'href' => empty($this->avatar)
714                     ? Avatar::defaultImage(AVATAR_PROFILE_SIZE)
715                     : $this->avatar
716                 ),
717                 null
718             );
719         }
720
721         // XXX: Gotta figure out mime-type! Gar.
722
723         if ($this->type == ActivityObject::GROUP) {
724             $xs->element(
725                 'link', array(
726                     'rel'  => 'avatar',
727                     'href' => $this->avatar
728                 ),
729                 null
730             );
731         }
732
733         if (!empty($this->geopoint)) {
734             $xs->element(
735                 'georss:point',
736                 null,
737                 $this->geopoint
738             );
739         }
740
741         if (!empty($this->poco)) {
742             $xs->raw($this->poco->asString());
743         }
744
745         $xs->elementEnd($tag);
746
747         return $xs->getString();
748     }
749 }
750
751 /**
752  * Utility class to hold a bunch of constant defining default verb types
753  *
754  * @category  OStatus
755  * @package   StatusNet
756  * @author    Evan Prodromou <evan@status.net>
757  * @copyright 2010 StatusNet, Inc.
758  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
759  * @link      http://status.net/
760  */
761
762 class ActivityVerb
763 {
764     const POST     = 'http://activitystrea.ms/schema/1.0/post';
765     const SHARE    = 'http://activitystrea.ms/schema/1.0/share';
766     const SAVE     = 'http://activitystrea.ms/schema/1.0/save';
767     const FAVORITE = 'http://activitystrea.ms/schema/1.0/favorite';
768     const PLAY     = 'http://activitystrea.ms/schema/1.0/play';
769     const FOLLOW   = 'http://activitystrea.ms/schema/1.0/follow';
770     const FRIEND   = 'http://activitystrea.ms/schema/1.0/make-friend';
771     const JOIN     = 'http://activitystrea.ms/schema/1.0/join';
772     const TAG      = 'http://activitystrea.ms/schema/1.0/tag';
773
774     // Custom OStatus verbs for the flipside until they're standardized
775     const DELETE     = 'http://ostatus.org/schema/1.0/unfollow';
776     const UNFAVORITE = 'http://ostatus.org/schema/1.0/unfavorite';
777     const UNFOLLOW   = 'http://ostatus.org/schema/1.0/unfollow';
778     const LEAVE      = 'http://ostatus.org/schema/1.0/leave';
779
780     // For simple profile-update pings; no content to share.
781     const UPDATE_PROFILE = 'http://ostatus.org/schema/1.0/update-profile';
782 }
783
784 class ActivityContext
785 {
786     public $replyToID;
787     public $replyToUrl;
788     public $location;
789     public $attention = array();
790     public $conversation;
791
792     const THR     = 'http://purl.org/syndication/thread/1.0';
793     const GEORSS  = 'http://www.georss.org/georss';
794     const OSTATUS = 'http://ostatus.org/schema/1.0';
795
796     const INREPLYTO = 'in-reply-to';
797     const REF       = 'ref';
798     const HREF      = 'href';
799
800     const POINT     = 'point';
801
802     const ATTENTION    = 'ostatus:attention';
803     const CONVERSATION = 'ostatus:conversation';
804
805     function __construct($element)
806     {
807         $replyToEl = ActivityUtils::child($element, self::INREPLYTO, self::THR);
808
809         if (!empty($replyToEl)) {
810             $this->replyToID  = $replyToEl->getAttribute(self::REF);
811             $this->replyToUrl = $replyToEl->getAttribute(self::HREF);
812         }
813
814         $this->location = $this->getLocation($element);
815
816         $this->conversation = ActivityUtils::getLink($element, self::CONVERSATION);
817
818         // Multiple attention links allowed
819
820         $links = $element->getElementsByTagNameNS(ActivityUtils::ATOM, ActivityUtils::LINK);
821
822         for ($i = 0; $i < $links->length; $i++) {
823
824             $link = $links->item($i);
825
826             $linkRel = $link->getAttribute(ActivityUtils::REL);
827
828             if ($linkRel == self::ATTENTION) {
829                 $this->attention[] = $link->getAttribute(self::HREF);
830             }
831         }
832     }
833
834     /**
835      * Parse location given as a GeoRSS-simple point, if provided.
836      * http://www.georss.org/simple
837      *
838      * @param feed item $entry
839      * @return mixed Location or false
840      */
841     function getLocation($dom)
842     {
843         $points = $dom->getElementsByTagNameNS(self::GEORSS, self::POINT);
844
845         for ($i = 0; $i < $points->length; $i++) {
846             $point = $points->item($i)->textContent;
847             return self::locationFromPoint($point);
848         }
849
850         return null;
851     }
852
853     // XXX: Move to ActivityUtils or Location?
854     static function locationFromPoint($point)
855     {
856         $point = str_replace(',', ' ', $point); // per spec "treat commas as whitespace"
857         $point = preg_replace('/\s+/', ' ', $point);
858         $point = trim($point);
859         $coords = explode(' ', $point);
860         if (count($coords) == 2) {
861             list($lat, $lon) = $coords;
862             if (is_numeric($lat) && is_numeric($lon)) {
863                 common_log(LOG_INFO, "Looking up location for $lat $lon from georss point");
864                 return Location::fromLatLon($lat, $lon);
865             }
866         }
867         common_log(LOG_ERR, "Ignoring bogus georss:point value $point");
868         return null;
869     }
870 }
871
872 /**
873  * An activity in the ActivityStrea.ms world
874  *
875  * An activity is kind of like a sentence: someone did something
876  * to something else.
877  *
878  * 'someone' is the 'actor'; 'did something' is the verb;
879  * 'something else' is the object.
880  *
881  * @category  OStatus
882  * @package   StatusNet
883  * @author    Evan Prodromou <evan@status.net>
884  * @copyright 2010 StatusNet, Inc.
885  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
886  * @link      http://status.net/
887  */
888
889 class Activity
890 {
891     const SPEC   = 'http://activitystrea.ms/spec/1.0/';
892     const SCHEMA = 'http://activitystrea.ms/schema/1.0/';
893
894     const VERB       = 'verb';
895     const OBJECT     = 'object';
896     const ACTOR      = 'actor';
897     const SUBJECT    = 'subject';
898     const OBJECTTYPE = 'object-type';
899     const CONTEXT    = 'context';
900     const TARGET     = 'target';
901
902     const ATOM = 'http://www.w3.org/2005/Atom';
903
904     const AUTHOR    = 'author';
905     const PUBLISHED = 'published';
906     const UPDATED   = 'updated';
907
908     public $actor;   // an ActivityObject
909     public $verb;    // a string (the URL)
910     public $object;  // an ActivityObject
911     public $target;  // an ActivityObject
912     public $context; // an ActivityObject
913     public $time;    // Time of the activity
914     public $link;    // an ActivityObject
915     public $entry;   // the source entry
916     public $feed;    // the source feed
917
918     public $summary; // summary of activity
919     public $content; // HTML content of activity
920     public $id;      // ID of the activity
921     public $title;   // title of the activity
922     public $categories = array(); // list of AtomCategory objects
923
924     /**
925      * Turns a regular old Atom <entry> into a magical activity
926      *
927      * @param DOMElement $entry Atom entry to poke at
928      * @param DOMElement $feed  Atom feed, for context
929      */
930
931     function __construct($entry = null, $feed = null)
932     {
933         if (is_null($entry)) {
934             return;
935         }
936
937         $this->entry = $entry;
938         $this->feed  = $feed;
939
940         $pubEl = $this->_child($entry, self::PUBLISHED, self::ATOM);
941
942         if (!empty($pubEl)) {
943             $this->time = strtotime($pubEl->textContent);
944         } else {
945             // XXX technically an error; being liberal. Good idea...?
946             $updateEl = $this->_child($entry, self::UPDATED, self::ATOM);
947             if (!empty($updateEl)) {
948                 $this->time = strtotime($updateEl->textContent);
949             } else {
950                 $this->time = null;
951             }
952         }
953
954         $this->link = ActivityUtils::getPermalink($entry);
955
956         $verbEl = $this->_child($entry, self::VERB);
957
958         if (!empty($verbEl)) {
959             $this->verb = trim($verbEl->textContent);
960         } else {
961             $this->verb = ActivityVerb::POST;
962             // XXX: do other implied stuff here
963         }
964
965         $objectEl = $this->_child($entry, self::OBJECT);
966
967         if (!empty($objectEl)) {
968             $this->object = new ActivityObject($objectEl);
969         } else {
970             $this->object = new ActivityObject($entry);
971         }
972
973         $actorEl = $this->_child($entry, self::ACTOR);
974
975         if (!empty($actorEl)) {
976
977             $this->actor = new ActivityObject($actorEl);
978
979         } else if (!empty($feed) &&
980                    $subjectEl = $this->_child($feed, self::SUBJECT)) {
981
982             $this->actor = new ActivityObject($subjectEl);
983
984         } else if ($authorEl = $this->_child($entry, self::AUTHOR, self::ATOM)) {
985
986             $this->actor = new ActivityObject($authorEl);
987
988         } else if (!empty($feed) && $authorEl = $this->_child($feed, self::AUTHOR,
989                                                               self::ATOM)) {
990
991             $this->actor = new ActivityObject($authorEl);
992         }
993
994         $contextEl = $this->_child($entry, self::CONTEXT);
995
996         if (!empty($contextEl)) {
997             $this->context = new ActivityContext($contextEl);
998         } else {
999             $this->context = new ActivityContext($entry);
1000         }
1001
1002         $targetEl = $this->_child($entry, self::TARGET);
1003
1004         if (!empty($targetEl)) {
1005             $this->target = new ActivityObject($targetEl);
1006         }
1007
1008         $this->summary = ActivityUtils::childContent($entry, 'summary');
1009         $this->id      = ActivityUtils::childContent($entry, 'id');
1010         $this->content = ActivityUtils::getContent($entry);
1011
1012         $catEls = $entry->getElementsByTagNameNS(self::ATOM, 'category');
1013         if ($catEls) {
1014             for ($i = 0; $i < $catEls->length; $i++) {
1015                 $catEl = $catEls->item($i);
1016                 $this->categories[] = new AtomCategory($catEl);
1017             }
1018         }
1019     }
1020
1021     /**
1022      * Returns an Atom <entry> based on this activity
1023      *
1024      * @return DOMElement Atom entry
1025      */
1026
1027     function toAtomEntry()
1028     {
1029         return null;
1030     }
1031
1032     function asString($namespace=false)
1033     {
1034         $xs = new XMLStringer(true);
1035
1036         if ($namespace) {
1037             $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1038                            'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
1039                            'xmlns:georss' => 'http://www.georss.org/georss',
1040                            'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
1041                            'xmlns:poco' => 'http://portablecontacts.net/spec/1.0');
1042         } else {
1043             $attrs = array();
1044         }
1045
1046         $xs->elementStart('entry', $attrs);
1047
1048         $xs->element('id', null, $this->id);
1049         $xs->element('title', null, $this->title);
1050         $xs->element('published', null, common_date_iso8601($this->time));
1051         $xs->element('content', array('type' => 'html'), $this->content);
1052
1053         if (!empty($this->summary)) {
1054             $xs->element('summary', null, $this->summary);
1055         }
1056
1057         if (!empty($this->link)) {
1058             $xs->element('link', array('rel' => 'alternate',
1059                                        'type' => 'text/html'),
1060                          $this->link);
1061         }
1062
1063         // XXX: add context
1064
1065         $xs->elementStart('author');
1066         $xs->element('uri', array(), $this->actor->id);
1067         if ($this->actor->title) {
1068             $xs->element('name', array(), $this->actor->title);
1069         }
1070         $xs->elementEnd('author');
1071         $xs->raw($this->actor->asString('activity:actor'));
1072
1073         $xs->element('activity:verb', null, $this->verb);
1074
1075         if ($this->object) {
1076             $xs->raw($this->object->asString());
1077         }
1078
1079         if ($this->target) {
1080             $xs->raw($this->target->asString('activity:target'));
1081         }
1082
1083         foreach ($this->categories as $cat) {
1084             $xs->raw($cat->asString());
1085         }
1086
1087         $xs->elementEnd('entry');
1088
1089         return $xs->getString();
1090     }
1091
1092     private function _child($element, $tag, $namespace=self::SPEC)
1093     {
1094         return ActivityUtils::child($element, $tag, $namespace);
1095     }
1096 }
1097
1098 class AtomCategory
1099 {
1100     public $term;
1101     public $scheme;
1102     public $label;
1103
1104     function __construct($element=null)
1105     {
1106         if ($element && $element->attributes) {
1107             $this->term = $this->extract($element, 'term');
1108             $this->scheme = $this->extract($element, 'scheme');
1109             $this->label = $this->extract($element, 'label');
1110         }
1111     }
1112
1113     protected function extract($element, $attrib)
1114     {
1115         $node = $element->attributes->getNamedItemNS(Activity::ATOM, $attrib);
1116         if ($node) {
1117             return trim($node->textContent);
1118         }
1119         $node = $element->attributes->getNamedItem($attrib);
1120         if ($node) {
1121             return trim($node->textContent);
1122         }
1123         return null;
1124     }
1125
1126     function asString()
1127     {
1128         $attribs = array();
1129         if ($this->term !== null) {
1130             $attribs['term'] = $this->term;
1131         }
1132         if ($this->scheme !== null) {
1133             $attribs['scheme'] = $this->scheme;
1134         }
1135         if ($this->label !== null) {
1136             $attribs['label'] = $this->label;
1137         }
1138         $xs = new XMLStringer();
1139         $xs->element('category', $attribs);
1140         return $xs->asString();
1141     }
1142 }