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
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'>
110 * Turns a regular old Atom <entry> into a magical activity
112 * @param DOMElement $entry Atom entry to poke at
113 * @param DOMElement $feed Atom feed, for context
115 function __construct($entry = null, $feed = null)
117 if (is_null($entry)) {
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.')
129 $this->entry = $entry;
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 if ($entry->namespaceURI == Activity::SPEC &&
139 $entry->localName == 'object') {
140 $this->_fromAtomEntry($entry, $feed);
142 // Low level exception. No need for i18n.
143 throw new Exception("Unknown DOM element: {$entry->namespaceURI} {$entry->localName}");
147 function _fromAtomEntry($entry, $feed)
149 $pubEl = $this->_child($entry, self::PUBLISHED, self::ATOM);
151 if (!empty($pubEl)) {
152 $this->time = strtotime($pubEl->textContent);
154 // XXX technically an error; being liberal. Good idea...?
155 $updateEl = $this->_child($entry, self::UPDATED, self::ATOM);
156 if (!empty($updateEl)) {
157 $this->time = strtotime($updateEl->textContent);
163 $this->link = ActivityUtils::getPermalink($entry);
165 $verbEl = $this->_child($entry, self::VERB);
167 if (!empty($verbEl)) {
168 $this->verb = trim($verbEl->textContent);
170 $this->verb = ActivityVerb::POST;
171 // XXX: do other implied stuff here
174 // get immediate object children
176 $objectEls = ActivityUtils::children($entry, self::OBJECT, self::SPEC);
178 if (count($objectEls) > 0) {
179 foreach ($objectEls as $objectEl) {
180 // Special case for embedded activities
181 $objectType = ActivityUtils::childContent($objectEl, self::OBJECTTYPE, self::SPEC);
182 if (!empty($objectType) && $objectType == ActivityObject::ACTIVITY) {
183 $this->objects[] = new Activity($objectEl);
185 $this->objects[] = new ActivityObject($objectEl);
190 $this->objects[] = new ActivityObject($entry);
193 $actorEl = $this->_child($entry, self::ACTOR);
195 if (!empty($actorEl)) {
196 // Standalone <activity:actor> elements are a holdover from older
197 // versions of ActivityStreams. Newer feeds should have this data
198 // integrated straight into <atom:author>.
200 $this->actor = new ActivityObject($actorEl);
202 // Cliqset has bad actor IDs (just nickname of user). We
203 // work around it by getting the author data and using its
206 if (!preg_match('/^\w+:/', $this->actor->id)) {
207 $authorEl = ActivityUtils::child($entry, 'author');
208 if (!empty($authorEl)) {
209 $authorObj = new ActivityObject($authorEl);
210 $this->actor->id = $authorObj->id;
213 } else if ($authorEl = $this->_child($entry, self::AUTHOR, self::ATOM)) {
215 // An <atom:author> in the entry overrides any author info on
216 // the surrounding feed.
217 $this->actor = new ActivityObject($authorEl);
219 } else if (!empty($feed) &&
220 $subjectEl = $this->_child($feed, self::SUBJECT)) {
222 // Feed subject is used for things like groups.
223 // Should actually possibly not be interpreted as an actor...?
224 $this->actor = new ActivityObject($subjectEl);
226 } else if (!empty($feed) && $authorEl = $this->_child($feed, self::AUTHOR,
229 // If there's no <atom:author> on the entry, it's safe to assume
230 // the containing feed's authorship info applies.
231 $this->actor = new ActivityObject($authorEl);
234 $contextEl = $this->_child($entry, self::CONTEXT);
236 if (!empty($contextEl)) {
237 $this->context = new ActivityContext($contextEl);
239 $this->context = new ActivityContext($entry);
242 $targetEl = $this->_child($entry, self::TARGET);
244 if (!empty($targetEl)) {
245 $this->target = new ActivityObject($targetEl);
248 $this->summary = ActivityUtils::childContent($entry, 'summary');
249 $this->id = ActivityUtils::childContent($entry, 'id');
250 $this->content = ActivityUtils::getContent($entry);
252 $catEls = $entry->getElementsByTagNameNS(self::ATOM, 'category');
254 for ($i = 0; $i < $catEls->length; $i++) {
255 $catEl = $catEls->item($i);
256 $this->categories[] = new AtomCategory($catEl);
260 foreach (ActivityUtils::getLinks($entry, 'enclosure') as $link) {
261 $this->enclosures[] = $link->getAttribute('href');
264 // From APP. Might be useful.
266 $this->selfLink = ActivityUtils::getLink($entry, 'self', 'application/atom+xml');
267 $this->editLink = ActivityUtils::getLink($entry, 'edit', 'application/atom+xml');
270 function _fromRssItem($item, $channel)
272 $verbEl = $this->_child($item, self::VERB);
274 if (!empty($verbEl)) {
275 $this->verb = trim($verbEl->textContent);
277 $this->verb = ActivityVerb::POST;
278 // XXX: do other implied stuff here
281 $pubDateEl = $this->_child($item, self::PUBDATE, self::RSS);
283 if (!empty($pubDateEl)) {
284 $this->time = strtotime($pubDateEl->textContent);
287 if ($authorEl = $this->_child($item, self::AUTHOR, self::RSS)) {
288 $this->actor = ActivityObject::fromRssAuthor($authorEl);
289 } else if ($dcCreatorEl = $this->_child($item, self::CREATOR, self::DC)) {
290 $this->actor = ActivityObject::fromDcCreator($dcCreatorEl);
291 } else if ($posterousEl = $this->_child($item, ActivityObject::AUTHOR, ActivityObject::POSTEROUS)) {
292 // Special case for Posterous.com
293 $this->actor = ActivityObject::fromPosterousAuthor($posterousEl);
294 } else if (!empty($channel)) {
295 $this->actor = ActivityObject::fromRssChannel($channel);
300 $this->title = ActivityUtils::childContent($item, ActivityObject::TITLE, self::RSS);
302 $contentEl = ActivityUtils::child($item, self::ENCODED, self::CONTENTNS);
304 if (!empty($contentEl)) {
305 // <content:encoded> XML node's text content is HTML; no further processing needed.
306 $this->content = $contentEl->textContent;
308 $descriptionEl = ActivityUtils::child($item, self::DESCRIPTION, self::RSS);
309 if (!empty($descriptionEl)) {
310 // Per spec, <description> must be plaintext.
311 // In practice, often there's HTML... but these days good
312 // feeds are using <content:encoded> which is explicitly
314 // We'll treat this following spec, and do HTML escaping
315 // to convert from plaintext to HTML.
316 $this->content = htmlspecialchars($descriptionEl->textContent);
320 $this->link = ActivityUtils::childContent($item, ActivityUtils::LINK, self::RSS);
323 // @fixme thumbnails... maybe
325 $guidEl = ActivityUtils::child($item, self::GUID, self::RSS);
327 if (!empty($guidEl)) {
328 $this->id = $guidEl->textContent;
330 if ($guidEl->hasAttribute('isPermaLink') && $guidEl->getAttribute('isPermaLink') != 'false') {
332 $this->link = $this->id;
336 $this->objects[] = new ActivityObject($item);
337 $this->context = new ActivityContext($item);
341 * Returns an Atom <entry> based on this activity
343 * @return DOMElement Atom entry
346 function toAtomEntry()
352 * Returns an array based on this activity suitable
353 * for encoding as a JSON object
355 * @return array $activity
363 $activity['actor'] = $this->actor->asArray();
366 $activity['content'] = $this->content;
368 // generator <-- We could use this when we know a notice is created
369 // locally. Or if we know the upstream Generator.
371 // icon <-- possibly a mini object representing verb?
374 $activity['id'] = $this->id;
378 if (count($this->objects) == 0) {
379 common_log(LOG_ERR, "Can't save " . $this->id);
381 if (count($this->objects) > 1) {
382 common_log(LOG_WARNING, "Ignoring " . (count($this->objects) - 1) . " extra objects in JSON output for activity " . $this->id);
384 $object = $this->objects[0];
386 if ($object instanceof Activity) {
387 // Sharing a post activity is more like sharing the original object
388 if ($this->verb == 'share' && $object->verb == 'post') {
389 // XXX: Here's one for the obfuscation record books
390 $object = $object->object;
394 $activity['object'] = $object->asArray();
396 if ($object instanceof Activity) {
397 $activity['object']['objectType'] = 'activity';
401 // Instead of adding enclosures as an extension to JSON
402 // Activities, it seems like we should be using the
403 // attachements property of ActivityObject
405 $attachments = array();
407 // XXX: OK, this is kinda cheating. We should probably figure out
408 // what kind of objects these are based on mime-type and then
409 // create specific object types. Right now this rely on
410 // duck-typing. Also, we should include an embed code for
411 // video attachments.
413 foreach ($this->enclosures as $enclosure) {
415 if (is_string($enclosure)) {
417 $attachments[]['id'] = $enclosure;
421 $attachments[]['id'] = $enclosure->url;
423 $mediaLink = new ActivityStreamsMediaLink(
428 // XXX: Add 'size' as an extension to MediaLink?
431 $attachments[]['mediaLink'] = $mediaLink->asArray(); // extension
433 if ($enclosure->title) {
434 $attachments[]['displayName'] = $enclosure->title;
439 if (!empty($attachments)) {
440 $activity['object']['attachments'] = $attachments;
446 if (!empty($this->context)) {
448 if (!empty($this->context->location)) {
449 $loc = $this->context->location;
451 $activity['location'] = array(
452 'objectType' => 'place',
453 'position' => sprintf("%+02.5F%+03.5F/", $loc->lat, $loc->lon),
458 $name = $loc->getName();
461 $activity['location']['displayName'] = $name;
464 $url = $loc->getURL();
467 $activity['location']['url'] = $url;
471 $activity['to'] = $this->context->getToArray();
473 $ctxarr = $this->context->asArray();
475 if (array_key_exists('inReplyTo', $ctxarr)) {
476 $activity['object']['inReplyTo'] = $ctxarr['inReplyTo'];
477 unset($ctxarr['inReplyTo']);
480 if (!array_key_exists('status_net', $activity)) {
481 $activity['status_net'] = array();
484 foreach ($ctxarr as $key => $value) {
485 $activity['status_net'][$key] = $value;
490 $activity['published'] = self::iso8601Date($this->time);
494 'objectType' => 'service',
495 'displayName' => common_config('site', 'name'),
496 'url' => common_root_url()
499 $activity['provider'] = $provider;
502 if (!empty($this->target)) {
503 $activity['target'] = $this->target->asArray();
507 $activity['title'] = $this->title;
509 // updated <-- Optional. Should we use this to indicate the time we r
510 // eceived a remote notice? Probably not.
514 $activity['verb'] = ActivityVerb::canonical($this->verb);
517 $activity['url'] = $this->id;
519 /* Purely extensions hereafter */
521 if ($activity['verb'] == 'post') {
523 foreach ($this->categories as $cat) {
524 if (mb_strlen($cat->term) > 0) {
525 // Couldn't figure out which object type to use, so...
526 $tags[] = array('objectType' => 'http://activityschema.org/object/hashtag',
527 'displayName' => $cat->term);
530 if (count($tags) > 0) {
531 $activity['object']['tags'] = $tags;
535 // XXX: a bit of a hack... Since JSON isn't namespaced we probably
536 // shouldn't be using 'statusnet:notice_info', but this will work
539 foreach ($this->extra as $e) {
540 list($objectName, $props, $txt) = $e;
541 if (!empty($objectName)) {
542 $parts = explode(":", $objectName);
543 if (count($parts) == 2 && $parts[0] == "statusnet") {
544 if (!array_key_exists('status_net', $activity)) {
545 $activity['status_net'] = array();
547 $activity['status_net'][$parts[1]] = $props;
549 $activity[$objectName] = $props;
554 return array_filter($activity);
557 function asString($namespace=false, $author=true, $source=false)
559 $xs = new XMLStringer(true);
560 $this->outputTo($xs, $namespace, $author, $source);
561 return $xs->getString();
564 function outputTo($xs, $namespace=false, $author=true, $source=false, $tag='entry')
567 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
568 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
569 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
570 'xmlns:georss' => 'http://www.georss.org/georss',
571 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
572 'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
573 'xmlns:media' => 'http://purl.org/syndication/atommedia',
574 'xmlns:statusnet' => 'http://status.net/schema/api/1/');
579 $xs->elementStart($tag, $attrs);
581 if ($tag != 'entry') {
582 $xs->element('activity:object-type', null, ActivityObject::ACTIVITY);
585 if ($this->verb == ActivityVerb::POST && count($this->objects) == 1 && $tag == 'entry') {
587 $obj = $this->objects[0];
588 $obj->outputTo($xs, null);
591 $xs->element('id', null, $this->id);
594 $xs->element('title', null, $this->title);
597 $xs->element('title', null, "");
600 $xs->element('content', array('type' => 'html'), $this->content);
602 if (!empty($this->summary)) {
603 $xs->element('summary', null, $this->summary);
606 if (!empty($this->link)) {
607 $xs->element('link', array('rel' => 'alternate',
608 'type' => 'text/html'),
614 $xs->element('activity:verb', null, $this->verb);
616 $published = self::iso8601Date($this->time);
618 $xs->element('published', null, $published);
619 $xs->element('updated', null, $published);
622 $this->actor->outputTo($xs, 'author');
625 if ($this->verb != ActivityVerb::POST || count($this->objects) != 1 || $tag != 'entry') {
626 foreach($this->objects as $object) {
627 if ($object instanceof Activity) {
628 $object->outputTo($xs, false, true, true, 'activity:object');
630 $object->outputTo($xs, 'activity:object');
635 if (!empty($this->context)) {
637 if (!empty($this->context->replyToID)) {
638 if (!empty($this->context->replyToUrl)) {
639 $xs->element('thr:in-reply-to',
640 array('ref' => $this->context->replyToID,
641 'href' => $this->context->replyToUrl));
643 $xs->element('thr:in-reply-to',
644 array('ref' => $this->context->replyToID));
648 if (!empty($this->context->replyToUrl)) {
649 $xs->element('link', array('rel' => 'related',
650 'href' => $this->context->replyToUrl));
653 if (!empty($this->context->conversation)) {
654 $xs->element('link', array('rel' => 'ostatus:conversation',
655 'href' => $this->context->conversation));
658 foreach ($this->context->attention as $attnURI) {
659 $xs->element('link', array('rel' => 'ostatus:attention',
660 'href' => $attnURI));
661 $xs->element('link', array('rel' => 'mentioned',
662 'href' => $attnURI));
665 // XXX: shoulda used ActivityVerb::SHARE
667 if (!empty($this->context->forwardID)) {
668 if (!empty($this->context->forwardUrl)) {
669 $xs->element('ostatus:forward',
670 array('ref' => $this->context->forwardID,
671 'href' => $this->context->forwardUrl));
673 $xs->element('ostatus:forward',
674 array('ref' => $this->context->forwardID));
678 if (!empty($this->context->location)) {
679 $loc = $this->context->location;
680 $xs->element('georss:point', null, $loc->lat . ' ' . $loc->lon);
685 $this->target->outputTo($xs, 'activity:target');
688 foreach ($this->categories as $cat) {
692 // can be either URLs or enclosure objects
694 foreach ($this->enclosures as $enclosure) {
695 if (is_string($enclosure)) {
696 $xs->element('link', array('rel' => 'enclosure',
697 'href' => $enclosure));
699 $attributes = array('rel' => 'enclosure',
700 'href' => $enclosure->url,
701 'type' => $enclosure->mimetype,
702 'length' => $enclosure->size);
703 if ($enclosure->title) {
704 $attributes['title'] = $enclosure->title;
706 $xs->element('link', $attributes);
710 // Info on the source feed
712 if ($source && !empty($this->source)) {
713 $xs->elementStart('source');
715 $xs->element('id', null, $this->source->id);
716 $xs->element('title', null, $this->source->title);
718 if (array_key_exists('alternate', $this->source->links)) {
719 $xs->element('link', array('rel' => 'alternate',
720 'type' => 'text/html',
721 'href' => $this->source->links['alternate']));
724 if (array_key_exists('self', $this->source->links)) {
725 $xs->element('link', array('rel' => 'self',
726 'type' => 'application/atom+xml',
727 'href' => $this->source->links['self']));
730 if (array_key_exists('license', $this->source->links)) {
731 $xs->element('link', array('rel' => 'license',
732 'href' => $this->source->links['license']));
735 if (!empty($this->source->icon)) {
736 $xs->element('icon', null, $this->source->icon);
739 if (!empty($this->source->updated)) {
740 $xs->element('updated', null, $this->source->updated);
743 $xs->elementEnd('source');
746 if (!empty($this->selfLink)) {
747 $xs->element('link', array('rel' => 'self',
748 'type' => 'application/atom+xml',
749 'href' => $this->selfLink));
752 if (!empty($this->editLink)) {
753 $xs->element('link', array('rel' => 'edit',
754 'type' => 'application/atom+xml',
755 'href' => $this->editLink));
758 // For throwing in extra elements; used for statusnet:notice_info
760 foreach ($this->extra as $el) {
761 list($tag, $attrs, $content) = $el;
762 $xs->element($tag, $attrs, $content);
765 $xs->elementEnd($tag);
770 private function _child($element, $tag, $namespace=self::SPEC)
772 return ActivityUtils::child($element, $tag, $namespace);
776 * For consistency, we'll always output UTC rather than local time.
777 * Note that clients *should* accept any timezone we give them as long
778 * as it's properly formatted.
780 * @param int $tm Unix timestamp
783 static function iso8601Date($tm)
785 $dateStr = date('d F Y H:i:s', $tm);
786 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
787 return $d->format('c');