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