]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/activity.php
d3eeadcee9eb106d095e7e901f892e58a476a338
[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
186             $this->actor = new ActivityObject($actorEl);
187
188             // Cliqset has bad actor IDs (just nickname of user). We
189             // work around it by getting the author data and using its
190             // id instead
191
192             if (!preg_match('/^\w+:/', $this->actor->id)) {
193                 $authorEl = ActivityUtils::child($entry, 'author');
194                 if (!empty($authorEl)) {
195                     $authorObj = new ActivityObject($authorEl);
196                     $this->actor->id = $authorObj->id;
197                 }
198             }
199         } else if (!empty($feed) &&
200                    $subjectEl = $this->_child($feed, self::SUBJECT)) {
201
202             $this->actor = new ActivityObject($subjectEl);
203
204         } else if ($authorEl = $this->_child($entry, self::AUTHOR, self::ATOM)) {
205
206             $this->actor = new ActivityObject($authorEl);
207
208         } else if (!empty($feed) && $authorEl = $this->_child($feed, self::AUTHOR,
209                                                               self::ATOM)) {
210
211             $this->actor = new ActivityObject($authorEl);
212         }
213
214         $contextEl = $this->_child($entry, self::CONTEXT);
215
216         if (!empty($contextEl)) {
217             $this->context = new ActivityContext($contextEl);
218         } else {
219             $this->context = new ActivityContext($entry);
220         }
221
222         $targetEl = $this->_child($entry, self::TARGET);
223
224         if (!empty($targetEl)) {
225             $this->target = new ActivityObject($targetEl);
226         }
227
228         $this->summary = ActivityUtils::childContent($entry, 'summary');
229         $this->id      = ActivityUtils::childContent($entry, 'id');
230         $this->content = ActivityUtils::getContent($entry);
231
232         $catEls = $entry->getElementsByTagNameNS(self::ATOM, 'category');
233         if ($catEls) {
234             for ($i = 0; $i < $catEls->length; $i++) {
235                 $catEl = $catEls->item($i);
236                 $this->categories[] = new AtomCategory($catEl);
237             }
238         }
239
240         foreach (ActivityUtils::getLinks($entry, 'enclosure') as $link) {
241             $this->enclosures[] = $link->getAttribute('href');
242         }
243
244         // From APP. Might be useful.
245
246         $this->selfLink = ActivityUtils::getLink($entry, 'self', 'application/atom+xml');
247         $this->editLink = ActivityUtils::getLink($entry, 'edit', 'application/atom+xml');
248     }
249
250     function _fromRssItem($item, $channel)
251     {
252         $verbEl = $this->_child($item, self::VERB);
253
254         if (!empty($verbEl)) {
255             $this->verb = trim($verbEl->textContent);
256         } else {
257             $this->verb = ActivityVerb::POST;
258             // XXX: do other implied stuff here
259         }
260
261         $pubDateEl = $this->_child($item, self::PUBDATE, self::RSS);
262
263         if (!empty($pubDateEl)) {
264             $this->time = strtotime($pubDateEl->textContent);
265         }
266
267         if ($authorEl = $this->_child($item, self::AUTHOR, self::RSS)) {
268             $this->actor = ActivityObject::fromRssAuthor($authorEl);
269         } else if ($dcCreatorEl = $this->_child($item, self::CREATOR, self::DC)) {
270             $this->actor = ActivityObject::fromDcCreator($dcCreatorEl);
271         } else if ($posterousEl = $this->_child($item, ActivityObject::AUTHOR, ActivityObject::POSTEROUS)) {
272             // Special case for Posterous.com
273             $this->actor = ActivityObject::fromPosterousAuthor($posterousEl);
274         } else if (!empty($channel)) {
275             $this->actor = ActivityObject::fromRssChannel($channel);
276         } else {
277             // No actor!
278         }
279
280         $this->title = ActivityUtils::childContent($item, ActivityObject::TITLE, self::RSS);
281
282         $contentEl = ActivityUtils::child($item, self::ENCODED, self::CONTENTNS);
283
284         if (!empty($contentEl)) {
285             // <content:encoded> XML node's text content is HTML; no further processing needed.
286             $this->content = $contentEl->textContent;
287         } else {
288             $descriptionEl = ActivityUtils::child($item, self::DESCRIPTION, self::RSS);
289             if (!empty($descriptionEl)) {
290                 // Per spec, <description> must be plaintext.
291                 // In practice, often there's HTML... but these days good
292                 // feeds are using <content:encoded> which is explicitly
293                 // real HTML.
294                 // We'll treat this following spec, and do HTML escaping
295                 // to convert from plaintext to HTML.
296                 $this->content = htmlspecialchars($descriptionEl->textContent);
297             }
298         }
299
300         $this->link = ActivityUtils::childContent($item, ActivityUtils::LINK, self::RSS);
301
302         // @fixme enclosures
303         // @fixme thumbnails... maybe
304
305         $guidEl = ActivityUtils::child($item, self::GUID, self::RSS);
306
307         if (!empty($guidEl)) {
308             $this->id = $guidEl->textContent;
309
310             if ($guidEl->hasAttribute('isPermaLink') && $guidEl->getAttribute('isPermaLink') != 'false') {
311                 // overwrites <link>
312                 $this->link = $this->id;
313             }
314         }
315
316         $this->objects[] = new ActivityObject($item);
317         $this->context   = new ActivityContext($item);
318     }
319
320     /**
321      * Returns an Atom <entry> based on this activity
322      *
323      * @return DOMElement Atom entry
324      */
325     function toAtomEntry()
326     {
327         return null;
328     }
329
330     function asString($namespace=false, $author=true)
331     {
332         $c = Cache::instance();
333
334         $str = $c->get(Cache::codeKey('activity:as-string:'.$this->id));
335
336         if (!empty($str)) {
337             return $str;
338         }
339
340         $xs = new XMLStringer(true);
341
342         if ($namespace) {
343             $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
344                            'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
345                            'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
346                            'xmlns:georss' => 'http://www.georss.org/georss',
347                            'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
348                            'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
349                            'xmlns:media' => 'http://purl.org/syndication/atommedia',
350                            'xmlns:statusnet' => 'http://status.net/schema/api/1/');
351         } else {
352             $attrs = array();
353         }
354
355         $xs->elementStart('entry', $attrs);
356
357         if ($this->verb == ActivityVerb::POST && count($this->objects) == 1) {
358
359             $obj = $this->objects[0];
360
361             $xs->element('id', null, $obj->id);
362             $xs->element('activity:object-type', null, $obj->type);
363             
364             if (!empty($obj->title)) {
365                 $xs->element('title', null, $obj->title);
366             } else {
367                 // XXX need a better default title
368                 $xs->element('title', null, _('Post'));
369             }
370
371             if (!empty($obj->content)) {
372                 $xs->element('content', array('type' => 'html'), $obj->content);
373             }
374             
375             if (!empty($obj->summary)) {
376                 $xs->element('summary', null, $obj->summary);
377             }
378             
379             if (!empty($obj->link)) {
380                 $xs->element('link', array('rel' => 'alternate',
381                                            'type' => 'text/html'),
382                              $obj->link);
383             }
384
385             // XXX: some object types might have other values here.
386
387         } else {
388             $xs->element('id', null, $this->id);
389             $xs->element('title', null, $this->title);
390
391             $xs->element('content', array('type' => 'html'), $this->content);
392             
393             if (!empty($this->summary)) {
394                 $xs->element('summary', null, $this->summary);
395             }
396             
397             if (!empty($this->link)) {
398                 $xs->element('link', array('rel' => 'alternate',
399                                            'type' => 'text/html'),
400                              $this->link);
401             }
402
403         }
404
405         $xs->element('activity:verb', null, $this->verb);
406
407         $published = self::iso8601Date($this->time);
408             
409         $xs->element('published', null, $published);
410         $xs->element('updated', null, $published);
411             
412         if ($author) {
413             $xs->elementStart('author');
414             $xs->element('uri', array(), $this->actor->id);
415             if ($this->actor->title) {
416                 $xs->element('name', array(), $this->actor->title);
417             }
418             $xs->elementEnd('author');
419             $xs->raw($this->actor->asString('activity:actor'));
420         }
421
422         if ($this->verb != ActivityVerb::POST || count($this->objects) != 1) {
423             foreach($this->objects as $object) {
424                 $xs->raw($object->asString());
425             }
426         }
427
428         if (!empty($this->context)) {
429
430             if (!empty($this->context->replyToID)) {
431                 if (!empty($this->context->replyToUrl)) {
432                     $xs->element('thr:in-reply-to',
433                                  array('ref' => $this->context->replyToID,
434                                        'href' => $this->context->replyToUrl));
435                 } else {
436                     $xs->element('thr:in-reply-to',
437                                  array('ref' => $this->context->replyToID));
438                 }
439             }
440
441             if (!empty($this->context->replyToUrl)) {
442                 $xs->element('link', array('rel' => 'related',
443                                            'href' => $this->context->replyToUrl));
444             }
445
446             if (!empty($this->context->conversation)) {
447                 $xs->element('link', array('rel' => 'ostatus:conversation',
448                                            'href' => $this->context->conversation));
449             }
450
451             foreach ($this->context->attention as $attnURI) {
452                 $xs->element('link', array('rel' => 'ostatus:attention',
453                                            'href' => $attnURI));
454                 $xs->element('link', array('rel' => 'mentioned',
455                                            'href' => $attnURI));
456             }
457
458             // XXX: shoulda used ActivityVerb::SHARE
459
460             if (!empty($this->context->forwardID)) {
461                 if (!empty($this->context->forwardUrl)) {
462                     $xs->element('ostatus:forward',
463                                  array('ref' => $this->context->forwardID,
464                                        'href' => $this->context->forwardUrl));
465                 } else {
466                     $xs->element('ostatus:forward',
467                                  array('ref' => $this->context->forwardID));
468                 }
469             }
470
471             if (!empty($this->context->location)) {
472                 $loc = $this->context->location;
473                 $xs->element('georss:point', null, $loc->lat . ' ' . $loc->lon);
474             }
475         }
476
477         if ($this->target) {
478             $xs->raw($this->target->asString('activity:target'));
479         }
480
481         foreach ($this->categories as $cat) {
482             $xs->raw($cat->asString());
483         }
484
485         // can be either URLs or enclosure objects
486         
487         foreach ($this->enclosures as $enclosure) {
488             if (is_string($enclosure)) {
489                 $xs->element('link', array('rel' => 'enclosure',
490                                            'href' => $enclosure));
491             } else {
492                 $attributes = array('rel' => 'enclosure',
493                                     'href' => $enclosure->url,
494                                     'type' => $enclosure->mimetype,
495                                     'length' => $enclosure->size);
496                 if ($enclosure->title) {
497                     $attributes['title'] = $enclosure->title;
498                 }
499                 $xs->element('link', $attributes);
500             }
501         }
502
503         // Info on the source feed
504
505         if (!empty($this->source)) {
506             $xs->elementStart('source');
507             
508             $xs->element('id', null, $this->source->id);
509             $xs->element('title', null, $this->source->title);
510
511             if (array_key_exists('alternate', $this->source->links)) {
512                 $xs->element('link', array('rel' => 'alternate',
513                                            'type' => 'text/html',
514                                            'href' => $this->source->links['alternate']));
515             }
516             
517             if (array_key_exists('self', $this->source->links)) {
518                 $xs->element('link', array('rel' => 'self',
519                                            'type' => 'application/atom+xml',
520                                            'href' => $this->source->links['self']));
521             }
522
523             if (array_key_exists('license', $this->source->links)) {
524                 $xs->element('link', array('rel' => 'license',
525                                            'href' => $this->source->links['license']));
526             }
527
528             if (!empty($this->source->icon)) {
529                 $xs->element('icon', null, $this->source->icon);
530             }
531
532             if (!empty($this->source->updated)) {
533                 $xs->element('updated', null, $this->source->updated);
534             }
535             
536             $xs->elementEnd('source');
537         }
538
539         if (!empty($this->selfLink)) {
540             $xs->element('link', array('rel' => 'self',
541                                        'type' => 'application/atom+xml',
542                                        'href' => $this->selfLink));
543         }
544
545         if (!empty($this->editLink)) {
546             $xs->element('link', array('rel' => 'edit',
547                                        'type' => 'application/atom+xml',
548                                        'href' => $this->editLink));
549         }
550
551         // For throwing in extra elements; used for statusnet:notice_info
552         
553         foreach ($this->extra as $el) {
554             list($tag, $attrs, $content) = $el;
555             $xs->element($tag, $attrs, $content);
556         }
557
558         $xs->elementEnd('entry');
559
560         $str = $xs->getString();
561         
562         $c->set(Cache::codeKey('activity:as-string:'.$this->id), $str);
563         
564         return $str;
565     }
566
567     private function _child($element, $tag, $namespace=self::SPEC)
568     {
569         return ActivityUtils::child($element, $tag, $namespace);
570     }
571
572     static function iso8601Date($tm)
573     {
574         $dateStr = date('d F Y H:i:s', $tm);
575         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
576         $d->setTimezone(new DateTimeZone(common_timezone()));
577         return $d->format('c');
578     }
579 }