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
111 * Turns a regular old Atom <entry> into a magical activity
113 * @param DOMElement $entry Atom entry to poke at
114 * @param DOMElement $feed Atom feed, for context
116 function __construct($entry = null, $feed = null)
118 if (is_null($entry)) {
122 // Insist on a feed's root DOMElement; don't allow a DOMDocument
123 if ($feed instanceof DOMDocument) {
124 throw new ClientException(
125 // TRANS: Client exception thrown when a feed instance is a DOMDocument.
126 _('Expecting a root feed element but got a whole XML document.')
130 $this->entry = $entry;
133 if ($entry->namespaceURI == Activity::ATOM &&
134 $entry->localName == 'entry') {
135 $this->_fromAtomEntry($entry, $feed);
136 } else if ($entry->namespaceURI == Activity::RSS &&
137 $entry->localName == 'item') {
138 $this->_fromRssItem($entry, $feed);
139 } else if ($entry->namespaceURI == Activity::SPEC &&
140 $entry->localName == 'object') {
141 $this->_fromAtomEntry($entry, $feed);
143 // Low level exception. No need for i18n.
144 throw new Exception("Unknown DOM element: {$entry->namespaceURI} {$entry->localName}");
148 function _fromAtomEntry($entry, $feed)
150 $pubEl = $this->_child($entry, self::PUBLISHED, self::ATOM);
152 if (!empty($pubEl)) {
153 $this->time = strtotime($pubEl->textContent);
155 // XXX technically an error; being liberal. Good idea...?
156 $updateEl = $this->_child($entry, self::UPDATED, self::ATOM);
157 if (!empty($updateEl)) {
158 $this->time = strtotime($updateEl->textContent);
164 $this->link = ActivityUtils::getPermalink($entry);
166 $verbEl = $this->_child($entry, self::VERB);
168 if (!empty($verbEl)) {
169 $this->verb = trim($verbEl->textContent);
171 $this->verb = ActivityVerb::POST;
172 // XXX: do other implied stuff here
175 // get immediate object children
177 $objectEls = ActivityUtils::children($entry, self::OBJECT, self::SPEC);
179 if (count($objectEls) > 0) {
180 foreach ($objectEls as $objectEl) {
181 // Special case for embedded activities
182 $objectType = ActivityUtils::childContent($objectEl, self::OBJECTTYPE, self::SPEC);
183 if (!empty($objectType) && $objectType == ActivityObject::ACTIVITY) {
184 $this->objects[] = new Activity($objectEl);
186 $this->objects[] = new ActivityObject($objectEl);
191 $this->objects[] = new ActivityObject($entry);
194 $actorEl = $this->_child($entry, self::ACTOR);
196 if (!empty($actorEl)) {
197 // Standalone <activity:actor> elements are a holdover from older
198 // versions of ActivityStreams. Newer feeds should have this data
199 // integrated straight into <atom:author>.
201 $this->actor = new ActivityObject($actorEl);
203 // Cliqset has bad actor IDs (just nickname of user). We
204 // work around it by getting the author data and using its
207 if (!preg_match('/^\w+:/', $this->actor->id)) {
208 $authorEl = ActivityUtils::child($entry, 'author');
209 if (!empty($authorEl)) {
210 $authorObj = new ActivityObject($authorEl);
211 $this->actor->id = $authorObj->id;
214 } else if ($authorEl = $this->_child($entry, self::AUTHOR, self::ATOM)) {
216 // An <atom:author> in the entry overrides any author info on
217 // the surrounding feed.
218 $this->actor = new ActivityObject($authorEl);
220 } else if (!empty($feed) &&
221 $subjectEl = $this->_child($feed, self::SUBJECT)) {
223 // Feed subject is used for things like groups.
224 // Should actually possibly not be interpreted as an actor...?
225 $this->actor = new ActivityObject($subjectEl);
227 } else if (!empty($feed) && $authorEl = $this->_child($feed, self::AUTHOR,
230 // If there's no <atom:author> on the entry, it's safe to assume
231 // the containing feed's authorship info applies.
232 $this->actor = new ActivityObject($authorEl);
235 $contextEl = $this->_child($entry, self::CONTEXT);
237 if (!empty($contextEl)) {
238 $this->context = new ActivityContext($contextEl);
240 $this->context = new ActivityContext($entry);
243 $targetEl = $this->_child($entry, self::TARGET);
245 if (!empty($targetEl)) {
246 $this->target = new ActivityObject($targetEl);
247 } elseif (ActivityUtils::compareTypes($this->verb, array(ActivityVerb::FAVORITE))) {
248 // StatusNet didn't send a 'target' for their Favorite atom entries
249 $this->target = clone($this->objects[0]);
252 $this->summary = ActivityUtils::childContent($entry, 'summary');
253 $this->id = ActivityUtils::childContent($entry, 'id');
254 $this->content = ActivityUtils::getContent($entry);
256 $catEls = $entry->getElementsByTagNameNS(self::ATOM, 'category');
258 for ($i = 0; $i < $catEls->length; $i++) {
259 $catEl = $catEls->item($i);
260 $this->categories[] = new AtomCategory($catEl);
264 foreach (ActivityUtils::getLinks($entry, 'enclosure') as $link) {
265 $this->enclosures[] = $link->getAttribute('href');
268 // From APP. Might be useful.
270 $this->selfLink = ActivityUtils::getLink($entry, 'self', 'application/atom+xml');
271 $this->editLink = ActivityUtils::getLink($entry, 'edit', 'application/atom+xml');
274 function _fromRssItem($item, $channel)
276 $verbEl = $this->_child($item, self::VERB);
278 if (!empty($verbEl)) {
279 $this->verb = trim($verbEl->textContent);
281 $this->verb = ActivityVerb::POST;
282 // XXX: do other implied stuff here
285 $pubDateEl = $this->_child($item, self::PUBDATE, self::RSS);
287 if (!empty($pubDateEl)) {
288 $this->time = strtotime($pubDateEl->textContent);
291 if ($authorEl = $this->_child($item, self::AUTHOR, self::RSS)) {
292 $this->actor = ActivityObject::fromRssAuthor($authorEl);
293 } else if ($dcCreatorEl = $this->_child($item, self::CREATOR, self::DC)) {
294 $this->actor = ActivityObject::fromDcCreator($dcCreatorEl);
295 } else if ($posterousEl = $this->_child($item, ActivityObject::AUTHOR, ActivityObject::POSTEROUS)) {
296 // Special case for Posterous.com
297 $this->actor = ActivityObject::fromPosterousAuthor($posterousEl);
298 } else if (!empty($channel)) {
299 $this->actor = ActivityObject::fromRssChannel($channel);
304 $this->title = ActivityUtils::childContent($item, ActivityObject::TITLE, self::RSS);
306 $contentEl = ActivityUtils::child($item, self::ENCODED, self::CONTENTNS);
308 if (!empty($contentEl)) {
309 // <content:encoded> XML node's text content is HTML; no further processing needed.
310 $this->content = $contentEl->textContent;
312 $descriptionEl = ActivityUtils::child($item, self::DESCRIPTION, self::RSS);
313 if (!empty($descriptionEl)) {
314 // Per spec, <description> must be plaintext.
315 // In practice, often there's HTML... but these days good
316 // feeds are using <content:encoded> which is explicitly
318 // We'll treat this following spec, and do HTML escaping
319 // to convert from plaintext to HTML.
320 $this->content = htmlspecialchars($descriptionEl->textContent);
324 $this->link = ActivityUtils::childContent($item, ActivityUtils::LINK, self::RSS);
327 // @fixme thumbnails... maybe
329 $guidEl = ActivityUtils::child($item, self::GUID, self::RSS);
331 if (!empty($guidEl)) {
332 $this->id = $guidEl->textContent;
334 if ($guidEl->hasAttribute('isPermaLink') && $guidEl->getAttribute('isPermaLink') != 'false') {
336 $this->link = $this->id;
340 $this->objects[] = new ActivityObject($item);
341 $this->context = new ActivityContext($item);
345 * Returns an Atom <entry> based on this activity
347 * @return DOMElement Atom entry
350 function toAtomEntry()
356 * Returns an array based on this activity suitable
357 * for encoding as a JSON object
359 * @return array $activity
367 $activity['actor'] = $this->actor->asArray();
370 $activity['content'] = $this->content;
374 if (!empty($this->generator)) {
375 $activity['generator'] = $this->generator->asArray();
378 // icon <-- possibly a mini object representing verb?
381 $activity['id'] = $this->id;
385 if (count($this->objects) == 0) {
386 common_log(LOG_ERR, "Can't save " . $this->id);
388 if (count($this->objects) > 1) {
389 common_log(LOG_WARNING, "Ignoring " . (count($this->objects) - 1) . " extra objects in JSON output for activity " . $this->id);
391 $object = $this->objects[0];
393 if ($object instanceof Activity) {
394 // Sharing a post activity is more like sharing the original object
395 if (ActivityVerb::canonical($this->verb) == ActivityVerb::canonical(ActivityVerb::SHARE) &&
396 ActivityVerb::canonical($object->verb) == ActivityVerb::canonical(ActivityVerb::POST)) {
397 // XXX: Here's one for the obfuscation record books
398 $object = $object->objects[0];
402 $activity['object'] = $object->asArray();
404 if ($object instanceof Activity) {
405 $activity['object']['objectType'] = 'activity';
408 foreach ($this->attachments as $attachment) {
409 if (empty($activity['object']['attachments'])) {
410 $activity['object']['attachments'] = array();
412 $activity['object']['attachments'][] = $attachment->asArray();
418 if (!empty($this->context)) {
420 if (!empty($this->context->location)) {
421 $loc = $this->context->location;
423 $activity['location'] = array(
424 'objectType' => 'place',
425 'position' => sprintf("%+02.5F%+03.5F/", $loc->lat, $loc->lon),
430 $name = $loc->getName();
433 $activity['location']['displayName'] = $name;
436 $url = $loc->getURL();
439 $activity['location']['url'] = $url;
443 $activity['to'] = $this->context->getToArray();
445 $ctxarr = $this->context->asArray();
447 if (array_key_exists('inReplyTo', $ctxarr)) {
448 $activity['object']['inReplyTo'] = $ctxarr['inReplyTo'];
449 unset($ctxarr['inReplyTo']);
452 if (!array_key_exists('status_net', $activity)) {
453 $activity['status_net'] = array();
456 foreach ($ctxarr as $key => $value) {
457 $activity['status_net'][$key] = $value;
462 $activity['published'] = self::iso8601Date($this->time);
466 'objectType' => 'service',
467 'displayName' => common_config('site', 'name'),
468 'url' => common_root_url()
471 $activity['provider'] = $provider;
474 if (!empty($this->target)) {
475 $activity['target'] = $this->target->asArray();
479 $activity['title'] = $this->title;
481 // updated <-- Optional. Should we use this to indicate the time we r
482 // eceived a remote notice? Probably not.
486 $activity['verb'] = ActivityVerb::canonical($this->verb);
490 $activity['url'] = $this->link;
493 /* Purely extensions hereafter */
495 if ($activity['verb'] == 'post') {
497 foreach ($this->categories as $cat) {
498 if (mb_strlen($cat->term) > 0) {
499 // Couldn't figure out which object type to use, so...
500 $tags[] = array('objectType' => 'http://activityschema.org/object/hashtag',
501 'displayName' => $cat->term);
504 if (count($tags) > 0) {
505 $activity['object']['tags'] = $tags;
509 // XXX: a bit of a hack... Since JSON isn't namespaced we probably
510 // shouldn't be using 'statusnet:notice_info', but this will work
513 foreach ($this->extra as $e) {
514 list($objectName, $props, $txt) = $e;
515 if (!empty($objectName)) {
516 $parts = explode(":", $objectName);
517 if (count($parts) == 2 && $parts[0] == "statusnet") {
518 if (!array_key_exists('status_net', $activity)) {
519 $activity['status_net'] = array();
521 $activity['status_net'][$parts[1]] = $props;
523 $activity[$objectName] = $props;
528 return array_filter($activity);
531 function asString($namespace=false, $author=true, $source=false)
533 $xs = new XMLStringer(true);
534 $this->outputTo($xs, $namespace, $author, $source);
535 return $xs->getString();
538 function outputTo($xs, $namespace=false, $author=true, $source=false, $tag='entry')
541 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
542 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
543 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
544 'xmlns:georss' => 'http://www.georss.org/georss',
545 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
546 'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
547 'xmlns:media' => 'http://purl.org/syndication/atommedia',
548 'xmlns:statusnet' => 'http://status.net/schema/api/1/');
553 $xs->elementStart($tag, $attrs);
555 if ($tag != 'entry') {
556 $xs->element('activity:object-type', null, ActivityObject::ACTIVITY);
559 if ($this->verb == ActivityVerb::POST && count($this->objects) == 1 && $tag == 'entry') {
561 $obj = $this->objects[0];
562 $obj->outputTo($xs, null);
565 $xs->element('id', null, $this->id);
568 $xs->element('title', null, $this->title);
571 $xs->element('title', null, "");
574 $xs->element('content', array('type' => 'html'), $this->content);
576 if (!empty($this->summary)) {
577 $xs->element('summary', null, $this->summary);
580 if (!empty($this->link)) {
581 $xs->element('link', array('rel' => 'alternate',
582 'type' => 'text/html'),
588 $xs->element('activity:verb', null, $this->verb);
590 $published = self::iso8601Date($this->time);
592 $xs->element('published', null, $published);
593 $xs->element('updated', null, $published);
596 $this->actor->outputTo($xs, 'author');
599 if ($this->verb != ActivityVerb::POST || count($this->objects) != 1 || $tag != 'entry') {
600 foreach($this->objects as $object) {
601 if ($object instanceof Activity) {
602 $object->outputTo($xs, false, true, true, 'activity:object');
604 $object->outputTo($xs, 'activity:object');
609 if (!empty($this->context)) {
611 if (!empty($this->context->replyToID)) {
612 if (!empty($this->context->replyToUrl)) {
613 $xs->element('thr:in-reply-to',
614 array('ref' => $this->context->replyToID,
615 'href' => $this->context->replyToUrl));
617 $xs->element('thr:in-reply-to',
618 array('ref' => $this->context->replyToID));
622 if (!empty($this->context->replyToUrl)) {
623 $xs->element('link', array('rel' => 'related',
624 'href' => $this->context->replyToUrl));
627 if (!empty($this->context->conversation)) {
628 $xs->element('link', array('rel' => ActivityContext::CONVERSATION,
629 'href' => $this->context->conversation));
632 foreach ($this->context->attention as $attnURI=>$type) {
633 $xs->element('link', array('rel' => ActivityContext::MENTIONED,
634 ActivityContext::OBJECTTYPE => $type, // FIXME: undocumented
635 'href' => $attnURI));
638 if (!empty($this->context->location)) {
639 $loc = $this->context->location;
640 $xs->element('georss:point', null, $loc->lat . ' ' . $loc->lon);
645 $this->target->outputTo($xs, 'activity:target');
648 foreach ($this->categories as $cat) {
652 // can be either URLs or enclosure objects
654 foreach ($this->enclosures as $enclosure) {
655 if (is_string($enclosure)) {
656 $xs->element('link', array('rel' => 'enclosure',
657 'href' => $enclosure));
659 $attributes = array('rel' => 'enclosure',
660 'href' => $enclosure->url,
661 'type' => $enclosure->mimetype,
662 'length' => $enclosure->size);
663 if ($enclosure->title) {
664 $attributes['title'] = $enclosure->title;
666 $xs->element('link', $attributes);
670 // Info on the source feed
672 if ($source && !empty($this->source)) {
673 $xs->elementStart('source');
675 $xs->element('id', null, $this->source->id);
676 $xs->element('title', null, $this->source->title);
678 if (array_key_exists('alternate', $this->source->links)) {
679 $xs->element('link', array('rel' => 'alternate',
680 'type' => 'text/html',
681 'href' => $this->source->links['alternate']));
684 if (array_key_exists('self', $this->source->links)) {
685 $xs->element('link', array('rel' => 'self',
686 'type' => 'application/atom+xml',
687 'href' => $this->source->links['self']));
690 if (array_key_exists('license', $this->source->links)) {
691 $xs->element('link', array('rel' => 'license',
692 'href' => $this->source->links['license']));
695 if (!empty($this->source->icon)) {
696 $xs->element('icon', null, $this->source->icon);
699 if (!empty($this->source->updated)) {
700 $xs->element('updated', null, $this->source->updated);
703 $xs->elementEnd('source');
706 if (!empty($this->selfLink)) {
707 $xs->element('link', array('rel' => 'self',
708 'type' => 'application/atom+xml',
709 'href' => $this->selfLink));
712 if (!empty($this->editLink)) {
713 $xs->element('link', array('rel' => 'edit',
714 'type' => 'application/atom+xml',
715 'href' => $this->editLink));
718 // For throwing in extra elements; used for statusnet:notice_info
720 foreach ($this->extra as $el) {
721 list($tag, $attrs, $content) = $el;
722 $xs->element($tag, $attrs, $content);
725 $xs->elementEnd($tag);
730 private function _child($element, $tag, $namespace=self::SPEC)
732 return ActivityUtils::child($element, $tag, $namespace);
736 * For consistency, we'll always output UTC rather than local time.
737 * Note that clients *should* accept any timezone we give them as long
738 * as it's properly formatted.
740 * @param int $tm Unix timestamp
743 static function iso8601Date($tm)
745 $dateStr = date('d F Y H:i:s', $tm);
746 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
747 return $d->format('c');