]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/activityutils.php
XSS vulnerability when remote-subscribing
[quix0rs-gnu-social.git] / lib / activityutils.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  * Utilities for turning DOMish things into Activityish things
37  *
38  * Some common functions that I didn't have the bandwidth to try to factor
39  * into some kind of reasonable superclass, so just dumped here. Might
40  * be useful to have an ActivityObject parent class or something.
41  *
42  * @category  OStatus
43  * @package   StatusNet
44  * @author    Evan Prodromou <evan@status.net>
45  * @copyright 2010 StatusNet, Inc.
46  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
47  * @link      http://status.net/
48  */
49 class ActivityUtils
50 {
51     const ATOM = 'http://www.w3.org/2005/Atom';
52
53     const LINK = 'link';
54     const REL  = 'rel';
55     const TYPE = 'type';
56     const HREF = 'href';
57
58     const CONTENT = 'content';
59     const SRC     = 'src';
60
61     /**
62      * Get the permalink for an Activity object
63      *
64      * @param DOMElement $element A DOM element
65      *
66      * @return string related link, if any
67      */
68     static function getPermalink($element)
69     {
70         return self::getLink($element, 'alternate', 'text/html');
71     }
72
73     /**
74      * Get the permalink for an Activity object
75      *
76      * @param DOMElement $element A DOM element
77      *
78      * @return string related link, if any
79      */
80     static function getLink(DOMNode $element, $rel, $type=null)
81     {
82         $els = $element->childNodes;
83
84         foreach ($els as $link) {
85             if (!($link instanceof DOMElement)) {
86                 continue;
87             }
88
89             if ($link->localName == self::LINK && $link->namespaceURI == self::ATOM) {
90                 $linkRel = $link->getAttribute(self::REL);
91                 $linkType = $link->getAttribute(self::TYPE);
92
93                 if ($linkRel == $rel &&
94                     (is_null($type) || $linkType == $type)) {
95                     return $link->getAttribute(self::HREF);
96                 }
97             }
98         }
99
100         return null;
101     }
102
103     static function getLinks(DOMNode $element, $rel, $type=null)
104     {
105         $els = $element->childNodes;
106         $out = array();
107         
108         for ($i = 0; $i < $els->length; $i++) {
109             $link = $els->item($i);
110             if ($link->localName == self::LINK && $link->namespaceURI == self::ATOM) {
111                 $linkRel = $link->getAttribute(self::REL);
112                 $linkType = $link->getAttribute(self::TYPE);
113
114                 if ($linkRel == $rel &&
115                     (is_null($type) || $linkType == $type)) {
116                     $out[] = $link;
117                 }
118             }
119         }
120
121         return $out;
122     }
123
124     /**
125      * Gets the first child element with the given tag
126      *
127      * @param DOMElement $element   element to pick at
128      * @param string     $tag       tag to look for
129      * @param string     $namespace Namespace to look under
130      *
131      * @return DOMElement found element or null
132      */
133     static function child(DOMNode $element, $tag, $namespace=self::ATOM)
134     {
135         $els = $element->childNodes;
136         if (empty($els) || $els->length == 0) {
137             return null;
138         } else {
139             for ($i = 0; $i < $els->length; $i++) {
140                 $el = $els->item($i);
141                 if ($el->localName == $tag && $el->namespaceURI == $namespace) {
142                     return $el;
143                 }
144             }
145         }
146     }
147
148     /**
149      * Gets all immediate child elements with the given tag
150      *
151      * @param DOMElement $element   element to pick at
152      * @param string     $tag       tag to look for
153      * @param string     $namespace Namespace to look under
154      *
155      * @return array found element or null
156      */
157
158     static function children(DOMNode $element, $tag, $namespace=self::ATOM)
159     {
160         $results = array();
161
162         $els = $element->childNodes;
163
164         if (!empty($els) && $els->length > 0) {
165             for ($i = 0; $i < $els->length; $i++) {
166                 $el = $els->item($i);
167                 if ($el->localName == $tag && $el->namespaceURI == $namespace) {
168                     $results[] = $el;
169                 }
170             }
171         }
172
173         return $results;
174     }
175
176     /**
177      * Grab the text content of a DOM element child of the current element
178      *
179      * @param DOMElement $element   Element whose children we examine
180      * @param string     $tag       Tag to look up
181      * @param string     $namespace Namespace to use, defaults to Atom
182      *
183      * @return string content of the child
184      */
185     static function childContent(DOMNode $element, $tag, $namespace=self::ATOM)
186     {
187         $el = self::child($element, $tag, $namespace);
188
189         if (empty($el)) {
190             return null;
191         } else {
192             return $el->textContent;
193         }
194     }
195
196     static function childHtmlContent(DOMNode $element, $tag, $namespace=self::ATOM)
197     {
198         $el = self::child($element, $tag, $namespace);
199
200         if (empty($el)) {
201             return null;
202         } else {
203             return self::textConstruct($el);
204         }
205     }
206
207     /**
208      * Get the content of an atom:entry-like object
209      *
210      * @param DOMElement $element The element to examine.
211      *
212      * @return string unencoded HTML content of the element, like "This -&lt; is <b>HTML</b>."
213      *
214      * @todo handle remote content
215      * @todo handle embedded XML mime types
216      * @todo handle base64-encoded non-XML and non-text mime types
217      */
218     static function getContent($element)
219     {
220         return self::childHtmlContent($element, self::CONTENT, self::ATOM);
221     }
222
223     static function textConstruct($el)
224     {
225         $src  = $el->getAttribute(self::SRC);
226
227         if (!empty($src)) {
228             // TRANS: Client exception thrown when there is no source attribute.
229             throw new ClientException(_("Can't handle remote content yet."));
230         }
231
232         $type = $el->getAttribute(self::TYPE);
233
234         // slavishly following http://atompub.org/rfc4287.html#rfc.section.4.1.3.3
235
236         if (empty($type) || $type == 'text') {
237             // We have plaintext saved as the XML text content.
238             // Since we want HTML, we need to escape any special chars.
239             return htmlspecialchars($el->textContent);
240         } else if ($type == 'html') {
241             // We have HTML saved as the XML text content.
242             // No additional processing required once we've got it.
243             $text = $el->textContent;
244             return $text;
245         } else if ($type == 'xhtml') {
246             // Per spec, the <content type="xhtml"> contains a single
247             // HTML <div> with XHTML namespace on it as a child node.
248             // We need to pull all of that <div>'s child nodes and
249             // serialize them back to an (X)HTML source fragment.
250             $divEl = ActivityUtils::child($el, 'div', 'http://www.w3.org/1999/xhtml');
251             if (empty($divEl)) {
252                 return null;
253             }
254             $doc = $divEl->ownerDocument;
255             $text = '';
256             $children = $divEl->childNodes;
257
258             for ($i = 0; $i < $children->length; $i++) {
259                 $child = $children->item($i);
260                 $text .= $doc->saveXML($child);
261             }
262             return trim($text);
263         } else if (in_array($type, array('text/xml', 'application/xml')) ||
264                    preg_match('#(+|/)xml$#', $type)) {
265             // TRANS: Client exception thrown when there embedded XML content is found that cannot be processed yet.
266             throw new ClientException(_("Can't handle embedded XML content yet."));
267         } else if (strncasecmp($type, 'text/', 5)) {
268             return $el->textContent;
269         } else {
270             // TRANS: Client exception thrown when base64 encoded content is found that cannot be processed yet.
271             throw new ClientException(_("Can't handle embedded Base64 content yet."));
272         }
273     }
274
275     /**
276      * Is this a valid URI for remote profile/notice identification?
277      * Does not have to be a resolvable URL.
278      * @param string $uri
279      * @return boolean
280      */
281     static function validateUri($uri)
282     {
283         // Check mailto: URIs first
284         $validate = new Validate();
285
286         if (preg_match('/^mailto:(.*)$/', $uri, $match)) {
287             return $validate->email($match[1], common_config('email', 'check_domain'));
288         }
289
290         if ($validate->uri($uri)) {
291             return true;
292         }
293
294         // Possibly an upstream bug; tag: URIs aren't validated properly
295         // unless you explicitly ask for them. All other schemes are accepted
296         // for basic URI validation without asking.
297         if ($validate->uri($uri, array('allowed_scheme' => array('tag')))) {
298             return true;
299         }
300
301         return false;
302     }
303
304     static function getFeedAuthor($feedEl)
305     {
306         // Try old and deprecated activity:subject
307
308         $subject = ActivityUtils::child($feedEl, Activity::SUBJECT, Activity::SPEC);
309
310         if (!empty($subject)) {
311             return new ActivityObject($subject);
312         }
313
314         // Try the feed author
315
316         $author = ActivityUtils::child($feedEl, Activity::AUTHOR, Activity::ATOM);
317
318         if (!empty($author)) {
319             return new ActivityObject($author);
320         }
321
322         // Sheesh. Not a very nice feed! Let's try fingerpoken in the
323         // entries.
324
325         $entries = $feedEl->getElementsByTagNameNS(Activity::ATOM, 'entry');
326
327         if (!empty($entries) && $entries->length > 0) {
328
329             $entry = $entries->item(0);
330
331             // Try the (deprecated) activity:actor
332
333             $actor = ActivityUtils::child($entry, Activity::ACTOR, Activity::SPEC);
334
335             if (!empty($actor)) {
336                 return new ActivityObject($actor);
337             }
338
339             // Try the author
340
341             $author = ActivityUtils::child($entry, Activity::AUTHOR, Activity::ATOM);
342
343             if (!empty($author)) {
344                 return new ActivityObject($author);
345             }
346         }
347
348         return null;
349     }
350
351     static function compareTypes($type, $objects)
352     {
353         $type = self::resolveUri($type);
354         foreach ((array)$objects as $object) {
355             if ($type === self::resolveUri($object)) {
356                 return true;
357             }
358         }
359         return false;
360     }
361
362     static function compareVerbs($type, $objects)
363     {
364         return self::compareTypes($type, $objects);
365     }
366
367     static function resolveUri($uri, $make_relative=false)
368     {
369         if (empty($uri)) {
370             throw new ServerException('No URI to resolve in ActivityUtils::resolveUri');
371         }
372
373         if (!$make_relative && parse_url($uri, PHP_URL_SCHEME) == '') { // relative -> absolute
374             $uri = Activity::SCHEMA . $uri;
375         } elseif ($make_relative) { // absolute -> relative
376             $uri = basename($uri); //preg_replace('/^http:\/\/activitystrea\.ms\/schema\/1\.0\//', '', $uri);
377         } // absolute schemas pass through unharmed
378
379         return $uri;
380     }
381
382     static function findLocalObject(array $uris, $type=ActivityObject::NOTE) {
383         $obj_class = null;
384         // TODO: Extend this in plugins etc. and describe in EVENTS.txt
385         if (Event::handle('StartFindLocalActivityObject', array($uris, $type, &$obj_class))) {
386             switch (self::resolveUri($type)) {
387             case ActivityObject::PERSON:
388                 // GROUP will also be here in due time...
389                 $obj_class = 'Profile';
390                 break;
391             default:
392                 $obj_class = 'Notice';
393             }
394         }
395         $object = null;
396         $uris = array_unique($uris);
397         foreach ($uris as $uri) {
398             try {
399                 // the exception thrown will cancel before reaching $object
400                 $object = call_user_func("{$obj_class}::fromUri", $uri);
401                 break;
402             } catch (UnknownUriException $e) {
403                 common_debug('Could not find local activity object from uri: '.$e->object_uri);
404             }
405         }
406         if (!$object instanceof Managed_DataObject) {
407             throw new ServerException('Could not find any activityobject stored locally with given URIs: '.var_export($uris,true));
408         }
409         Event::handle('EndFindLocalActivityObject', array($object->getUri(), $object->getObjectType(), $object));
410         return $object;
411     }
412
413     // Check authorship by supplying a Profile as a default and letting plugins
414     // set it to something else if the activity's author is actually someone
415     // else (like with a group or peopletag feed as handled in OStatus).
416     //
417     // NOTE: Returned is not necessarily the supplied profile! For example,
418     // the "feed author" may be a group, but the "activity author" is a person!
419     static function checkAuthorship(Activity $activity, Profile $profile)
420     {
421         if (Event::handle('CheckActivityAuthorship', array($activity, &$profile))) {
422             // if (empty($activity->actor)), then we generated this Activity ourselves and can trust $profile
423
424             $actor_uri = $profile->getUri();
425
426             if (!in_array($actor_uri, array($activity->actor->id, $activity->actor->link))) {
427                 // A mismatch between our locally stored URI and the supplied author?
428                 // Probably not more than a blog feed or something (with multiple authors or so)
429                 // but log it for future inspection.
430                 common_log(LOG_WARNING, "Got an actor '{$activity->actor->title}' ({$activity->actor->id}) on single-user feed for " . $actor_uri);
431             } elseif (empty($activity->actor->id)) {
432                 // Plain <author> without ActivityStreams actor info.
433                 // We'll just ignore this info for now and save the update under the feed's identity.
434             }
435         }
436
437         if (!$profile instanceof Profile) {
438             throw new ServerException('Could not get an author Profile for activity');
439         }
440
441         return $profile;
442     }
443
444     static public function typeToTitle($type)
445     {
446         return ucfirst(self::resolveUri($type, true));
447     }
448
449     static public function verbToTitle($verb)
450     {
451         return ucfirst(self::resolveUri($verb, true));
452     }
453 }