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