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