activityutils.php 10.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
<?php
/**
 * StatusNet, the distributed open-source microblogging tool
 *
 * An activity
 *
 * PHP version 5
 *
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  Feed
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @author    Zach Copley <zach@status.net>
 * @copyright 2010 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
 * @link      http://status.net/
 */

if (!defined('STATUSNET')) {
    exit(1);
}

/**
 * Utilities for turning DOMish things into Activityish things
 *
 * Some common functions that I didn't have the bandwidth to try to factor
 * into some kind of reasonable superclass, so just dumped here. Might
 * be useful to have an ActivityObject parent class or something.
 *
 * @category  OStatus
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2010 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3
 * @link      http://status.net/
 */
class ActivityUtils
{
    const ATOM = 'http://www.w3.org/2005/Atom';

    const LINK = 'link';
    const REL  = 'rel';
    const TYPE = 'type';
    const HREF = 'href';

    const CONTENT = 'content';
    const SRC     = 'src';

    /**
     * Get the permalink for an Activity object
     *
     * @param DOMElement $element A DOM element
     *
     * @return string related link, if any
     */
    static function getPermalink($element)
    {
        return self::getLink($element, 'alternate', 'text/html');
    }

    /**
     * Get the permalink for an Activity object
     *
     * @param DOMElement $element A DOM element
     *
     * @return string related link, if any
     */
    static function getLink(DOMNode $element, $rel, $type=null)
    {
        $els = $element->childNodes;

        foreach ($els as $link) {
            if (!($link instanceof DOMElement)) {
                continue;
            }

            if ($link->localName == self::LINK && $link->namespaceURI == self::ATOM) {
                $linkRel = $link->getAttribute(self::REL);
                $linkType = $link->getAttribute(self::TYPE);

                if ($linkRel == $rel &&
                    (is_null($type) || $linkType == $type)) {
                    return $link->getAttribute(self::HREF);
                }
            }
        }

        return null;
    }

    static function getLinks(DOMNode $element, $rel, $type=null)
    {
        $els = $element->childNodes;
        $out = array();
107 108 109
        
        for ($i = 0; $i < $els->length; $i++) {
            $link = $els->item($i);
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
            if ($link->localName == self::LINK && $link->namespaceURI == self::ATOM) {
                $linkRel = $link->getAttribute(self::REL);
                $linkType = $link->getAttribute(self::TYPE);

                if ($linkRel == $rel &&
                    (is_null($type) || $linkType == $type)) {
                    $out[] = $link;
                }
            }
        }

        return $out;
    }

    /**
     * Gets the first child element with the given tag
     *
     * @param DOMElement $element   element to pick at
     * @param string     $tag       tag to look for
     * @param string     $namespace Namespace to look under
     *
     * @return DOMElement found element or null
     */
    static function child(DOMNode $element, $tag, $namespace=self::ATOM)
    {
        $els = $element->childNodes;
        if (empty($els) || $els->length == 0) {
            return null;
        } else {
            for ($i = 0; $i < $els->length; $i++) {
                $el = $els->item($i);
                if ($el->localName == $tag && $el->namespaceURI == $namespace) {
                    return $el;
                }
            }
        }
    }

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
    /**
     * Gets all immediate child elements with the given tag
     *
     * @param DOMElement $element   element to pick at
     * @param string     $tag       tag to look for
     * @param string     $namespace Namespace to look under
     *
     * @return array found element or null
     */

    static function children(DOMNode $element, $tag, $namespace=self::ATOM)
    {
        $results = array();

        $els = $element->childNodes;

        if (!empty($els) && $els->length > 0) {
            for ($i = 0; $i < $els->length; $i++) {
                $el = $els->item($i);
                if ($el->localName == $tag && $el->namespaceURI == $namespace) {
                    $results[] = $el;
                }
            }
        }

        return $results;
    }

176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
    /**
     * Grab the text content of a DOM element child of the current element
     *
     * @param DOMElement $element   Element whose children we examine
     * @param string     $tag       Tag to look up
     * @param string     $namespace Namespace to use, defaults to Atom
     *
     * @return string content of the child
     */
    static function childContent(DOMNode $element, $tag, $namespace=self::ATOM)
    {
        $el = self::child($element, $tag, $namespace);

        if (empty($el)) {
            return null;
        } else {
            return $el->textContent;
        }
    }

    static function childHtmlContent(DOMNode $element, $tag, $namespace=self::ATOM)
    {
        $el = self::child($element, $tag, $namespace);

        if (empty($el)) {
            return null;
        } else {
            return self::textConstruct($el);
        }
    }

    /**
     * Get the content of an atom:entry-like object
     *
     * @param DOMElement $element The element to examine.
     *
     * @return string unencoded HTML content of the element, like "This -&lt; is <b>HTML</b>."
     *
     * @todo handle remote content
     * @todo handle embedded XML mime types
     * @todo handle base64-encoded non-XML and non-text mime types
     */
    static function getContent($element)
    {
        return self::childHtmlContent($element, self::CONTENT, self::ATOM);
    }

    static function textConstruct($el)
    {
        $src  = $el->getAttribute(self::SRC);

        if (!empty($src)) {
228
            // TRANS: Client exception thrown when there is no source attribute.
229 230 231 232 233 234 235 236
            throw new ClientException(_("Can't handle remote content yet."));
        }

        $type = $el->getAttribute(self::TYPE);

        // slavishly following http://atompub.org/rfc4287.html#rfc.section.4.1.3.3

        if (empty($type) || $type == 'text') {
237 238 239
            // We have plaintext saved as the XML text content.
            // Since we want HTML, we need to escape any special chars.
            return htmlspecialchars($el->textContent);
240
        } else if ($type == 'html') {
241 242
            // We have HTML saved as the XML text content.
            // No additional processing required once we've got it.
243
            $text = $el->textContent;
244
            return $text;
245
        } else if ($type == 'xhtml') {
246 247 248 249
            // Per spec, the <content type="xhtml"> contains a single
            // HTML <div> with XHTML namespace on it as a child node.
            // We need to pull all of that <div>'s child nodes and
            // serialize them back to an (X)HTML source fragment.
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
            $divEl = ActivityUtils::child($el, 'div', 'http://www.w3.org/1999/xhtml');
            if (empty($divEl)) {
                return null;
            }
            $doc = $divEl->ownerDocument;
            $text = '';
            $children = $divEl->childNodes;

            for ($i = 0; $i < $children->length; $i++) {
                $child = $children->item($i);
                $text .= $doc->saveXML($child);
            }
            return trim($text);
        } else if (in_array($type, array('text/xml', 'application/xml')) ||
                   preg_match('#(+|/)xml$#', $type)) {
265
            // TRANS: Client exception thrown when there embedded XML content is found that cannot be processed yet.
266 267 268 269
            throw new ClientException(_("Can't handle embedded XML content yet."));
        } else if (strncasecmp($type, 'text/', 5)) {
            return $el->textContent;
        } else {
270
            // TRANS: Client exception thrown when base64 encoded content is found that cannot be processed yet.
271 272 273
            throw new ClientException(_("Can't handle embedded Base64 content yet."));
        }
    }
274 275 276 277 278 279 280 281 282

    /**
     * Is this a valid URI for remote profile/notice identification?
     * Does not have to be a resolvable URL.
     * @param string $uri
     * @return boolean
     */
    static function validateUri($uri)
    {
283 284 285 286 287 288
        // Check mailto: URIs first

        if (preg_match('/^mailto:(.*)$/', $uri, $match)) {
            return Validate::email($match[1], common_config('email', 'check_domain'));
        }

289 290 291 292 293 294 295 296 297 298 299 300 301
        if (Validate::uri($uri)) {
            return true;
        }

        // Possibly an upstream bug; tag: URIs aren't validated properly
        // unless you explicitly ask for them. All other schemes are accepted
        // for basic URI validation without asking.
        if (Validate::uri($uri, array('allowed_scheme' => array('tag')))) {
            return true;
        }

        return false;
    }
302 303 304 305 306 307 308 309 310 311 312

    static function getFeedAuthor($feedEl)
    {
        // Try old and deprecated activity:subject

        $subject = ActivityUtils::child($feedEl, Activity::SUBJECT, Activity::SPEC);

        if (!empty($subject)) {
            return new ActivityObject($subject);
        }

313 314 315 316 317 318 319 320
        // Try the feed author

        $author = ActivityUtils::child($feedEl, Activity::AUTHOR, Activity::ATOM);

        if (!empty($author)) {
            return new ActivityObject($author);
        }

321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
        // Sheesh. Not a very nice feed! Let's try fingerpoken in the
        // entries.

        $entries = $feedEl->getElementsByTagNameNS(Activity::ATOM, 'entry');

        if (!empty($entries) && $entries->length > 0) {

            $entry = $entries->item(0);

            // Try the (deprecated) activity:actor

            $actor = ActivityUtils::child($entry, Activity::ACTOR, Activity::SPEC);

            if (!empty($actor)) {
                return new ActivityObject($actor);
            }
337 338 339 340 341 342 343 344

            // Try the author

            $author = ActivityUtils::child($entry, Activity::AUTHOR, Activity::ATOM);

            if (!empty($author)) {
                return new ActivityObject($author);
            }
345 346 347 348
        }

        return null;
    }
349
}