]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/activityobject.php
[XML/HTML Outputter] General improvements and refactoring as well as some bug fixes
[quix0rs-gnu-social.git] / lib / activityobject.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('GNUSOCIAL')) {
32     exit(1);
33 }
34
35 require_once(INSTALLDIR . '/lib/activitystreamjsondocument.php');
36
37 /**
38  * A noun-ish thing in the activity universe
39  *
40  * The activity streams spec talks about activity objects, while also having
41  * a tag activity:object, which is in fact an activity object. Aaaaaah!
42  *
43  * This is just a thing in the activity universe. Can be the subject, object,
44  * or indirect object (target!) of an activity verb. Rotten name, and I'm
45  * propagating it. *sigh*
46  *
47  * @category  OStatus
48  * @package   StatusNet
49  * @author    Evan Prodromou <evan@status.net>
50  * @copyright 2010 StatusNet, Inc.
51  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
52  * @link      http://status.net/
53  */
54 class ActivityObject
55 {
56     const ARTICLE     = 'http://activitystrea.ms/schema/1.0/article';
57     const BLOGENTRY   = 'http://activitystrea.ms/schema/1.0/blog-entry';
58     const NOTE        = 'http://activitystrea.ms/schema/1.0/note';
59     const STATUS      = 'http://activitystrea.ms/schema/1.0/status';
60     const FILE        = 'http://activitystrea.ms/schema/1.0/file';
61     const PHOTO       = 'http://activitystrea.ms/schema/1.0/photo';
62     const ALBUM       = 'http://activitystrea.ms/schema/1.0/photo-album';
63     const PLAYLIST    = 'http://activitystrea.ms/schema/1.0/playlist';
64     const VIDEO       = 'http://activitystrea.ms/schema/1.0/video';
65     const AUDIO       = 'http://activitystrea.ms/schema/1.0/audio';
66     const BOOKMARK    = 'http://activitystrea.ms/schema/1.0/bookmark';
67     const PERSON      = 'http://activitystrea.ms/schema/1.0/person';
68     const GROUP       = 'http://activitystrea.ms/schema/1.0/group';
69     const _LIST       = 'http://activitystrea.ms/schema/1.0/list'; // LIST is reserved
70     const PLACE       = 'http://activitystrea.ms/schema/1.0/place';
71     const COMMENT     = 'http://activitystrea.ms/schema/1.0/comment';
72     // ^^^^^^^^^^ tea!
73     const ACTIVITY    = 'http://activitystrea.ms/schema/1.0/activity';
74     const SERVICE     = 'http://activitystrea.ms/schema/1.0/service';
75     const IMAGE       = 'http://activitystrea.ms/schema/1.0/image';
76     const COLLECTION  = 'http://activitystrea.ms/schema/1.0/collection';
77     const APPLICATION = 'http://activitystrea.ms/schema/1.0/application';
78
79     // Atom elements we snarf
80
81     const TITLE = 'title';
82     const SUMMARY = 'summary';
83     const ID = 'id';
84     const SOURCE = 'source';
85
86     const NAME = 'name';
87     const URI = 'uri';
88     const EMAIL = 'email';
89
90     const POSTEROUS = 'http://posterous.com/help/rss/1.0';
91     const AUTHOR = 'author';
92     const USERIMAGE = 'userImage';
93     const PROFILEURL = 'profileUrl';
94     const NICKNAME = 'nickName';
95     const DISPLAYNAME = 'displayName';
96     const MEDIA_DESCRIPTION = 'description';
97     public $element;
98     public $type;
99     public $id;
100     public $title;
101     public $summary;
102     public $content;
103     public $owner;
104     public $link;   // think APP (Atom Publishing Protocol)
105     public $selfLink;
106     public $source;
107     public $avatarLinks = [];
108     public $geopoint;
109     public $poco;
110
111     // @todo move this stuff to it's own PHOTO activity object
112     public $displayName;
113     public $thumbnail;
114     public $largerImage;
115     public $description;
116     public $extra = [];
117
118     public $stream;
119
120     /**
121      * Constructor
122      *
123      * This probably needs to be refactored
124      * to generate a local class (ActivityPerson, ActivityFile, ...)
125      * based on the object type.
126      *
127      * @param DOMElement $element DOM thing to turn into an Activity thing
128      */
129     public function __construct($element = null)
130     {
131         if (empty($element)) {
132             return;
133         }
134
135         $this->element = $element;
136
137         $this->geopoint = $this->_childContent(
138             $element,
139             ActivityContext::POINT,
140             ActivityContext::GEORSS
141         );
142
143         if ($element->tagName == 'author') {
144             $this->_fromAuthor($element);
145         } elseif ($element->tagName == 'item') {
146             $this->_fromRssItem($element);
147         } else {
148             $this->_fromAtomEntry($element);
149         }
150
151         // Some per-type attributes...
152         if ($this->type == self::PERSON || $this->type == self::GROUP) {
153             $this->displayName = $this->title;
154
155             $photos = ActivityUtils::getLinks($element, 'photo');
156             if (count($photos)) {
157                 foreach ($photos as $link) {
158                     $this->avatarLinks[] = new AvatarLink($link);
159                 }
160             } else {
161                 $avatars = ActivityUtils::getLinks($element, 'avatar');
162                 foreach ($avatars as $link) {
163                     $this->avatarLinks[] = new AvatarLink($link);
164                 }
165             }
166
167             $this->poco = new PoCo($element);
168         }
169
170         if ($this->type == self::PHOTO) {
171             $this->thumbnail = ActivityUtils::getLink($element, 'preview');
172             $this->largerImage = ActivityUtils::getLink($element, 'enclosure');
173
174             $this->description = ActivityUtils::childContent(
175                 $element,
176                 ActivityObject::MEDIA_DESCRIPTION,
177                 Activity::MEDIA
178             );
179         }
180         if ($this->type == self::_LIST) {
181             $owner = ActivityUtils::child($this->element, Activity::AUTHOR, Activity::SPEC);
182             $this->owner = new ActivityObject($owner);
183         }
184     }
185
186     private function _childContent($element, $tag, $namespace = ActivityUtils::ATOM)
187     {
188         return ActivityUtils::childContent($element, $tag, $namespace);
189     }
190
191     private function _fromAuthor($element)
192     {
193         $this->type = $this->_childContent(
194             $element,
195             Activity::OBJECTTYPE,
196             Activity::SPEC
197         );
198
199         if (empty($this->type)) {
200             $this->type = self::PERSON; // XXX: is this fair?
201         }
202
203
204         // Start with <poco::displayName>
205
206         $this->title = ActivityUtils::childContent($element, PoCo::DISPLAYNAME, PoCo::NS);
207
208         // try falling back to <atom:title>
209
210         if (empty($this->title)) {
211             $title = ActivityUtils::childHtmlContent($element, self::TITLE);
212
213             if (!empty($title)) {
214                 $this->title = common_strip_html($title);
215             }
216         }
217
218         // fall back to <atom:name> as a last resort
219
220         if (empty($this->title)) {
221             $this->title = $this->_childContent($element, self::NAME);
222         }
223
224         // start with <atom:id>
225
226         $this->id = $this->_childContent($element, self::ID);
227
228         // fall back to <atom:uri>
229
230         if (empty($this->id)) {
231             $this->id = $this->_childContent($element, self::URI);
232         }
233
234         // fall further back to <atom:email>
235
236         if (empty($this->id)) {
237             $email = $this->_childContent($element, self::EMAIL);
238             if (!empty($email)) {
239                 // XXX: acct: ?
240                 $this->id = 'mailto:' . $email;
241             }
242         }
243
244         $this->link = ActivityUtils::getPermalink($element);
245
246         // fall finally back to <link rel=alternate>
247
248         if (empty($this->id) && !empty($this->link)) { // fallback if there's no ID
249             $this->id = $this->link;
250         }
251     }
252
253     // @todo FIXME: rationalize with Activity::_fromRssItem()
254
255     private function _fromRssItem($item)
256     {
257         if (empty($this->type)) {
258             $this->type = ActivityObject::NOTE;
259         }
260
261         $this->title = ActivityUtils::childContent($item, ActivityObject::TITLE, Activity::RSS);
262
263         $contentEl = ActivityUtils::child($item, ActivityUtils::CONTENT, Activity::CONTENTNS);
264
265         if (!empty($contentEl)) {
266             $this->content = htmlspecialchars_decode($contentEl->textContent, ENT_QUOTES);
267         } else {
268             $descriptionEl = ActivityUtils::child($item, Activity::DESCRIPTION, Activity::RSS);
269             if (!empty($descriptionEl)) {
270                 $this->content = htmlspecialchars_decode($descriptionEl->textContent, ENT_QUOTES);
271             }
272         }
273
274         $this->link = ActivityUtils::childContent($item, ActivityUtils::LINK, Activity::RSS);
275
276         $guidEl = ActivityUtils::child($item, Activity::GUID, Activity::RSS);
277
278         if (!empty($guidEl)) {
279             $this->id = $guidEl->textContent;
280
281             if ($guidEl->hasAttribute('isPermaLink') && $guidEl->getAttribute('isPermaLink') != 'false') {
282                 // overwrites <link>
283                 $this->link = $this->id;
284             }
285         }
286     }
287
288     private function _fromAtomEntry($element)
289     {
290         $this->type = $this->_childContent(
291             $element,
292             Activity::OBJECTTYPE,
293             Activity::SPEC
294         );
295
296         if (empty($this->type)) {
297             $this->type = ActivityObject::NOTE;
298         }
299
300         $this->summary = ActivityUtils::childHtmlContent($element, self::SUMMARY);
301         $this->content = ActivityUtils::getContent($element);
302
303         // We don't like HTML in our titles, although it's technically allowed
304         $this->title = common_strip_html(ActivityUtils::childHtmlContent($element, self::TITLE));
305
306         $this->source = $this->_getSource($element);
307
308         $this->link = ActivityUtils::getPermalink($element);
309         $this->selfLink = ActivityUtils::getSelfLink($element);
310
311         $this->id = $this->_childContent($element, self::ID);
312
313         if (empty($this->id) && !empty($this->link)) { // fallback if there's no ID
314             $this->id = $this->link;
315         }
316
317         $els = $element->childNodes;
318
319         for ($i = 0; $i < $els->length; $i++) {
320             $link = $els->item($i);
321             if ($link->localName == ActivityUtils::LINK && $link->namespaceURI == ActivityUtils::ATOM) {
322                 $attrs = [];
323                 foreach ($link->attributes as $attrName => $attrNode) {
324                     $attrs[$attrName] = $attrNode->nodeValue;
325                 }
326                 $this->extra[] = [$link->localName,
327                     $attrs,
328                     $link->nodeValue];
329             }
330         }
331     }
332
333     private function _getSource($element)
334     {
335         $sourceEl = ActivityUtils::child($element, 'source');
336
337         if (empty($sourceEl)) {
338             return null;
339         } else {
340             $href = ActivityUtils::getLink($sourceEl, 'self');
341             if (!empty($href)) {
342                 return $href;
343             } else {
344                 return ActivityUtils::childContent($sourceEl, 'id');
345             }
346         }
347     }
348
349     public static function fromRssAuthor($el)
350     {
351         $text = $el->textContent;
352
353         if (preg_match('/^(.*?) \((.*)\)$/', $text, $match)) {
354             $email = $match[1];
355             $name = $match[2];
356         } elseif (preg_match('/^(.*?) <(.*)>$/', $text, $match)) {
357             $name = $match[1];
358             $email = $match[2];
359         } elseif (preg_match('/.*@.*/', $text)) {
360             $email = $text;
361             $name = null;
362         } else {
363             $name = $text;
364             $email = null;
365         }
366
367         // Not really enough info
368
369         $obj = new ActivityObject();
370
371         $obj->element = $el;
372
373         $obj->type = ActivityObject::PERSON;
374         $obj->title = $name;
375
376         if (!empty($email)) {
377             $obj->id = 'mailto:' . $email;
378         }
379
380         return $obj;
381     }
382
383     public static function fromDcCreator($el)
384     {
385         // Not really enough info
386
387         $text = $el->textContent;
388
389         $obj = new ActivityObject();
390
391         $obj->element = $el;
392
393         $obj->title = $text;
394         $obj->type = ActivityObject::PERSON;
395
396         return $obj;
397     }
398
399     public static function fromRssChannel($el)
400     {
401         $obj = new ActivityObject();
402
403         $obj->element = $el;
404
405         $obj->type = ActivityObject::PERSON; // @fixme guess better
406
407         $obj->title = ActivityUtils::childContent($el, ActivityObject::TITLE, Activity::RSS);
408         $obj->link = ActivityUtils::childContent($el, ActivityUtils::LINK, Activity::RSS);
409         $obj->id = ActivityUtils::getLink($el, Activity::SELF);
410
411         if (empty($obj->id)) {
412             $obj->id = $obj->link;
413         }
414
415         $desc = ActivityUtils::childContent($el, Activity::DESCRIPTION, Activity::RSS);
416
417         if (!empty($desc)) {
418             $obj->content = htmlspecialchars_decode($desc, ENT_QUOTES);
419         }
420
421         $imageEl = ActivityUtils::child($el, Activity::IMAGE, Activity::RSS);
422
423         if (!empty($imageEl)) {
424             $url = ActivityUtils::childContent($imageEl, Activity::URL, Activity::RSS);
425             $al = new AvatarLink();
426             $al->url = $url;
427             $obj->avatarLinks[] = $al;
428         }
429
430         return $obj;
431     }
432
433     // Try to get a unique id for the source feed
434
435     public static function fromPosterousAuthor($el)
436     {
437         $obj = new ActivityObject();
438
439         $obj->type = ActivityObject::PERSON; // @fixme any others...?
440
441         $userImage = ActivityUtils::childContent($el, self::USERIMAGE, self::POSTEROUS);
442
443         if (!empty($userImage)) {
444             $al = new AvatarLink();
445             $al->url = $userImage;
446             $obj->avatarLinks[] = $al;
447         }
448
449         $obj->link = ActivityUtils::childContent($el, self::PROFILEURL, self::POSTEROUS);
450         $obj->id = $obj->link;
451
452         $obj->poco = new PoCo();
453
454         $obj->poco->preferredUsername = ActivityUtils::childContent($el, self::NICKNAME, self::POSTEROUS);
455         $obj->poco->displayName = ActivityUtils::childContent($el, self::DISPLAYNAME, self::POSTEROUS);
456
457         $obj->title = $obj->poco->displayName;
458
459         return $obj;
460     }
461
462     public static function fromGroup(User_group $group)
463     {
464         $object = new ActivityObject();
465
466         if (Event::handle('StartActivityObjectFromGroup', [$group, &$object])) {
467             $object->type = ActivityObject::GROUP;
468             $object->id = $group->getUri();
469             $object->title = $group->getBestName();
470             $object->link = $group->getUri();
471
472             $object->avatarLinks[] = AvatarLink::fromFilename(
473                 $group->homepage_logo,
474                 AVATAR_PROFILE_SIZE
475             );
476
477             $object->avatarLinks[] = AvatarLink::fromFilename(
478                 $group->stream_logo,
479                 AVATAR_STREAM_SIZE
480             );
481
482             $object->avatarLinks[] = AvatarLink::fromFilename(
483                 $group->mini_logo,
484                 AVATAR_MINI_SIZE
485             );
486
487             $object->poco = PoCo::fromGroup($group);
488             Event::handle('EndActivityObjectFromGroup', [$group, &$object]);
489         }
490
491         return $object;
492     }
493
494     public static function fromPeopletag($ptag)
495     {
496         $object = new ActivityObject();
497         if (Event::handle('StartActivityObjectFromPeopletag', [$ptag, &$object])) {
498             $object->type = ActivityObject::_LIST;
499
500             $object->id = $ptag->getUri();
501             $object->title = $ptag->tag;
502             $object->summary = $ptag->description;
503             $object->link = $ptag->homeUrl();
504             $object->owner = Profile::getKV('id', $ptag->tagger);
505             $object->poco = PoCo::fromProfile($object->owner);
506             Event::handle('EndActivityObjectFromPeopletag', [$ptag, &$object]);
507         }
508         return $object;
509     }
510
511     public static function fromFile(File $file)
512     {
513         $object = new ActivityObject();
514
515         if (Event::handle('StartActivityObjectFromFile', [$file, &$object])) {
516             $object->type = self::mimeTypeToObjectType($file->mimetype);
517             $object->id = TagURI::mint(sprintf("file:%d", $file->id));
518             $object->link = $file->getAttachmentUrl();
519
520             if ($file->title) {
521                 $object->title = $file->title;
522             }
523
524             if ($file->date) {
525                 $object->date = $file->date;
526             }
527
528             try {
529                 $thumbnail = $file->getThumbnail();
530                 $object->thumbnail = $thumbnail;
531             } catch (UseFileAsThumbnailException $e) {
532                 $object->thumbnail = null;
533             } catch (UnsupportedMediaException $e) {
534                 $object->thumbnail = null;
535             }
536
537             switch (self::canonicalType($object->type)) {
538                 case 'image':
539                     $object->largerImage = $file->getUrl();
540                     break;
541                 case 'video':
542                 case 'audio':
543                     $object->stream = $file->getUrl();
544                     break;
545             }
546
547             Event::handle('EndActivityObjectFromFile', [$file, &$object]);
548         }
549
550         return $object;
551     }
552
553     public static function mimeTypeToObjectType($mimeType)
554     {
555         $ot = null;
556
557         // Default
558
559         if (empty($mimeType)) {
560             return self::FILE;
561         }
562
563         $parts = explode('/', $mimeType);
564
565         switch ($parts[0]) {
566             case 'image':
567                 $ot = self::IMAGE;
568                 break;
569             case 'audio':
570                 $ot = self::AUDIO;
571                 break;
572             case 'video':
573                 $ot = self::VIDEO;
574                 break;
575             default:
576                 $ot = self::FILE;
577         }
578
579         return $ot;
580     }
581
582     public static function canonicalType($type)
583     {
584         return ActivityUtils::resolveUri($type, true);
585     }
586
587     public static function fromNoticeSource(Notice_source $source)
588     {
589         $object = new ActivityObject();
590         $wellKnown = ['web', 'xmpp', 'mail', 'omb', 'system', 'api', 'ostatus',
591             'activity', 'feed', 'mirror', 'twitter', 'facebook'];
592
593         if (Event::handle('StartActivityObjectFromNoticeSource', [$source, &$object])) {
594             $object->type = ActivityObject::APPLICATION;
595
596             if (in_array($source->code, $wellKnown)) {
597                 // We use one ID for all well-known StatusNet sources
598                 $object->id = "tag:status.net,2009:notice-source:" . $source->code;
599             } elseif ($source->url) {
600                 // They registered with an URL
601                 $object->id = $source->url;
602             } else {
603                 // Locally-registered, no URL
604                 $object->id = TagURI::mint("notice-source:" . $source->code);
605             }
606
607             if ($source->url) {
608                 $object->link = $source->url;
609             }
610
611             if ($source->name) {
612                 $object->title = $source->name;
613             } else {
614                 $object->title = $source->code;
615             }
616
617             if ($source->created) {
618                 $object->date = $source->created;
619             }
620
621             $object->extra[] = ['status_net', ['source_code' => $source->code]];
622
623             Event::handle('EndActivityObjectFromNoticeSource', [$source, &$object]);
624         }
625
626         return $object;
627     }
628
629     public static function fromMessage(Message $message)
630     {
631         $object = new ActivityObject();
632
633         if (Event::handle('StartActivityObjectFromMessage', [$message, &$object])) {
634             $object->type = ActivityObject::NOTE;
635             $object->id = ($message->uri) ? $message->uri : (($message->url) ? $message->url : TagURI::mint(sprintf("message:%d", $message->id)));
636             $object->content = $message->rendered;
637             $object->date = $message->created;
638
639             if ($message->url) {
640                 $object->link = $message->url;
641             } else {
642                 $object->link = common_local_url('showmessage', ['message' => $message->id]);
643             }
644
645             $object->extra[] = ['status_net', ['message_id' => $message->id]];
646
647             Event::handle('EndActivityObjectFromMessage', [$message, &$object]);
648         }
649
650         return $object;
651     }
652
653     /*
654      * Returns an array based on this Activity Object suitable for
655      * encoding as JSON.
656      *
657      * @return array $object the activity object array
658      */
659
660     public function asString($tag = 'activity:object')
661     {
662         $xs = new XMLStringer(true);
663
664         $this->outputTo($xs, $tag);
665
666         return $xs->getString();
667     }
668
669     public function outputTo($xo, $tag = 'activity:object')
670     {
671         if (!empty($tag)) {
672             $xo->elementStart($tag);
673         }
674
675         if (Event::handle('StartActivityObjectOutputAtom', [$this, $xo])) {
676             $xo->element('activity:object-type', null, $this->type);
677
678             // <author> uses URI
679
680             if ($tag == 'author') {
681                 $xo->element(self::URI, null, $this->id);
682             } else {
683                 $xo->element(self::ID, null, $this->id);
684             }
685
686             if (!empty($this->title)) {
687                 $name = common_xml_safe_str($this->title);
688                 if ($tag == 'author') {
689                     // XXX: Backward compatibility hack -- atom:name should contain
690                     // full name here, instead of nickname, i.e.: $name. Change
691                     // this in the next version.
692                     $xo->element(self::NAME, null, $this->poco->preferredUsername);
693                 } else {
694                     $xo->element(self::TITLE, null, $name);
695                 }
696             }
697
698             if (!empty($this->summary)) {
699                 $xo->element(
700                     self::SUMMARY,
701                     null,
702                     common_xml_safe_str($this->summary)
703                 );
704             }
705
706             if (!empty($this->content)) {
707                 // XXX: assuming HTML content here
708                 $xo->element(
709                     ActivityUtils::CONTENT,
710                     ['type' => 'html'],
711                     common_xml_safe_str($this->content)
712                 );
713             }
714
715             if (!empty($this->link)) {
716                 $xo->element(
717                     'link',
718                     [
719                         'rel' => 'alternate',
720                         'type' => 'text/html',
721                         'href' => $this->link
722                     ]
723                 );
724             }
725
726             if (!empty($this->selfLink)) {
727                 $xo->element(
728                     'link',
729                     [
730                         'rel' => 'self',
731                         'type' => 'application/atom+xml',
732                         'href' => $this->selfLink
733                     ]
734                 );
735             }
736
737             if (!empty($this->owner)) {
738                 $owner = $this->owner->asActivityNoun(self::AUTHOR);
739                 $xo->raw($owner);
740             }
741
742             if ($this->type == ActivityObject::PERSON
743                 || $this->type == ActivityObject::GROUP) {
744                 foreach ($this->avatarLinks as $alink) {
745                     $xo->element(
746                         'link',
747                         [
748                             'rel' => 'avatar',
749                             'type' => $alink->type,
750                             'media:width' => $alink->width,
751                             'media:height' => $alink->height,
752                             'href' => $alink->url,
753                         ]
754                     );
755                 }
756             }
757
758             if (!empty($this->geopoint)) {
759                 $xo->element(
760                     'georss:point',
761                     null,
762                     $this->geopoint
763                 );
764             }
765
766             if (!empty($this->poco)) {
767                 $this->poco->outputTo($xo);
768             }
769
770             // @fixme there's no way here to make a tree; elements can only contain plaintext
771             // @fixme these may collide with JSON extensions
772             foreach ($this->extra as $el) {
773                 list($extraTag, $attrs, $content) = array_pad($el, 3, null);
774                 $xo->element($extraTag, $attrs, $content);
775             }
776
777             Event::handle('EndActivityObjectOutputAtom', [$this, $xo]);
778         }
779
780         if (!empty($tag)) {
781             $xo->elementEnd($tag);
782         }
783
784         return;
785     }
786
787     public function asArray()
788     {
789         $object = [];
790
791         if (Event::handle('StartActivityObjectOutputJson', [$this, &$object])) {
792             // XXX: attachments are added by Activity
793
794             // author (Add object for author? Could be useful for repeats.)
795
796             // content (Add rendered version of the notice?)
797
798             // downstreamDuplicates
799
800             // id
801
802             if ($this->id) {
803                 $object['id'] = $this->id;
804             } elseif ($this->link) {
805                 $object['id'] = $this->link;
806             }
807
808             if ($this->type == ActivityObject::PERSON
809                 || $this->type == ActivityObject::GROUP) {
810
811                 // displayName
812                 $object['displayName'] = $this->title;
813
814                 // XXX: Not sure what the best avatar is to use for the
815                 // author's "image". For now, I'm using the large size.
816
817                 $imgLink = null;
818                 $avatarMediaLinks = [];
819
820                 foreach ($this->avatarLinks as $a) {
821
822                     // Make a MediaLink for every other Avatar
823                     $avatar = new ActivityStreamsMediaLink(
824                         $a->url,
825                         $a->width,
826                         $a->height,
827                         $a->type,
828                         'avatar'
829                     );
830
831                     // Find the big avatar to use as the "image"
832                     if ($a->height == AVATAR_PROFILE_SIZE) {
833                         $imgLink = $avatar;
834                     }
835
836                     $avatarMediaLinks[] = $avatar->asArray();
837                 }
838
839                 if (!array_key_exists('status_net', $object)) {
840                     $object['status_net'] = [];
841                 }
842
843                 $object['status_net']['avatarLinks'] = $avatarMediaLinks; // extension
844
845                 // image
846                 if (!empty($imgLink)) {
847                     $object['image'] = $imgLink->asArray();
848                 }
849             }
850
851             // objectType
852             //
853             // We can probably use the whole schema URL here but probably the
854             // relative simple name is easier to parse
855
856             $object['objectType'] = self::canonicalType($this->type);
857
858             // summary
859             $object['summary'] = $this->summary;
860
861             // content, usually rendered HTML
862             $object['content'] = $this->content;
863
864             // published (probably don't need. Might be useful for repeats.)
865
866             // updated (probably don't need this)
867
868             // TODO: upstreamDuplicates
869
870             if ($this->link) {
871                 $object['url'] = $this->link;
872             }
873
874             /* Extensions */
875             // @fixme these may collide with XML extensions
876             // @fixme multiple tags of same name will overwrite each other
877             // @fixme text content from XML extensions will be lost
878
879             foreach ($this->extra as $e) {
880                 list($objectName, $props, $txt) = array_pad($e, 3, null);
881                 if (!empty($objectName)) {
882                     $parts = explode(":", $objectName);
883                     if (count($parts) == 2 && $parts[0] == "statusnet") {
884                         if (!array_key_exists('status_net', $object)) {
885                             $object['status_net'] = [];
886                         }
887                         $object['status_net'][$parts[1]] = $props;
888                     } else {
889                         $object[$objectName] = $props;
890                     }
891                 }
892             }
893
894             if (!empty($this->geopoint)) {
895                 list($lat, $lon) = explode(' ', $this->geopoint);
896
897                 if (!empty($lat) && !empty($lon)) {
898                     $object['location'] = [
899                         'objectType' => 'place',
900                         'position' => sprintf("%+02.5F%+03.5F/", $lat, $lon),
901                         'lat' => $lat,
902                         'lon' => $lon
903                     ];
904
905                     $loc = Location::fromLatLon((float)$lat, (float)$lon);
906
907                     if ($loc) {
908                         $name = $loc->getName();
909
910                         if ($name) {
911                             $object['location']['displayName'] = $name;
912                         }
913                         $url = $loc->getURL();
914
915                         if ($url) {
916                             $object['location']['url'] = $url;
917                         }
918                     }
919                 }
920             }
921
922             if (!empty($this->poco)) {
923                 $object['portablecontacts_net'] = array_filter($this->poco->asArray());
924             }
925
926             if (!empty($this->thumbnail)) {
927                 if (is_string($this->thumbnail)) {
928                     $object['image'] = ['url' => $this->thumbnail];
929                 } else {
930                     $object['image'] = ['url' => $this->thumbnail->getUrl()];
931                     if ($this->thumbnail->width) {
932                         $object['image']['width'] = $this->thumbnail->width;
933                     }
934                     if ($this->thumbnail->height) {
935                         $object['image']['height'] = $this->thumbnail->height;
936                     }
937                 }
938             }
939
940             switch (self::canonicalType($this->type)) {
941                 case 'image':
942                     if (!empty($this->largerImage)) {
943                         $object['fullImage'] = ['url' => $this->largerImage];
944                     }
945                     break;
946                 case 'audio':
947                 case 'video':
948                     if (!empty($this->stream)) {
949                         $object['stream'] = ['url' => $this->stream];
950                     }
951                     break;
952             }
953
954             Event::handle('EndActivityObjectOutputJson', [$this, &$object]);
955         }
956         return array_filter($object);
957     }
958
959     public function getIdentifiers()
960     {
961         $ids = [];
962         foreach (['id', 'link', 'url'] as $id) {
963             if (isset($this->$id)) {
964                 $ids[] = $this->$id;
965             }
966         }
967         return array_unique($ids);
968     }
969 }