3 * StatusNet, the distributed open-source microblogging tool
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.
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.
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/>.
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/
31 if (!defined('STATUSNET')) {
36 * An activity in the ActivityStrea.ms world
38 * An activity is kind of like a sentence: someone did something
41 * 'someone' is the 'actor'; 'did something' is the verb;
42 * 'something else' is the object.
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/
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';
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';
65 const ATOM = 'http://www.w3.org/2005/Atom';
67 const AUTHOR = 'author';
68 const PUBLISHED = 'published';
69 const UPDATED = 'updated';
71 const RSS = null; // no namespace!
73 const PUBDATE = 'pubDate';
74 const DESCRIPTION = 'description';
77 const IMAGE = 'image';
80 const DC = 'http://purl.org/dc/elements/1.1/';
82 const CREATOR = 'creator';
84 const CONTENTNS = 'http://purl.org/rss/1.0/modules/content/';
85 const ENCODED = 'encoded';
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
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 public $attachments = array(); // list of attachments
105 public $extra = array(); // extra elements as array(tag, attrs, content)
106 public $source; // ActivitySource object representing 'home feed'
107 public $selfLink; // <link rel='self' type='application/atom+xml'>
108 public $editLink; // <link rel='edit' type='application/atom+xml'>
109 public $generator; // ActivityObject representing the generating application
112 * Turns a regular old Atom <entry> into a magical activity
114 * @param DOMElement $entry Atom entry to poke at
115 * @param DOMElement $feed Atom feed, for context
117 function __construct($entry = null, $feed = null)
119 if (is_null($entry)) {
123 // Insist on a feed's root DOMElement; don't allow a DOMDocument
124 if ($feed instanceof DOMDocument) {
125 throw new ClientException(
126 // TRANS: Client exception thrown when a feed instance is a DOMDocument.
127 _('Expecting a root feed element but got a whole XML document.')
131 $this->entry = $entry;
134 if ($entry->namespaceURI == Activity::ATOM &&
135 $entry->localName == 'entry') {
136 $this->_fromAtomEntry($entry, $feed);
137 } else if ($entry->namespaceURI == Activity::RSS &&
138 $entry->localName == 'item') {
139 $this->_fromRssItem($entry, $feed);
140 } else if ($entry->namespaceURI == Activity::SPEC &&
141 $entry->localName == 'object') {
142 $this->_fromAtomEntry($entry, $feed);
144 // Low level exception. No need for i18n.
145 throw new Exception("Unknown DOM element: {$entry->namespaceURI} {$entry->localName}");
149 function _fromAtomEntry($entry, $feed)
151 $pubEl = $this->_child($entry, self::PUBLISHED, self::ATOM);
153 if (!empty($pubEl)) {
154 $this->time = strtotime($pubEl->textContent);
156 // XXX technically an error; being liberal. Good idea...?
157 $updateEl = $this->_child($entry, self::UPDATED, self::ATOM);
158 if (!empty($updateEl)) {
159 $this->time = strtotime($updateEl->textContent);
165 $this->link = ActivityUtils::getPermalink($entry);
167 $verbEl = $this->_child($entry, self::VERB);
169 if (!empty($verbEl)) {
170 $this->verb = trim($verbEl->textContent);
172 $this->verb = ActivityVerb::POST;
173 // XXX: do other implied stuff here
176 // get immediate object children
178 $objectEls = ActivityUtils::children($entry, self::OBJECT, self::SPEC);
180 if (count($objectEls) > 0) {
181 foreach ($objectEls as $objectEl) {
182 // Special case for embedded activities
183 $objectType = ActivityUtils::childContent($objectEl, self::OBJECTTYPE, self::SPEC);
184 if (!empty($objectType) && $objectType == ActivityObject::ACTIVITY) {
185 $this->objects[] = new Activity($objectEl);
187 $this->objects[] = new ActivityObject($objectEl);
192 $this->objects[] = new ActivityObject($entry);
195 $actorEl = $this->_child($entry, self::ACTOR);
197 if (!empty($actorEl)) {
198 // Standalone <activity:actor> elements are a holdover from older
199 // versions of ActivityStreams. Newer feeds should have this data
200 // integrated straight into <atom:author>.
202 $this->actor = new ActivityObject($actorEl);
204 // Cliqset has bad actor IDs (just nickname of user). We
205 // work around it by getting the author data and using its
208 if (!preg_match('/^\w+:/', $this->actor->id)) {
209 $authorEl = ActivityUtils::child($entry, 'author');
210 if (!empty($authorEl)) {
211 $authorObj = new ActivityObject($authorEl);
212 $this->actor->id = $authorObj->id;
215 } else if ($authorEl = $this->_child($entry, self::AUTHOR, self::ATOM)) {
217 // An <atom:author> in the entry overrides any author info on
218 // the surrounding feed.
219 $this->actor = new ActivityObject($authorEl);
221 } else if (!empty($feed) &&
222 $subjectEl = $this->_child($feed, self::SUBJECT)) {
224 // Feed subject is used for things like groups.
225 // Should actually possibly not be interpreted as an actor...?
226 $this->actor = new ActivityObject($subjectEl);
228 } else if (!empty($feed) && $authorEl = $this->_child($feed, self::AUTHOR,
231 // If there's no <atom:author> on the entry, it's safe to assume
232 // the containing feed's authorship info applies.
233 $this->actor = new ActivityObject($authorEl);
236 $contextEl = $this->_child($entry, self::CONTEXT);
238 if (!empty($contextEl)) {
239 $this->context = new ActivityContext($contextEl);
241 $this->context = new ActivityContext($entry);
244 $targetEl = $this->_child($entry, self::TARGET);
246 if (!empty($targetEl)) {
247 $this->target = new ActivityObject($targetEl);
248 } elseif (ActivityUtils::compareTypes($this->verb, array(ActivityVerb::FAVORITE))) {
249 // StatusNet didn't send a 'target' for their Favorite atom entries
250 $this->target = clone($this->objects[0]);
253 $this->summary = ActivityUtils::childContent($entry, 'summary');
254 $this->id = ActivityUtils::childContent($entry, 'id');
255 $this->content = ActivityUtils::getContent($entry);
257 $catEls = $entry->getElementsByTagNameNS(self::ATOM, 'category');
259 for ($i = 0; $i < $catEls->length; $i++) {
260 $catEl = $catEls->item($i);
261 $this->categories[] = new AtomCategory($catEl);
265 foreach (ActivityUtils::getLinks($entry, 'enclosure') as $link) {
266 $this->enclosures[] = $link->getAttribute('href');
269 // From APP. Might be useful.
271 $this->selfLink = ActivityUtils::getLink($entry, 'self', 'application/atom+xml');
272 $this->editLink = ActivityUtils::getLink($entry, 'edit', 'application/atom+xml');
275 function _fromRssItem($item, $channel)
277 $verbEl = $this->_child($item, self::VERB);
279 if (!empty($verbEl)) {
280 $this->verb = trim($verbEl->textContent);
282 $this->verb = ActivityVerb::POST;
283 // XXX: do other implied stuff here
286 $pubDateEl = $this->_child($item, self::PUBDATE, self::RSS);
288 if (!empty($pubDateEl)) {
289 $this->time = strtotime($pubDateEl->textContent);
292 if ($authorEl = $this->_child($item, self::AUTHOR, self::RSS)) {
293 $this->actor = ActivityObject::fromRssAuthor($authorEl);
294 } else if ($dcCreatorEl = $this->_child($item, self::CREATOR, self::DC)) {
295 $this->actor = ActivityObject::fromDcCreator($dcCreatorEl);
296 } else if ($posterousEl = $this->_child($item, ActivityObject::AUTHOR, ActivityObject::POSTEROUS)) {
297 // Special case for Posterous.com
298 $this->actor = ActivityObject::fromPosterousAuthor($posterousEl);
299 } else if (!empty($channel)) {
300 $this->actor = ActivityObject::fromRssChannel($channel);
305 $this->title = ActivityUtils::childContent($item, ActivityObject::TITLE, self::RSS);
307 $contentEl = ActivityUtils::child($item, self::ENCODED, self::CONTENTNS);
309 if (!empty($contentEl)) {
310 // <content:encoded> XML node's text content is HTML; no further processing needed.
311 $this->content = $contentEl->textContent;
313 $descriptionEl = ActivityUtils::child($item, self::DESCRIPTION, self::RSS);
314 if (!empty($descriptionEl)) {
315 // Per spec, <description> must be plaintext.
316 // In practice, often there's HTML... but these days good
317 // feeds are using <content:encoded> which is explicitly
319 // We'll treat this following spec, and do HTML escaping
320 // to convert from plaintext to HTML.
321 $this->content = htmlspecialchars($descriptionEl->textContent);
325 $this->link = ActivityUtils::childContent($item, ActivityUtils::LINK, self::RSS);
328 // @fixme thumbnails... maybe
330 $guidEl = ActivityUtils::child($item, self::GUID, self::RSS);
332 if (!empty($guidEl)) {
333 $this->id = $guidEl->textContent;
335 if ($guidEl->hasAttribute('isPermaLink') && $guidEl->getAttribute('isPermaLink') != 'false') {
337 $this->link = $this->id;
341 $this->objects[] = new ActivityObject($item);
342 $this->context = new ActivityContext($item);
346 * Returns an Atom <entry> based on this activity
348 * @return DOMElement Atom entry
351 function toAtomEntry()
357 * Returns an array based on this activity suitable
358 * for encoding as a JSON object
360 * @return array $activity
368 $activity['actor'] = $this->actor->asArray();
371 $activity['content'] = $this->content;
375 if (!empty($this->generator)) {
376 $activity['generator'] = $this->generator->asArray();
379 // icon <-- possibly a mini object representing verb?
382 $activity['id'] = $this->id;
386 if (count($this->objects) == 0) {
387 common_log(LOG_ERR, "Can't save " . $this->id);
389 if (count($this->objects) > 1) {
390 common_log(LOG_WARNING, "Ignoring " . (count($this->objects) - 1) . " extra objects in JSON output for activity " . $this->id);
392 $object = $this->objects[0];
394 if ($object instanceof Activity) {
395 // Sharing a post activity is more like sharing the original object
396 if (ActivityVerb::canonical($this->verb) == ActivityVerb::canonical(ActivityVerb::SHARE) &&
397 ActivityVerb::canonical($object->verb) == ActivityVerb::canonical(ActivityVerb::POST)) {
398 // XXX: Here's one for the obfuscation record books
399 $object = $object->objects[0];
403 $activity['object'] = $object->asArray();
405 if ($object instanceof Activity) {
406 $activity['object']['objectType'] = 'activity';
409 foreach ($this->attachments as $attachment) {
410 if (empty($activity['object']['attachments'])) {
411 $activity['object']['attachments'] = array();
413 $activity['object']['attachments'][] = $attachment->asArray();
419 if (!empty($this->context)) {
421 if (!empty($this->context->location)) {
422 $loc = $this->context->location;
424 $activity['location'] = array(
425 'objectType' => 'place',
426 'position' => sprintf("%+02.5F%+03.5F/", $loc->lat, $loc->lon),
431 $name = $loc->getName();
434 $activity['location']['displayName'] = $name;
437 $url = $loc->getURL();
440 $activity['location']['url'] = $url;
444 $activity['to'] = $this->context->getToArray();
446 $ctxarr = $this->context->asArray();
448 if (array_key_exists('inReplyTo', $ctxarr)) {
449 $activity['object']['inReplyTo'] = $ctxarr['inReplyTo'];
450 unset($ctxarr['inReplyTo']);
453 if (!array_key_exists('status_net', $activity)) {
454 $activity['status_net'] = array();
457 foreach ($ctxarr as $key => $value) {
458 $activity['status_net'][$key] = $value;
463 $activity['published'] = self::iso8601Date($this->time);
467 'objectType' => 'service',
468 'displayName' => common_config('site', 'name'),
469 'url' => common_root_url()
472 $activity['provider'] = $provider;
475 if (!empty($this->target)) {
476 $activity['target'] = $this->target->asArray();
480 $activity['title'] = $this->title;
482 // updated <-- Optional. Should we use this to indicate the time we r
483 // eceived a remote notice? Probably not.
487 $activity['verb'] = ActivityVerb::canonical($this->verb);
491 $activity['url'] = $this->link;
494 /* Purely extensions hereafter */
496 if ($activity['verb'] == 'post') {
498 foreach ($this->categories as $cat) {
499 if (mb_strlen($cat->term) > 0) {
500 // Couldn't figure out which object type to use, so...
501 $tags[] = array('objectType' => 'http://activityschema.org/object/hashtag',
502 'displayName' => $cat->term);
505 if (count($tags) > 0) {
506 $activity['object']['tags'] = $tags;
510 // XXX: a bit of a hack... Since JSON isn't namespaced we probably
511 // shouldn't be using 'statusnet:notice_info', but this will work
514 foreach ($this->extra as $e) {
515 list($objectName, $props, $txt) = $e;
516 if (!empty($objectName)) {
517 $parts = explode(":", $objectName);
518 if (count($parts) == 2 && $parts[0] == "statusnet") {
519 if (!array_key_exists('status_net', $activity)) {
520 $activity['status_net'] = array();
522 $activity['status_net'][$parts[1]] = $props;
524 $activity[$objectName] = $props;
529 return array_filter($activity);
532 function asString($namespace=false, $author=true, $source=false)
534 $xs = new XMLStringer(true);
535 $this->outputTo($xs, $namespace, $author, $source);
536 return $xs->getString();
539 function outputTo($xs, $namespace=false, $author=true, $source=false, $tag='entry')
542 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
543 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
544 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
545 'xmlns:georss' => 'http://www.georss.org/georss',
546 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
547 'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
548 'xmlns:media' => 'http://purl.org/syndication/atommedia',
549 'xmlns:statusnet' => 'http://status.net/schema/api/1/');
554 $xs->elementStart($tag, $attrs);
556 if ($tag != 'entry') {
557 $xs->element('activity:object-type', null, ActivityObject::ACTIVITY);
560 if ($this->verb == ActivityVerb::POST && count($this->objects) == 1 && $tag == 'entry') {
562 $obj = $this->objects[0];
563 $obj->outputTo($xs, null);
566 $xs->element('id', null, $this->id);
569 $xs->element('title', null, $this->title);
572 $xs->element('title', null, "");
575 $xs->element('content', array('type' => 'html'), $this->content);
577 if (!empty($this->summary)) {
578 $xs->element('summary', null, $this->summary);
581 if (!empty($this->link)) {
582 $xs->element('link', array('rel' => 'alternate',
583 'type' => 'text/html'),
589 $xs->element('activity:verb', null, $this->verb);
591 $published = self::iso8601Date($this->time);
593 $xs->element('published', null, $published);
594 $xs->element('updated', null, $published);
597 $this->actor->outputTo($xs, 'author');
600 if ($this->verb != ActivityVerb::POST || count($this->objects) != 1 || $tag != 'entry') {
601 foreach($this->objects as $object) {
602 if ($object instanceof Activity) {
603 $object->outputTo($xs, false, true, true, 'activity:object');
605 $object->outputTo($xs, 'activity:object');
610 if (!empty($this->context)) {
612 if (!empty($this->context->replyToID)) {
613 if (!empty($this->context->replyToUrl)) {
614 $xs->element('thr:in-reply-to',
615 array('ref' => $this->context->replyToID,
616 'href' => $this->context->replyToUrl));
618 $xs->element('thr:in-reply-to',
619 array('ref' => $this->context->replyToID));
623 if (!empty($this->context->replyToUrl)) {
624 $xs->element('link', array('rel' => 'related',
625 'href' => $this->context->replyToUrl));
628 if (!empty($this->context->conversation)) {
629 $xs->element('link', array('rel' => ActivityContext::CONVERSATION,
630 'href' => $this->context->conversation));
631 $xs->element(ActivityContext::CONVERSATION, null, $this->context->conversation);
632 /* Since we use XMLWriter we just use the previously hardcoded prefix for ostatus,
633 otherwise we should use something like this:
634 $xs->elementNS(array(ActivityContext::OSTATUS => 'ostatus'), // namespace
635 'conversation', // tag (or the element name from ActivityContext::CONVERSATION)
637 $this->context->conversation); // content
641 foreach ($this->context->attention as $attnURI=>$type) {
642 $xs->element('link', array('rel' => ActivityContext::MENTIONED,
643 ActivityContext::OBJECTTYPE => $type, // FIXME: undocumented
644 'href' => $attnURI));
647 if (!empty($this->context->location)) {
648 $loc = $this->context->location;
649 $xs->element('georss:point', null, $loc->lat . ' ' . $loc->lon);
654 $this->target->outputTo($xs, 'activity:target');
657 foreach ($this->categories as $cat) {
661 // can be either URLs or enclosure objects
663 foreach ($this->enclosures as $enclosure) {
664 if (is_string($enclosure)) {
665 $xs->element('link', array('rel' => 'enclosure',
666 'href' => $enclosure));
668 $attributes = array('rel' => 'enclosure',
669 'href' => $enclosure->url,
670 'type' => $enclosure->mimetype,
671 'length' => $enclosure->size);
672 if ($enclosure->title) {
673 $attributes['title'] = $enclosure->title;
675 $xs->element('link', $attributes);
679 // Info on the source feed
681 if ($source && !empty($this->source)) {
682 $xs->elementStart('source');
684 $xs->element('id', null, $this->source->id);
685 $xs->element('title', null, $this->source->title);
687 if (array_key_exists('alternate', $this->source->links)) {
688 $xs->element('link', array('rel' => 'alternate',
689 'type' => 'text/html',
690 'href' => $this->source->links['alternate']));
693 if (array_key_exists('self', $this->source->links)) {
694 $xs->element('link', array('rel' => 'self',
695 'type' => 'application/atom+xml',
696 'href' => $this->source->links['self']));
699 if (array_key_exists('license', $this->source->links)) {
700 $xs->element('link', array('rel' => 'license',
701 'href' => $this->source->links['license']));
704 if (!empty($this->source->icon)) {
705 $xs->element('icon', null, $this->source->icon);
708 if (!empty($this->source->updated)) {
709 $xs->element('updated', null, $this->source->updated);
712 $xs->elementEnd('source');
715 if (!empty($this->selfLink)) {
716 $xs->element('link', array('rel' => 'self',
717 'type' => 'application/atom+xml',
718 'href' => $this->selfLink));
721 if (!empty($this->editLink)) {
722 $xs->element('link', array('rel' => 'edit',
723 'type' => 'application/atom+xml',
724 'href' => $this->editLink));
727 // For throwing in extra elements; used for statusnet:notice_info
729 foreach ($this->extra as $el) {
730 list($tag, $attrs, $content) = $el;
731 $xs->element($tag, $attrs, $content);
734 $xs->elementEnd($tag);
739 private function _child($element, $tag, $namespace=self::SPEC)
741 return ActivityUtils::child($element, $tag, $namespace);
745 * For consistency, we'll always output UTC rather than local time.
746 * Note that clients *should* accept any timezone we give them as long
747 * as it's properly formatted.
749 * @param int $tm Unix timestamp
752 static function iso8601Date($tm)
754 $dateStr = date('d F Y H:i:s', $tm);
755 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
756 return $d->format('c');