]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/activityobject.php
Widget automatically delegates unimplemented methods to attribute
[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('STATUSNET')) {
32     exit(1);
33 }
34
35 /**
36  * A noun-ish thing in the activity universe
37  *
38  * The activity streams spec talks about activity objects, while also having
39  * a tag activity:object, which is in fact an activity object. Aaaaaah!
40  *
41  * This is just a thing in the activity universe. Can be the subject, object,
42  * or indirect object (target!) of an activity verb. Rotten name, and I'm
43  * propagating it. *sigh*
44  *
45  * @category  OStatus
46  * @package   StatusNet
47  * @author    Evan Prodromou <evan@status.net>
48  * @copyright 2010 StatusNet, Inc.
49  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
50  * @link      http://status.net/
51  */
52 class ActivityObject
53 {
54     const ARTICLE   = 'http://activitystrea.ms/schema/1.0/article';
55     const BLOGENTRY = 'http://activitystrea.ms/schema/1.0/blog-entry';
56     const NOTE      = 'http://activitystrea.ms/schema/1.0/note';
57     const STATUS    = 'http://activitystrea.ms/schema/1.0/status';
58     const FILE      = 'http://activitystrea.ms/schema/1.0/file';
59     const PHOTO     = 'http://activitystrea.ms/schema/1.0/photo';
60     const ALBUM     = 'http://activitystrea.ms/schema/1.0/photo-album';
61     const PLAYLIST  = 'http://activitystrea.ms/schema/1.0/playlist';
62     const VIDEO     = 'http://activitystrea.ms/schema/1.0/video';
63     const AUDIO     = 'http://activitystrea.ms/schema/1.0/audio';
64     const BOOKMARK  = 'http://activitystrea.ms/schema/1.0/bookmark';
65     const PERSON    = 'http://activitystrea.ms/schema/1.0/person';
66     const GROUP     = 'http://activitystrea.ms/schema/1.0/group';
67     const PLACE     = 'http://activitystrea.ms/schema/1.0/place';
68     const COMMENT   = 'http://activitystrea.ms/schema/1.0/comment';
69     // ^^^^^^^^^^ tea!
70
71     // Atom elements we snarf
72
73     const TITLE   = 'title';
74     const SUMMARY = 'summary';
75     const ID      = 'id';
76     const SOURCE  = 'source';
77
78     const NAME  = 'name';
79     const URI   = 'uri';
80     const EMAIL = 'email';
81
82     const POSTEROUS   = 'http://posterous.com/help/rss/1.0';
83     const AUTHOR      = 'author';
84     const USERIMAGE   = 'userImage';
85     const PROFILEURL  = 'profileUrl';
86     const NICKNAME    = 'nickName';
87     const DISPLAYNAME = 'displayName';
88
89     public $element;
90     public $type;
91     public $id;
92     public $title;
93     public $summary;
94     public $content;
95     public $link;
96     public $source;
97     public $avatarLinks = array();
98     public $geopoint;
99     public $poco;
100     public $displayName;
101
102     // @todo move this stuff to it's own PHOTO activity object
103     const MEDIA_DESCRIPTION = 'description';
104
105     public $thumbnail;
106     public $largerImage;
107     public $description;
108     public $extra = array();
109
110     /**
111      * Constructor
112      *
113      * This probably needs to be refactored
114      * to generate a local class (ActivityPerson, ActivityFile, ...)
115      * based on the object type.
116      *
117      * @param DOMElement $element DOM thing to turn into an Activity thing
118      */
119     function __construct($element = null)
120     {
121         if (empty($element)) {
122             return;
123         }
124
125         $this->element = $element;
126
127         $this->geopoint = $this->_childContent(
128             $element,
129             ActivityContext::POINT,
130             ActivityContext::GEORSS
131         );
132
133         if ($element->tagName == 'author') {
134             $this->_fromAuthor($element);
135         } else if ($element->tagName == 'item') {
136             $this->_fromRssItem($element);
137         } else {
138             $this->_fromAtomEntry($element);
139         }
140
141         // Some per-type attributes...
142         if ($this->type == self::PERSON || $this->type == self::GROUP) {
143             $this->displayName = $this->title;
144
145             $photos = ActivityUtils::getLinks($element, 'photo');
146             if (count($photos)) {
147                 foreach ($photos as $link) {
148                     $this->avatarLinks[] = new AvatarLink($link);
149                 }
150             } else {
151                 $avatars = ActivityUtils::getLinks($element, 'avatar');
152                 foreach ($avatars as $link) {
153                     $this->avatarLinks[] = new AvatarLink($link);
154                 }
155             }
156
157             $this->poco = new PoCo($element);
158         }
159
160         if ($this->type == self::PHOTO) {
161
162             $this->thumbnail   = ActivityUtils::getLink($element, 'preview');
163             $this->largerImage = ActivityUtils::getLink($element, 'enclosure');
164
165             $this->description = ActivityUtils::childContent(
166                 $element,
167                 ActivityObject::MEDIA_DESCRIPTION,
168                 Activity::MEDIA
169             );
170         }
171     }
172
173     private function _fromAuthor($element)
174     {
175         $this->type = $this->_childContent($element,
176                                            Activity::OBJECTTYPE,
177                                            Activity::SPEC);
178
179         if (empty($this->type)) {
180             $this->type = self::PERSON; // XXX: is this fair?
181         }
182
183         // start with <atom:title>
184
185         $title = ActivityUtils::childHtmlContent($element, self::TITLE);
186
187         if (!empty($title)) {
188             $this->title = html_entity_decode(strip_tags($title), ENT_QUOTES, 'UTF-8');
189         }
190
191         // fall back to <atom:name>
192
193         if (empty($this->title)) {
194             $this->title = $this->_childContent($element, self::NAME);
195         }
196
197         // start with <atom:id>
198
199         $this->id = $this->_childContent($element, self::ID);
200
201         // fall back to <atom:uri>
202
203         if (empty($this->id)) {
204             $this->id = $this->_childContent($element, self::URI);
205         }
206
207         // fall further back to <atom:email>
208
209         if (empty($this->id)) {
210             $email = $this->_childContent($element, self::EMAIL);
211             if (!empty($email)) {
212                 // XXX: acct: ?
213                 $this->id = 'mailto:'.$email;
214             }
215         }
216
217         $this->link = ActivityUtils::getPermalink($element);
218
219         // fall finally back to <link rel=alternate>
220
221         if (empty($this->id) && !empty($this->link)) { // fallback if there's no ID
222             $this->id = $this->link;
223         }
224     }
225
226     private function _fromAtomEntry($element)
227     {
228         $this->type = $this->_childContent($element, Activity::OBJECTTYPE,
229                                            Activity::SPEC);
230
231         if (empty($this->type)) {
232             $this->type = ActivityObject::NOTE;
233         }
234
235         $this->summary = ActivityUtils::childHtmlContent($element, self::SUMMARY);
236         $this->content = ActivityUtils::getContent($element);
237
238         // We don't like HTML in our titles, although it's technically allowed
239
240         $title = ActivityUtils::childHtmlContent($element, self::TITLE);
241
242         $this->title = html_entity_decode(strip_tags($title), ENT_QUOTES, 'UTF-8');
243
244         $this->source  = $this->_getSource($element);
245
246         $this->link = ActivityUtils::getPermalink($element);
247
248         $this->id = $this->_childContent($element, self::ID);
249
250         if (empty($this->id) && !empty($this->link)) { // fallback if there's no ID
251             $this->id = $this->link;
252         }
253     }
254
255     // @todo FIXME: rationalize with Activity::_fromRssItem()
256     private function _fromRssItem($item)
257     {
258         $this->title = ActivityUtils::childContent($item, ActivityObject::TITLE, Activity::RSS);
259
260         $contentEl = ActivityUtils::child($item, ActivityUtils::CONTENT, Activity::CONTENTNS);
261
262         if (!empty($contentEl)) {
263             $this->content = htmlspecialchars_decode($contentEl->textContent, ENT_QUOTES);
264         } else {
265             $descriptionEl = ActivityUtils::child($item, Activity::DESCRIPTION, Activity::RSS);
266             if (!empty($descriptionEl)) {
267                 $this->content = htmlspecialchars_decode($descriptionEl->textContent, ENT_QUOTES);
268             }
269         }
270
271         $this->link = ActivityUtils::childContent($item, ActivityUtils::LINK, Activity::RSS);
272
273         $guidEl = ActivityUtils::child($item, Activity::GUID, Activity::RSS);
274
275         if (!empty($guidEl)) {
276             $this->id = $guidEl->textContent;
277
278             if ($guidEl->hasAttribute('isPermaLink')) {
279                 // overwrites <link>
280                 $this->link = $this->id;
281             }
282         }
283     }
284
285     public static function fromRssAuthor($el)
286     {
287         $text = $el->textContent;
288
289         if (preg_match('/^(.*?) \((.*)\)$/', $text, $match)) {
290             $email = $match[1];
291             $name = $match[2];
292         } else if (preg_match('/^(.*?) <(.*)>$/', $text, $match)) {
293             $name = $match[1];
294             $email = $match[2];
295         } else if (preg_match('/.*@.*/', $text)) {
296             $email = $text;
297             $name = null;
298         } else {
299             $name = $text;
300             $email = null;
301         }
302
303         // Not really enough info
304
305         $obj = new ActivityObject();
306
307         $obj->element = $el;
308
309         $obj->type  = ActivityObject::PERSON;
310         $obj->title = $name;
311
312         if (!empty($email)) {
313             $obj->id = 'mailto:'.$email;
314         }
315
316         return $obj;
317     }
318
319     public static function fromDcCreator($el)
320     {
321         // Not really enough info
322
323         $text = $el->textContent;
324
325         $obj = new ActivityObject();
326
327         $obj->element = $el;
328
329         $obj->title = $text;
330         $obj->type  = ActivityObject::PERSON;
331
332         return $obj;
333     }
334
335     public static function fromRssChannel($el)
336     {
337         $obj = new ActivityObject();
338
339         $obj->element = $el;
340
341         $obj->type = ActivityObject::PERSON; // @fixme guess better
342
343         $obj->title = ActivityUtils::childContent($el, ActivityObject::TITLE, Activity::RSS);
344         $obj->link  = ActivityUtils::childContent($el, ActivityUtils::LINK, Activity::RSS);
345         $obj->id    = ActivityUtils::getLink($el, Activity::SELF);
346
347         if (empty($obj->id)) {
348             $obj->id = $obj->link;
349         }
350
351         $desc = ActivityUtils::childContent($el, Activity::DESCRIPTION, Activity::RSS);
352
353         if (!empty($desc)) {
354             $obj->content = htmlspecialchars_decode($desc, ENT_QUOTES);
355         }
356
357         $imageEl = ActivityUtils::child($el, Activity::IMAGE, Activity::RSS);
358
359         if (!empty($imageEl)) {
360             $url = ActivityUtils::childContent($imageEl, Activity::URL, Activity::RSS);
361             $al = new AvatarLink();
362             $al->url = $url;
363             $obj->avatarLinks[] = $al;
364         }
365
366         return $obj;
367     }
368
369     public static function fromPosterousAuthor($el)
370     {
371         $obj = new ActivityObject();
372
373         $obj->type = ActivityObject::PERSON; // @fixme any others...?
374
375         $userImage = ActivityUtils::childContent($el, self::USERIMAGE, self::POSTEROUS);
376
377         if (!empty($userImage)) {
378             $al = new AvatarLink();
379             $al->url = $userImage;
380             $obj->avatarLinks[] = $al;
381         }
382
383         $obj->link = ActivityUtils::childContent($el, self::PROFILEURL, self::POSTEROUS);
384         $obj->id   = $obj->link;
385
386         $obj->poco = new PoCo();
387
388         $obj->poco->preferredUsername = ActivityUtils::childContent($el, self::NICKNAME, self::POSTEROUS);
389         $obj->poco->displayName       = ActivityUtils::childContent($el, self::DISPLAYNAME, self::POSTEROUS);
390
391         $obj->title = $obj->poco->displayName;
392
393         return $obj;
394     }
395
396     private function _childContent($element, $tag, $namespace=ActivityUtils::ATOM)
397     {
398         return ActivityUtils::childContent($element, $tag, $namespace);
399     }
400
401     // Try to get a unique id for the source feed
402
403     private function _getSource($element)
404     {
405         $sourceEl = ActivityUtils::child($element, 'source');
406
407         if (empty($sourceEl)) {
408             return null;
409         } else {
410             $href = ActivityUtils::getLink($sourceEl, 'self');
411             if (!empty($href)) {
412                 return $href;
413             } else {
414                 return ActivityUtils::childContent($sourceEl, 'id');
415             }
416         }
417     }
418
419     static function fromNotice(Notice $notice)
420     {
421         $object = new ActivityObject();
422
423                 if (Event::handle('StartActivityObjectFromNotice', array($notice, &$object))) {
424
425                         $object->type    = (empty($notice->object_type)) ? ActivityObject::NOTE : $notice->object_type;
426
427                         $object->id      = $notice->uri;
428                         $object->title   = $notice->content;
429                         $object->content = $notice->rendered;
430                         $object->link    = $notice->bestUrl();
431
432                         Event::handle('EndActivityObjectFromNotice', array($notice, &$object));
433                 }
434
435         return $object;
436     }
437
438     static function fromProfile(Profile $profile)
439     {
440         $object = new ActivityObject();
441
442                 if (Event::handle('StartActivityObjectFromProfile', array($profile, &$object))) {
443
444                         $object->type   = ActivityObject::PERSON;
445                         $object->id     = $profile->getUri();
446                         $object->title  = $profile->getBestName();
447                         $object->link   = $profile->profileurl;
448
449                         $orig = $profile->getOriginalAvatar();
450
451                         if (!empty($orig)) {
452                                 $object->avatarLinks[] = AvatarLink::fromAvatar($orig);
453                         }
454
455                         $sizes = array(
456                 AVATAR_PROFILE_SIZE,
457                 AVATAR_STREAM_SIZE,
458                 AVATAR_MINI_SIZE
459             );
460
461                         foreach ($sizes as $size) {
462                                 $alink  = null;
463                                 $avatar = $profile->getAvatar($size);
464
465                                 if (!empty($avatar)) {
466                                         $alink = AvatarLink::fromAvatar($avatar);
467                                 } else {
468                                         $alink = new AvatarLink();
469                                         $alink->type   = 'image/png';
470                                         $alink->height = $size;
471                                         $alink->width  = $size;
472                                         $alink->url    = Avatar::defaultImage($size);
473
474                                         if ($size == AVATAR_PROFILE_SIZE) {
475                                                 // Hack for Twitter import: we don't have a 96x96 image,
476                                                 // but we do have a 73x73 image. For now, fake it with that.
477                                                 $avatar = $profile->getAvatar(73);
478                                                 if ($avatar) {
479                                                         $alink = AvatarLink::fromAvatar($avatar);
480                                                         $alink->height= $size;
481                                                         $alink->width = $size;
482                                                 }
483                                         }
484                                 }
485
486                                 $object->avatarLinks[] = $alink;
487                         }
488
489                         if (isset($profile->lat) && isset($profile->lon)) {
490                                 $object->geopoint = (float)$profile->lat
491                                         . ' ' . (float)$profile->lon;
492                         }
493
494                         $object->poco = PoCo::fromProfile($profile);
495
496                         Event::handle('EndActivityObjectFromProfile', array($profile, &$object));
497                 }
498
499         return $object;
500     }
501
502     static function fromGroup($group)
503     {
504         $object = new ActivityObject();
505
506                 if (Event::handle('StartActivityObjectFromGroup', array($group, &$object))) {
507
508                         $object->type   = ActivityObject::GROUP;
509                         $object->id     = $group->getUri();
510                         $object->title  = $group->getBestName();
511                         $object->link   = $group->getUri();
512
513                         $object->avatarLinks[] = AvatarLink::fromFilename($group->homepage_logo,
514                                                                                                                           AVATAR_PROFILE_SIZE);
515
516                         $object->avatarLinks[] = AvatarLink::fromFilename($group->stream_logo,
517                                                                                                                           AVATAR_STREAM_SIZE);
518
519                         $object->avatarLinks[] = AvatarLink::fromFilename($group->mini_logo,
520                                                                                                                           AVATAR_MINI_SIZE);
521
522                         $object->poco = PoCo::fromGroup($group);
523
524                         Event::handle('EndActivityObjectFromGroup', array($group, &$object));
525                 }
526
527         return $object;
528     }
529
530         function outputTo($xo, $tag='activity:object')
531         {
532                 if (!empty($tag)) {
533                         $xo->elementStart($tag);
534                 }
535
536         if (Event::handle('StartActivityObjectOutputAtom', array($this, $xo))) {
537             $xo->element('activity:object-type', null, $this->type);
538
539             // <author> uses URI
540
541             if ($tag == 'author') {
542                 $xo->element(self::URI, null, $this->id);
543             } else {
544                 $xo->element(self::ID, null, $this->id);
545             }
546
547             if (!empty($this->title)) {
548                 $name = common_xml_safe_str($this->title);
549                 if ($tag == 'author') {
550                     // XXX: Backward compatibility hack -- atom:name should contain
551                     // full name here, instead of nickname, i.e.: $name. Change
552                     // this in the next version.
553                     $xo->element(self::NAME, null, $this->poco->preferredUsername);
554                 } else {
555                     $xo->element(self::TITLE, null, $name);
556                 }
557             }
558
559             if (!empty($this->summary)) {
560                 $xo->element(
561                     self::SUMMARY,
562                     null,
563                     common_xml_safe_str($this->summary)
564                 );
565             }
566
567             if (!empty($this->content)) {
568                 // XXX: assuming HTML content here
569                 $xo->element(
570                     ActivityUtils::CONTENT,
571                     array('type' => 'html'),
572                     common_xml_safe_str($this->content)
573                 );
574             }
575
576             if (!empty($this->link)) {
577                 $xo->element(
578                     'link',
579                     array(
580                         'rel' => 'alternate',
581                         'type' => 'text/html',
582                         'href' => $this->link
583                     ),
584                     null
585                 );
586             }
587
588             if ($this->type == ActivityObject::PERSON
589                 || $this->type == ActivityObject::GROUP) {
590
591                 foreach ($this->avatarLinks as $avatar) {
592                     $xo->element(
593                         'link', array(
594                             'rel'  => 'avatar',
595                             'type'         => $avatar->type,
596                             'media:width'  => $avatar->width,
597                             'media:height' => $avatar->height,
598                             'href' => $avatar->url
599                         ),
600                         null
601                     );
602                 }
603             }
604
605             if (!empty($this->geopoint)) {
606                 $xo->element(
607                     'georss:point',
608                     null,
609                     $this->geopoint
610                 );
611             }
612
613             if (!empty($this->poco)) {
614                 $this->poco->outputTo($xo);
615             }
616
617             // @fixme there's no way here to make a tree; elements can only contain plaintext
618             // @fixme these may collide with JSON extensions
619             foreach ($this->extra as $el) {
620                 list($extraTag, $attrs, $content) = $el;
621                 $xo->element($extraTag, $attrs, $content);
622             }
623
624             Event::handle('EndActivityObjectOutputAtom', array($this, $xo));
625         }
626
627                 if (!empty($tag)) {
628                         $xo->elementEnd($tag);
629                 }
630
631         return;
632         }
633
634     function asString($tag='activity:object')
635     {
636         $xs = new XMLStringer(true);
637
638                 $this->outputTo($xs, $tag);
639
640         return $xs->getString();
641     }
642
643     /*
644      * Returns an array based on this Activity Object suitable for
645      * encoding as JSON.
646      *
647      * @return array $object the activity object array
648      */
649
650     function asArray()
651     {
652         $object = array();
653
654         if (Event::handle('StartActivityObjectOutputJson', array($this, &$object))) {
655             // XXX: attachedObjects are added by Activity
656
657             // displayName
658             $object['displayName'] = $this->title;
659
660             // TODO: downstreamDuplicates
661
662             // embedCode (used for video)
663
664             // id
665             //
666             // XXX: Should we use URL here? or a crazy tag URI?
667             $object['id'] = $this->id;
668
669             if ($this->type == ActivityObject::PERSON
670                 || $this->type == ActivityObject::GROUP) {
671
672                 // XXX: Not sure what the best avatar is to use for the
673                 // author's "image". For now, I'm using the large size.
674
675                 $avatarLarge      = null;
676                 $avatarMediaLinks = array();
677
678                 foreach ($this->avatarLinks as $a) {
679
680                     // Make a MediaLink for every other Avatar
681                     $avatar = new ActivityStreamsMediaLink(
682                         $a->url,
683                         $a->width,
684                         $a->height,
685                         $a->type,
686                         'avatar'
687                     );
688
689                     // Find the big avatar to use as the "image"
690                     if ($a->height == AVATAR_PROFILE_SIZE) {
691                         $imgLink = $avatar;
692                     }
693
694                     $avatarMediaLinks[] = $avatar->asArray();
695                 }
696
697                 $object['avatarLinks'] = $avatarMediaLinks; // extension
698
699                 // image
700                 $object['image']  = $imgLink->asArray();
701             }
702
703             // objectType
704             //
705             // We can probably use the whole schema URL here but probably the
706             // relative simple name is easier to parse
707             // @fixme this breaks extension URIs
708             $object['type'] = substr($this->type, strrpos($this->type, '/') + 1);
709
710             // summary
711             $object['summary'] = $this->summary;
712
713             // TODO: upstreamDuplicates
714
715             // url (XXX: need to put the right thing here...)
716             $object['url'] = $this->id;
717
718             /* Extensions */
719             // @fixme these may collide with XML extensions
720             // @fixme multiple tags of same name will overwrite each other
721             // @fixme text content from XML extensions will be lost
722             foreach ($this->extra as $e) {
723                 list($objectName, $props, $txt) = $e;
724                 $object[$objectName] = $props;
725             }
726
727             // GeoJSON
728
729             if (!empty($this->geopoint)) {
730
731                 list($lat, $long) = explode(' ', $this->geopoint);
732
733                 $object['geopoint'] = array(
734                     'type'        => 'Point',
735                     'coordinates' => array($lat, $long)
736                 );
737             }
738
739             if (!empty($this->poco)) {
740                 $object['contact'] = $this->poco->asArray();
741             }
742             Event::handle('EndActivityObjectOutputJson', array($this, &$object));
743         }
744         return array_filter($object);
745     }
746 }