code:
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social.  If not, see <http://www.gnu.org/licenses/>.

namespace Tests\Unit;

if (!defined('INSTALLDIR')) {
    define('INSTALLDIR', dirname(dirname(__DIR__)));
}
if (!defined('PUBLICDIR')) {
    define('PUBLICDIR', INSTALLDIR . DIRECTORY_SEPARATOR . 'public');
}
if (!defined('GNUSOCIAL')) {
    define('GNUSOCIAL', true);
}
if (!defined('STATUSNET')) { // Compatibility
    define('STATUSNET', true);
}

use PHPUnit\Framework\TestCase;

require_once INSTALLDIR . '/lib/util/common.php';

final class URLDetectionTest extends TestCase
{
    /**
     * @dataProvider provider
     * @param $content
     * @param $expected
     */
    public function testProduction($content, $expected)
    {
        $rendered = common_render_text($content);
        // hack!
        $rendered = preg_replace('/id="attachment-\d+"/', 'id="attachment-XXX"', $rendered);
        $this->assertEquals($expected, $rendered);
    }

    /**
     * @dataProvider linkifyProvider
     * @param $content
     * @param $expected
     * @param $config
     */
    public function testLinkifyProduction($content, $expected, $config)
    {
        $rendered = common_render_text($content);
        // hack!
        $rendered = preg_replace('/id="attachment-\d+"/', 'id="attachment-XXX"', $rendered);
        if (common_config('linkify', $config)) {
            $this->assertEquals($expected, $rendered);
        } else {
            $content = common_remove_unicode_formatting(nl2br(htmlspecialchars($content)));
            $this->assertEquals($content, $rendered);
        }
    }

    static public function provider()
    {
        return array(
            array('not a link :: no way',
                'not a link :: no way'),
            array('link http://www.somesite.com/xyz/35637563@N00/52803365/ link',
                'link http://www.somesite.com/xyz/35637563@N00/52803365/ link'),
            array('http://127.0.0.1',
                'http://127.0.0.1'),
            array('http://[::1]:99/test.php',
                'http://[::1]:99/test.php'),
            array('http://::1/test.php',
                'http://::1/test.php'),
            array('http://::1',
                'http://::1'),
            array('http://127.0.0.1',
                'http://127.0.0.1'),
            array('http://example.com',
                'http://example.com'),
            array('http://example.com.',
                'http://example.com.'),
            array('/var/lib/example.so',
                '/var/lib/example.so'),
            array('example',
                'example'),
            array('mailto:user@example.com',
                'mailto:user@example.com'),
            array('mailto:user@example.com?subject=test',
                'mailto:user@example.com?subject=test'),
            array('xmpp:user@example.com',
                'xmpp:user@example.com'),
            array('#example',
                '# common_canonical_tag('example'))) . '" rel="tag">example'),
            array('#example.com',
                '# common_canonical_tag('example.com'))) . '" rel="tag">example.com'),
            array('#.net',
                '# common_canonical_tag('.net'))) . '" rel="tag">.net'),
            array('http://example',
                'http://example'),
            array('http://3xampl3',
                'http://3xampl3'),
            array('http://example/',
                'http://example/'),
            array('http://example/path',
                'http://example/path'),
            array('http://example.com',
                'http://example.com'),
            array('https://example.com',
                'https://example.com'),
            array('ftp://example.com',
                'ftp://example.com'),
            array('ftps://example.com',
                'ftps://example.com'),
            array('http://user@example.com',
                'http://user@example.com'),
            array('http://user:pass@example.com',
                'http://user:pass@example.com'),
            array('http://example.com:8080',
                'http://example.com:8080'),
            array('http://example.com:8080/test.php',
                'http://example.com:8080/test.php'),
            array('http://www.example.com',
                'http://www.example.com'),
            array('http://example.com/',
                'http://example.com/'),
            array('http://example.com/path',
                'http://example.com/path'),
            array('http://example.com/path.html',
                'http://example.com/path.html'),
            array('http://example.com/path.html#fragment',
                'http://example.com/path.html#fragment'),
            array('http://example.com/path.php?foo=bar&bar=foo',
                'http://example.com/path.php?foo=bar&bar=foo'),
            array('http://example.com.',
                'http://example.com.'),
            array('http://müllärör.de',
                'http://müllärör.de'),
            array('http://ﺱﺲﺷ.com',
                'http://ﺱﺲﺷ.com'),
            array('http://сделаткартинки.com',
                'http://сделаткартинки.com'),
            array('http://tūdaliņ.lv',
                'http://tūdaliņ.lv'),
            array('http://brændendekærlighed.com',
                'http://brændendekærlighed.com'),
            array('http://あーるいん.com',
                'http://あーるいん.com'),
            array('http://예비교사.com',
                'http://예비교사.com'),
            array('http://example.com.',
                'http://example.com.'),
            array('http://example.com?',
                'http://example.com?'),
            array('http://example.com!',
                'http://example.com!'),
            array('http://example.com,',
                'http://example.com,'),
            array('http://example.com;',
                'http://example.com;'),
            array('http://example.com:',
                'http://example.com:'),
            array('\'http://example.com\'',
                '\'http://example.com\''),
            array('"http://example.com"',
                '"http://example.com"'),
            array('"http://example.com/"',
                '"http://example.com/"'),
            array('http://example.com',
                'http://example.com'),
            array('(http://example.com)',
                '(http://example.com)'),
            array('[http://example.com]',
                '[http://example.com]'),
            array('<http://example.com>',
                '<http://example.com>'),
            array('http://example.com/path/(foo)/bar',
                'http://example.com/path/(foo)/bar'),
            array('http://example.com/path/[foo]/bar',
                'http://example.com/path/[foo]/bar'),
            array('http://example.com/path/foo/(bar)',
                'http://example.com/path/foo/(bar)'),
            //Not a valid url - urls cannot contain unencoded square brackets
            array('http://example.com/path/foo/[bar]',
                'http://example.com/path/foo/[bar]'),
            array('Hey, check out my cool site http://example.com okay?',
                'Hey, check out my cool site http://example.com okay?'),
            array('What about parens (e.g. http://example.com/path/foo/(bar))?',
                'What about parens (e.g. http://example.com/path/foo/(bar))?'),
            array('What about parens (e.g. http://example.com/path/foo/(bar)?',
                'What about parens (e.g. http://example.com/path/foo/(bar)?'),
            array('What about parens (e.g. http://example.com/path/foo/(bar).)?',
                'What about parens (e.g. http://example.com/path/foo/(bar).)?'),
            //Not a valid url - urls cannot contain unencoded commas
            array('What about parens (e.g. http://example.com/path/(foo,bar)?',
                'What about parens (e.g. http://example.com/path/(foo,bar)?'),
            array('Unbalanced too (e.g. http://example.com/path/((((foo)/bar)?',
                'Unbalanced too (e.g. http://example.com/path/((((foo)/bar)?'),
            array('Unbalanced too (e.g. http://example.com/path/(foo))))/bar)?',
                'Unbalanced too (e.g. http://example.com/path/(foo))))/bar)?'),
            array('Unbalanced too (e.g. http://example.com/path/foo/((((bar)?',
                'Unbalanced too (e.g. http://example.com/path/foo/((((bar)?'),
            array('Unbalanced too (e.g. http://example.com/path/foo/(bar))))?',
                'Unbalanced too (e.g. http://example.com/path/foo/(bar))))?'),
            array('file.ext',
                'file.ext'),
            array('file.html',
                'file.html'),
            array('file.php',
                'file.php'),

            // scheme-less HTTP URLs with @ in the path: http://status.net/open-source/issues/2248
            array('http://flickr.com/photos/34807140@N05/3838905434',
                'http://flickr.com/photos/34807140@N05/3838905434'),
        );
    }

    static public function linkifyProvider()
    {
        return array(
            //bare ip addresses are no longer supported
            array('127.0.0.1',
                '127.0.0.1',
                'bare_ipv4'),
            array('127.0.0.1:99',
                '127.0.0.1:99',
                'bare_ipv4'),
            array('127.0.0.1/Name:test.php',
                '127.0.0.1/Name:test.php',
                'bare_ipv4'),
            array('127.0.0.1/~test',
                '127.0.0.1/~test',
                'bare_ipv4'),
            array('127.0.0.1/+test',
                '127.0.0.1/+test',
                'bare_ipv4'),
            array('127.0.0.1/$test',
                '127.0.0.1/$test',
                'bare_ipv4'),
            array('127.0.0.1/\'test',
                '127.0.0.1/\'test',
                'bare_ipv4'),
            array('127.0.0.1/"test',
                '127.0.0.1/"test',
                'bare_ipv4'),
            array('127.0.0.1/test"test',
                '127.0.0.1/test"test',
                'bare_ipv4'),
            array('127.0.0.1/-test',
                '127.0.0.1/-test',
                'bare_ipv4'),
            array('127.0.0.1/_test',
                '127.0.0.1/_test',
                'bare_ipv4'),
            array('127.0.0.1/!test',
                '127.0.0.1/!test',
                'bare_ipv4'),
            array('127.0.0.1/*test',
                '127.0.0.1/*test',
                'bare_ipv4'),
            array('127.0.0.1/test%20stuff',
                '127.0.0.1/test%20stuff',
                'bare_ipv4'),
            array('2001:4978:1b5:0:21d:e0ff:fe66:59ab/test.php',
                '2001:4978:1b5:0:21d:e0ff:fe66:59ab/test.php',
                'bare_ipv6'),
            array('[2001:4978:1b5:0:21d:e0ff:fe66:59ab]:99/test.php',
                '[2001:4978:1b5:0:21d:e0ff:fe66:59ab]:99/test.php',
                'bare_ipv6'),
            array('2001:4978:1b5:0:21d:e0ff:fe66:59ab',
                '2001:4978:1b5:0:21d:e0ff:fe66:59ab',
                'bare_ipv6'),
            array('example.com',
                'example.com',
                'bare_domains'),
            array('flickr.com/photos/34807140@N05/3838905434',
                'flickr.com/photos/34807140@N05/3838905434',
                'bare_domains'),
            array('What about parens (e.g. example.com/path/foo/(bar))?',
                'What about parens (e.g. example.com/path/foo/(bar))?',
                'bare_domains'),
            array('What about parens (e.g. example.com/path/foo/(bar)?',
                'What about parens (e.g. example.com/path/foo/(bar)?',
                'bare_domains'),
            array('What about parens (e.g. example.com/path/foo/(bar).)?',
                'What about parens (e.g. example.com/path/foo/(bar).?',
                'bare_domains'),
            array('What about parens (e.g. example.com/path/(foo,bar)?',
                'What about parens (e.g. example.com/path/(foo,bar)?',
                'bare_domains'),
            array('example.com',
                'example.com',
                'bare_domains'),
            array('example.org',
                'example.org',
                'bare_domains'),
            array('example.co.uk',
                'example.co.uk',
                'bare_domains'),
            array('www.example.co.uk',
                'www.example.co.uk',
                'bare_domains'),
            array('farm1.images.example.co.uk',
                'farm1.images.example.co.uk',
                'bare_domains'),
            array('example.museum',
                'example.museum',
                'bare_domains'),
            array('example.travel',
                'example.travel',
                'bare_domains'),
            array('example.com.',
                'example.com.',
                'bare_domains'),
            array('example.com?',
                'example.com?',
                'bare_domains'),
            array('example.com!',
                'example.com!',
                'bare_domains'),
            array('example.com,',
                'example.com,',
                'bare_domains'),
            array('example.com;',
                'example.com;',
                'bare_domains'),
            array('example.com:',
                'example.com:',
                'bare_domains'),
            array('\'example.com\'',
                '\'example.com\'',
                'bare_domains'),
            array('"example.com"',
                '"example.com"',
                'bare_domains'),
            array('example.com',
                'example.com',
                'bare_domains'),
            array('(example.com)',
                '(example.com)',
                'bare_domains'),
            array('[example.com]',
                '[example.com]',
                'bare_domains'),
            array('<example.com>',
                '<example.com>',
                'bare_domains'),
            array('Hey, check out my cool site example.com okay?',
                'Hey, check out my cool site example.com okay?',
                'bare_domains'),
            array('Hey, check out my cool site example.com.I made it.',
                'Hey, check out my cool site example.com.I made it.',
                'bare_domains'),
            array('Hey, check out my cool site example.com.Funny thing...',
                'Hey, check out my cool site example.com.Funny thing...',
                'bare_domains'),
            array('Hey, check out my cool site example.com.You will love it.',
                'Hey, check out my cool site example.com.You will love it.',
                'bare_domains'),
            array('example.com:8080/test.php',
                'example.com:8080/test.php',
                'bare_domains'),
            array('user_name+other@example.com',
                'user_name+other@example.com',
                'bare_domains'),
            array('user@example.com',
                'user@example.com',
                'bare_domains'),
        );
    }
}


code:
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social.  If not, see <http://www.gnu.org/licenses/>.

namespace Tests\Unit;

if (!defined('INSTALLDIR')) {
    define('INSTALLDIR', dirname(dirname(__DIR__)));
}
if (!defined('PUBLICDIR')) {
    define('PUBLICDIR', INSTALLDIR . DIRECTORY_SEPARATOR . 'public');
}
if (!defined('GNUSOCIAL')) {
    define('GNUSOCIAL', true);
}
if (!defined('STATUSNET')) { // Compatibility
    define('STATUSNET', true);
}

use PHPUnit\Framework\TestCase;
use UUID;

require_once INSTALLDIR . '/lib/util/common.php';

final class UUIDTest extends TestCase
{
    public function testGenerate()
    {
        $result = UUID::gen();
        $this->assertRegExp('/^[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}$/',
            $result);
        // Check version number
        $this->assertEquals(0x4000, hexdec(substr($result, 14, 4)) & 0xF000);
        $this->assertEquals(0x8000, hexdec(substr($result, 19, 4)) & 0xC000);
    }

    public function testUnique()
    {
        $reps = 100;
        $ids = array();

        for ($i = 0; $i < $reps; $i++) {
            $ids[] = UUID::gen();
        }

        $this->assertEquals(count($ids), count(array_unique($ids)), "UUIDs must be unique");
    }
}

repo_name: spookie/gnu

license: mit


code:
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social.  If not, see <http://www.gnu.org/licenses/>.

namespace Tests\Unit;

if (!defined('INSTALLDIR')) {
    define('INSTALLDIR', dirname(dirname(__DIR__)));
}
if (!defined('PUBLICDIR')) {
    define('PUBLICDIR', INSTALLDIR . DIRECTORY_SEPARATOR . 'public');
}
if (!defined('GNUSOCIAL')) {
    define('GNUSOCIAL', true);
}
if (!defined('STATUSNET')) { // Compatibility
    define('STATUSNET', true);
}

use Activity;
use ActivityObject;
use DOMDocument;
use PHPUnit\Framework\TestCase;

require_once INSTALLDIR . '/lib/util/common.php';

final class UserFeedParseTests extends TestCase
{
    public function testFeed1()
    {
        global $_testfeed1;
        $dom = new DOMDocument();
        $dom->loadXML($_testfeed1);
        $this->assertFalse(empty($dom));

        $entries = $dom->getElementsByTagName('entry');

        $entry1 = $entries->item(0);
        $this->assertFalse(empty($entry1));

        $feedEl = $dom->getElementsByTagName('feed')->item(0);
        $this->assertFalse(empty($feedEl));

        // Test actor (from activity:subject)

        $act1 = new Activity($entry1, $feedEl);
        $this->assertFalse(empty($act1));
        $this->assertFalse(empty($act1->actor));
        $this->assertEquals($act1->actor->type, ActivityObject::PERSON);
        $this->assertEquals($act1->actor->title, 'Zach Copley');
        $this->assertEquals($act1->actor->id, 'http://localhost/statusnet/user/1');
        $this->assertEquals($act1->actor->link, 'http://localhost/statusnet/zach');

        $avatars = $act1->actor->avatarLinks;

        $this->assertEquals(
            $avatars[0]->url,
            'http://localhost/statusnet/theme/default/default-avatar-profile.png'
        );

        $this->assertEquals(
            $avatars[1]->url,
            'http://localhost/statusnet/theme/default/default-avatar-stream.png'
        );

        $this->assertEquals(
            $avatars[2]->url,
            'http://localhost/statusnet/theme/default/default-avatar-mini.png'
        );

        $this->assertEquals($act1->actor->displayName, 'Zach Copley');

        $poco = $act1->actor->poco;
        $this->assertEquals($poco->preferredUsername, 'zach');
        $this->assertEquals($poco->address->formatted, 'El Cerrito, CA');
        $this->assertEquals($poco->urls[0]->type, 'homepage');
        $this->assertEquals($poco->urls[0]->value, 'http://zach.copley.name');
        $this->assertEquals($poco->urls[0]->primary, true);
        $this->assertEquals($poco->note, 'Zach Hack Attack');

        // test the post

        //var_export($act1);
        $this->assertEquals($act1->objects[0]->type, 'http://activitystrea.ms/schema/1.0/note');
        $this->assertEquals($act1->objects[0]->title, 'And now for something completely insane...');

        $this->assertEquals($act1->objects[0]->content, 'And now for something completely insane...');
        $this->assertEquals($act1->objects[0]->id, 'http://localhost/statusnet/notice/3');

    }

}

$_testfeed1 = <<<TESTFEED1
<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0" xmlns:georss="http://www.georss.org/georss" xmlns:activity="http://activitystrea.ms/spec/1.0/" xmlns:media="http://purl.org/syndication/atommedia" xmlns:poco="http://portablecontacts.net/spec/1.0" xmlns:ostatus="http://ostatus.org/schema/1.0">
 <id>http://localhost/statusnet/api/statuses/user_timeline/1.atom</id>
 <title>zach timeline</title>
 <subtitle>Updates from zach on Zach Dev!</subtitle>
 <logo>http://localhost/statusnet/theme/default/default-avatar-profile.png</logo>
 <updated>2010-03-04T01:41:14+00:00</updated>
<author>
 <name>zach</name>
 <uri>http://localhost/statusnet/user/1</uri>

</author>
 <link href="http://localhost/statusnet/zach" rel="alternate" type="text/html"/>
 <link href="http://localhost/statusnet/main/sup#1" rel="http://api.friendfeed.com/2008/03#sup" type="application/json"/>
 <link href="http://localhost/statusnet/main/push/hub" rel="hub"/>
 <link href="http://localhost/statusnet/main/salmon/user/1" rel="http://salmon-protocol.org/ns/salmon-replies"/>
 <link href="http://localhost/statusnet/main/salmon/user/1" rel="http://salmon-protocol.org/ns/salmon-mention"/>
 <link href="http://localhost/statusnet/api/statuses/user_timeline/1.atom" rel="self" type="application/atom+xml"/>
<activity:subject>
 <activity:object-type>http://activitystrea.ms/schema/1.0/person</activity:object-type>
 <id>http://localhost/statusnet/user/1</id>
 <title>Zach Copley</title>
 <link rel="alternate" type="text/html" href="http://localhost/statusnet/zach"/>
 <link rel="avatar" type="image/png" media:width="96" media:height="96" href="http://localhost/statusnet/theme/default/default-avatar-profile.png"/>
 <link rel="avatar" type="image/png" media:width="48" media:height="48" href="http://localhost/statusnet/theme/default/default-avatar-stream.png"/>
 <link rel="avatar" type="image/png" media:width="24" media:height="24" href="http://localhost/statusnet/theme/default/default-avatar-mini.png"/>

<poco:preferredUsername>zach</poco:preferredUsername>
<poco:displayName>Zach Copley</poco:displayName>
<poco:note>Zach Hack Attack</poco:note>
<poco:address>
 <poco:formatted>El Cerrito, CA</poco:formatted>
</poco:address>
<poco:urls>
 <poco:type>homepage</poco:type>
 <poco:value>http://zach.copley.name</poco:value>
 <poco:primary>true</poco:primary>

</poco:urls>
</activity:subject>
<entry>
 <title>And now for something completely insane...</title>
 <link rel="alternate" type="text/html" href="http://localhost/statusnet/notice/3"/>
 <id>http://localhost/statusnet/notice/3</id>
 <published>2010-03-04T01:41:07+00:00</published>
 <updated>2010-03-04T01:41:07+00:00</updated>
 <link rel="ostatus:conversation" href="http://localhost/statusnet/conversation/3"/>
 <content type="html">And now for something completely insane...</content>
</entry>

</feed>
TESTFEED1;


code:
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social.  If not, see <http://www.gnu.org/licenses/>.

namespace Tests\Unit;

if (!defined('INSTALLDIR')) {
    define('INSTALLDIR', dirname(dirname(__DIR__)));
}
if (!defined('PUBLICDIR')) {
    define('PUBLICDIR', INSTALLDIR . DIRECTORY_SEPARATOR . 'public');
}
if (!defined('GNUSOCIAL')) {
    define('GNUSOCIAL', true);
}
if (!defined('STATUSNET')) { // Compatibility
    define('STATUSNET', true);
}

use Exception;
use PHPUnit\Framework\TestCase;
use User;

require_once INSTALLDIR . '/lib/util/common.php';

final class UserRightsTest extends TestCase
{
    protected $user = null;

    function setUp(): void
    {
        $user = User::getKV('nickname', 'userrightstestuser');
        if ($user) {
            // Leftover from a broken test run?
            $profile = $user->getProfile();
            $user->delete();
            $profile->delete();
        }
        $this->user = User::register(array('nickname' => 'userrightstestuser'));
        if (!$this->user) {
            throw new Exception("Couldn't register userrightstestuser");
        }
    }

    function tearDown(): void
    {
        if ($this->user) {
            $profile = $this->user->getProfile();
            $this->user->delete();
            $profile->delete();
        }
    }

    function testInvalidRole()
    {
        $this->assertFalse($this->user->hasRole('invalidrole'));
    }

    function standardRoles()
    {
        return array(array('admin'),
            array('moderator'));
    }

    /**
     * @dataProvider standardRoles
     * @param $role
     */

    function testUngrantedRole($role)
    {
        $this->assertFalse($this->user->hasRole($role));
    }

    /**
     * @dataProvider standardRoles
     * @param $role
     */

    function testGrantedRole($role)
    {
        $this->user->grantRole($role);
        $this->assertTrue($this->user->hasRole($role));
    }
}


code:
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social.  If not, see <http://www.gnu.org/licenses/>.

namespace Tests\Unit;

if (!defined('INSTALLDIR')) {
    define('INSTALLDIR', dirname(dirname(__DIR__)));
}
if (!defined('PUBLICDIR')) {
    define('PUBLICDIR', INSTALLDIR . DIRECTORY_SEPARATOR . 'public');
}
if (!defined('GNUSOCIAL')) {
    define('GNUSOCIAL', true);
}
if (!defined('STATUSNET')) { // Compatibility
    define('STATUSNET', true);
}

use GNUsocial;
use PHPUnit\Framework\TestCase;
use XmppPlugin;

require_once INSTALLDIR . '/lib/util/common.php';
require_once INSTALLDIR . '/plugins/Xmpp/XmppModule.php';

final class XmppValidateTest extends TestCase
{
    public function setUp(): void
    {
        if (!array_key_exists('Xmpp', GNUsocial::getActiveModules())) {
            $this->markTestSkipped('XmppPlugin is not enabled.');
        }
    }

    /**
     * @dataProvider validationCases
     * @param $jid
     * @param $validFull
     * @param $validBase
     */
    public function testValidate($jid, $validFull, $validBase)
    {
        $xmpp = new TestXmppPlugin();
        $this->assertEquals($validFull || $validBase, $xmpp->validate($jid));
        $this->assertEquals($validFull, $xmpp->validateFullJid($jid), "validating as full or base JID");
        $this->assertEquals($validBase, $xmpp->validateBaseJid($jid), "validating as base JID only");
    }

    /**
     * @dataProvider normalizationCases
     * @param $jid
     * @param $expected
     */
    public function testNormalize($jid, $expected)
    {
        $xmpp = new XmppPlugin();
        $this->assertEquals($expected, $xmpp->normalize($jid));
    }

    /**
     * @dataProvider domainCheckCases()
     * @param $domain
     * @param $expected
     * @param $note
     */
    public function testDomainCheck($domain, $expected, $note)
    {
        $xmpp = new TestXmppPlugin();
        $this->assertEquals($expected, $xmpp->checkDomain($domain), $note);
    }

    static public function validationCases()
    {
        $long1023 = "long1023" . str_repeat('x', 1023 - 8);
        $long1024 = "long1024" . str_repeat('x', 1024 - 8);
        return array(
            // Our own test cases for standard things & those mentioned in bug reports
            // (jid, valid_full, valid_base)
            array('user@example.com', true, true),
            array('user@example.com/resource', true, false),
            array('user with spaces@example.com', false, false), // not kosher

            array('user.@example.com', true, true), // "common in intranets"
            array('example.com', true, true),
            array('example.com/resource', true, false),
            array('jabchat', true, true),

            array("$long1023@$long1023/$long1023", true, false), // max 1023 "bytes" per portion per spec. Do they really mean bytes though?
            array("$long1024@$long1023/$long1023", false, false),
            array("$long1023@$long1024/$long1023", false, false),
            array("$long1023@$long1023/$long1024", false, false),

            // Borrowed from test_jabber_jutil.c in libpurple
            array("gmail.com", true, true),
            array("gmail.com/Test", true, false),
            array("gmail.com/Test@", true, false),
            array("gmail.com/@", true, false),
            array("gmail.com/Test@alkjaweflkj", true, false),
            array("mark.doliner@gmail.com", true, true),
            array("mark.doliner@gmail.com/Test12345", true, false),
            array("mark.doliner@gmail.com/Test@12345", true, false),
            array("mark.doliner@gmail.com/Te/st@12@//345", true, false),
            array("わいど@conference.jabber.org", true, true),
            array("まりるーむ@conference.jabber.org", true, true),
            array("mark.doliner@gmail.com/まりるーむ", true, false),
            array("mark.doliner@gmail/stuff.org", true, false),
            array("stuart@nödåtXäYZ.se", true, true),
            array("stuart@nödåtXäYZ.se/まりるーむ", true, false),
            array("mark.doliner@わいど.org", true, true),
            array("nick@まつ.おおかみ.net", true, true),
            array("paul@10.0.42.230/s", true, false),
            array("paul@[::1]", true, true), /* IPv6 */
            array("paul@[2001:470:1f05:d58::2]", true, true),
            array("paul@[2001:470:1f05:d58::2]/foo", true, false),
            array("pa=ul@10.0.42.230", true, true),
            array("pa,ul@10.0.42.230", true, true),

            array("@gmail.com", false, false),
            array("@@gmail.com", false, false),
            array("mark.doliner@@gmail.com/Test12345", false, false),
            array("mark@doliner@gmail.com/Test12345", false, false),
            array("@gmail.com/Test@12345", false, false),
            array("/Test@12345", false, false),
            array("mark.doliner@", false, false),
            array("mark.doliner/", false, false),
            array("mark.doliner@gmail_stuff.org", false, false),
            array("mark.doliner@gmail[stuff.org", false, false),
            array("mark.doliner@gmail\\stuff.org", false, false),
            array("paul@[::1]124", false, false),
            array("paul@2[::1]124/as", false, false),
            array("paul@まつ.おおかみ/\x01", false, false),

            /*
             * RFC 3454 Section 6 reads, in part,
             * "If a string contains any RandALCat character, the
             *  string MUST NOT contain any LCat character."
             * The character is U+066D (ARABIC FIVE POINTED STAR).
             */
            // Leaving this one commented out for the moment
            // as it shouldn't hurt anything for our purposes.
            //array("foo@example.com/٭simplexe٭", false, false)
        );
    }

    static public function normalizationCases()
    {
        return array(
            // Borrowed from test_jabber_jutil.c in libpurple
            array('PaUL@DaRkRain42.org', 'paul@darkrain42.org'),
            array('PaUL@DaRkRain42.org/', 'paul@darkrain42.org'),
            array('PaUL@DaRkRain42.org/resource', 'paul@darkrain42.org'),

            // Also adapted from libpurple tests...
            array('Ф@darkrain42.org', 'ф@darkrain42.org'),
            array('paul@Өarkrain.org', 'paul@өarkrain.org'),
        );
    }

    static public function domainCheckCases()
    {
        return array(
            array('gmail.com', true, 'known SRV record'),
            array('jabber.org', true, 'known SRV record'),
            array('status.net', true, 'known SRV record'),
            array('status.leuksman.com', true, 'known no SRV record but valid domain'),
        );
    }

}

class TestXmppPlugin extends XmppPlugin
{
    public function checkDomain($domain)
    {
        return parent::checkDomain($domain);
    }

    public function validateBaseJid($jid, $check_domain = false)
    {
        return parent::validateBaseJid($jid, $check_domain);
    }

    public function validateFullJid($jid, $check_domain = false)
    {
        return parent::validateFullJid($jid, $check_domain);
    }
}


code:
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social.  If not, see <http://www.gnu.org/licenses/>.

namespace Tests\Unit;

if (!defined('INSTALLDIR')) {
    define('INSTALLDIR', dirname(dirname(__DIR__)));
}
if (!defined('PUBLICDIR')) {
    define('PUBLICDIR', INSTALLDIR . DIRECTORY_SEPARATOR . 'public');
}
if (!defined('GNUSOCIAL')) {
    define('GNUSOCIAL', true);
}
if (!defined('STATUSNET')) { // Compatibility
    define('STATUSNET', true);
}

use ClientException;
use Exception;
use MediaFile;
use PHPUnit\Framework\TestCase;
use ServerException;

require_once INSTALLDIR . '/lib/util/common.php';

final class MediaFileTest extends TestCase
{

    public function setup(): void
    {
        $this->old_attachments_supported = common_config('attachments', 'supported');
        $GLOBALS['config']['attachments']['supported'] = true;
    }

    public function tearDown(): void
    {
        $GLOBALS['config']['attachments']['supported'] = $this->old_attachments_supported;
    }

    /**
     * @dataProvider fileTypeCases
     * @param $filename
     * @param $expectedType
     * @throws ClientException
     * @throws ServerException
     */
    public function testMimeType($filename, $expectedType)
    {
        if (!file_exists($filename)) {
            throw new Exception("Test file $filename missing");
        }

        $type = MediaFile::getUploadedMimeType($filename, basename($filename));
        $this->assertEquals($expectedType, $type);
    }

    /**
     * @dataProvider fileTypeCases
     * @param $filename
     * @param $expectedType
     * @throws ClientException
     * @throws ServerException
     */
    public function testUploadedMimeType($filename, $expectedType)
    {
        if (!file_exists($filename)) {
            throw new Exception("WTF? $filename test file missing");
        }
        $tmp = tmpfile();
        fwrite($tmp, file_get_contents($filename));

        $tmp_metadata = stream_get_meta_data($tmp);
        $type = MediaFile::getUploadedMimeType($tmp_metadata['uri'], basename($filename));
        $this->assertEquals($expectedType, $type);
    }

    static public function fileTypeCases()
    {
        $base = dirname(__FILE__);
        $dir = "$base/sample-uploads";
        $files = array(
            "image.png" => "image/png",
            "image.gif" => "image/gif",
            "image.jpg" => "image/jpeg",
            "image.jpeg" => "image/jpeg",
            "office.pdf" => "application/pdf",
            "wordproc.odt" => "application/vnd.oasis.opendocument.text",
            "wordproc.ott" => "application/vnd.oasis.opendocument.text-template",
            "wordproc.doc" => "application/msword",
            "wordproc.docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            "wordproc.rtf" => "text/rtf",
            "spreadsheet.ods" => "application/vnd.oasis.opendocument.spreadsheet",
            "spreadsheet.ots" => "application/vnd.oasis.opendocument.spreadsheet-template",
            "spreadsheet.xls" => "application/vnd.ms-excel",
            "spreadsheet.xlt" => "application/vnd.ms-excel",
            "spreadsheet.xlsx" =>"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "presentation.odp" => "application/vnd.oasis.opendocument.presentation",
            "presentation.otp" => "application/vnd.oasis.opendocument.presentation-template",
            "presentation.ppt" => "application/vnd.ms-powerpoint",
            "presentation.pptx" => 'application/zip', //"application/vnd.openxmlformats-officedocument.presentationml.presentation",
        );

        $dataset = array();
        foreach ($files as $file => $type) {
            $dataset[] = array("$dir/$file", $type);
        }
        return $dataset;
    }

}


code:
#!/usr/bin/env php
<?php
/*
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2010, StatusNet, Inc.
 *
 * 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/>.
 */

if (!defined('INSTALLDIR')) {
    define('INSTALLDIR', dirname(dirname(__DIR__)));
}

$shortoptions = 'n:p:';
$longoptions = array('nickname=', 'password=', 'dry-run');

$helptext = <<<END_OF_HELP
USAGE: atompub_test.php [options]

Runs some tests on the AtomPub interface for the site. You must provide
a user account to authenticate as; it will be used to make some test
posts on the site.

Options:
  -n<user>  --nickname=<user>  Nickname of account to post as
  -p<pass>  --password=<pass>  Password for account
  --dry-run                    Skip tests that modify the site (post, delete)

END_OF_HELP;

require_once INSTALLDIR.'/scripts/commandline.inc';

$user = get_option_value('n', 'nickname');
$pass = get_option_value('p', 'password');

if (!$user) {
    die("Must set a user: --nickname=<username>\n");
}
if (!$pass) {
    die("Must set a password: --password=<username>\n");
}

// discover the feed...
// @fixme will this actually work?
$url = common_local_url('ApiTimelineUser', array('format' => 'atom', 'id' => $user));

echo "Collection URL is: $url\n";

$collection = new AtomPubClient($url, $user, $pass);

// confirm the feed has edit links ..... ?

echo "Posting an empty message (should fail)... ";
try {
    $noticeUrl = $collection->post('');
    die("FAILED, succeeded!\n");
} catch (Exception $e) {
    echo "ok\n";
}

echo "Posting an invalid XML message (should fail)... ";
try {
    $noticeUrl = $collection->post('<feed<entry>barf</yomomma>');
    die("FAILED, succeeded!\n");
} catch (Exception $e) {
    echo "ok\n";
}

echo "Posting a valid XML but non-Atom message (should fail)... ";
try {
    $noticeUrl = $collection->post('<feed xmlns="http://notatom.com"><id>arf</id><entry><id>barf</id></entry></feed>');
    die("FAILED, succeeded!\n");
} catch (Exception $e) {
    echo "ok\n";
}

// post!
$rand = mt_rand(0, 99999);
$atom = <<<END_ATOM
<entry xmlns="http://www.w3.org/2005/Atom">
    <title>This is an AtomPub test post title ($rand)</title>
    <content>This is an AtomPub test post content ($rand)</content>
</entry>
END_ATOM;

echo "Posting a new message... ";
$noticeUrl = $collection->post($atom);
echo "ok, got $noticeUrl\n";

echo "Fetching the new notice... ";
$notice = new AtomPubClient($noticeUrl, $user, $pass);
$body = $notice->get();
AtomPubClient::validateAtomEntry($body);
echo "ok\n";

echo "Getting the notice ID URI... ";
$noticeUri = AtomPubClient::entryId($body);
echo "ok: $noticeUri\n";

echo "Confirming new entry points to itself right... ";
$editUrl = AtomPubClient::entryEditURL($body);
if ($editUrl != $noticeUrl) {
    die("Entry lists edit URL as $editUrl, no match!\n");
}
echo "OK\n";

echo "Refetching the collection... ";
$feed = $collection->get();
echo "ok\n";

echo "Confirming new entry is in the feed... ";
$entry = AtomPubClient::getEntryInFeed($feed, $noticeUri);
if (!$entry) {
    die("missing!\n");
}
//  edit URL should match
echo "ok\n";

echo "Editing notice (should fail)... ";
try {
    $notice->put($target, $atom2);
    die("ERROR: editing a notice should have failed.\n");
} catch (Exception $e) {
    echo "ok (failed as expected)\n";
}

echo "Deleting notice... ";
$notice->delete();
echo "ok\n";

echo "Refetching deleted notice to confirm it's gone... ";
try {
    $body = $notice->get();
    var_dump($body);
    die("ERROR: notice should be gone now.\n");
} catch (Exception $e) {
    echo "ok\n";
}

echo "Refetching the collection.. ";
$feed = $collection->get();
echo "ok\n";

echo "Confirming deleted notice is no longer in the feed... ";
$entry = AtomPubClient::getEntryInFeed($feed, $noticeUri);
if ($entry) {
    die("still there!\n");
}
echo "ok\n";

// make subscriptions
// make some posts
// make sure the posts go through or not depending on the subs
// remove subscriptions
// test that they don't go through now

// group memberships too

// make sure we can't post to someone else's feed!
// make sure we can't delete someone else's messages
// make sure we can't create/delete someone else's subscriptions
// make sure we can't create/delete someone else's group memberships


code:
Some very rough test scripts for hitting up the OAuth endpoints.

These instructions assume you understand the basics of how OAuth
works. You may want to read up about it first. Here are some good
resources for learning about OAuth:

    http://hueniverse.com/oauth/
    http://tools.ietf.org/html/rfc5849

To use these scripts (and OAuth in general) first you will need to
register and OAuth client application with your StatusNet instance:

    http://example.status.net/settings/oauthapps

oauth.ini
---------

Using oauth.ini.sample as a guide, put your StatusNet OAuth endpoints
and consumer key and secret in a file called oauth.ini and save it
in the same directory as these scripts.

fetch_temp_creds.php
--------------------

Will fetch a request token, token secret and a URL to authorize the
token.  Once you authorize the request token, you can exchange it
for an access token.

example usage:

    $ php fetch_temp_creds.php
    Request Token
       - oauth_token        = 89d481e376edc622f08da5791e6a4446
       - oauth_token_secret = 6d028bcd1ea125cbed7da2f254219885
    Authorize URL
        http://example.status.net/api/oauth/authorize?oauth_token=89d481e376edc622f08da5791e6a4446

    Now paste the Authorize URL into your browser and authorize your temporary credentials.

fetch_token_creds.php
---------------------

After you have authorized your request token, you will be presented
with a verifier code, or pin, in your browser, which you will need
to get an access token. Make sure you copy it into a text buffer
or write it down or something. Then call fetch_token_credentials.php
to exchange your temporary credentials for real token credentials.

example usage:

    $ php fetch_token_creds.php -t 89d481e376edc622f08da5791e6a4446 -s 6d028bcd1ea125cbed7da2f254219885 -v 305162
    Access Token
       - oauth_token        = 9b354df102d8e2b4621122c85d8d045c
       - oauth_token_secret = 1800a88f1574b47d595214a74e5b1ec5

oauth_verify_credentials.php
----------------------------

Now you should have real token credentials (an OAuth access token)
and you can access protected API resources. This is an example
script that calls /api/account/verify_credentials.xml.

example usage:

    $ php oauth_verify_creds.php -t 80305cd15c5c69834364ac02d7f9178c -s 673e3b2978b1b92c8edbfe172505fee1
    <?xml version="1.0" encoding="UTF-8"?>
    <user xmlns:statusnet="http://status.net/schema/api/1/">
     <id>23</id>
     <name>zach</name>
     <screen_name>zach</screen_name>
     <location></location>
     <description></description>
     <profile_image_url>http://example.status.net/theme/default/default-avatar-stream.png</profile_image_url>
     <url></url>
     <protected>false</protected>
     <followers_count>0</followers_count>
     <profile_background_color></profile_background_color>
     <profile_text_color></profile_text_color>
     <profile_link_color></profile_link_color>
     <profile_sidebar_fill_color></profile_sidebar_fill_color>
     <profile_sidebar_border_color></profile_sidebar_border_color>
     <friends_count>0</friends_count>
     <created_at>Thu Sep 30 23:11:00 +0000 2010</created_at>
     <favourites_count>0</favourites_count>
     <utc_offset>0</utc_offset>
     <time_zone>UTC</time_zone>
     <profile_background_image_url></profile_background_image_url>
     <profile_background_tile>false</profile_background_tile>
     <statuses_count>4</statuses_count>
     <following>true</following>
     <statusnet:blocking>false</statusnet:blocking>
     <notifications>true</notifications>
     <status>
      <text>gar</text>
      <truncated>false</truncated>
      <created_at>Wed Oct 06 23:40:14 +0000 2010</created_at>
      <in_reply_to_status_id></in_reply_to_status_id>
      <source>web</source>
      <id>7</id>
      <in_reply_to_user_id></in_reply_to_user_id>
      <in_reply_to_screen_name></in_reply_to_screen_name>
      <geo></geo>
      <favorited>false</favorited>
      <statusnet:html>gar</statusnet:html>
     </status>
     <statusnet:profile_url>http://example.status.net/statusnet/zach</statusnet:profile_url>
    </user>

oauth_post_notice.php
---------------------

This is another test script that lets you post a notice via OAuth.

example usage:

    $ php oauth_post_notice.php -t 80305cd15c5c69834364ac02d7f9178c -s 673e3b2978b1b92c8edbfe172505fee1 -u 'Test test test...'
    <?xml version="1.0" encoding="UTF-8"?>
    <status xmlns:statusnet="http://status.net/schema/api/1/">
     <text>Test test test...</text>
     <truncated>false</truncated>
     <created_at>Fri Oct 08 02:37:35 +0000 2010</created_at>
     <in_reply_to_status_id></in_reply_to_status_id>
     <source>Banana</source>
     <id>8</id>
     <in_reply_to_user_id></in_reply_to_user_id>
     <in_reply_to_screen_name></in_reply_to_screen_name>
     <geo></geo>
     <favorited>false</favorited>
     <user>
      <id>23</id>
      <name>zach</name>
      <screen_name>zach</screen_name>
      <location></location>
      <description></description>
      <profile_image_url>http://example.status.net/statusnet/theme/default/default-avatar-stream.png</profile_image_url>
      <url></url>
      <protected>false</protected>
      <followers_count>0</followers_count>
      <profile_background_color></profile_background_color>
      <profile_text_color></profile_text_color>
      <profile_link_color></profile_link_color>
      <profile_sidebar_fill_color></profile_sidebar_fill_color>
      <profile_sidebar_border_color></profile_sidebar_border_color>
      <friends_count>0</friends_count>
      <created_at>Thu Sep 30 23:11:00 +0000 2010</created_at>
      <favourites_count>0</favourites_count>
      <utc_offset>0</utc_offset>
      <time_zone>UTC</time_zone>
      <profile_background_image_url></profile_background_image_url>
      <profile_background_tile>false</profile_background_tile>
      <statuses_count>5</statuses_count>
      <following>true</following>
      <statusnet:blocking>false</statusnet:blocking>
      <notifications>true</notifications>
      <statusnet:profile_url>http://example.status.net/statusnet/zach</statusnet:profile_url>
     </user>
     <statusnet:html>Test test test...</statusnet:html>
    </status>

path: tests/oauth/README


code:
#!/usr/bin/env php
<?php
/*
 * StatusNet - a distributed open-source microblogging tool
 * Copyright (C) 2010, StatusNet, Inc.
 *
 * 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/>.
 */

define('INSTALLDIR', realpath(dirname(__FILE__) . '/../..'));

require_once INSTALLDIR . '/scripts/commandline.inc';
require_once INSTALLDIR . '/extlib/OAuth.php';

$ini = parse_ini_file("oauth.ini");

// Check to make sure we have everything we need from the ini file
foreach(array('consumer_key', 'consumer_secret', 'apiroot', 'request_token_url') as $inikey) {
    if (empty($ini[$inikey])) {
        print "You forgot to specify a $inikey in your oauth.ini file.\n";
        exit(1);
    }
}

$consumer = new OAuthConsumer($ini['consumer_key'], $ini['consumer_secret']);
$endpoint = $ini['apiroot'] . $ini['request_token_url'];
$parsed   = parse_url($endpoint);
$params   = array();

parse_str($parsed['query'], $params);
$params['oauth_callback'] = 'oob'; // out-of-band

$hmac_method = new OAuthSignatureMethod_HMAC_SHA1();

try {
    $req = OAuthRequest::from_consumer_and_token(
        $consumer,
        null,
        "POST",
        $endpoint,
        $params
    );
    $req->sign_request($hmac_method, $consumer, NULL);
    $r = httpRequest($endpoint, $req->to_postdata());
} catch (Exception $e) {
    // oh noez
    print $e->getMessage();
    print "\nOAuth Request:\n";
    var_dump($req);
    exit(1);
}

$body       = $r->getBody();
$tokenStuff = array();

parse_str($body, $tokenStuff);

$tok       = $tokenStuff['oauth_token'];
$confirmed = $tokenStuff['oauth_callback_confirmed'];

if (empty($tokenStuff['oauth_token'])
    || empty($tokenStuff['oauth_token_secret'])
    || empty($confirmed)
    || $confirmed != 'true')
{
    print "Error! HTTP response body: $body\n";
    exit(1);
}

$authurl = $ini['apiroot'] . $ini['authorize_url'] . '?oauth_token=' . $tok;

print "Request Token\n";
print '   - oauth_token        = ' . $tokenStuff['oauth_token'] . "\n";
print '   - oauth_token_secret = ' . $tokenStuff['oauth_token_secret'] . "\n";
print "Authorize URL\n    $authurl\n\n";
print "Now paste the Authorize URL into your browser and authorize your temporary credentials.\n";

function httpRequest($endpoint, $poststr)
{
    $request = HTTPClient::start();

    $request->setConfig(
        array(
            'follow_redirects' => true,
	    'connect_timeout' => 120,
	    'timeout' => 120,
	    'ssl_verify_peer' => false,
	    'ssl_verify_host' => false
        )
    );

    // Turn signed request query string back into an array
    parse_str($poststr, $postdata);
    return $request->post($endpoint, null, $postdata);
}


code:
#!/usr/bin/env php
<?php
/*
 * StatusNet - a distributed open-source microblogging tool
 * Copyright (C) 2008, 2009, StatusNet, Inc.
 *
 * 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/>.
 */

define('INSTALLDIR', realpath(dirname(__FILE__) . '/../..'));

require_once INSTALLDIR . '/extlib/OAuth.php';

$ini = parse_ini_file("oauth.ini");

// Check to make sure we have everything we need from the ini file
foreach(array('consumer_key', 'consumer_secret', 'apiroot', 'access_token_url') as $inikey) {
    if (empty($ini[$inikey])) {
        print "You forgot to specify a $inikey in your oauth.ini file.\n";
        exit(1);
    }
}

$consumer = new OAuthConsumer($ini['consumer_key'], $ini['consumer_secret']);

$endpoint = $ini['apiroot'] . $ini['access_token_url'];

$shortoptions = 't:s:v:';
$longoptions = array('oauth_token=', 'oauth_token_secret=', 'oauth_verifier=');

$helptext = <<<END_OF_ETOKENS_HELP
  fetch_token_creds.php [options]

  Exchange authorized OAuth temporary credentials for token credentials
  (an authorized request token for an access token)

    -t --oauth_token        authorized request token
    -s --oauth_token_secret authorized request token secret
    -v --oauth_verifier     authorized request token verifier

END_OF_ETOKENS_HELP;

require_once INSTALLDIR . '/scripts/commandline.inc';

$token = $secret = $verifier = null;

if (have_option('t', 'oauth_token')) {
    $token = get_option_value('t', 'oauth_token');
}

if (have_option('s', 'oauth_token_secret')) {
    $secret = get_option_value('s', 'oauth_token_secret');
}

if (have_option('v', 'oauth_verifier')) {
    $verifier = get_option_value('v', 'oauth_verifier');
}

if (empty($token)) {
    print "Please specify the request token (--help for help).\n";
    exit(1);
}

if (empty($secret)) {
    print "Please specify the request token secret (--help for help).\n";
    exit(1);
}

if (empty($verifier)) {
    print "Please specify the request token verifier (--help for help).\n";
    exit(1);
}

$rtok   = new OAuthToken($token, $secret);
$parsed = parse_url($endpoint);
parse_str($parsed['query'], $params);

$params['oauth_verifier'] = $verifier; // 1.0a

$hmac_method = new OAuthSignatureMethod_HMAC_SHA1();

try {

    $oauthReq = OAuthRequest::from_consumer_and_token(
        $consumer,
        $rtok,
        "POST",
        $endpoint,
        $params
    );

    $oauthReq->sign_request($hmac_method, $consumer, $rtok);

    $httpReq    = httpRequest($endpoint, $oauthReq->to_postdata());
    $body       = $httpReq->getBody();

} catch (Exception $e) {
    // oh noez
    print $e->getMessage();
    print "\nOAuth Request:\n";
    var_dump($oauthReq);
    exit(1);
}

$tokenStuff = array();
parse_str($body, $tokenStuff);

if (empty($tokenStuff['oauth_token']) || empty($tokenStuff['oauth_token_secret'])) {
    print "Error! HTTP response body: $body\n";
    exit(1);
}

print "Access Token\n";
print '   - oauth_token        = ' . $tokenStuff['oauth_token'] . "\n";
print '   - oauth_token_secret = ' . $tokenStuff['oauth_token_secret'] . "\n";

function httpRequest($endpoint, $poststr)
{
    $request = HTTPClient::start();

    $request->setConfig(
        array(
            'follow_redirects' => true,
	    'connect_timeout'  => 120,
	    'timeout'          => 120,
	    'ssl_verify_peer'  => false,
	    'ssl_verify_host'  => false
	)
    );

    parse_str($poststr, $postdata);
    return $request->post($endpoint, null, $postdata);
}


code:
; Setup OAuth info here
apiroot       = "https://YOURSTATUSNET/api"

request_token_url = "/oauth/request_token"
authorize_url     = "/oauth/authorize"
access_token_url  = "/oauth/access_token"

consumer_key  = "b748968e9bea81a53f3a3c15aa0c686f"
consumer_secret = "5434e18cce05d9e53cdd48029a62fa41"


code:
#!/usr/bin/env php
<?php
/*
 * StatusNet - a distributed open-source microblogging tool
 * Copyright (C) 2010, StatusNet, Inc.
 *
 *  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/>.
 **/

define('INSTALLDIR', realpath(dirname(__FILE__) . '/../..'));

require_once INSTALLDIR . '/extlib/OAuth.php';

$shortoptions = 't:s:u:';
$longoptions = array('oauth_token=', 'oauth_token_secret=', 'update=');

$helptext = <<<END_OF_VERIFY_HELP
    oauth_post_notice.php [options]
    Update your status via OAuth

    -t --oauth_token        access token
    -s --oauth_token_secret access token secret
    -u --update             status update

END_OF_VERIFY_HELP;

$token        = null;
$token_secret = null;
$update       = null;

require_once INSTALLDIR . '/scripts/commandline.inc';

if (have_option('t', 'oauth_token')) {
    $token = get_option_value('t', 'oauth_token');
}

if (have_option('s', 'oauth_token_secret')) {
    $token_secret = get_option_value('s', 'oauth_token_secret');
}

if (have_option('u', 'update')) {
    $update = get_option_value('u', 'update');
}

if (empty($token)) {
    print "Please specify an access token.\n";
    exit(1);
}

if (empty($token_secret)) {
    print "Please specify an access token secret.\n";
    exit(1);
}

if (empty($update)) {
    print "You forgot to update your status!\n";
    exit(1);
}

$ini      = parse_ini_file("oauth.ini");
$consumer = new OAuthConsumer($ini['consumer_key'], $ini['consumer_secret']);
$endpoint = $ini['apiroot'] . '/statuses/update.xml';

$atok = new OAuthToken($token, $token_secret);

$parsed = parse_url($endpoint);
parse_str($parsed['query'], $params);

$params['status'] = $update;

$hmac_method = new OAuthSignatureMethod_HMAC_SHA1();

try {

    $oauthReq = OAuthRequest::from_consumer_and_token(
        $consumer,
        $atok,
        'POST',
        $endpoint,
        $params
    );

    $oauthReq->sign_request($hmac_method, $consumer, $atok);

    $httpReq = httpRequest($endpoint, $oauthReq->to_postdata());

    print $httpReq->getBody();

} catch (Exception $e) {
    print "Error! . $e->getMessage() . 'HTTP reponse body: " . $httpReq->getBody();
    exit(1);
}

function httpRequest($endpoint, $poststr)
{
    $request = HTTPClient::start();

    $request->setConfig(
        array(
            'follow_redirects' => true,
	    'connect_timeout' => 120,
	    'timeout' => 120,
	    'ssl_verify_peer' => false,
	    'ssl_verify_host' => false
        )
    );

    // Turn signed request query string back into an array
    parse_str($poststr, $postdata);
    return $request->post($endpoint, null, $postdata);
}


code:
#!/usr/bin/env php
<?php
/*
 * StatusNet - a distributed open-source microblogging tool
 * Copyright (C) 2008, 2009, StatusNet, Inc.
 *
 * 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/>.
 */

define('INSTALLDIR', realpath(dirname(__FILE__) . '/../..'));

require_once INSTALLDIR . '/extlib/OAuth.php';

$shortoptions = 't:s:';
$longoptions = array('oauth_token=', 'oauth_token_secret=');

$helptext = <<<END_OF_VERIFY_HELP
  oauth_verify_creds.php [options]
  Access /api/account/verify_credentials.xml with OAuth

    -t --oauth_token        access token
    -s --oauth_token_secret access token secret

END_OF_VERIFY_HELP;

$token        = null;
$token_secret = null;

require_once INSTALLDIR . '/scripts/commandline.inc';

if (have_option('t', 'oauth_token')) {
    $token = get_option_value('t', 'oauth_token');
}

if (have_option('s', 'oauth_token_secret')) {
    $token_secret = get_option_value('s', 'oauth_token_secret');
}

if (empty($token)) {
    print "Please specify an access token (--help for help).\n";
    exit(1);
}

if (empty($token_secret)) {
    print "Please specify an access token secret (--help for help).\n";
    exit(1);
}

$ini      = parse_ini_file("oauth.ini");
$consumer = new OAuthConsumer($ini['consumer_key'], $ini['consumer_secret']);
$endpoint = $ini['apiroot'] . '/account/verify_credentials.xml';

$atok   = new OAuthToken($token, $token_secret);
$parsed = parse_url($endpoint);

parse_str($parsed['query'], $params);

try {

    $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();

    $oauthReq = OAuthRequest::from_consumer_and_token(
        $consumer,
        $atok,
        "GET",
        $endpoint,
        $params
    );

    $oauthReq->sign_request($hmac_method, $consumer, $atok);

    $httpReq = httpRequest($oauthReq->to_url());

} catch (Exception $e) {
    print "Error! HTTP response body: " . $httpReq->getBody();
    exit(1);
}

print $httpReq->getBody();

function httpRequest($url)
{
    $request = HTTPClient::start();

    $request->setConfig(
        array(
            'follow_redirects' => true,
	    'connect_timeout' => 120,
	    'timeout' => 120,
	    'ssl_verify_peer' => false,
	    'ssl_verify_host' => false
        )
    );

    return $request->get($url);
}


code:
DO NOT "FIX" CODE IN THIS DIRECTORY.

ONLY UPSTREAM VERSIONS OF SOFTWARE GO IN THIS DIRECTORY.

This directory is provided as a courtesy to our users who might be
unable or unwilling to find and install libraries we depend on.

If we "fix" software in this directory, we hamstring users who do the
right thing and keep a single version of upstream libraries in a
system-wide library. We introduce subtle and maddening bugs where
our code is "accidentally" using the "wrong" library version. We may
unwittingly interfere with other software that depends on the
canonical release versions of those same libraries!

Forking upstream software for trivial reasons makes us bad citizens in
the Open Source community and adds unnecessary heartache for our
users. Don't make us "that" project.

Frequently Asked Questions
--------------------------

Q: What should we do when we find a bug in upstream software?

A: First and foremost, REPORT THE BUG, and if possible send in a patch.

   Watch for a release of the upstream software and integrate with it
   when it's released.

   In the meantime, work around the bug, if at all possible. Usually,
   it's quite possible, if slightly harder or less efficient.

Q: What if the bug can't be worked around?

A: If the upstream developers have accepted a bug patch, it's
   undesirable but acceptable to apply that patch to the library in
   the extlib dir. Ideally, use a release version for upstream or a
   version control system snapshot.

   Note that this is a last resort.

Q: What if upstream is unresponsive or won't accept a patch?

A: Try again.

Q: I tried again, and upstream is still unresponsive and nobody's
   checked on my patch. Now what?

A: If the upstream project is moribund and there's a way to adopt it,
   propose having the GNU social dev team adopt the project. Or, adopt
   it yourself.

Q: What if there's no upstream authority and it can't be adopted?

A: Then we fork it. Make a new name and a new version. Include it in
   extlib/ instead of vendor/, and use the GNUsocial_* prefix to change
   the namespace to avoid collisions.

   This is a last resort; consult with the rest of the dev group
   before taking this radical step.


code:
/docs/ export-ignore
/test/ export-ignore
/utils/ export-ignore
/.buildpath export-ignore
/.gitignore export-ignore
/.project export-ignore
/.travis.yml export-ignore


code:
<?php

/**
 * Licensed to Jasig under one or more contributor license
 * agreements. See the NOTICE file distributed with this work for
 * additional information regarding copyright ownership.
 *
 * Jasig licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at:
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *  PHP Version 5
 *
 * @file     CAS.php
 * @category Authentication
 * @package  PhpCAS
 * @author   Adam Franco <afranco@middlebury.edu>
 * @license  http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link     https://wiki.jasig.org/display/CASC/phpCAS
 */

require_once dirname(__FILE__).'/source/CAS.php';


code:
Copyright 2007-2011, JA-SIG, Inc.
This project includes software developed by Jasig.
http://www.jasig.org/

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this software except in compliance with the License.
You may obtain a copy of the License at:

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

===========================================================================

Copyright © 2003-2007, The ESUP-Portail consortium

Requirements for sources originally licensed under the New BSD License:

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

- Neither the name of JA-SIG, Inc. nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

===========================================================================

Copyright (c) 2009, Regents of the University of Nebraska
All rights reserved.

Requirements for CAS_Autloader originally licensed under the New BSD License:

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

Neither the name of the University of Nebraska nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

path: vendor/apereo/phpcas/NOTICE


code:
phpCAS
=======

phpCAS is an authentication library that allows PHP applications to easily authenticate
users via a Central Authentication Service (CAS) server.

Please see the wiki website for more information:

https://wiki.jasig.org/display/CASC/phpCAS

Api documentation can be found here:

https://apereo.github.io/phpCAS/

[![Build Status](https://travis-ci.org/apereo/phpCAS.png)](https://travis-ci.org/apereo/phpCAS)

LICENSE
-------

Copyright 2007-2015, JA-SIG, Inc.
This project includes software developed by Jasig.
http://www.jasig.org/

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this software except in compliance with the License.
You may obtain a copy of the License at:

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


apereo/phpcas

description: Provides a simple API for authenticating users against a CAS server

keywords: cas jasig apereo

type: library