]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/activity.php
Merge branch 'testing' into 0.9.x
[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     static function getLinks(DOMNode $element, $rel, $type=null)
364     {
365         $links = $element->getElementsByTagnameNS(self::ATOM, self::LINK);
366         $out = array();
367
368         foreach ($links as $link) {
369
370             $linkRel = $link->getAttribute(self::REL);
371             $linkType = $link->getAttribute(self::TYPE);
372
373             if ($linkRel == $rel &&
374                 (is_null($type) || $linkType == $type)) {
375                 $out[] = $link;
376             }
377         }
378
379         return $out;
380     }
381
382     /**
383      * Gets the first child element with the given tag
384      *
385      * @param DOMElement $element   element to pick at
386      * @param string     $tag       tag to look for
387      * @param string     $namespace Namespace to look under
388      *
389      * @return DOMElement found element or null
390      */
391
392     static function child(DOMNode $element, $tag, $namespace=self::ATOM)
393     {
394         $els = $element->childNodes;
395         if (empty($els) || $els->length == 0) {
396             return null;
397         } else {
398             for ($i = 0; $i < $els->length; $i++) {
399                 $el = $els->item($i);
400                 if ($el->localName == $tag && $el->namespaceURI == $namespace) {
401                     return $el;
402                 }
403             }
404         }
405     }
406
407     /**
408      * Grab the text content of a DOM element child of the current element
409      *
410      * @param DOMElement $element   Element whose children we examine
411      * @param string     $tag       Tag to look up
412      * @param string     $namespace Namespace to use, defaults to Atom
413      *
414      * @return string content of the child
415      */
416
417     static function childContent(DOMNode $element, $tag, $namespace=self::ATOM)
418     {
419         $el = self::child($element, $tag, $namespace);
420
421         if (empty($el)) {
422             return null;
423         } else {
424             return $el->textContent;
425         }
426     }
427
428     /**
429      * Get the content of an atom:entry-like object
430      *
431      * @param DOMElement $element The element to examine.
432      *
433      * @return string unencoded HTML content of the element, like "This -&lt; is <b>HTML</b>."
434      *
435      * @todo handle remote content
436      * @todo handle embedded XML mime types
437      * @todo handle base64-encoded non-XML and non-text mime types
438      */
439
440     static function getContent($element)
441     {
442         $contentEl = ActivityUtils::child($element, self::CONTENT);
443
444         if (!empty($contentEl)) {
445
446             $src  = $contentEl->getAttribute(self::SRC);
447
448             if (!empty($src)) {
449                 throw new ClientException(_("Can't handle remote content yet."));
450             }
451
452             $type = $contentEl->getAttribute(self::TYPE);
453
454             // slavishly following http://atompub.org/rfc4287.html#rfc.section.4.1.3.3
455
456             if ($type == 'text') {
457                 return $contentEl->textContent;
458             } else if ($type == 'html') {
459                 $text = $contentEl->textContent;
460                 return htmlspecialchars_decode($text, ENT_QUOTES);
461             } else if ($type == 'xhtml') {
462                 $divEl = ActivityUtils::child($contentEl, 'div');
463                 if (empty($divEl)) {
464                     return null;
465                 }
466                 $doc = $divEl->ownerDocument;
467                 $text = '';
468                 $children = $divEl->childNodes;
469
470                 for ($i = 0; $i < $children->length; $i++) {
471                     $child = $children->item($i);
472                     $text .= $doc->saveXML($child);
473                 }
474                 return trim($text);
475             } else if (in_array(array('text/xml', 'application/xml'), $type) ||
476                        preg_match('#(+|/)xml$#', $type)) {
477                 throw new ClientException(_("Can't handle embedded XML content yet."));
478             } else if (strncasecmp($type, 'text/', 5)) {
479                 return $contentEl->textContent;
480             } else {
481                 throw new ClientException(_("Can't handle embedded Base64 content yet."));
482             }
483         }
484     }
485 }
486
487 // XXX: Arg! This wouldn't be necessary if we used Avatars conistently
488 class AvatarLink
489 {
490     public $url;
491     public $type;
492     public $size;
493     public $width;
494     public $height;
495
496     function __construct($element=null)
497     {
498         if ($element) {
499             // @fixme use correct namespaces
500             $this->url = $element->getAttribute('href');
501             $this->type = $element->getAttribute('type');
502             $width = $element->getAttribute('media:width');
503             if ($width != null) {
504                 $this->width = intval($width);
505             }
506             $height = $element->getAttribute('media:height');
507             if ($height != null) {
508                 $this->height = intval($height);
509             }
510         }
511     }
512
513     static function fromAvatar($avatar)
514     {
515         if (empty($avatar)) {
516             return null;
517         }
518         $alink = new AvatarLink();
519         $alink->type   = $avatar->mediatype;
520         $alink->height = $avatar->height;
521         $alink->width  = $avatar->width;
522         $alink->url    = $avatar->displayUrl();
523         return $alink;
524     }
525
526     static function fromFilename($filename, $size)
527     {
528         $alink = new AvatarLink();
529         $alink->url    = $filename;
530         $alink->height = $size;
531         if (!empty($filename)) {
532             $alink->width  = $size;
533             $alink->type   = self::mediatype($filename);
534         } else {
535             $alink->url    = User_group::defaultLogo($size);
536             $alink->type   = 'image/png';
537         }
538         return $alink;
539     }
540
541     // yuck!
542     static function mediatype($filename) {
543         $ext = strtolower(end(explode('.', $filename)));
544         if ($ext == 'jpeg') {
545             $ext = 'jpg';
546         }
547         // hope we don't support any others
548         $types = array('png', 'gif', 'jpg', 'jpeg');
549         if (in_array($ext, $types)) {
550             return 'image/' . $ext;
551         }
552         return null;
553     }
554 }
555
556 /**
557  * A noun-ish thing in the activity universe
558  *
559  * The activity streams spec talks about activity objects, while also having
560  * a tag activity:object, which is in fact an activity object. Aaaaaah!
561  *
562  * This is just a thing in the activity universe. Can be the subject, object,
563  * or indirect object (target!) of an activity verb. Rotten name, and I'm
564  * propagating it. *sigh*
565  *
566  * @category  OStatus
567  * @package   StatusNet
568  * @author    Evan Prodromou <evan@status.net>
569  * @copyright 2010 StatusNet, Inc.
570  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
571  * @link      http://status.net/
572  */
573
574 class ActivityObject
575 {
576     const ARTICLE   = 'http://activitystrea.ms/schema/1.0/article';
577     const BLOGENTRY = 'http://activitystrea.ms/schema/1.0/blog-entry';
578     const NOTE      = 'http://activitystrea.ms/schema/1.0/note';
579     const STATUS    = 'http://activitystrea.ms/schema/1.0/status';
580     const FILE      = 'http://activitystrea.ms/schema/1.0/file';
581     const PHOTO     = 'http://activitystrea.ms/schema/1.0/photo';
582     const ALBUM     = 'http://activitystrea.ms/schema/1.0/photo-album';
583     const PLAYLIST  = 'http://activitystrea.ms/schema/1.0/playlist';
584     const VIDEO     = 'http://activitystrea.ms/schema/1.0/video';
585     const AUDIO     = 'http://activitystrea.ms/schema/1.0/audio';
586     const BOOKMARK  = 'http://activitystrea.ms/schema/1.0/bookmark';
587     const PERSON    = 'http://activitystrea.ms/schema/1.0/person';
588     const GROUP     = 'http://activitystrea.ms/schema/1.0/group';
589     const PLACE     = 'http://activitystrea.ms/schema/1.0/place';
590     const COMMENT   = 'http://activitystrea.ms/schema/1.0/comment';
591     // ^^^^^^^^^^ tea!
592
593     // Atom elements we snarf
594
595     const TITLE   = 'title';
596     const SUMMARY = 'summary';
597     const ID      = 'id';
598     const SOURCE  = 'source';
599
600     const NAME  = 'name';
601     const URI   = 'uri';
602     const EMAIL = 'email';
603
604     public $element;
605     public $type;
606     public $id;
607     public $title;
608     public $summary;
609     public $content;
610     public $link;
611     public $source;
612     public $avatarLinks = array();
613     public $geopoint;
614     public $poco;
615     public $displayName;
616
617     /**
618      * Constructor
619      *
620      * This probably needs to be refactored
621      * to generate a local class (ActivityPerson, ActivityFile, ...)
622      * based on the object type.
623      *
624      * @param DOMElement $element DOM thing to turn into an Activity thing
625      */
626
627     function __construct($element = null)
628     {
629         if (empty($element)) {
630             return;
631         }
632
633         $this->element = $element;
634
635         $this->geopoint = $this->_childContent(
636             $element,
637             ActivityContext::POINT,
638             ActivityContext::GEORSS
639         );
640
641         if ($element->tagName == 'author') {
642
643             $this->type  = self::PERSON; // XXX: is this fair?
644             $this->title = $this->_childContent($element, self::NAME);
645             $this->id    = $this->_childContent($element, self::URI);
646
647             if (empty($this->id)) {
648                 $email = $this->_childContent($element, self::EMAIL);
649                 if (!empty($email)) {
650                     // XXX: acct: ?
651                     $this->id = 'mailto:'.$email;
652                 }
653             }
654
655         } else {
656
657             $this->type = $this->_childContent($element, Activity::OBJECTTYPE,
658                                                Activity::SPEC);
659
660             if (empty($this->type)) {
661                 $this->type = ActivityObject::NOTE;
662             }
663
664             $this->id      = $this->_childContent($element, self::ID);
665             $this->title   = $this->_childContent($element, self::TITLE);
666             $this->summary = $this->_childContent($element, self::SUMMARY);
667
668             $this->source  = $this->_getSource($element);
669
670             $this->content = ActivityUtils::getContent($element);
671
672             $this->link = ActivityUtils::getPermalink($element);
673
674         }
675
676         // Some per-type attributes...
677         if ($this->type == self::PERSON || $this->type == self::GROUP) {
678             $this->displayName = $this->title;
679
680             $avatars = ActivityUtils::getLinks($element, 'avatar');
681             foreach ($avatars as $link) {
682                 $this->avatarLinks[] = new AvatarLink($link);
683             }
684
685             $this->poco = new PoCo($element);
686         }
687     }
688
689     private function _childContent($element, $tag, $namespace=ActivityUtils::ATOM)
690     {
691         return ActivityUtils::childContent($element, $tag, $namespace);
692     }
693
694     // Try to get a unique id for the source feed
695
696     private function _getSource($element)
697     {
698         $sourceEl = ActivityUtils::child($element, 'source');
699
700         if (empty($sourceEl)) {
701             return null;
702         } else {
703             $href = ActivityUtils::getLink($sourceEl, 'self');
704             if (!empty($href)) {
705                 return $href;
706             } else {
707                 return ActivityUtils::childContent($sourceEl, 'id');
708             }
709         }
710     }
711
712     static function fromNotice($notice)
713     {
714         $object = new ActivityObject();
715
716         $object->type    = ActivityObject::NOTE;
717
718         $object->id      = $notice->uri;
719         $object->title   = $notice->content;
720         $object->content = $notice->rendered;
721         $object->link    = $notice->bestUrl();
722
723         return $object;
724     }
725
726     static function fromProfile($profile)
727     {
728         $object = new ActivityObject();
729
730         $object->type   = ActivityObject::PERSON;
731         $object->id     = $profile->getUri();
732         $object->title  = $profile->getBestName();
733         $object->link   = $profile->profileurl;
734
735         $orig = $profile->getOriginalAvatar();
736
737         if (!empty($orig)) {
738             $object->avatarLinks[] = AvatarLink::fromAvatar($orig);
739         }
740
741         $sizes = array(
742             AVATAR_PROFILE_SIZE,
743             AVATAR_STREAM_SIZE,
744             AVATAR_MINI_SIZE
745         );
746
747         foreach ($sizes as $size) {
748
749             $alink  = null;
750             $avatar = $profile->getAvatar($size);
751
752             if (!empty($avatar)) {
753                 $alink = AvatarLink::fromAvatar($avatar);
754             } else {
755                 $alink = new AvatarLink();
756                 $alink->type   = 'image/png';
757                 $alink->height = $size;
758                 $alink->width  = $size;
759                 $alink->url    = Avatar::defaultImage($size);
760             }
761
762             $object->avatarLinks[] = $alink;
763         }
764
765         if (isset($profile->lat) && isset($profile->lon)) {
766             $object->geopoint = (float)$profile->lat
767                 . ' ' . (float)$profile->lon;
768         }
769
770         $object->poco = PoCo::fromProfile($profile);
771
772         return $object;
773     }
774
775     static function fromGroup($group)
776     {
777         $object = new ActivityObject();
778
779         $object->type   = ActivityObject::GROUP;
780         $object->id     = $group->getUri();
781         $object->title  = $group->getBestName();
782         $object->link   = $group->getUri();
783
784         $object->avatarLinks[] = AvatarLink::fromFilename(
785             $group->homepage_logo,
786             AVATAR_PROFILE_SIZE
787         );
788
789         $object->avatarLinks[] = AvatarLink::fromFilename(
790             $group->stream_logo,
791             AVATAR_STREAM_SIZE
792         );
793
794         $object->avatarLinks[] = AvatarLink::fromFilename(
795             $group->mini_logo,
796             AVATAR_MINI_SIZE
797         );
798
799         $object->poco = PoCo::fromGroup($group);
800
801         return $object;
802     }
803
804
805     function asString($tag='activity:object')
806     {
807         $xs = new XMLStringer(true);
808
809         $xs->elementStart($tag);
810
811         $xs->element('activity:object-type', null, $this->type);
812
813         $xs->element(self::ID, null, $this->id);
814
815         if (!empty($this->title)) {
816             $xs->element(self::TITLE, null, $this->title);
817         }
818
819         if (!empty($this->summary)) {
820             $xs->element(self::SUMMARY, null, $this->summary);
821         }
822
823         if (!empty($this->content)) {
824             // XXX: assuming HTML content here
825             $xs->element(ActivityUtils::CONTENT, array('type' => 'html'), $this->content);
826         }
827
828         if (!empty($this->link)) {
829             $xs->element(
830                 'link',
831                 array(
832                     'rel' => 'alternate',
833                     'type' => 'text/html',
834                     'href' => $this->link
835                 ),
836                 null
837             );
838         }
839
840         if ($this->type == ActivityObject::PERSON
841             || $this->type == ActivityObject::GROUP) {
842
843             foreach ($this->avatarLinks as $avatar) {
844                 $xs->element(
845                     'link', array(
846                         'rel'  => 'avatar',
847                         'type'         => $avatar->type,
848                         'media:width'  => $avatar->width,
849                         'media:height' => $avatar->height,
850                         'href' => $avatar->url
851                     ),
852                     null
853                 );
854             }
855         }
856
857         if (!empty($this->geopoint)) {
858             $xs->element(
859                 'georss:point',
860                 null,
861                 $this->geopoint
862             );
863         }
864
865         if (!empty($this->poco)) {
866             $xs->raw($this->poco->asString());
867         }
868
869         $xs->elementEnd($tag);
870
871         return $xs->getString();
872     }
873 }
874
875 /**
876  * Utility class to hold a bunch of constant defining default verb types
877  *
878  * @category  OStatus
879  * @package   StatusNet
880  * @author    Evan Prodromou <evan@status.net>
881  * @copyright 2010 StatusNet, Inc.
882  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
883  * @link      http://status.net/
884  */
885
886 class ActivityVerb
887 {
888     const POST     = 'http://activitystrea.ms/schema/1.0/post';
889     const SHARE    = 'http://activitystrea.ms/schema/1.0/share';
890     const SAVE     = 'http://activitystrea.ms/schema/1.0/save';
891     const FAVORITE = 'http://activitystrea.ms/schema/1.0/favorite';
892     const PLAY     = 'http://activitystrea.ms/schema/1.0/play';
893     const FOLLOW   = 'http://activitystrea.ms/schema/1.0/follow';
894     const FRIEND   = 'http://activitystrea.ms/schema/1.0/make-friend';
895     const JOIN     = 'http://activitystrea.ms/schema/1.0/join';
896     const TAG      = 'http://activitystrea.ms/schema/1.0/tag';
897
898     // Custom OStatus verbs for the flipside until they're standardized
899     const DELETE     = 'http://ostatus.org/schema/1.0/unfollow';
900     const UNFAVORITE = 'http://ostatus.org/schema/1.0/unfavorite';
901     const UNFOLLOW   = 'http://ostatus.org/schema/1.0/unfollow';
902     const LEAVE      = 'http://ostatus.org/schema/1.0/leave';
903
904     // For simple profile-update pings; no content to share.
905     const UPDATE_PROFILE = 'http://ostatus.org/schema/1.0/update-profile';
906 }
907
908 class ActivityContext
909 {
910     public $replyToID;
911     public $replyToUrl;
912     public $location;
913     public $attention = array();
914     public $conversation;
915
916     const THR     = 'http://purl.org/syndication/thread/1.0';
917     const GEORSS  = 'http://www.georss.org/georss';
918     const OSTATUS = 'http://ostatus.org/schema/1.0';
919
920     const INREPLYTO = 'in-reply-to';
921     const REF       = 'ref';
922     const HREF      = 'href';
923
924     const POINT     = 'point';
925
926     const ATTENTION    = 'ostatus:attention';
927     const CONVERSATION = 'ostatus:conversation';
928
929     function __construct($element)
930     {
931         $replyToEl = ActivityUtils::child($element, self::INREPLYTO, self::THR);
932
933         if (!empty($replyToEl)) {
934             $this->replyToID  = $replyToEl->getAttribute(self::REF);
935             $this->replyToUrl = $replyToEl->getAttribute(self::HREF);
936         }
937
938         $this->location = $this->getLocation($element);
939
940         $this->conversation = ActivityUtils::getLink($element, self::CONVERSATION);
941
942         // Multiple attention links allowed
943
944         $links = $element->getElementsByTagNameNS(ActivityUtils::ATOM, ActivityUtils::LINK);
945
946         for ($i = 0; $i < $links->length; $i++) {
947
948             $link = $links->item($i);
949
950             $linkRel = $link->getAttribute(ActivityUtils::REL);
951
952             if ($linkRel == self::ATTENTION) {
953                 $this->attention[] = $link->getAttribute(self::HREF);
954             }
955         }
956     }
957
958     /**
959      * Parse location given as a GeoRSS-simple point, if provided.
960      * http://www.georss.org/simple
961      *
962      * @param feed item $entry
963      * @return mixed Location or false
964      */
965     function getLocation($dom)
966     {
967         $points = $dom->getElementsByTagNameNS(self::GEORSS, self::POINT);
968
969         for ($i = 0; $i < $points->length; $i++) {
970             $point = $points->item($i)->textContent;
971             return self::locationFromPoint($point);
972         }
973
974         return null;
975     }
976
977     // XXX: Move to ActivityUtils or Location?
978     static function locationFromPoint($point)
979     {
980         $point = str_replace(',', ' ', $point); // per spec "treat commas as whitespace"
981         $point = preg_replace('/\s+/', ' ', $point);
982         $point = trim($point);
983         $coords = explode(' ', $point);
984         if (count($coords) == 2) {
985             list($lat, $lon) = $coords;
986             if (is_numeric($lat) && is_numeric($lon)) {
987                 common_log(LOG_INFO, "Looking up location for $lat $lon from georss point");
988                 return Location::fromLatLon($lat, $lon);
989             }
990         }
991         common_log(LOG_ERR, "Ignoring bogus georss:point value $point");
992         return null;
993     }
994 }
995
996 /**
997  * An activity in the ActivityStrea.ms world
998  *
999  * An activity is kind of like a sentence: someone did something
1000  * to something else.
1001  *
1002  * 'someone' is the 'actor'; 'did something' is the verb;
1003  * 'something else' is the object.
1004  *
1005  * @category  OStatus
1006  * @package   StatusNet
1007  * @author    Evan Prodromou <evan@status.net>
1008  * @copyright 2010 StatusNet, Inc.
1009  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
1010  * @link      http://status.net/
1011  */
1012
1013 class Activity
1014 {
1015     const SPEC   = 'http://activitystrea.ms/spec/1.0/';
1016     const SCHEMA = 'http://activitystrea.ms/schema/1.0/';
1017
1018     const VERB       = 'verb';
1019     const OBJECT     = 'object';
1020     const ACTOR      = 'actor';
1021     const SUBJECT    = 'subject';
1022     const OBJECTTYPE = 'object-type';
1023     const CONTEXT    = 'context';
1024     const TARGET     = 'target';
1025
1026     const ATOM = 'http://www.w3.org/2005/Atom';
1027
1028     const AUTHOR    = 'author';
1029     const PUBLISHED = 'published';
1030     const UPDATED   = 'updated';
1031
1032     public $actor;   // an ActivityObject
1033     public $verb;    // a string (the URL)
1034     public $object;  // an ActivityObject
1035     public $target;  // an ActivityObject
1036     public $context; // an ActivityObject
1037     public $time;    // Time of the activity
1038     public $link;    // an ActivityObject
1039     public $entry;   // the source entry
1040     public $feed;    // the source feed
1041
1042     public $summary; // summary of activity
1043     public $content; // HTML content of activity
1044     public $id;      // ID of the activity
1045     public $title;   // title of the activity
1046     public $categories = array(); // list of AtomCategory objects
1047
1048     /**
1049      * Turns a regular old Atom <entry> into a magical activity
1050      *
1051      * @param DOMElement $entry Atom entry to poke at
1052      * @param DOMElement $feed  Atom feed, for context
1053      */
1054
1055     function __construct($entry = null, $feed = null)
1056     {
1057         if (is_null($entry)) {
1058             return;
1059         }
1060
1061         $this->entry = $entry;
1062         $this->feed  = $feed;
1063
1064         $pubEl = $this->_child($entry, self::PUBLISHED, self::ATOM);
1065
1066         if (!empty($pubEl)) {
1067             $this->time = strtotime($pubEl->textContent);
1068         } else {
1069             // XXX technically an error; being liberal. Good idea...?
1070             $updateEl = $this->_child($entry, self::UPDATED, self::ATOM);
1071             if (!empty($updateEl)) {
1072                 $this->time = strtotime($updateEl->textContent);
1073             } else {
1074                 $this->time = null;
1075             }
1076         }
1077
1078         $this->link = ActivityUtils::getPermalink($entry);
1079
1080         $verbEl = $this->_child($entry, self::VERB);
1081
1082         if (!empty($verbEl)) {
1083             $this->verb = trim($verbEl->textContent);
1084         } else {
1085             $this->verb = ActivityVerb::POST;
1086             // XXX: do other implied stuff here
1087         }
1088
1089         $objectEl = $this->_child($entry, self::OBJECT);
1090
1091         if (!empty($objectEl)) {
1092             $this->object = new ActivityObject($objectEl);
1093         } else {
1094             $this->object = new ActivityObject($entry);
1095         }
1096
1097         $actorEl = $this->_child($entry, self::ACTOR);
1098
1099         if (!empty($actorEl)) {
1100
1101             $this->actor = new ActivityObject($actorEl);
1102
1103         } else if (!empty($feed) &&
1104                    $subjectEl = $this->_child($feed, self::SUBJECT)) {
1105
1106             $this->actor = new ActivityObject($subjectEl);
1107
1108         } else if ($authorEl = $this->_child($entry, self::AUTHOR, self::ATOM)) {
1109
1110             $this->actor = new ActivityObject($authorEl);
1111
1112         } else if (!empty($feed) && $authorEl = $this->_child($feed, self::AUTHOR,
1113                                                               self::ATOM)) {
1114
1115             $this->actor = new ActivityObject($authorEl);
1116         }
1117
1118         $contextEl = $this->_child($entry, self::CONTEXT);
1119
1120         if (!empty($contextEl)) {
1121             $this->context = new ActivityContext($contextEl);
1122         } else {
1123             $this->context = new ActivityContext($entry);
1124         }
1125
1126         $targetEl = $this->_child($entry, self::TARGET);
1127
1128         if (!empty($targetEl)) {
1129             $this->target = new ActivityObject($targetEl);
1130         }
1131
1132         $this->summary = ActivityUtils::childContent($entry, 'summary');
1133         $this->id      = ActivityUtils::childContent($entry, 'id');
1134         $this->content = ActivityUtils::getContent($entry);
1135
1136         $catEls = $entry->getElementsByTagNameNS(self::ATOM, 'category');
1137         if ($catEls) {
1138             for ($i = 0; $i < $catEls->length; $i++) {
1139                 $catEl = $catEls->item($i);
1140                 $this->categories[] = new AtomCategory($catEl);
1141             }
1142         }
1143     }
1144
1145     /**
1146      * Returns an Atom <entry> based on this activity
1147      *
1148      * @return DOMElement Atom entry
1149      */
1150
1151     function toAtomEntry()
1152     {
1153         return null;
1154     }
1155
1156     function asString($namespace=false)
1157     {
1158         $xs = new XMLStringer(true);
1159
1160         if ($namespace) {
1161             $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1162                            'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
1163                            'xmlns:georss' => 'http://www.georss.org/georss',
1164                            'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
1165                            'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
1166                            'xmlns:media' => 'http://purl.org/syndication/atommedia');
1167         } else {
1168             $attrs = array();
1169         }
1170
1171         $xs->elementStart('entry', $attrs);
1172
1173         $xs->element('id', null, $this->id);
1174         $xs->element('title', null, $this->title);
1175         $xs->element('published', null, common_date_iso8601($this->time));
1176         $xs->element('content', array('type' => 'html'), $this->content);
1177
1178         if (!empty($this->summary)) {
1179             $xs->element('summary', null, $this->summary);
1180         }
1181
1182         if (!empty($this->link)) {
1183             $xs->element('link', array('rel' => 'alternate',
1184                                        'type' => 'text/html'),
1185                          $this->link);
1186         }
1187
1188         // XXX: add context
1189
1190         $xs->elementStart('author');
1191         $xs->element('uri', array(), $this->actor->id);
1192         if ($this->actor->title) {
1193             $xs->element('name', array(), $this->actor->title);
1194         }
1195         $xs->elementEnd('author');
1196         $xs->raw($this->actor->asString('activity:actor'));
1197
1198         $xs->element('activity:verb', null, $this->verb);
1199
1200         if ($this->object) {
1201             $xs->raw($this->object->asString());
1202         }
1203
1204         if ($this->target) {
1205             $xs->raw($this->target->asString('activity:target'));
1206         }
1207
1208         foreach ($this->categories as $cat) {
1209             $xs->raw($cat->asString());
1210         }
1211
1212         $xs->elementEnd('entry');
1213
1214         return $xs->getString();
1215     }
1216
1217     private function _child($element, $tag, $namespace=self::SPEC)
1218     {
1219         return ActivityUtils::child($element, $tag, $namespace);
1220     }
1221 }
1222
1223 class AtomCategory
1224 {
1225     public $term;
1226     public $scheme;
1227     public $label;
1228
1229     function __construct($element=null)
1230     {
1231         if ($element && $element->attributes) {
1232             $this->term = $this->extract($element, 'term');
1233             $this->scheme = $this->extract($element, 'scheme');
1234             $this->label = $this->extract($element, 'label');
1235         }
1236     }
1237
1238     protected function extract($element, $attrib)
1239     {
1240         $node = $element->attributes->getNamedItemNS(Activity::ATOM, $attrib);
1241         if ($node) {
1242             return trim($node->textContent);
1243         }
1244         $node = $element->attributes->getNamedItem($attrib);
1245         if ($node) {
1246             return trim($node->textContent);
1247         }
1248         return null;
1249     }
1250
1251     function asString()
1252     {
1253         $attribs = array();
1254         if ($this->term !== null) {
1255             $attribs['term'] = $this->term;
1256         }
1257         if ($this->scheme !== null) {
1258             $attribs['scheme'] = $this->scheme;
1259         }
1260         if ($this->label !== null) {
1261             $attribs['label'] = $this->label;
1262         }
1263         $xs = new XMLStringer();
1264         $xs->element('category', $attribs);
1265         return $xs->asString();
1266     }
1267 }