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