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