]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/activity.php
a8e6d25af955281c33244ab3be419a38fd73a96b
[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 /**
36  * An activity in the ActivityStrea.ms world
37  *
38  * An activity is kind of like a sentence: someone did something
39  * to something else.
40  *
41  * 'someone' is the 'actor'; 'did something' is the verb;
42  * 'something else' is the object.
43  *
44  * @category  OStatus
45  * @package   StatusNet
46  * @author    Evan Prodromou <evan@status.net>
47  * @copyright 2010 StatusNet, Inc.
48  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
49  * @link      http://status.net/
50  */
51 class Activity
52 {
53     const SPEC   = 'http://activitystrea.ms/spec/1.0/';
54     const SCHEMA = 'http://activitystrea.ms/schema/1.0/';
55     const MEDIA  = 'http://purl.org/syndication/atommedia';
56
57     const VERB       = 'verb';
58     const OBJECT     = 'object';
59     const ACTOR      = 'actor';
60     const SUBJECT    = 'subject';
61     const OBJECTTYPE = 'object-type';
62     const CONTEXT    = 'context';
63     const TARGET     = 'target';
64
65     const ATOM = 'http://www.w3.org/2005/Atom';
66
67     const AUTHOR    = 'author';
68     const PUBLISHED = 'published';
69     const UPDATED   = 'updated';
70
71     const RSS = null; // no namespace!
72
73     const PUBDATE     = 'pubDate';
74     const DESCRIPTION = 'description';
75     const GUID        = 'guid';
76     const SELF        = 'self';
77     const IMAGE       = 'image';
78     const URL         = 'url';
79
80     const DC = 'http://purl.org/dc/elements/1.1/';
81
82     const CREATOR = 'creator';
83
84     const CONTENTNS = 'http://purl.org/rss/1.0/modules/content/';
85     const ENCODED = 'encoded';
86
87     public $actor;   // an ActivityObject
88     public $verb;    // a string (the URL)
89     public $objects = array();  // an array of ActivityObjects
90     public $target;  // an ActivityObject
91     public $context; // an ActivityObject
92     public $time;    // Time of the activity
93     public $link;    // an ActivityObject
94     public $entry;   // the source entry
95     public $feed;    // the source feed
96
97     public $summary; // summary of activity
98     public $content; // HTML content of activity
99     public $id;      // ID of the activity
100     public $title;   // title of the activity
101     public $categories = array(); // list of AtomCategory objects
102     public $enclosures = array(); // list of enclosure URL references
103
104     public $extra = array(); // extra elements as array(tag, attrs, content)
105     public $source;  // ActivitySource object representing 'home feed'
106     public $selfLink; // <link rel='self' type='application/atom+xml'>
107     public $editLink; // <link rel='edit' type='application/atom+xml'>
108
109     /**
110      * Turns a regular old Atom <entry> into a magical activity
111      *
112      * @param DOMElement $entry Atom entry to poke at
113      * @param DOMElement $feed  Atom feed, for context
114      */
115     function __construct($entry = null, $feed = null)
116     {
117         if (is_null($entry)) {
118             return;
119         }
120
121         // Insist on a feed's root DOMElement; don't allow a DOMDocument
122         if ($feed instanceof DOMDocument) {
123             throw new ClientException(
124                 // TRANS: Client exception thrown when a feed instance is a DOMDocument.
125                 _('Expecting a root feed element but got a whole XML document.')
126             );
127         }
128
129         $this->entry = $entry;
130         $this->feed  = $feed;
131
132         if ($entry->namespaceURI == Activity::ATOM &&
133             $entry->localName == 'entry') {
134             $this->_fromAtomEntry($entry, $feed);
135         } else if ($entry->namespaceURI == Activity::RSS &&
136                    $entry->localName == 'item') {
137             $this->_fromRssItem($entry, $feed);
138         } else {
139             // Low level exception. No need for i18n.
140             throw new Exception("Unknown DOM element: {$entry->namespaceURI} {$entry->localName}");
141         }
142     }
143
144     function _fromAtomEntry($entry, $feed)
145     {
146         $pubEl = $this->_child($entry, self::PUBLISHED, self::ATOM);
147
148         if (!empty($pubEl)) {
149             $this->time = strtotime($pubEl->textContent);
150         } else {
151             // XXX technically an error; being liberal. Good idea...?
152             $updateEl = $this->_child($entry, self::UPDATED, self::ATOM);
153             if (!empty($updateEl)) {
154                 $this->time = strtotime($updateEl->textContent);
155             } else {
156                 $this->time = null;
157             }
158         }
159
160         $this->link = ActivityUtils::getPermalink($entry);
161
162         $verbEl = $this->_child($entry, self::VERB);
163
164         if (!empty($verbEl)) {
165             $this->verb = trim($verbEl->textContent);
166         } else {
167             $this->verb = ActivityVerb::POST;
168             // XXX: do other implied stuff here
169         }
170
171         $objectEls = $entry->getElementsByTagNameNS(self::SPEC, self::OBJECT);
172
173         if ($objectEls->length > 0) {
174             for ($i = 0; $i < $objectEls->length; $i++) {
175                 $objectEl = $objectEls->item($i);
176                 $this->objects[] = new ActivityObject($objectEl);
177             }
178         } else {
179             $this->objects[] = new ActivityObject($entry);
180         }
181
182         $actorEl = $this->_child($entry, self::ACTOR);
183
184         if (!empty($actorEl)) {
185             // Standalone <activity:actor> elements are a holdover from older
186             // versions of ActivityStreams. Newer feeds should have this data
187             // integrated straight into <atom:author>.
188
189             $this->actor = new ActivityObject($actorEl);
190
191             // Cliqset has bad actor IDs (just nickname of user). We
192             // work around it by getting the author data and using its
193             // id instead
194
195             if (!preg_match('/^\w+:/', $this->actor->id)) {
196                 $authorEl = ActivityUtils::child($entry, 'author');
197                 if (!empty($authorEl)) {
198                     $authorObj = new ActivityObject($authorEl);
199                     $this->actor->id = $authorObj->id;
200                 }
201             }
202         } else if ($authorEl = $this->_child($entry, self::AUTHOR, self::ATOM)) {
203
204             // An <atom:author> in the entry overrides any author info on
205             // the surrounding feed.
206             $this->actor = new ActivityObject($authorEl);
207
208         } else if (!empty($feed) &&
209                    $subjectEl = $this->_child($feed, self::SUBJECT)) {
210
211             // Feed subject is used for things like groups.
212             // Should actually possibly not be interpreted as an actor...?
213             $this->actor = new ActivityObject($subjectEl);
214
215         } else if (!empty($feed) && $authorEl = $this->_child($feed, self::AUTHOR,
216                                                               self::ATOM)) {
217
218             // If there's no <atom:author> on the entry, it's safe to assume
219             // the containing feed's authorship info applies.
220             $this->actor = new ActivityObject($authorEl);
221         }
222
223         $contextEl = $this->_child($entry, self::CONTEXT);
224
225         if (!empty($contextEl)) {
226             $this->context = new ActivityContext($contextEl);
227         } else {
228             $this->context = new ActivityContext($entry);
229         }
230
231         $targetEl = $this->_child($entry, self::TARGET);
232
233         if (!empty($targetEl)) {
234             $this->target = new ActivityObject($targetEl);
235         }
236
237         $this->summary = ActivityUtils::childContent($entry, 'summary');
238         $this->id      = ActivityUtils::childContent($entry, 'id');
239         $this->content = ActivityUtils::getContent($entry);
240
241         $catEls = $entry->getElementsByTagNameNS(self::ATOM, 'category');
242         if ($catEls) {
243             for ($i = 0; $i < $catEls->length; $i++) {
244                 $catEl = $catEls->item($i);
245                 $this->categories[] = new AtomCategory($catEl);
246             }
247         }
248
249         foreach (ActivityUtils::getLinks($entry, 'enclosure') as $link) {
250             $this->enclosures[] = $link->getAttribute('href');
251         }
252
253         // From APP. Might be useful.
254
255         $this->selfLink = ActivityUtils::getLink($entry, 'self', 'application/atom+xml');
256         $this->editLink = ActivityUtils::getLink($entry, 'edit', 'application/atom+xml');
257     }
258
259     function _fromRssItem($item, $channel)
260     {
261         $verbEl = $this->_child($item, self::VERB);
262
263         if (!empty($verbEl)) {
264             $this->verb = trim($verbEl->textContent);
265         } else {
266             $this->verb = ActivityVerb::POST;
267             // XXX: do other implied stuff here
268         }
269
270         $pubDateEl = $this->_child($item, self::PUBDATE, self::RSS);
271
272         if (!empty($pubDateEl)) {
273             $this->time = strtotime($pubDateEl->textContent);
274         }
275
276         if ($authorEl = $this->_child($item, self::AUTHOR, self::RSS)) {
277             $this->actor = ActivityObject::fromRssAuthor($authorEl);
278         } else if ($dcCreatorEl = $this->_child($item, self::CREATOR, self::DC)) {
279             $this->actor = ActivityObject::fromDcCreator($dcCreatorEl);
280         } else if ($posterousEl = $this->_child($item, ActivityObject::AUTHOR, ActivityObject::POSTEROUS)) {
281             // Special case for Posterous.com
282             $this->actor = ActivityObject::fromPosterousAuthor($posterousEl);
283         } else if (!empty($channel)) {
284             $this->actor = ActivityObject::fromRssChannel($channel);
285         } else {
286             // No actor!
287         }
288
289         $this->title = ActivityUtils::childContent($item, ActivityObject::TITLE, self::RSS);
290
291         $contentEl = ActivityUtils::child($item, self::ENCODED, self::CONTENTNS);
292
293         if (!empty($contentEl)) {
294             // <content:encoded> XML node's text content is HTML; no further processing needed.
295             $this->content = $contentEl->textContent;
296         } else {
297             $descriptionEl = ActivityUtils::child($item, self::DESCRIPTION, self::RSS);
298             if (!empty($descriptionEl)) {
299                 // Per spec, <description> must be plaintext.
300                 // In practice, often there's HTML... but these days good
301                 // feeds are using <content:encoded> which is explicitly
302                 // real HTML.
303                 // We'll treat this following spec, and do HTML escaping
304                 // to convert from plaintext to HTML.
305                 $this->content = htmlspecialchars($descriptionEl->textContent);
306             }
307         }
308
309         $this->link = ActivityUtils::childContent($item, ActivityUtils::LINK, self::RSS);
310
311         // @fixme enclosures
312         // @fixme thumbnails... maybe
313
314         $guidEl = ActivityUtils::child($item, self::GUID, self::RSS);
315
316         if (!empty($guidEl)) {
317             $this->id = $guidEl->textContent;
318
319             if ($guidEl->hasAttribute('isPermaLink') && $guidEl->getAttribute('isPermaLink') != 'false') {
320                 // overwrites <link>
321                 $this->link = $this->id;
322             }
323         }
324
325         $this->objects[] = new ActivityObject($item);
326         $this->context   = new ActivityContext($item);
327     }
328
329     /**
330      * Returns an Atom <entry> based on this activity
331      *
332      * @return DOMElement Atom entry
333      */
334
335     function toAtomEntry()
336     {
337         return null;
338     }
339
340     /**
341      * Returns an array based on this activity suitable
342      * for encoding as a JSON object
343      *
344      * @return array $activity
345      */
346
347     function asArray()
348     {
349         $activity = array();
350
351         // actor
352         $activity['actor'] = $this->actor->asArray();
353
354         // body
355         $activity['body'] = $this->content;
356
357         // generator <-- We should use this when we know a notice is created
358         //               locally
359
360         // icon <-- Should we use this? Maybe a little bubble like we have
361         //          on Facebook posts?
362
363         // object
364         if ($this->verb == ActivityVerb::POST && count($this->objects) == 1) {
365             $activity['object'] = $this->objects[0]->asArray();
366
367             // Instead of adding enclosures as an extension to JSON
368             // Activities, it seems like we should be using the
369             // attachedObjects property of ActivityObject
370
371             $attachedObjects = array();
372
373             // XXX: OK, this is kinda cheating. We should probably figure out
374             // what kind of objects these are based on mime-type and then
375             // create specific object types. Right now this rely on
376             // duck-typing.  Also, we should include an embed code for
377             // video attachments.
378
379             foreach ($this->enclosures as $enclosure) {
380
381                 if (is_string($enclosure)) {
382
383                     $attachedObjects[]['id']  = $enclosure;
384
385                 } else {
386
387                     $attachedObjects[]['id']  = $enclosure->url;
388
389                     $mediaLink = new ActivityStreamsMediaLink(
390                         $enclosure->url,
391                         null,
392                         null,
393                         $enclosure->mimetype
394                         // XXX: Add 'size' as an extension to MediaLink?
395                     );
396
397                     $attachedObjects[]['mediaLink'] = $mediaLink->asArray(); // extension
398
399                     if ($enclosure->title) {
400                         $attachedObjects[]['displayName'] = $enclosure->title;
401                     }
402                }
403             }
404
405             if (!empty($attachedObjects)) {
406                 $activity['object']['attachedObjects'] = $attachedObjects;
407             }
408
409         } else {
410             $activity['object'] = array();
411             foreach($this->objects as $object) {
412                 $activity['object'][] = $object->asArray();
413             }
414         }
415
416         $activity['postedTime'] = self::iso8601Date($this->time); // Change to exactly be RFC3339?
417
418         // provider <-- We should probably use this for showing the the source
419         //              of remote notices, if known
420
421         // target
422         if (!empty($this->target)) {
423             $activity['target'] = $this->target->asArray();
424         }
425
426         // title
427         $activity['title'] = $this->title;
428
429         // updatedTime <-- Should we use this to indicate the time we received
430         //                 a remote notice? Probably not.
431
432         // verb
433         //
434         // We can probably use the whole schema URL here but probably the
435         // relative simple name is easier to parse
436         $activity['verb'] = substr($this->verb, strrpos($this->verb, '/') + 1);
437
438         /* Purely extensions hereafter */
439
440         // XXX: a bit of a hack... Since JSON isn't namespaced we probably
441         // shouldn't be using 'statusnet:notice_info', but this will work
442         // for the moment.
443
444         foreach ($this->extra as $e) {
445             list($objectName, $props, $txt) = $e;
446             if (!empty($objectName)) {
447                 $activity[$objectName] = $props;
448             }
449         }
450         return array_filter($activity);
451     }
452
453     function asString($namespace=false, $author=true, $source=false)
454     {
455         $xs = new XMLStringer(true);
456         $this->outputTo($xs, $namespace, $author, $source);
457         return $xs->getString();
458     }
459
460     function outputTo($xs, $namespace=false, $author=true, $source=false)
461     {
462         if ($namespace) {
463             $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
464                            'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
465                            'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
466                            'xmlns:georss' => 'http://www.georss.org/georss',
467                            'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
468                            'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
469                            'xmlns:media' => 'http://purl.org/syndication/atommedia',
470                            'xmlns:statusnet' => 'http://status.net/schema/api/1/');
471         } else {
472             $attrs = array();
473         }
474
475         $xs->elementStart('entry', $attrs);
476
477         if ($this->verb == ActivityVerb::POST && count($this->objects) == 1) {
478
479             $obj = $this->objects[0];
480                         $obj->outputTo($xs, null);
481
482         } else {
483             $xs->element('id', null, $this->id);
484             $xs->element('title', null, $this->title);
485
486             $xs->element('content', array('type' => 'html'), $this->content);
487
488             if (!empty($this->summary)) {
489                 $xs->element('summary', null, $this->summary);
490             }
491
492             if (!empty($this->link)) {
493                 $xs->element('link', array('rel' => 'alternate',
494                                            'type' => 'text/html'),
495                              $this->link);
496             }
497
498         }
499
500         $xs->element('activity:verb', null, $this->verb);
501
502         $published = self::iso8601Date($this->time);
503
504         $xs->element('published', null, $published);
505         $xs->element('updated', null, $published);
506
507         if ($author) {
508             $this->actor->outputTo($xs, 'author');
509
510             // XXX: Remove <activity:actor> ASAP! Author information
511             // has been moved to the author element in the Activity
512             // Streams spec. We're outputting actor only for backward
513             // compatibility with clients that can only parse
514             // activities based on older versions of the spec.
515
516             $depMsg = 'Deprecation warning: activity:actor is present '
517                 . 'only for backward compatibility. It will be '
518                 . 'removed in the next version of StatusNet.';
519             $xs->comment($depMsg);
520             $this->actor->outputTo($xs, 'activity:actor');
521         }
522
523         if ($this->verb != ActivityVerb::POST || count($this->objects) != 1) {
524             foreach($this->objects as $object) {
525                 $object->outputTo($xs, 'activity:object');
526             }
527         }
528
529         if (!empty($this->context)) {
530
531             if (!empty($this->context->replyToID)) {
532                 if (!empty($this->context->replyToUrl)) {
533                     $xs->element('thr:in-reply-to',
534                                  array('ref' => $this->context->replyToID,
535                                        'href' => $this->context->replyToUrl));
536                 } else {
537                     $xs->element('thr:in-reply-to',
538                                  array('ref' => $this->context->replyToID));
539                 }
540             }
541
542             if (!empty($this->context->replyToUrl)) {
543                 $xs->element('link', array('rel' => 'related',
544                                            'href' => $this->context->replyToUrl));
545             }
546
547             if (!empty($this->context->conversation)) {
548                 $xs->element('link', array('rel' => 'ostatus:conversation',
549                                            'href' => $this->context->conversation));
550             }
551
552             foreach ($this->context->attention as $attnURI) {
553                 $xs->element('link', array('rel' => 'ostatus:attention',
554                                            'href' => $attnURI));
555                 $xs->element('link', array('rel' => 'mentioned',
556                                            'href' => $attnURI));
557             }
558
559             // XXX: shoulda used ActivityVerb::SHARE
560
561             if (!empty($this->context->forwardID)) {
562                 if (!empty($this->context->forwardUrl)) {
563                     $xs->element('ostatus:forward',
564                                  array('ref' => $this->context->forwardID,
565                                        'href' => $this->context->forwardUrl));
566                 } else {
567                     $xs->element('ostatus:forward',
568                                  array('ref' => $this->context->forwardID));
569                 }
570             }
571
572             if (!empty($this->context->location)) {
573                 $loc = $this->context->location;
574                 $xs->element('georss:point', null, $loc->lat . ' ' . $loc->lon);
575             }
576         }
577
578         if ($this->target) {
579             $this->target->outputTo($xs, 'activity:target');
580         }
581
582         foreach ($this->categories as $cat) {
583             $cat->outputTo($xs);
584         }
585
586         // can be either URLs or enclosure objects
587
588         foreach ($this->enclosures as $enclosure) {
589             if (is_string($enclosure)) {
590                 $xs->element('link', array('rel' => 'enclosure',
591                                            'href' => $enclosure));
592             } else {
593                 $attributes = array('rel' => 'enclosure',
594                                     'href' => $enclosure->url,
595                                     'type' => $enclosure->mimetype,
596                                     'length' => $enclosure->size);
597                 if ($enclosure->title) {
598                     $attributes['title'] = $enclosure->title;
599                 }
600                 $xs->element('link', $attributes);
601             }
602         }
603
604         // Info on the source feed
605
606         if ($source && !empty($this->source)) {
607             $xs->elementStart('source');
608
609             $xs->element('id', null, $this->source->id);
610             $xs->element('title', null, $this->source->title);
611
612             if (array_key_exists('alternate', $this->source->links)) {
613                 $xs->element('link', array('rel' => 'alternate',
614                                            'type' => 'text/html',
615                                            'href' => $this->source->links['alternate']));
616             }
617
618             if (array_key_exists('self', $this->source->links)) {
619                 $xs->element('link', array('rel' => 'self',
620                                            'type' => 'application/atom+xml',
621                                            'href' => $this->source->links['self']));
622             }
623
624             if (array_key_exists('license', $this->source->links)) {
625                 $xs->element('link', array('rel' => 'license',
626                                            'href' => $this->source->links['license']));
627             }
628
629             if (!empty($this->source->icon)) {
630                 $xs->element('icon', null, $this->source->icon);
631             }
632
633             if (!empty($this->source->updated)) {
634                 $xs->element('updated', null, $this->source->updated);
635             }
636
637             $xs->elementEnd('source');
638         }
639
640         if (!empty($this->selfLink)) {
641             $xs->element('link', array('rel' => 'self',
642                                        'type' => 'application/atom+xml',
643                                        'href' => $this->selfLink));
644         }
645
646         if (!empty($this->editLink)) {
647             $xs->element('link', array('rel' => 'edit',
648                                        'type' => 'application/atom+xml',
649                                        'href' => $this->editLink));
650         }
651
652         // For throwing in extra elements; used for statusnet:notice_info
653
654         foreach ($this->extra as $el) {
655             list($tag, $attrs, $content) = $el;
656             $xs->element($tag, $attrs, $content);
657         }
658
659         $xs->elementEnd('entry');
660
661         return;
662     }
663
664     private function _child($element, $tag, $namespace=self::SPEC)
665     {
666         return ActivityUtils::child($element, $tag, $namespace);
667     }
668
669     static function iso8601Date($tm)
670     {
671         $dateStr = date('d F Y H:i:s', $tm);
672         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
673         $d->setTimezone(new DateTimeZone(common_timezone()));
674         return $d->format('c');
675     }
676 }