Merge remote-tracking branch 'upstream/develop' into more-bots

pull/873/head
Michael 2019-08-07 05:50:07 +00:00
commit 321de7ba08
39 changed files with 10542 additions and 38 deletions

View File

@ -21,7 +21,8 @@
}
],
"require": {
"abraham/twitteroauth": "^0.7.4"
"abraham/twitteroauth": "^0.7.4",
"jublonet/codebird-php": "dev-master"
},
"license": "3-clause BSD license",
"minimum-stability": "stable",

187
twitter/composer.lock generated
View File

@ -1,10 +1,10 @@
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "341c2ca2f25177375c65577f7e5d7369",
"content-hash": "eaeac282537509fd7d0bc4f92f01bc04",
"packages": [
{
"name": "abraham/twitteroauth",
@ -59,12 +59,193 @@
"twitter"
],
"time": "2017-06-30T22:02:01+00:00"
},
{
"name": "composer/installers",
"version": "v1.6.0",
"source": {
"type": "git",
"url": "https://github.com/composer/installers.git",
"reference": "cfcca6b1b60bc4974324efb5783c13dca6932b5b"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/composer/installers/zipball/cfcca6b1b60bc4974324efb5783c13dca6932b5b",
"reference": "cfcca6b1b60bc4974324efb5783c13dca6932b5b",
"shasum": ""
},
"require": {
"composer-plugin-api": "^1.0"
},
"replace": {
"roundcube/plugin-installer": "*",
"shama/baton": "*"
},
"require-dev": {
"composer/composer": "1.0.*@dev",
"phpunit/phpunit": "^4.8.36"
},
"type": "composer-plugin",
"extra": {
"class": "Composer\\Installers\\Plugin",
"branch-alias": {
"dev-master": "1.0-dev"
}
},
"autoload": {
"psr-4": {
"Composer\\Installers\\": "src/Composer/Installers"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Kyle Robinson Young",
"email": "kyle@dontkry.com",
"homepage": "https://github.com/shama"
}
],
"description": "A multi-framework Composer library installer",
"homepage": "https://composer.github.io/installers/",
"keywords": [
"Craft",
"Dolibarr",
"Eliasis",
"Hurad",
"ImageCMS",
"Kanboard",
"Lan Management System",
"MODX Evo",
"Mautic",
"Maya",
"OXID",
"Plentymarkets",
"Porto",
"RadPHP",
"SMF",
"Thelia",
"WolfCMS",
"agl",
"aimeos",
"annotatecms",
"attogram",
"bitrix",
"cakephp",
"chef",
"cockpit",
"codeigniter",
"concrete5",
"croogo",
"dokuwiki",
"drupal",
"eZ Platform",
"elgg",
"expressionengine",
"fuelphp",
"grav",
"installer",
"itop",
"joomla",
"kohana",
"laravel",
"lavalite",
"lithium",
"magento",
"majima",
"mako",
"mediawiki",
"modulework",
"modx",
"moodle",
"osclass",
"phpbb",
"piwik",
"ppi",
"puppet",
"pxcms",
"reindex",
"roundcube",
"shopware",
"silverstripe",
"sydes",
"symfony",
"typo3",
"wordpress",
"yawik",
"zend",
"zikula"
],
"time": "2018-08-27T06:10:37+00:00"
},
{
"name": "jublonet/codebird-php",
"version": "dev-master",
"source": {
"type": "git",
"url": "https://github.com/jublonet/codebird-php.git",
"reference": "df362d8ad629aad6c4c7dbf36a440e569ec41368"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/jublonet/codebird-php/zipball/df362d8ad629aad6c4c7dbf36a440e569ec41368",
"reference": "df362d8ad629aad6c4c7dbf36a440e569ec41368",
"shasum": ""
},
"require": {
"composer/installers": "~1.0",
"ext-hash": "*",
"ext-json": "*",
"lib-openssl": "*",
"php": ">=5.5.0"
},
"require-dev": {
"php-coveralls/php-coveralls": ">=0.6",
"phpunit/phpunit": ">=7.3",
"squizlabs/php_codesniffer": "2.*"
},
"type": "library",
"autoload": {
"classmap": [
"src/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"GPL-3.0+"
],
"authors": [
{
"name": "Joshua Atkins",
"role": "Developer",
"email": "joshua.atkins@jublo.net",
"homepage": "http://atkins.im/"
},
{
"name": "J.M.",
"role": "Developer",
"email": "jm@jublo.net",
"homepage": "http://mynetx.net/"
}
],
"description": "Easy access to the Twitter REST API, Direct Messages API, Account Activity API, TON (Object Nest) API and Twitter Ads API — all from one PHP library.",
"homepage": "https://www.jublo.net/projects/codebird/php",
"keywords": [
"api",
"networking",
"twitter"
],
"time": "2018-08-16T00:07:08+00:00"
}
],
"packages-dev": [],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": [],
"stability-flags": {
"jublonet/codebird-php": 20
},
"prefer-stable": false,
"prefer-lowest": false,
"platform": [],

View File

@ -64,6 +64,7 @@
use Abraham\TwitterOAuth\TwitterOAuth;
use Abraham\TwitterOAuth\TwitterOAuthException;
use Codebird\Codebird;
use Friendica\App;
use Friendica\Content\OEmbed;
use Friendica\Content\Text\BBCode;
@ -591,6 +592,10 @@ function twitter_post_hook(App $a, array &$b)
return;
}
Codebird::setConsumerKey($ckey, $csecret);
$cb = Codebird::getInstance();
$cb->setToken($otoken, $osecret);
$connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
// Set the timeout for upload to 30 seconds
@ -616,19 +621,15 @@ function twitter_post_hook(App $a, array &$b)
$msg = Plaintext::shorten($msgarr["title"], $max_char - 50);
}
$image = "";
if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
if (($msgarr['url'] == $b['plink']) && !empty($msgarr['images']) && (count($msgarr['images']) <= 4)) {
$url_added = false;
} elseif (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
$msg .= "\n" . $msgarr["url"];
$url_added = true;
} else {
$url_added = false;
}
if (isset($msgarr["image"]) && ($msgarr["type"] != "video")) {
$image = $msgarr["image"];
}
if (empty($msg)) {
return;
}
@ -636,32 +637,42 @@ function twitter_post_hook(App $a, array &$b)
// and now tweet it :-)
$post = [];
if (!empty($image)) {
if (!empty($msgarr['images'])) {
try {
$img_str = Network::fetchUrl($image);
$media_ids = [];
foreach ($msgarr['images'] as $image) {
if (count($media_ids) == 4) {
continue;
}
$tempfile = tempnam(get_temppath(), 'cache');
file_put_contents($tempfile, $img_str);
$img_str = Network::fetchUrl($image['url']);
$media = $connection->upload('media/upload', ['media' => $tempfile]);
$tempfile = tempnam(get_temppath(), 'cache');
file_put_contents($tempfile, $img_str);
unlink($tempfile);
$media = $connection->upload('media/upload', ['media' => $tempfile]);
if (isset($media->media_id_string)) {
$post['media_ids'] = $media->media_id_string;
} else {
throw new Exception('Failed upload of ' . $image);
unlink($tempfile);
if (isset($media->media_id_string)) {
$media_ids[] = $media->media_id_string;
if (!empty($image['description'])) {
$data = ['media_id' => $media->media_id_string,
'alt_text' => ['text' => substr($image['description'], 0, 420)]];
$ret = $cb->media_metadata_create($data);
Logger::info('Metadata create', ['data' => $data, 'return' => json_encode($ret)]);
}
} else {
throw new Exception('Failed upload of ' . $image['url']);
}
}
$post['media_ids'] = implode(',', $media_ids);
if (empty($post['media_ids'])) {
unset($post['media_ids']);
}
} catch (Exception $e) {
Logger::log('Exception when trying to send to Twitter: ' . $e->getMessage());
// Workaround: Remove the picture link so that the post can be reposted without it
// When there is another url already added, a second url would be superfluous.
if (!$url_added) {
$msg .= "\n" . $image;
}
$image = "";
}
}

View File

@ -4,4 +4,4 @@
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInitd051a3fd38373f38066f9a7f62be4c25::getLoader();
return ComposerAutoloaderInitTwitterAddon::getLoader();

View File

@ -377,7 +377,7 @@ class ClassLoader
$subPath = $class;
while (false !== $lastPos = strrpos($subPath, '\\')) {
$subPath = substr($subPath, 0, $lastPos);
$search = $subPath.'\\';
$search = $subPath . '\\';
if (isset($this->prefixDirsPsr4[$search])) {
$pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
foreach ($this->prefixDirsPsr4[$search] as $dir) {

View File

@ -6,4 +6,9 @@ $vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'Codebird\\Codebird' => $vendorDir . '/jublonet/codebird-php/src/codebird.php',
'Codebird\\CodebirdAuthException' => $vendorDir . '/jublonet/codebird-php/src/codebird.php',
'Codebird\\CodebirdCredentialsException' => $vendorDir . '/jublonet/codebird-php/src/codebird.php',
'Codebird\\CodebirdEndpointException' => $vendorDir . '/jublonet/codebird-php/src/codebird.php',
'Codebird\\CodebirdMediaException' => $vendorDir . '/jublonet/codebird-php/src/codebird.php',
);

View File

@ -6,5 +6,6 @@ $vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'Composer\\Installers\\' => array($vendorDir . '/composer/installers/src/Composer/Installers'),
'Abraham\\TwitterOAuth\\' => array($vendorDir . '/abraham/twitteroauth/src'),
);

View File

@ -2,7 +2,7 @@
// autoload_real.php @generated by Composer
class ComposerAutoloaderInitd051a3fd38373f38066f9a7f62be4c25
class ComposerAutoloaderInitTwitterAddon
{
private static $loader;
@ -19,15 +19,15 @@ class ComposerAutoloaderInitd051a3fd38373f38066f9a7f62be4c25
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInitd051a3fd38373f38066f9a7f62be4c25', 'loadClassLoader'), true, true);
spl_autoload_register(array('ComposerAutoloaderInitTwitterAddon', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInitd051a3fd38373f38066f9a7f62be4c25', 'loadClassLoader'));
spl_autoload_unregister(array('ComposerAutoloaderInitTwitterAddon', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) {
require_once __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInitd051a3fd38373f38066f9a7f62be4c25::getInitializer($loader));
call_user_func(\Composer\Autoload\ComposerStaticInitTwitterAddon::getInitializer($loader));
} else {
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {

View File

@ -4,9 +4,13 @@
namespace Composer\Autoload;
class ComposerStaticInitd051a3fd38373f38066f9a7f62be4c25
class ComposerStaticInitTwitterAddon
{
public static $prefixLengthsPsr4 = array (
'C' =>
array (
'Composer\\Installers\\' => 20,
),
'A' =>
array (
'Abraham\\TwitterOAuth\\' => 21,
@ -14,17 +18,30 @@ class ComposerStaticInitd051a3fd38373f38066f9a7f62be4c25
);
public static $prefixDirsPsr4 = array (
'Composer\\Installers\\' =>
array (
0 => __DIR__ . '/..' . '/composer/installers/src/Composer/Installers',
),
'Abraham\\TwitterOAuth\\' =>
array (
0 => __DIR__ . '/..' . '/abraham/twitteroauth/src',
),
);
public static $classMap = array (
'Codebird\\Codebird' => __DIR__ . '/..' . '/jublonet/codebird-php/src/codebird.php',
'Codebird\\CodebirdAuthException' => __DIR__ . '/..' . '/jublonet/codebird-php/src/codebird.php',
'Codebird\\CodebirdCredentialsException' => __DIR__ . '/..' . '/jublonet/codebird-php/src/codebird.php',
'Codebird\\CodebirdEndpointException' => __DIR__ . '/..' . '/jublonet/codebird-php/src/codebird.php',
'Codebird\\CodebirdMediaException' => __DIR__ . '/..' . '/jublonet/codebird-php/src/codebird.php',
);
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInitd051a3fd38373f38066f9a7f62be4c25::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInitd051a3fd38373f38066f9a7f62be4c25::$prefixDirsPsr4;
$loader->prefixLengthsPsr4 = ComposerStaticInitTwitterAddon::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInitTwitterAddon::$prefixDirsPsr4;
$loader->classMap = ComposerStaticInitTwitterAddon::$classMap;
}, null, ClassLoader::class);
}

View File

@ -54,5 +54,188 @@
"social",
"twitter"
]
},
{
"name": "composer/installers",
"version": "v1.6.0",
"version_normalized": "1.6.0.0",
"source": {
"type": "git",
"url": "https://github.com/composer/installers.git",
"reference": "cfcca6b1b60bc4974324efb5783c13dca6932b5b"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/composer/installers/zipball/cfcca6b1b60bc4974324efb5783c13dca6932b5b",
"reference": "cfcca6b1b60bc4974324efb5783c13dca6932b5b",
"shasum": ""
},
"require": {
"composer-plugin-api": "^1.0"
},
"replace": {
"roundcube/plugin-installer": "*",
"shama/baton": "*"
},
"require-dev": {
"composer/composer": "1.0.*@dev",
"phpunit/phpunit": "^4.8.36"
},
"time": "2018-08-27T06:10:37+00:00",
"type": "composer-plugin",
"extra": {
"class": "Composer\\Installers\\Plugin",
"branch-alias": {
"dev-master": "1.0-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"Composer\\Installers\\": "src/Composer/Installers"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Kyle Robinson Young",
"email": "kyle@dontkry.com",
"homepage": "https://github.com/shama"
}
],
"description": "A multi-framework Composer library installer",
"homepage": "https://composer.github.io/installers/",
"keywords": [
"Craft",
"Dolibarr",
"Eliasis",
"Hurad",
"ImageCMS",
"Kanboard",
"Lan Management System",
"MODX Evo",
"Mautic",
"Maya",
"OXID",
"Plentymarkets",
"Porto",
"RadPHP",
"SMF",
"Thelia",
"WolfCMS",
"agl",
"aimeos",
"annotatecms",
"attogram",
"bitrix",
"cakephp",
"chef",
"cockpit",
"codeigniter",
"concrete5",
"croogo",
"dokuwiki",
"drupal",
"eZ Platform",
"elgg",
"expressionengine",
"fuelphp",
"grav",
"installer",
"itop",
"joomla",
"kohana",
"laravel",
"lavalite",
"lithium",
"magento",
"majima",
"mako",
"mediawiki",
"modulework",
"modx",
"moodle",
"osclass",
"phpbb",
"piwik",
"ppi",
"puppet",
"pxcms",
"reindex",
"roundcube",
"shopware",
"silverstripe",
"sydes",
"symfony",
"typo3",
"wordpress",
"yawik",
"zend",
"zikula"
]
},
{
"name": "jublonet/codebird-php",
"version": "dev-master",
"version_normalized": "9999999-dev",
"source": {
"type": "git",
"url": "https://github.com/jublonet/codebird-php.git",
"reference": "df362d8ad629aad6c4c7dbf36a440e569ec41368"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/jublonet/codebird-php/zipball/df362d8ad629aad6c4c7dbf36a440e569ec41368",
"reference": "df362d8ad629aad6c4c7dbf36a440e569ec41368",
"shasum": ""
},
"require": {
"composer/installers": "~1.0",
"ext-hash": "*",
"ext-json": "*",
"lib-openssl": "*",
"php": ">=5.5.0"
},
"require-dev": {
"php-coveralls/php-coveralls": ">=0.6",
"phpunit/phpunit": ">=7.3",
"squizlabs/php_codesniffer": "2.*"
},
"time": "2018-08-16T00:07:08+00:00",
"type": "library",
"installation-source": "source",
"autoload": {
"classmap": [
"src/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"GPL-3.0+"
],
"authors": [
{
"name": "Joshua Atkins",
"role": "Developer",
"email": "joshua.atkins@jublo.net",
"homepage": "http://atkins.im/"
},
{
"name": "J.M.",
"role": "Developer",
"email": "jm@jublo.net",
"homepage": "http://mynetx.net/"
}
],
"description": "Easy access to the Twitter REST API, Direct Messages API, Account Activity API, TON (Object Nest) API and Twitter Ads API — all from one PHP library.",
"homepage": "https://www.jublo.net/projects/codebird/php",
"keywords": [
"api",
"networking",
"twitter"
]
}
]

View File

@ -0,0 +1,2 @@
# Auto detect text files and perform LF normalization
* text=auto

View File

@ -0,0 +1,7 @@
build
composer.lock
RELEASE_MESSAGE*
test*.php
vendor
*.jpg
*.mp4

View File

@ -0,0 +1,47 @@
# The Travis setup:
# - run testsuite for every PHP version
# - run lint for every PHP version
language: php
sudo: false
php:
- "7.2"
- "7.1"
- hhvm
- nightly
sudo: false
before_script:
- export PATH=~/.composer/vendor/bin/:$PATH
- composer install --no-interaction
- pip install --user codecov
script:
- ant clean
- set -e;
if [ $TRAVIS_PHP_VERSION == "hhvm" ] ; then
ant phpunit-hhvm ;
else
ant phpunit ;
fi
after_script:
- if [ -f vendor/bin/coveralls ] ; then php vendor/bin/coveralls -v || true ; fi
- codecov
- if [ -f php.log ] ; then cat php.log ; fi
matrix:
allow_failures:
- php: hhvm
- php: nightly
fast_finish: true
cache:
directories:
- $HOME/.composer/cache/
- $HOME/runkit
# trigger Buildtime Trend Service to parse Travis CI log
notifications:
webhooks:
- https://buildtimetrend.herokuapp.com/travis

View File

@ -0,0 +1,185 @@
codebird-php - changelog
========================
4.0.0 (not yet released)
+ #161 Update oembed API method endpoint
+ Update to Twitter Ads API Version 1
+ Add Ads API POST tailored_audience_memberships method
+ Add Ads Sandbox API POST accounts method
+ Add Ads Sandbox API POST accounts/:account_id/features method
+ Add Ads Sandbox API POST accounts/:account_id/funding_instruments method
+ Update more Ads API methods
- Fix Ads API batch methods to send JSON body
+ Update Ads API Analytics methods (stats)
+ #177 Add async media/upload calls status by GET
+ Add POST media/metadata/create method
- Fix TON API upload - add additional header parsing
+ Add custom Codebird Exception classes
+ Add Account Activity API methods
+ Add new Direct Messages API
+ Update cacert.pem file
- Remove sunsetting Direct Messages API
- Remove sunsetting Streaming API
- Remove contributor API methods
- Remove deprecated statuses/update_with_media method
- Remove deprecated statuses/update_profile_background_image method
3.1.0 (2016-02-15)
+ #143 Add support for proxy types
+ #152 Throw Exception on failed remote media download
+ Add REST API POST statuses/unretweet/:id
+ Add Ads API GET insights/keywords/search
+ #151 Avoid JSON_BIGINT_AS_STRING errors
- Fix typo in changelog
3.0.0 (2016-01-01)
+ Add unit testing suite
+ #32 Support Twitter Streaming API
+ #144 Support Twitter Collections API
+ #145 Support Twitter TON (Object Nest) API
+ #120 Support Twitter Ads API
+ #117 Drop cURL workarounds added for PHP 5.3
+ Update cacert.pem
+ #121 Allow for multiple parameters in templated methods
by replacing preg_match with preg_match_all
+ #134 Add support for compressed remote images
+ #129 Allow to change remote media download timeout
+ Support WebP media format
+ Fixes for non-multipart media uploads, see #141
+ Return rate-limiting info as object, when return format = object
- #107 Decoding issue for big ints on 32-bit servers
- #147 Undefined index when checking for possible media files
2.7.2 (2015-09-23)
- #135 Invalid HTTP request headers in non-cURL mode
2.7.1 (2015-08-16)
+ #124 Download redirected remote images
2.7.0 (2015-05-14)
- #92, #108 Fix issues with uploading special chars
+ #109 Proxy support
- Drop support for internal and old API methods
+ #111 Set user agent for remote calls
+ #106 Add logout method
+ #86 Return exception for failed cURL requests
2.6.1 (2014-12-13)
- #90 Allow uploading media with special chars
2.6.0 (2014-10-12)
+ #67 Don't require cURL, allow stream connections too
+ Use default timeout
+ #69 Add composer/installers to allow install path changes
- Regression: Codebird::getApiMethods removed accidentally in 2.5.0
+ #66 Allow remote media uploads
- #81 CURLOPT_TIMEOUT_MS and CURLOPT_CONNECTTIMEOUT_MS errors on PHP 5.3
- #83 Use POST for users/lookup and statuses/lookup, params may get too long for GET
+ Update README to reflect new process for uploading single/multiple media, see #78
2.5.0 (2014-06-20)
+ Add section about cacert.pem to README
+ Option to set cURL timeout
+ #42 Allow to get the supported API methods as array
+ #48 Update composer file to jublonet path
+ Update cacert.pem root certificates file
+ #58 support for GET statuses/retweeters/ids
+ #53 Better Proxy HTTP status detection
- #62 Places & Geo API call issue
+ #33 Support internal API methods
+ #59 Support all known API methods
+ Reset bearer token when requesting a new token
+ #61 Return rate limit details with each API call
+ #60 Support uploading multiple media
- #63 Return rate-limiting info only if contained in response
- #57 Don't require consumer key if bearer token is already known
2.4.1 (2013-06-23)
+ #26 Stringify null and boolean parameters
+ Validate Twitter SSL certificate for oauth2/token method
2.4.0 (2013-06-15)
+ Add contributing guidelines
+ rfe #21 JSON return format
+ Support HTTP proxy replies
+ Validate Twitter SSL certificate
+ #23 Readme: Fix authentication sample
2.3.6 (2013-05-12)
+ Add backslash to stdClass construction, due to namespace
2.3.5 (2013-04-30)
+ Fix fatal error: Class 'Codebird\Exception' not found
2.3.4 (2013-04-28)
+ Fix namespace not properly cased
2.3.3 (2013-04-26)
+ Detect API error responses as XML, see #1
+ OAuth: add support for force_login, screen_name parameters, see #14
+ Add namespace
2.3.2 (2013-04-09)
+ Use protected keyword for methods that may be overriden in extended classes
2.3.1 (2013-03-23)
- Re-remove statuses/sample. It's streaming API, which Codebird doesn't currently support
+ Don't send multipart POST to non-multipart methods, fix issue #8
+ Remove auto-added backslashes from parsed API method parameters if magic quotes are on, fix #7
2.3.0 (2013-03-19)
+ Update README with info about how to get details of the current user
+ Clarify that the consumer secret and access token secret are not the same
+ Readme: Clarify authentication tokens
+ Add README section about rate-limiting
+ Add README section about cursored results
+ Add OAuth2 application-only auth
- Drop support for statuses/public_timeline
- Drop support for v1 API
+ add statuses/sample, friendships/no_retweets/ids methods
+ Add Changelog
2.2.3 (2012-12-03)
+ Fix wrong assignment operator in _detectMethod for multi HTTP method endpoints
+ Add documentation about $params in _detectMethod
+ Add new methods now available in 1.1
+ Add friends/list, followers/list API methods
2.2.2 (2012-10-17)
+ Add profile banner methods
+ Drop separate media upload method as noted at https://dev.twitter.com/docs/api/1.1/post/statuses/update_with_media
+ Fix wrong Exception
+ add support for old endpoints
+ Update endpoints to 1.1 endpoints
2.2.1 (2012-09-17)
+ Update to Twitter API 1.1
2.2.0 (2012-07-08)
+ Add support for users/profile_image/:screen_name
- drop support for string return format
2.1 (2012-07-07)
+ Add documentation in readme
+ make OAuth consumer key and secret static
+ Highlight the 'uploading files to Twitter' docs
+ Return HTTP status with array return_format
2.0 (2012-07-06)
+ Complete rewrite. Now supports media uploads.
+ Support API methods with templated variables (like statuses/show/:id)
+ Add documentation
1.2 (2012-07-04)
+ Apply PEAR coding standards
+ Use self instead of class name
1.1 (2011-07-08)
+ Fixed: Removed ; sign.
+ Added: Detect parameter-less messages (such as, error messages).
+ Changed: Oauth_Authorize should return the URL instead of redirecting there.
+ Added: Ability to provide parameters to oauth/request_token.
+ Changed: Use api.twitter.com as OAuth hostname.
+ Added: Allow oauth/access_token to have parameters.
+ Changed: Don't rely on intval() for the large tweet id's that Snowflake is generating nowadays.
+ Fixed: Decode empty JSON arrays [] properly.

View File

@ -0,0 +1,11 @@
### Which branch?
- Bugs are fixed in the master branch, please base your bugfix pull requests on this branch.
- New features are added to the develop branch, please base your feature-add pull requests on that branch.
### Code style
- Please use 2 soft spaces per indent level.
- Take a look at the coding style used in codebird.php and apply the same convention to your contributed code.
The styleguide is also available online at https://pear.php.net/manual/en/standards.php.
### License
- Code contributed by you will get the same license as Codebird itself, that is, GPU General Public License V3.

View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@ -0,0 +1,891 @@
codebird-php
============
*Easy access to the Twitter REST API, Direct Messages API, Account Activity API, TON (Object Nest) API and Twitter Ads API — all from one PHP library.*
Copyright (C) 2010-2018 Jublo Limited <support@jublo.net>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/3cd81a521d334648b9958327621a3070)](https://www.codacy.com/app/jublonet/codebird-php?utm_source=github.com&utm_medium=referral&utm_content=jublonet/codebird-php&utm_campaign=badger)
[![Coverage Status](https://img.shields.io/coveralls/jublonet/codebird-php/develop.svg)](https://coveralls.io/github/jublonet/codebird-php?branch=develop)
[![Travis Status](https://img.shields.io/travis/jublonet/codebird-php/develop.svg)](https://travis-ci.org/jublonet/codebird-php/branches)
### Requirements
- PHP 7.1.0 or higher
- OpenSSL extension
Summary
-------
Use Codebird to connect to the Twitter **REST API, Streaming API, Collections API, TON (Object Nest) API**
and **Twitter Ads API** from your PHP code — all using just one library.
Codebird supports full 3-way OAuth as well as application-only auth.
Authentication
--------------
To authenticate your API requests on behalf of a certain Twitter user
(following OAuth 1.0a), take a look at these steps:
```php
require_once ('codebird.php');
\Codebird\Codebird::setConsumerKey('YOURKEY', 'YOURSECRET'); // static, see README
$cb = \Codebird\Codebird::getInstance();
```
You may either set the OAuth token and secret, if you already have them:
```php
$cb->setToken('YOURTOKEN', 'YOURTOKENSECRET');
```
Or you authenticate, like this:
```php
session_start();
if (! isset($_SESSION['oauth_token'])) {
// get the request token
$reply = $cb->oauth_requestToken([
'oauth_callback' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
]);
// store the token
$cb->setToken($reply->oauth_token, $reply->oauth_token_secret);
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
$_SESSION['oauth_verify'] = true;
// redirect to auth website
$auth_url = $cb->oauth_authorize();
header('Location: ' . $auth_url);
die();
} elseif (isset($_GET['oauth_verifier']) && isset($_SESSION['oauth_verify'])) {
// verify the token
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
unset($_SESSION['oauth_verify']);
// get the access token
$reply = $cb->oauth_accessToken([
'oauth_verifier' => $_GET['oauth_verifier']
]);
// store the token (which is different from the request token!)
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
// send to same URL, without oauth GET parameters
header('Location: ' . basename(__FILE__));
die();
}
// assign access token on each page load
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
```
### Logging out
In case you want to log out the current user (to log in a different user without
creating a new Codebird object), just call the `logout()` method.
```
$cb->logout();
```
### Application-only auth
Some API methods also support authenticating on a per-application level.
This is useful for getting data that are not directly related to a specific
Twitter user, but generic to the Twitter ecosystem (such as ```search/tweets```).
To obtain an app-only bearer token, call the appropriate API:
```php
$reply = $cb->oauth2_token();
$bearer_token = $reply->access_token;
```
I strongly recommend that you store the obtained bearer token in your database.
There is no need to re-obtain the token with each page load, as it becomes invalid
only when you call the ```oauth2/invalidate_token``` method.
If you already have your token, tell Codebird to use it:
```php
\Codebird\Codebird::setBearerToken('YOURBEARERTOKEN');
```
In this case, you don't need to set the consumer key and secret.
For sending an API request with app-only auth, see the Usage examples section.
### A word on your callback URL
Twitter is very restrictive about which URLs may be used for your callback URL.
For example, even the presence of the www subdomain must match with the domain
that you specified in the settings of your app at https://developer.twitter.com/en/apps.
Mapping API methods to Codebird function calls
----------------------------------------------
As you can see from the last example, there is a general way how Twitters API methods
map to Codebird function calls. The general rules are:
1. For each slash in a Twitter API method, use an underscore in the Codebird function.
Example: ```statuses/update``` maps to ```Codebird::statuses_update()```.
2. For each underscore in a Twitter API method, use camelCase in the Codebird function.
Example: ```statuses/home_timeline``` maps to ```Codebird::statuses_homeTimeline()```.
3. For each parameter template in method, use UPPERCASE in the Codebird function.
Also dont forget to include the parameter in your parameter list.
Examples:
- ```statuses/show/:id``` maps to ```Codebird::statuses_show_ID('id=12345')```.
- ```users/profile_image/:screen_name``` maps to
`Codebird::users_profileImage_SCREEN_NAME('screen_name=jublonet')`.
Usage examples
--------------
When you have an access token, calling the API is simple:
```php
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']); // see above
$reply = (array) $cb->statuses_homeTimeline();
print_r($reply);
```
Tweeting is as easy as this:
```php
$reply = $cb->statuses_update('status=Whohoo, I just Tweeted!');
```
:warning: *Make sure to urlencode any parameter values that contain
query-reserved characters, like Tweeting the `&` sign:*
```php
$reply = $cb->statuses_update('status=' . urlencode('Fish & chips'));
// will result in this:
$reply = $cb->statuses_update('status=Fish+%26+chips');
```
In most cases, giving all parameters in an array is easier,
because no encoding is needed:
```php
$params = [
'status' => 'Fish & chips'
];
$reply = $cb->statuses_update($params);
```
```php
$params = [
'status' => 'I love London',
'lat' => 51.5033,
'long' => 0.1197
];
$reply = $cb->statuses_update($params);
```
```php
$params = [
'screen_name' => 'jublonet'
];
$reply = $cb->users_show($params);
```
This is the [resulting Tweet](https://twitter.com/LarryMcTweet/status/482239971399835648)
sent with the code above.
### Requests with app-only auth
To send API requests without an access token for a user (app-only auth),
add a second parameter to your method call, like this:
```php
$reply = $cb->search_tweets('q=Twitter', true);
```
Bear in mind that not all API methods support application-only auth.
HTTP methods (GET, POST, DELETE etc.)
-------------------------------------
Never care about which HTTP method (verb) to use when calling a Twitter API.
Codebird is intelligent enough to find out on its own.
Response codes
--------------
The HTTP response code that the API gave is included in any return values.
You can find it within the return objects ```httpstatus``` property.
### Dealing with rate-limits
Basically, Codebird leaves it up to you to handle Twitters rate limit.
The library returns the response HTTP status code, so you can detect rate limits.
I suggest you to check if the ```$reply->httpstatus``` property is ```400```
and check with the Twitter API to find out if you are currently being
rate-limited.
See the [Rate Limiting FAQ](https://developer.twitter.com/en/docs/basics/rate-limiting)
for more information.
Unless your return format is JSON, you will receive rate-limiting details
in the returned datas ```$reply->rate``` property,
if the Twitter API responds with rate-limiting HTTP headers.
Return formats
--------------
The default return format for API calls is a PHP object.
For API methods returning multiple data (like ```statuses/home_timeline```),
you should cast the reply to array, like this:
```php
$reply = $cb->statuses_homeTimeline();
$data = (array) $reply;
```
Upon your choice, you may also get PHP arrays directly:
```php
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_ARRAY);
```
The Twitter API natively responds to API calls in JSON (JS Object Notation).
To get a JSON string, set the corresponding return format:
```php
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_JSON);
```
Uploading images and videos
---------------------------
Twitter will accept the following media types, all of which are supported by Codebird:
- PNG
- JPEG
- BMP
- WebP
- GIF
- Animated GIF
- Video
Tweet media can be uploaded in a 2-step process:
**First** you send each media to Twitter. For **images**, it works like this:
```php
// these files to upload. You can also just upload 1 image!
$media_files = [
'bird1.jpg', 'bird2.jpg', 'bird3.jpg'
];
// will hold the uploaded IDs
$media_ids = [];
foreach ($media_files as $file) {
// upload all media files
$reply = $cb->media_upload([
'media' => $file
]);
// and collect their IDs
$media_ids[] = $reply->media_id_string;
}
```
Uploading **videos** requires you to send the data in chunks. See the next section on this.
**Second,** you attach the collected media ids for all images to your call
to ```statuses/update```, like this:
```php
// convert media ids to string list
$media_ids = implode(',', $media_ids);
// send Tweet with these medias
$reply = $cb->statuses_update([
'status' => 'These are some of my relatives.',
'media_ids' => $media_ids
]);
print_r($reply);
```
Here is a [sample Tweet](https://twitter.com/LarryMcTweet/status/475276535386365952)
sent with the code above.
More [documentation for uploading media](https://developer.twitter.com/en/docs/media/upload-media/overview) is available on the Twitter Developer site.
### Remote files
Remote files received from `http` and `https` servers are supported, too:
```php
$reply = $cb->media_upload(array(
'media' => 'http://www.bing.com/az/hprichbg/rb/BilbaoGuggenheim_EN-US11232447099_1366x768.jpg'
));
```
:warning: *URLs containing Unicode characters should be normalised. A sample normalisation function can be found at http://stackoverflow.com/a/6059053/1816603*
To circumvent download issues when remote servers are slow to respond,
you may customise the remote download timeout, like this:
```php
$cb->setRemoteDownloadTimeout(10000); // milliseconds
```
### Video files
Uploading videos to Twitter (≤ 15MB, MP4) requires you to send them in chunks.
You need to perform at least 3 calls to obtain your `media_id` for the video:
1. Send an `INIT` event to get a `media_id` draft.
2. Upload your chunks with `APPEND` events, each one up to 5MB in size.
3. Send a `FINALIZE` event to convert the draft to a ready-to-Tweet `media_id`.
4. Post your Tweet with video attached.
Heres a sample for video uploads:
```php
$file = 'demo-video.mp4';
$size_bytes = filesize($file);
$fp = fopen($file, 'r');
// INIT the upload
$reply = $cb->media_upload([
'command' => 'INIT',
'media_type' => 'video/mp4',
'total_bytes' => $size_bytes
]);
$media_id = $reply->media_id_string;
// APPEND data to the upload
$segment_id = 0;
while (! feof($fp)) {
$chunk = fread($fp, 1048576); // 1MB per chunk for this sample
$reply = $cb->media_upload([
'command' => 'APPEND',
'media_id' => $media_id,
'segment_index' => $segment_id,
'media' => $chunk
]);
$segment_id++;
}
fclose($fp);
// FINALIZE the upload
$reply = $cb->media_upload([
'command' => 'FINALIZE',
'media_id' => $media_id
]);
var_dump($reply);
if ($reply->httpstatus < 200 || $reply->httpstatus > 299) {
die();
}
// if you have a field `processing_info` in the reply,
// use the STATUS command to check if the video has finished processing.
// Now use the media_id in a Tweet
$reply = $cb->statuses_update([
'status' => 'Twitter now accepts video uploads.',
'media_ids' => $media_id
]);
```
**Find more information about [accepted media formats](https://developer.twitter.com/en/docs/media/upload-media/uploading-media/media-best-practices) in the Twitter Developer docs.**
:warning: When uploading a video in multiple chunks, you may run into an error `The validation of media ids failed.` even though the `media_id` is correct. This is known. Please check back in the [Twitter community forums](https://twittercommunity.com/tags/video).
Twitter Streaming API
---------------------
The Streaming APIs give developers low latency access to Twitters global stream of
Tweet data. A proper implementation of a streaming client will be pushed messages
indicating Tweets and other events have occurred, without any of the overhead
associated with polling a REST endpoint.
To consume one of the available Twitter streams, follow these **two steps:**
1. Set up a callback function that gets called for every new streaming message that arrives.
Codebird also calls this function once per second, to allow you to work on any due tasks, and to give you the chance to cancel the stream even if no new messages appear.
2. After creating the callback, tell Codebird about it using a [callable](http://php.net/manual/en/language.types.callable.php). Then start consuming the stream.
```php
// First, create a callback function:
function some_callback($message)
{
// gets called for every new streamed message
// gets called with $message = NULL once per second
if ($message !== null) {
print_r($message);
flush();
}
// return false to continue streaming
// return true to close the stream
// close streaming after 1 minute for this simple sample
// don't rely on globals in your code!
if (time() - $GLOBALS['time_start'] >= 60) {
return true;
}
return false;
}
// set the streaming callback in Codebird
$cb->setStreamingCallback('some_callback');
// any callable is accepted:
// $cb->setStreamingCallback(['MyClass', 'some_callback']);
// for canceling, see callback function body
// not considered good practice in real world!
$GLOBALS['time_start'] = time();
// Second, start consuming the stream:
$reply = $cb->statuses_filter();
// See the *Mapping API methods to Codebird function calls* section for method names.
// $reply = $cb->statuses_filter('track=Windows');
```
You should be able to set a timeout for the streaming API using `setTimeout`.
In addition, your callback will receive empty messages if no events occur,
and you should make your function `return true;` in order to cancel the stream.
Find more information on the [Streaming API](https://developer.twitter.com/en/docs/tweets/filter-realtime/overview)
in the developer documentation website.
Twitter Collections, Direct Messages and Account Activity APIs
--------------------------------------------------------------
Collections are a type of timeline that you control and can be hand curated
and/or programmed using an API.
Pay close attention to the differences in how collections are presented —
often they will be decomposed, efficient objects with information about users,
Tweets, and timelines grouped, simplified, and stripped of unnecessary repetition.
Never care about the OAuth signing specialities and the JSON POST body
for POST and PUT calls to these special APIs. Codebird takes off the work for you
and will always send the correct Content-Type automatically.
Find out more about the [Collections API](https://developer.twitter.com/en/docs/tweets/curate-a-collection/overview/about_collections) in the Twitter API docs.
More information on the [Direct Messages API](https://developer.twitter.com/en/docs/direct-messages/api-features) and the [Account Activity API](https://developer.twitter.com/en/docs/accounts-and-users/subscribe-account-activity/overview) is available there as well.
Heres a sample for adding a Tweet using the Collections API:
```php
$reply = $cb->collections_entries_curate([
'id' => 'custom-672852634622144512',
'changes' => [
['op' => 'add', 'tweet_id' => '672727928262828032']
]
]);
var_dump($reply);
```
TON (Twitter Object Nest) API
-----------------------------
The [TON (Twitter Object Nest) API](https://developer.twitter.com/en/docs/ads/audiences/overview/ton-upload.html) allows implementers to upload media and various assets to Twitter.
The TON API supports non-resumable and resumable upload methods based on the size of the file.
For files less than 64MB, non-resumable may be used. For files greater than or equal to 64MB,
resumable must be used. Resumable uploads require chunk sizes of less than 64MB.
For accessing the TON API, please adapt the following code samples for uploading:
### Single-chunk upload
```php
// single-chunk upload
$reply = $cb->ton_bucket_BUCKET([
'bucket' => 'ta_partner',
'Content-Type' => 'image/jpeg',
'media' => $file
]);
var_dump($reply);
// use the Location header now...
echo $reply->Location;
```
As you see from that sample, Codebird rewrites the special TON API headers into the reply,
so you can easily access them. This also applies to the `X-TON-Min-Chunk-Size` and
`X-Ton-Max-Chunk-Size` for chunked uploads:
### Multi-chunk upload
```php
// multi-chunk upload
$file = 'demo-video.mp4';
$size_bytes = filesize($file);
$fp = fopen($file, 'r');
// INIT the upload
$reply = $cb->__call(
'ton/bucket/BUCKET?resumable=true',
[[ // note the double square braces when using __call
'bucket' => 'ta_partner',
'Content-Type' => 'video/mp4',
'X-Ton-Content-Type' => 'video/mp4',
'X-Ton-Content-Length' => $size_bytes
]]
);
$target = $reply->Location;
// something like: '/1.1/ton/bucket/ta_partner/SzFxGfAg_Zj.mp4?resumable=true&resumeId=28401873'
$match = [];
// match the location parts
preg_match('/ton\/bucket\/.+\/(.+)\?resumable=true&resumeId=(\d+)/', $target, $match);
list ($target, $file, $resumeId) = $match;
// APPEND data to the upload
$segment_id = 0;
while (! feof($fp)) {
$chunk = fread($fp, 1048576); // 1MB per chunk for this sample
// special way to call Codebird for the upload chunks
$reply = $cb->__call(
'ton/bucket/BUCKET/FILE?resumable=true&resumeId=RESUMEID',
[[ // note the double square braces when using __call
'bucket' => 'ta_partner',
'file' => $file, // you get real filename from INIT, see above
'Content-Type' => 'image/jpeg',
'Content-Range' => 'bytes '
. ($segment_id * 1048576) . '-' . strlen($chunk) . '/' . $size_bytes,
'resumeId' => $resumeId,
'media' => $chunk
]]
);
$segment_id++;
}
fclose($fp);
```
Twitter Ads API
---------------
The [Twitter Ads API](https://developer.twitter.com/en/docs/ads/general/overview) allows partners to
integrate with the Twitter advertising platform in their own advertising solutions.
Selected partners have the ability to create custom tools to manage and execute
Twitter Ad campaigns.
When accessing the Ads API or Ads Sandbox API, access it by prefixing your call
with `ads_`. Watch out for the usual replacements for in-url parameters,
particularly `:account_id`.
**Tip:** For accessing the Ads Sandbox API, use the `ads_sandbox_` prefix,
like shown further down.
Here is an example for calling the Twitter Ads API:
```php
$reply = $cb->ads_accounts_ACCOUNT_ID_cards_appDownload([
'account_id' => '123456789',
'name' => 'Test',
'app_country_code' => 'DE'
]);
```
### Multiple-method API calls
In the Twitter Ads API, there are multiple methods that can be reached by
HTTP `GET`, `POST`, `PUT` and/or `DELETE`. While Codebird does its best to guess
which HTTP verb youll want to use, its the safest bet to give a hint yourself,
like this:
```php
$reply = $cb->ads_sandbox_accounts_ACCOUNT_ID_cards_imageConversation_CARD_ID([
'httpmethod' => 'DELETE',
'account_id' => '123456789',
'card_id' => '2468013579'
]);
```
Codebird will remove the `httpmethod` parameter from the parameters list automatically,
and set the corresponding HTTP verb.
How Do I…?
----------
### …use multiple Codebird instances?
By default, Codebird works with just one instance. This programming paradigma is
called a *singleton*.
Getting the main Codebird object is done like this:
```php
$cb = \Codebird\Codebird::getInstance();
```
If you need to run requests to the Twitter API for multiple users at once,
Codebird supports this as well. Instead of getting the instance like shown above,
create a new object:
```php
$cb1 = new \Codebird\Codebird;
$cb2 = new \Codebird\Codebird;
```
Please note that your OAuth consumer key and secret is shared within
multiple Codebird instances, while the OAuth request and access tokens with their
secrets are *not* shared.
### …access a users profile image?
First retrieve the user object using
```$reply = $cb->users_show("screen_name=$username");```
with ```$username``` being the username of the account you wish to retrieve the profile image from.
Then get the value from the index ```profile_image_url``` or ```profile_image_url_https``` of the user object previously retrieved.
For example:
```$reply['profile_image_url']``` will then return the profile image url without https.
### …get user ID, screen name and more details about the current user?
When the user returns from the authentication screen, you need to trade
the obtained request token for an access token, using the OAuth verifier.
As discussed in the section Usage example, you use a call to
```oauth/access_token``` to do that.
The API reply to this method call tells you details about the user that just logged in.
These details contain the **user ID** and the **screen name.**
Take a look at the returned data as follows:
```
stdClass Object
(
[oauth_token] => 14648265-rPn8EJwfB**********************
[oauth_token_secret] => agvf3L3**************************
[user_id] => 14648265
[screen_name] => jublonet
[httpstatus] => 200
)
```
If you need to get more details, such as the users latest Tweet,
you should fetch the complete User Entity. The simplest way to get the
user entity of the currently authenticated user is to use the
```account/verify_credentials``` API method. In Codebird, it works like this:
```php
$reply = $cb->account_verifyCredentials();
print_r($reply);
```
I suggest to cache the User Entity after obtaining it, as the
```account/verify_credentials``` method is rate-limited by 15 calls per 15 minutes.
### …walk through cursored results?
The Twitter REST API utilizes a technique called cursoring to paginate
large result sets. Cursoring separates results into pages of no more than
5000 results at a time, and provides a means to move backwards and
forwards through these pages.
Here is how you can walk through cursored results with Codebird.
1. Get the first result set of a cursored method:
```php
$result1 = $cb->followers_list();
```
2. To navigate forth, take the ```next_cursor_str```:
```php
$nextCursor = $result1->next_cursor_str;
```
3. If ```$nextCursor``` is not 0, use this cursor to request the next result page:
```php
if ($nextCursor > 0) {
$result2 = $cb->followers_list('cursor=' . $nextCursor);
}
```
To navigate back instead of forth, use the field ```$resultX->previous_cursor_str```
instead of ```next_cursor_str```.
It might make sense to use the cursors in a loop. Watch out, though,
not to send more than the allowed number of requests to ```followers/list```
per rate-limit timeframe, or else you will hit your rate-limit.
### …use xAuth with Codebird?
Codebird supports xAuth just like every other authentication used at Twitter.
Remember that your application needs to be whitelisted to be able to use xAuth.
Heres an example:
```php
$reply = $cb->oauth_accessToken([
'x_auth_username' => 'username',
'x_auth_password' => '4h3_p4$$w0rd',
'x_auth_mode' => 'client_auth'
]);
```
Are you getting a strange error message? If the user is enrolled in
login verification, the server will return a HTTP 401 error with a custom body.
If you are using the ```send_error_codes``` parameter, you will receive the
following error message in the response body:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<errors>
<error code="231">User must verify login</error>
</errors>
```
Otherwise, the response body will contain a plaintext response:
```
User must verify login
```
When this error occurs, advise the user to
[generate a temporary password](https://twitter.com/settings/applications)
on twitter.com and use that to complete signing in to the application.
### …know what cacert.pem is for?
Connections to the Twitter API are done over a secured SSL connection.
Codebird-php checks if the Twitter API server has a valid SSL certificate.
Valid certificates have a correct signature-chain.
The cacert.pem file contains a list of all public certificates for root
certificate authorities. You can find more information about this file
at http://curl.haxx.se/docs/caextract.html.
### …set the timeout for requests to the Twitter API?
For connecting to Twitter, Codebird uses the cURL library, if available.
You can specify both the connection timeout and the request timeout,
in milliseconds:
```php
$cb->setConnectionTimeout(2000);
$cb->setTimeout(5000);
```
If you don't specify the timeout, codebird uses these values:
- connection time = 3000 ms = 3 s
- timeout = 10000 ms = 10 s
### …disable cURL?
Codebird automatically detects whether you have the PHP cURL extension enabled.
If not, the library will try to connect to Twitter via socket.
For this to work, the PHP setting `allow_url_fopen` must be enabled.
You may also manually disable cURL. Use the following call:
```php
$cb->setUseCurl(false);
```
### …use a proxy?
Codebird allows proxy support for both cURL handles and sockets.
To activate proxy mode, use the following call:
```php
$cb->setProxy('<host>', '<port>');
```
You may also use an authenticated proxy. Use the following call:
```php
$cb->setProxy('<host>', '<port>');
$cb->setProxyAuthentication('<username>:<password>');
```
By default, a HTTP proxy is assumed. To use a different proxy type,
use the corresponding [`CURLPROXY_*` constants](http://php.net/curl_setopt), like this:
```php
$cb->setProxy('<host>', '<port>', CURLPROXY_SOCKS5);
```
### …quote a Tweet?
Quoting a Tweet is different from a Retweet because you may add your own text.
The original Tweet will appear below your quote.
To quote a Tweet, add a link to the original Tweet to your quote, like in this sample:
```php
$original_tweet = [
'id_str' => '684483801687392256',
'user' => [
'screen_name' => 'LarryMcTweet'
]
];
$original_tweet = (object) $original_tweet; // sample, get real Tweet from API
$id = $original_tweet->id_str; // use the `id_str` field because of long numbers
$screen_name = $original_tweet->user->screen_name;
// looks like this: https://twitter.com/LarryMcTweet/status/684483801687392256
$url = "https://twitter.com/$screen_name/status/$id";
$text = 'Id like to quote a Tweet.'; // maximum length = 140 minus 24 (link length) minus 1 space
$reply = $cb->statuses_update([
'status' => "$text $url"
]);
```

View File

@ -0,0 +1,25 @@
{
"name": "codebird-php",
"version": "3.1.0",
"homepage": "https://www.jublo.net/projects/codebird/php",
"authors": [
"Joshua Atkins <joshua.atkins@jublo.net>",
"J.M. <jm@jublo.net>"
],
"description": "Easy access to the Twitter REST, Direct Messages, Account Activity, TON (Object Nest) and Twitter Ads API — all from one PHP library.",
"main": "src/codebird.php",
"moduleType": [],
"keywords": [
"Twitter",
"API",
"networking"
],
"license": "GPL-3.0+",
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests"
]
}

View File

@ -0,0 +1,115 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="codebird-php" default="build" basedir=".">
<property name="source" value="src"/>
<property name="source_comma_sep" value="."/>
<property environment="env"/>
<property name="env.PHPUNIT_XML" value="phpunit.xml"/>
<property name="env.PHPUNIT_XML_HHVM" value="phpunit.xml.hhvm"/>
<property name="env.PHPUNIT_ARGS" value=""/>
<target name="clean" description="Clean up and create artifact directories">
<delete dir="${basedir}/build/api"/>
<delete dir="${basedir}/build/code-browser"/>
<delete dir="${basedir}/build/coverage"/>
<delete dir="${basedir}/build/logs"/>
<delete dir="${basedir}/build/pdepend"/>
<mkdir dir="${basedir}/build/api"/>
<mkdir dir="${basedir}/build/code-browser"/>
<mkdir dir="${basedir}/build/coverage"/>
<mkdir dir="${basedir}/build/logs"/>
<mkdir dir="${basedir}/build/pdepend"/>
</target>
<target name="phpunit" description="Run unit tests using PHPUnit and generates junit.xml and clover.xml">
<exec executable="${basedir}/vendor/bin/phpunit" failonerror="true">
<arg line="--configuration ${env.PHPUNIT_XML} ${env.PHPUNIT_ARGS}"/>
</exec>
</target>
<target name="phpunit-hhvm" description="Run unit tests using PHPUnit with HHVM specific config">
<exec executable="${basedir}/vendor/bin/phpunit" failonerror="true">
<arg line="--configuration ${env.PHPUNIT_XML_HHVM} ${env.PHPUNIT_ARGS}"/>
</exec>
</target>
<target name="pdepend" description="Generate jdepend.xml and software metrics charts using PHP_Depend">
<exec executable="pdepend">
<arg line="'--jdepend-xml=${basedir}/build/logs/jdepend.xml'
'--jdepend-chart=${basedir}/build/pdepend/dependencies.svg'
'--overview-pyramid=${basedir}/build/pdepend/overview-pyramid.svg'
${source_comma_sep}" />
</exec>
</target>
<target name="phpmd" description="Generate pmd.xml using PHPMD">
<exec executable="phpmd">
<arg line="${source_comma_sep}
xml
codesize,design,naming,unusedcode
--exclude test,build,vendor
--reportfile '${basedir}/build/logs/pmd.xml'" />
</exec>
</target>
<target name="phpcpd" description="Generate pmd-cpd.xml using PHPCPD">
<exec executable="phpcpd">
<arg line="--log-pmd '${basedir}/build/logs/pmd-cpd.xml'
--exclude test
--exclude build
--exclude vendor
${source}" />
</exec>
</target>
<target name="phploc" description="Generate phploc.csv">
<exec executable="phploc">
<arg line="--log-csv '${basedir}/build/logs/phploc.csv'
--exclude test
--exclude build
--exclude vendor
${source}" />
</exec>
</target>
<target name="phpcs" description="Generate checkstyle.xml using PHP_CodeSniffer excluding third party libraries">
<exec executable="phpcs">
<arg line="
--ignore=*/vendor/*,*/build/*
--report=checkstyle
--extensions=php
--report-file='${basedir}/build/logs/checkstyle.xml'
--standard=PEAR
${source}" />
</exec>
</target>
<target name="phpdoc" description="Generate API documentation using PHPDocumentor">
<exec executable="phpdoc">
<arg line="-d ${source} -t '${basedir}/build/api'" />
</exec>
</target>
<target name="phpcb" description="Aggregate tool output with PHP_CodeBrowser">
<exec executable="phpcb">
<arg line="--log '${basedir}/build/logs'
--source '${source}'
--output '${basedir}/build/code-browser'" />
</exec>
</target>
<target name="lint" description="Perform syntax check of sourcecode files">
<apply executable="php" failonerror="true" output="${basedir}/build/logs/lint.log" logError="true">
<arg value="-l" />
<fileset dir="${basedir}">
<include name="src/**/*.php" />
<include name="test/**/*.php" />
<modified />
</fileset>
</apply>
</target>
<target name="build" depends="clean,phpunit,pdepend,phpmd,phpcpd,phpcs,phpdoc,phploc,phpcb,lint"/>
</project>

View File

@ -0,0 +1,45 @@
{
"name": "jublonet/codebird-php",
"description" : "Easy access to the Twitter REST API, Direct Messages API, Account Activity API, TON (Object Nest) API and Twitter Ads API — all from one PHP library.",
"keywords": [
"Twitter",
"API",
"networking"
],
"homepage": "https://www.jublo.net/projects/codebird/php",
"license": "GPL-3.0+",
"authors": [
{
"name": "Joshua Atkins",
"email": "joshua.atkins@jublo.net",
"homepage": "http://atkins.im/",
"role": "Developer"
},
{
"name": "J.M.",
"email": "jm@jublo.net",
"homepage": "http://mynetx.net/",
"role": "Developer"
}
],
"support": {
"email": "support@jublo.net",
"issues": "https://github.com/jublonet/codebird-php/issues",
"source": "https://github.com/jublonet/codebird-php/releases"
},
"require": {
"php": ">=5.5.0",
"ext-hash": "*",
"ext-json": "*",
"lib-openssl": "*",
"composer/installers": "~1.0"
},
"autoload": {
"classmap": ["src/"]
},
"require-dev": {
"php-coveralls/php-coveralls": ">=0.6",
"phpunit/phpunit": ">=7.3",
"squizlabs/php_codesniffer": "2.*"
}
}

View File

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="true"
backupStaticAttributes="false"
colors="true"
verbose="true">
<testsuites>
<testsuite name="Environment">
<file>test/environment_test.php</file>
</testsuite>
<testsuite name="Unit">
<directory suffix="_tests.php">test</directory>
</testsuite>
</testsuites>
<logging>
<log type="coverage-clover" target="build/logs/clover.xml"/>
<log type="junit" target="build/logs/junit.xml" logIncompleteSkipped="false"/>
</logging>
<filter>
<whitelist addUncoveredFilesFromWhitelist="true">
<directory suffix=".php">src</directory>
</whitelist>
</filter>
</phpunit>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="true"
backupStaticAttributes="false"
strict="true"
timeoutForSmallTests="10"
timeoutForMediumTests="30"
colors="true"
verbose="true">
<testsuites>
<testsuite name="Environment">
<file>test/environment_test.php</file>
</testsuite>
<testsuite name="Unit">
<directory suffix="_tests.php">test</directory>
</testsuite>
</testsuites>
<logging>
<log type="junit" target="build/logs/junit.xml" logIncompleteSkipped="false"/>
</logging>
</phpunit>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,16 @@
The following methods are not covered by unit tests yet:
_getMultipartRequestFromParams
_checkForFiles
_buildMultipart
_buildBinaryBody
_callApi
_callApiCurl
_callApiNoCurl
_callApiPreparationsGet
_callApiPreparationsPost
_callApiPreparations
_callApiStreaming
_deliverStreamingMessage

View File

@ -0,0 +1,204 @@
<?php
namespace Codebird;
require_once ('test/codebirdt.php');
/**
* A Twitter library in PHP.
*
* @package codebird-test
* @author Jublo Solutions <support@jublo.net>
* @copyright 2010-2016 Jublo Solutions <support@jublo.net>
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* @link https://github.com/jublonet/codebird-php
*/
/**
* Codebird testing class with mock data source
*
* @package codebird-test
*/
class CodebirdM extends CodebirdT
{
/**
* Stores the request data
*/
protected $_requests = [];
/**
* Mock API replies
*/
protected static $_mock_replies = [
'default' => [
'httpstatus' => 404,
'reply' => "HTTP/1.1 404 Not Found\r\ncontent-length: 68\r\ncontent-type: application/json;charset=utf-8\r\ndate: Sun, 06 Dec 2015 14:43:28 GMT\r\nserver: tsa_b\r\nset-cookie: guest_id=v1%3A144941300885288055; Domain=.twitter.com; Path=/; Expires=Tue, 05-Dec-2017 14:43:28 UTC\r\nstrict-transport-security: max-age=631138519\r\nx-connection-hash: 12218aef9e9757609afb08e661fa3b9b\r\nx-response-time: 2\r\n\r\n{\"errors\":[{\"message\":\"Sorry, that page does not exist\",\"code\":34}]}"
],
'proxy1' => [
'httpstatus' => 404,
'reply' => "HTTP/1.1 200 Connection Established\r\n\r\nHTTP/1.1 404 Not Found\r\ncontent-length: 68\r\ncontent-type: application/json;charset=utf-8\r\ndate: Sun, 06 Dec 2015 14:43:28 GMT\r\nserver: tsa_b\r\nset-cookie: guest_id=v1%3A144941300885288055; Domain=.twitter.com; Path=/; Expires=Tue, 05-Dec-2017 14:43:28 UTC\r\nstrict-transport-security: max-age=631138519\r\nx-connection-hash: 12218aef9e9757609afb08e661fa3b9b\r\nx-response-time: 2\r\n\r\n{\"errors\":[{\"message\":\"Sorry, that page does not exist\",\"code\":34}]}"
],
'GET http://www.example.org/found.txt' => [
'httpstatus' => 200,
'reply' => "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nA test file."
],
'GET https://api.twitter.com/1.1/users/show.json?screen_name=TwitterAPI' => [
'httpstatus' => 200,
'reply' => "HTTP/1.1 200 OK\r\ncache-control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0\r\ncontent-disposition: attachment; filename=json.json\r\ncontent-length: 2801\r\ncontent-type: application/json;charset=utf-8\r\ndate: Sun, 06 Dec 2015 14:55:46 GMT\r\nexpires: Tue, 31 Mar 1981 05:00:00 GMT\r\nlast-modified: Sun, 06 Dec 2015 14:55:46 GMT\r\npragma: no-cache\r\nserver: tsa_b\r\nset-cookie: lang=en-gb; Path=/\r\nset-cookie: guest_id=v1%3A144941374684866365; Domain=.twitter.com; Path=/; Expires=Tue, 05-Dec-2017 14:55:46 UTC\r\nstatus: 200 OK\r\nstrict-transport-security: max-age=631138519\r\nx-access-level: read-write-directmessages\r\nx-connection-hash: 1906b689730b92318bccf65b496f74d0\r\nx-content-type-options: nosniff\r\nx-frame-options: SAMEORIGIN\r\nx-rate-limit-limit: 181\r\nx-rate-limit-remaining: 177\r\nx-rate-limit-reset: 1449414513\r\nx-response-time: 44\r\nx-transaction: 663cc05c64857ba0\r\nx-twitter-response-tags: BouncerCompliant\r\nx-xss-protection: 1; mode=block\r\n\r\n{\"id\":6253282,\"id_str\":\"6253282\",\"name\":\"Twitter API\",\"screen_name\":\"twitterapi\",\"location\":\"San Francisco, CA\",\"profile_location\":null,\"description\":\"The Real Twitter API. I tweet about API changes, service issues and happily answer questions about Twitter and our API. Don't get an answer? It's on my website.\",\"url\":\"http:\/\/t.co\/78pYTvWfJd\",\"entities\":{\"url\":{\"urls\":[{\"url\":\"http:\/\/t.co\/78pYTvWfJd\",\"expanded_url\":\"http:\/\/dev.twitter.com\",\"display_url\":\"dev.twitter.com\",\"indices\":[0,22]}]},\"description\":{\"urls\":[]}},\"protected\":false,\"followers_count\":4993679,\"friends_count\":48,\"listed_count\":13001,\"created_at\":\"Wed May 23 06:01:13 +0000 2007\",\"favourites_count\":27,\"utc_offset\":-28800,\"time_zone\":\"Pacific Time (US & Canada)\",\"geo_enabled\":true,\"verified\":true,\"statuses_count\":3553,\"lang\":\"en\",\"status\":{\"created_at\":\"Tue Nov 24 08:56:07 +0000 2015\",\"id\":669077021138493440,\"id_str\":\"669077021138493440\",\"text\":\"Additional 64-bit entity ID migration coming in Feb 2016 https:\/\/t.co\/eQIGvw1rsJ\",\"source\":\"\u003ca href=\\\"https:\/\/about.twitter.com\/products\/tweetdeck\\\" rel=\\\"nofollow\\\"\u003eTweetDeck\u003c\/a\u003e\",\"truncated\":false,\"in_reply_to_status_id\":null,\"in_reply_to_status_id_str\":null,\"in_reply_to_user_id\":null,\"in_reply_to_user_id_str\":null,\"in_reply_to_screen_name\":null,\"geo\":null,\"coordinates\":null,\"place\":null,\"contributors\":null,\"retweet_count\":67,\"favorite_count\":79,\"entities\":{\"hashtags\":[],\"symbols\":[],\"user_mentions\":[],\"urls\":[{\"url\":\"https:\/\/t.co\/eQIGvw1rsJ\",\"expanded_url\":\"https:\/\/twittercommunity.com\/t\/migration-of-twitter-core-entities-to-64-bit-ids\/56881\",\"display_url\":\"twittercommunity.com\/t\/migration-of\u2026\",\"indices\":[57,80]}]},\"favorited\":false,\"retweeted\":false,\"possibly_sensitive\":false,\"lang\":\"en\"},\"contributors_enabled\":false,\"is_translator\":false,\"is_translation_enabled\":false,\"profile_background_color\":\"C0DEED\",\"profile_background_image_url\":\"http:\/\/pbs.twimg.com\/profile_background_images\/656927849\/miyt9dpjz77sc0w3d4vj.png\",\"profile_background_image_url_https\":\"https:\/\/pbs.twimg.com\/profile_background_images\/656927849\/miyt9dpjz77sc0w3d4vj.png\",\"profile_background_tile\":true,\"profile_image_url\":\"http:\/\/pbs.twimg.com\/profile_images\/2284174872\/7df3h38zabcvjylnyfe3_normal.png\",\"profile_image_url_https\":\"https:\/\/pbs.twimg.com\/profile_images\/2284174872\/7df3h38zabcvjylnyfe3_normal.png\",\"profile_banner_url\":\"https:\/\/pbs.twimg.com\/profile_banners\/6253282\/1431474710\",\"profile_link_color\":\"0084B4\",\"profile_sidebar_border_color\":\"C0DEED\",\"profile_sidebar_fill_color\":\"DDEEF6\",\"profile_text_color\":\"333333\",\"profile_use_background_image\":true,\"has_extended_profile\":false,\"default_profile\":false,\"default_profile_image\":false,\"following\":true,\"follow_request_sent\":false,\"notifications\":false}"
],
'POST https://api.twitter.com/oauth2/token' => [
'httpstatus' => 200,
'reply' => "HTTP/1.1 200 OK\r\ncache-control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0\r\ncontent-disposition: attachment; filename=json.json\r\ncontent-length: 52\r\ncontent-type: application/json;charset=utf-8\r\ndate: Sun, 06 Dec 2015 15:53:02 GMT\r\nexpires: Tue, 31 Mar 1981 05:00:00 GMT\r\nlast-modified: Sun, 06 Dec 2015 15:53:01 GMT\r\nml: S\r\npragma: no-cache\r\nserver: tsa_b\r\nset-cookie: guest_id=v1%3A144941718194388038; Domain=.twitter.com; Path=/; Expires=Tue, 05-Dec-2017 15:53:02 UTC\r\nstatus: 200 OK\r\nstrict-transport-security: max-age=631138519\r\nx-connection-hash: 97f4d4e6a33433b477510d8c58a0b026\r\nx-content-type-options: nosniff\r\nx-frame-options: DENY\r\nx-response-time: 87\r\nx-transaction: 6a0e5e8144d7e6df\r\nx-tsa-request-body-time: 164\r\nx-twitter-response-tags: BouncerCompliant\r\nx-ua-compatible: IE=edge,chrome=1\r\nx-xss-protection: 1; mode=block\r\n\r\n{\"token_type\":\"bearer\",\"access_token\":\"VqiO0n2HrKE\"}"
]
];
/**
* Gets a mock cURL handle
* @param string $url the URL for the curl initialization
* @return string connection ID
*/
protected function _curl_init($url = null)
{
$request = [
'url' => $url,
CURLOPT_RETURNTRANSFER => false
];
$id = mt_rand();
$this->_requests[$id] = $request;
return $id;
}
/**
* Sets mock cURL parameters
* @param string $id connection ID
* @param int $option cURL option to set
* @param mixed $value Value to set for the option
* @return bool
*/
protected function _curl_setopt($id, $option, $value)
{
if (!isset($this->_requests[$id])) {
return false;
}
$this->_requests[$id][$option] = $value;
return true;
}
/**
* Executes mock cURL transfer
* @param string $id connection ID
* @return bool|string
*/
protected function _curl_exec($id)
{
if (!isset($this->_requests[$id])) {
return false;
}
$request = $this->_requests[$id];
$url = $this->_requests[$id]['url'];
$reply = self::$_mock_replies['default'];
$httpmethod = 'GET';
if (isset($request[CURLOPT_POST]) && $request[CURLOPT_POST]) {
$httpmethod = 'POST';
}
if (isset($request[CURLOPT_CUSTOMREQUEST])) {
$httpmethod = $request[CURLOPT_CUSTOMREQUEST];
}
$index = $httpmethod . ' ' . $url;
if (isset(self::$_mock_replies[$index])) {
$reply = self::$_mock_replies[$index];
}
$this->_requests[$id][CURLINFO_HTTP_CODE] = $reply['httpstatus'];
$this->_requests[$id]['reply'] = $reply['reply'];
if (! $this->_requests[$id][CURLOPT_HEADER]
&& stristr($reply['reply'], "\r\n\r\n")
) {
$reply_parts = explode("\r\n\r\n", $reply['reply'], 2);
$reply['reply'] = $reply_parts[1];
}
if ($this->_requests[$id][CURLOPT_RETURNTRANSFER]) {
return $reply['reply'];
}
return true;
}
/**
* Gets cURL error
* @param string $id connection ID
* @return string
*/
protected function _curl_error($id)
{
return '';
}
/**
* Gets cURL error
* @param string $id connection ID
* @return int
*/
protected function _curl_errno($id)
{
return 0;
}
/**
* Gets info about cURL connection
* @param string $id connection ID
* @param int $opt option to get
* @return mixed
*/
protected function _curl_getinfo($id, $opt = 0)
{
if (!isset($this->_requests[$id])) {
return false;
}
$request = $this->_requests[$id];
if (!$opt) {
return [
'url' => $request['url'],
'http_code' => $request[CURLINFO_HTTP_CODE]
];
}
if (isset($request[$opt])) {
return $request[$opt];
}
return false;
}
/**
* Gets fake time
* @return int Timestamp
*/
protected function _time()
{
return 1412345678;
}
/**
* Gets fake time
* @param bool $get_as_float
* @return int Timestamp
*/
protected function _microtime($get_as_float = false)
{
if ($get_as_float) {
return 1412345678.777;
}
return '777 1412345678';
}
}

View File

@ -0,0 +1,97 @@
<?php
namespace Codebird;
require_once ('src/codebird.php');
/**
* A Twitter library in PHP.
*
* @package codebird-test
* @author Jublo Solutions <support@jublo.net>
* @copyright 2010-2016 Jublo Solutions <support@jublo.net>
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* @link https://github.com/jublonet/codebird-php
*/
/**
* Codebird testing class
*
* @package codebird-test
*/
class CodebirdT extends Codebird
{
/**
* Returns properties
*
* @param string $property The property to get
*
* @return mixed Property
*/
public function get($property)
{
if (property_exists($this, $property)) {
return $this->$property;
}
throw new \Exception('Property ' . $property . ' is not defined.');
}
/**
* Returns static properties
*
* @param string $property The property to get
*
* @return mixed Property
*/
public function getStatic($property)
{
if (property_exists($this, $property)) {
return static::$$property;
}
throw new \Exception('Static property ' . $property . ' is not defined.');
}
/**
* Calls methods
*
* @param string $property The property to get
*
* @return mixed Property
*/
public function call($method, $params = [], &$params2 = null)
{
$methods_byref = [
'_mapFnToApiMethod',
'_mapFnInlineParams',
'_detectMethod'
];
if (in_array($method, $methods_byref)) {
return $this->$method($params, $params2);
}
if (method_exists($this, $method)) {
return call_user_func_array([$this, $method], $params);
}
throw new \Exception('Method ' . $method . ' is not defined.');
}
/**
* Calls methods
*
* @param string $property The property to get
*
* @return mixed Property
*/
public function callStatic($method, $params = [])
{
if (function_exists([self, $method])) {
return call_user_func_array([self, $method], $params);
}
throw new \Exception('Static method ' . $method . ' is not defined.');
}
/**
* Streaming callback test
*/
public static function streamingCallbackTest()
{
}
}

View File

@ -0,0 +1,40 @@
<?php
namespace Codebird;
require_once ('test/codebirdt.php');
/**
* A Twitter library in PHP.
*
* @package codebird-test
* @author Jublo Limited <support@jublo.net>
* @copyright 2010-2018 Jublo Limited <support@jublo.net>
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* @link https://github.com/jublonet/codebird-php
*/
/**
* Constant tests
*
* @package codebird-test
*/
class Constant_Test extends \PHPUnit\Framework\TestCase
{
/**
* Tests if constants defined
*/
public function testConstants()
{
$constants = [
'CODEBIRD_RETURNFORMAT_OBJECT',
'CODEBIRD_RETURNFORMAT_ARRAY',
'CODEBIRD_RETURNFORMAT_JSON'
];
foreach ($constants as $constant) {
$this->assertTrue(
defined($constant),
$constant
);
}
}
}

View File

@ -0,0 +1,57 @@
<?php
namespace Codebird;
require_once ('test/codebirdm.php');
/**
* A Twitter library in PHP.
*
* @package codebird-test
* @author Jublo Limited <support@jublo.net>
* @copyright 2010-2018 Jublo Limited <support@jublo.net>
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* @link https://github.com/jublonet/codebird-php
*/
/**
* cURL tests
*
* @package codebird-test
*/
class Curl_Test extends \PHPUnit\Framework\TestCase
{
/**
* Initialise Codebird class
*
* @return \Codebird\Codebird The Codebird class
*/
protected function getCB()
{
$cb = new CodebirdM();
return $cb;
}
/**
* Tests _getCurlInitialization
*/
public function testGetCurlInitialization()
{
$cb = $this->getCB();
$id = $cb->call('_getCurlInitialization', ['https://test']);
$this->assertEquals(
[
'url' => 'https://test',
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION => 0,
CURLOPT_HEADER => 1,
CURLOPT_SSL_VERIFYPEER => 1,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_CAINFO => substr(__DIR__, 0, -strlen(basename(__DIR__))) . 'src/cacert.pem',
CURLOPT_USERAGENT => 'codebird-php/' . $cb->getStatic('_version')
. ' +https://github.com/jublonet/codebird-php'
],
$cb->get('_requests')[$id]
);
}
}

View File

@ -0,0 +1,288 @@
<?php
namespace Codebird;
require_once ('test/codebirdm.php');
/**
* A Twitter library in PHP.
*
* @package codebird-test
* @author Jublo Limited <support@jublo.net>
* @copyright 2010-2018 Jublo Limited <support@jublo.net>
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* @link https://github.com/jublonet/codebird-php
*/
/**
* Detection tests
*
* @package codebird-test
*/
class Detection_Test extends \PHPUnit\Framework\TestCase
{
/**
* Initialise Codebird class
*
* @return \Codebird\Codebird The Codebird class
*/
protected function getCB()
{
$cb = new CodebirdM();
return $cb;
}
/**
* Tests _detectMethod
* @expectedException \Exception
* @expectedExceptionMessage Can't find HTTP method to use for "non-existent".
*/
public function testDetectMethod1()
{
$cb = $this->getCB();
$params = [];
$cb->call('_detectMethod', 'non-existent', $params);
}
/**
* Tests _detectMethod
*/
public function testDetectMethod2()
{
$cb = $this->getCB();
// forced httpmethod
$params = ['httpmethod' => 'DELETE'];
$this->assertEquals(
'DELETE',
$cb->call('_detectMethod', 'doesnt-matter', $params)
);
// normal detection
$params = [];
$post = ['httpmethod' => 'POST'];
$this->assertEquals('GET', $cb->call('_detectMethod', 'search/tweets', $params));
$this->assertEquals('POST', $cb->call('_detectMethod', 'statuses/update', $params));
$this->assertEquals('POST', $cb->call('_detectMethod', 'ads/sandbox/accounts', $post));
$this->assertEquals(
'PUT',
$cb->call(
'_detectMethod',
'ton/bucket/:bucket/:file?resumable=true&resumeId=:resumeId',
$params
)
);
// parameter-based detection
$this->assertEquals('GET', $cb->call('_detectMethod', 'account/settings', $params));
$params = ['test' => 12];
$this->assertEquals('POST', $cb->call('_detectMethod', 'account/settings', $params));
$params = [];
$this->assertEquals('POST', $cb->call('_detectMethod', 'media/upload', $params));
$params = ['command' => 'STATUS'];
$this->assertEquals('GET', $cb->call('_detectMethod', 'media/upload', $params));
$httpmethods_by_param = [
'POST' => [
'campaign_id' => [
'ads/accounts/:account_id/line_items',
'ads/sandbox/accounts/:account_id/line_items'
],
'name' => [
'ads/accounts/:account_id/app_lists',
'ads/accounts/:account_id/campaigns',
'ads/accounts/:account_id/cards/app_download',
'ads/accounts/:account_id/cards/image_app_download',
'ads/accounts/:account_id/cards/image_conversation',
'ads/accounts/:account_id/cards/lead_gen',
'ads/accounts/:account_id/cards/video_app_download',
'ads/accounts/:account_id/cards/video_conversation',
'ads/accounts/:account_id/cards/website',
'ads/accounts/:account_id/tailored_audiences',
'ads/accounts/:account_id/web_event_tags',
'ads/sandbox/accounts/:account_id/app_lists',
'ads/sandbox/accounts/:account_id/campaigns',
'ads/sandbox/accounts/:account_id/cards/app_download',
'ads/sandbox/accounts/:account_id/cards/image_app_download',
'ads/sandbox/accounts/:account_id/cards/image_conversation',
'ads/sandbox/accounts/:account_id/cards/lead_gen',
'ads/sandbox/accounts/:account_id/cards/video_app_download',
'ads/sandbox/accounts/:account_id/cards/video_conversation',
'ads/sandbox/accounts/:account_id/cards/website',
'ads/sandbox/accounts/:account_id/tailored_audiences',
'ads/sandbox/accounts/:account_id/web_event_tags'
],
'tailored_audience_id' => [
'ads/accounts/:account_id/tailored_audience_changes',
'ads/sandbox/accounts/:account_id/tailored_audience_changes'
],
'targeting_value' => [
'ads/accounts/:account_id/targeting_criteria',
'ads/sandbox/accounts/:account_id/targeting_criteria'
],
'tweet_ids' => [
'ads/accounts/:account_id/promoted_tweets',
'ads/sandbox/accounts/:account_id/promoted_tweets'
],
'user_id' => [
'ads/accounts/:account_id/promoted_accounts',
'ads/sandbox/accounts/:account_id/promoted_accounts'
],
'video_media_id' => [
'ads/accounts/:account_id/videos',
'ads/sandbox/accounts/:account_id/videos'
]
],
'PUT' => [
'name' => [
'ads/accounts/:account_id/cards/image_conversation/:card_id',
'ads/accounts/:account_id/cards/video_conversation/:card_id',
'ads/accounts/:account_id/cards/website/:card_id',
'ads/sandbox/accounts/:account_id/cards/image_conversation/:card_id',
'ads/sandbox/accounts/:account_id/cards/video_conversation/:card_id',
'ads/sandbox/accounts/:account_id/cards/website/:card_id'
]
]
];
foreach ($httpmethods_by_param as $httpmethod => $methods_by_param) {
foreach ($methods_by_param as $param => $methods) {
foreach ($methods as $method) {
$params = [];
$this->assertEquals(
'GET',
$cb->call('_detectMethod', $method, $params),
$method
);
$params[$param] = '123';
$this->assertEquals(
$httpmethod,
$cb->call('_detectMethod', $method, $params),
$method
);
}
}
}
}
/**
* Tests _detectMultipart
*/
public function testDetectMultipart()
{
$cb = $this->getCB();
$this->assertFalse($cb->call('_detectMultipart', ['statuses/update']));
$this->assertTrue($cb->call('_detectMultipart', ['media/upload']));
}
/**
* Tests _detectMedia
*/
public function testDetectMedia()
{
$cb = $this->getCB();
$this->assertFalse($cb->call('_detectMedia', ['statuses/update']));
$this->assertTrue($cb->call('_detectMedia', ['media/upload']));
}
/**
* Tests _detectJsonBody
*/
public function testDetectJsonBody()
{
$cb = $this->getCB();
$this->assertFalse($cb->call('_detectJsonBody', ['statuses/update']));
$this->assertTrue($cb->call('_detectJsonBody', ['collections/entries/curate']));
$this->assertTrue($cb->call('_detectJsonBody', ['ads/batch/accounts/:account_id/targeting_criteria']));
}
/**
* Tests _detectBinaryBody
*/
public function testDetectBinaryBody()
{
$cb = $this->getCB();
$this->assertFalse($cb->call('_detectBinaryBody', ['statuses/update']));
$this->assertTrue($cb->call('_detectBinaryBody', ['ton/bucket/:bucket']));
$this->assertTrue($cb->call('_detectBinaryBody', ['ton/bucket/:bucket?resumable=true']));
$this->assertTrue($cb->call(
'_detectBinaryBody',
['ton/bucket/:bucket/:file?resumable=true&resumeId=:resumeId']
));
}
/**
* Tests _detectStreaming
*/
public function testDetectStreaming()
{
$cb = $this->getCB();
$this->assertFalse($cb->call('_detectStreaming', ['statuses/update']));
$this->assertEquals('public', $cb->call('_detectStreaming', ['statuses/sample']));
$this->assertEquals('public', $cb->call('_detectStreaming', ['statuses/filter']));
}
/**
* Tests _getEndpoint
*/
public function testGetEndpoint()
{
$cb = $this->getCB();
$this->assertEquals(
'https://api.twitter.com/1.1/statuses/update.json',
$cb->call('_getEndpoint', ['statuses/update', 'statuses/update']),
'statuses/update'
);
$this->assertEquals(
'https://api.twitter.com/oauth/authenticate',
$cb->call('_getEndpoint', ['oauth/authenticate', 'oauth/authenticate']),
'oauth/authenticate'
);
$this->assertEquals(
'https://api.twitter.com/oauth2/token',
$cb->call('_getEndpoint', ['oauth2/token', 'oauth2/token']),
'oauth2/token'
);
$this->assertEquals(
'https://upload.twitter.com/1.1/media/upload.json',
$cb->call('_getEndpoint', ['media/upload', 'media/upload']),
'media/upload'
);
$this->assertEquals(
'https://upload.twitter.com/1.1/media/metadata/create.json',
$cb->call('_getEndpoint', ['media/metadata/create', 'media/metadata/create']),
'media/metadata/create'
);
$this->assertEquals(
'https://publish.twitter.com/oembed',
$cb->call('_getEndpoint', ['statuses/oembed', 'statuses/oembed']),
'statuses/oembed'
);
$this->assertEquals(
'https://stream.twitter.com/1.1/statuses/filter.json',
$cb->call('_getEndpoint', ['statuses/filter', 'statuses/filter']),
'statuses/filter'
);
$this->assertEquals(
'https://ton.twitter.com/1.1/ton/bucket/ta_partner',
$cb->call('_getEndpoint', ['ton/bucket/ta_partner', 'ton/bucket/:bucket']),
'ton/bucket/:bucket'
);
$this->assertEquals(
'https://ads-api.twitter.com/2/accounts/1234/campaigns',
$cb->call(
'_getEndpoint',
['ads/accounts/1234/campaigns', 'ads/accounts/:account_id/campaigns']
),
'ads/accounts/:account_id/campaigns'
);
$this->assertEquals(
'https://ads-api-sandbox.twitter.com/2/accounts/1234/campaigns',
$cb->call(
'_getEndpoint',
['ads/sandbox/accounts/1234/campaigns', 'ads/sandbox/accounts/:account_id/campaigns']
),
'ads/sandbox/accounts/:account_id/campaigns'
);
}
}

View File

@ -0,0 +1,40 @@
<?php
namespace Codebird;
/**
* A Twitter library in PHP.
*
* @package codebird-test
* @author Jublo Limited <support@jublo.net>
* @copyright 2010-2018 Jublo Limited <support@jublo.net>
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* @link https://github.com/jublonet/codebird-php
*/
/**
* Environment tests
*
* @package codebird-test
*/
class Environment_Test extends \PHPUnit\Framework\TestCase
{
/**
* Tests PHP version
*/
public function testPhpVersion()
{
$this->assertTrue(
version_compare('7.1', phpversion(), '<='),
'Codebird requires PHP 7.1 or above'
);
}
/**
* Tests OpenSSL module availability
*/
public function testOpenssl()
{
$this->assertTrue(function_exists('openssl_open'));
}
}

View File

@ -0,0 +1,56 @@
<?php
namespace Codebird;
require_once ('test/codebirdm.php');
/**
* A Twitter library in PHP.
*
* @package codebird-test
* @author Jublo Limited <support@jublo.net>
* @copyright 2010-2018 Jublo Limited <support@jublo.net>
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* @link https://github.com/jublonet/codebird-php
*/
/**
* Media tests
*
* @package codebird-test
*/
class Media_Test extends \PHPUnit\Framework\TestCase
{
/**
* Initialise Codebird class
*
* @return \Codebird\Codebird The Codebird class
*/
protected function getCB()
{
Codebird::setConsumerKey('123', '456');
$cb = new CodebirdM();
return $cb;
}
/**
* Tests _fetchRemoteFile
*/
public function testFetchRemoteFile()
{
$cb = $this->getCB();
$expected = $cb->call('_fetchRemoteFile', ['http://www.example.org/found.txt']);
$this->assertEquals($expected, 'A test file.');
}
/**
* Tests _fetchRemoteFile
* @expectedException \Exception
* @expectedExceptionMessage Downloading a remote media file failed.
*/
public function testFetchRemoteFile1()
{
$cb = $this->getCB();
$reply = $cb->call('_fetchRemoteFile', ['http://www.example.org/not-found.jpg']);
}
}

View File

@ -0,0 +1,130 @@
<?php
namespace Codebird;
require_once ('test/codebirdm.php');
/**
* A Twitter library in PHP.
*
* @package codebird-test
* @author Jublo Limited <support@jublo.net>
* @copyright 2010-2018 Jublo Limited <support@jublo.net>
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* @link https://github.com/jublonet/codebird-php
*/
/**
* OAuth tests
*
* @package codebird-test
*/
class Oauth_Test extends \PHPUnit\Framework\TestCase
{
/**
* Initialise Codebird class
*
* @return \Codebird\Codebird The Codebird class
*/
protected function getCB()
{
Codebird::setConsumerKey('123', '456');
$cb = new CodebirdM();
return $cb;
}
/**
* Tests oauth_authenticate
*/
public function testOauthAuthenticate()
{
$cb = $this->getCB();
$cb->setToken('123', '456');
$this->assertEquals(
'https://api.twitter.com/oauth/authenticate?oauth_token=123',
$cb->oauth_authenticate()
);
$this->assertEquals(
'https://api.twitter.com/oauth/authenticate?oauth_token=123&force_login=1',
$cb->oauth_authenticate($force_login = true)
);
$this->assertEquals(
'https://api.twitter.com/oauth/authenticate?'
. 'oauth_token=123&force_login=1&screen_name=TwitterAPI',
$cb->oauth_authenticate($force_login = true, $screen_name = 'TwitterAPI')
);
$this->assertEquals(
'https://api.twitter.com/oauth/authenticate?'
. 'oauth_token=123&screen_name=TwitterAPI',
$cb->oauth_authenticate($force_login = false, $screen_name = 'TwitterAPI')
);
}
/**
* Tests oauth_authorize
*/
public function testOauthAuthorize()
{
$cb = $this->getCB();
$cb->setToken('123', '456');
$this->assertEquals(
'https://api.twitter.com/oauth/authorize?oauth_token=123',
$cb->oauth_authorize()
);
$this->assertEquals(
'https://api.twitter.com/oauth/authorize?oauth_token=123&force_login=1',
$cb->oauth_authorize($force_login = true)
);
$this->assertEquals(
'https://api.twitter.com/oauth/authorize?'
. 'oauth_token=123&force_login=1&screen_name=TwitterAPI',
$cb->oauth_authorize($force_login = true, $screen_name = 'TwitterAPI')
);
$this->assertEquals(
'https://api.twitter.com/oauth/authorize?'
. 'oauth_token=123&screen_name=TwitterAPI',
$cb->oauth_authorize($force_login = false, $screen_name = 'TwitterAPI')
);
}
/**
* Tests oauth2_token
*/
public function testOauth2Token()
{
$cb = $this->getCB();
$expected = new \stdClass;
$expected->token_type = 'bearer';
$expected->access_token = 'VqiO0n2HrKE';
$expected->httpstatus = '200';
$expected->rate = null;
$this->assertEquals($expected, $cb->oauth2_token());
}
/**
* Tests _getBearerAuthorization
* @expectedException \Exception
* @expectedExceptionMessage To make an app-only auth API request, consumer key or bearer token must be set.
*/
public function testGetBearerAuthorization1()
{
$cb = $this->getCB();
Codebird::setConsumerKey(null, null);
$cb->setBearerToken(null);
$cb->call('_getBearerAuthorization', []);
}
/**
* Tests _getBearerAuthorization
*/
public function testGetBearerAuthorization2()
{
$cb = $this->getCB();
$cb->setBearerToken('12345678');
$this->assertEquals('Bearer 12345678', $cb->call('_getBearerAuthorization', []));
// automatic fetching
$cb->setBearerToken(null);
$this->assertEquals('Bearer VqiO0n2HrKE', $cb->call('_getBearerAuthorization', []));
}
}

View File

@ -0,0 +1,361 @@
<?php
namespace Codebird;
require_once ('test/codebirdm.php');
/**
* A Twitter library in PHP.
*
* @package codebird-test
* @author Jublo Limited <support@jublo.net>
* @copyright 2010-2018 Jublo Limited <support@jublo.net>
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* @link https://github.com/jublonet/codebird-php
*/
/**
* Reply parsing tests
*
* @package codebird-test
*/
class Replyparse_Test extends \PHPUnit\Framework\TestCase
{
/**
* Initialise Codebird class
*
* @return \Codebird\Codebird The Codebird class
*/
protected function getCB()
{
Codebird::setConsumerKey('123', '456');
$cb = new CodebirdM();
return $cb;
}
/**
* Tests _getHttpStatusFromHeaders
*/
public function testGetHttpStatusFromHeaders()
{
$cb = $this->getCB();
$this->assertEquals(
'500',
$cb->call('_getHttpStatusFromHeaders', [['']])
);
$this->assertEquals(
'200',
$cb->call('_getHttpStatusFromHeaders', [
['HTTP/1.1 200 OK'],
['X-Some-Data: test']
])
);
$this->assertEquals(
'404',
$cb->call('_getHttpStatusFromHeaders', [
['HTTP/1.1 404 Not Found'],
['X-Some-Data: test']
])
);
}
/**
* Tests _parseBearerReply
*/
public function testParseBearerReply()
{
$cb = $this->getCB();
$cb->setBearerToken(null);
// get raw reply from mock collection
$reply = $cb->getStatic('_mock_replies')['POST https://api.twitter.com/oauth2/token'];
// check that bearer token is not yet set
$this->assertNull($cb->getStatic('_bearer_token'));
// parse it as object
$result = $cb->call(
'_parseBearerReply',
[
$reply['reply'],
$reply['httpstatus']
]
);
$expected = new \stdClass;
$expected->token_type = 'bearer';
$expected->access_token = 'VqiO0n2HrKE';
$expected->httpstatus = 200;
$expected->rate = null;
$this->assertEquals($expected, $result);
// check that bearer token was actually set
$this->assertNotNull($cb->getStatic('_bearer_token'));
// array
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_ARRAY);
$cb->setBearerToken(null);
$result = $cb->call(
'_parseBearerReply',
[
$reply['reply'],
$reply['httpstatus']
]
);
$expected = [
'token_type' => 'bearer',
'access_token' => 'VqiO0n2HrKE',
'httpstatus' => 200,
'rate' => null
];
$this->assertEquals($expected, $result);
// check that bearer token was actually set
$this->assertNotNull($cb->getStatic('_bearer_token'));
// JSON
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_JSON);
$cb->setBearerToken(null);
$result = $cb->call(
'_parseBearerReply',
[
$reply['reply'],
$reply['httpstatus']
]
);
$expected = '{"token_type":"bearer","access_token":"VqiO0n2HrKE"}';
$this->assertEquals($expected, $result);
// check that bearer token was actually set
$this->assertNotNull($cb->getStatic('_bearer_token'));
}
/**
* Tests _getRateLimitInfo
*/
public function testGetRateLimitInfo()
{
$cb = $this->getCB();
$headers = [
'content-length' => 68,
'content-type' => 'application/json;charset=utf-8',
'date' => 'Sun, 06 Dec 2015 14:43:28 GMT'
];
$this->assertNull($cb->call('_getRateLimitInfo', [$headers]));
// set rate-limit headers
$headers['x-rate-limit-limit'] = 180;
$headers['x-rate-limit-remaining'] = 123;
$headers['x-rate-limit-reset'] = time() + 234;
$rate = $cb->call('_getRateLimitInfo', [$headers]);
$expected = new \stdClass;
$expected->limit = $headers['x-rate-limit-limit'];
$expected->remaining = $headers['x-rate-limit-remaining'];
$expected->reset = $headers['x-rate-limit-reset'];
$this->assertEquals($expected, $rate);
// array
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_ARRAY);
$rate = $cb->call('_getRateLimitInfo', [$headers]);
$expected = [
'limit' => $headers['x-rate-limit-limit'],
'remaining' => $headers['x-rate-limit-remaining'],
'reset' => $headers['x-rate-limit-reset']
];
$this->assertEquals($expected, $rate);
}
/**
* Tests _validateSslCertificate
*/
public function testValidateSslCertificate1()
{
$cb = $this->getCB();
$cb->call('_validateSslCertificate', [0]);
}
/**
* Tests _validateSslCertificate
* @expectedException \Exception
* @expectedExceptionMessage Error 58 while validating the Twitter API certificate.
*/
public function testValidateSslCertificate2()
{
$cb = $this->getCB();
$cb->call('_validateSslCertificate', [CURLE_SSL_CERTPROBLEM]);
}
/**
* Tests _appendHttpStatusAndRate
*/
public function testAppendHttpStatusAndRate()
{
$cb = $this->getCB();
// object
$reply = new \stdClass;
$reply->somedata = 123;
$reply->moredata = '456';
$rate = new \stdClass;
$rate->field1 = 180;
$rate->field2 = 177;
$expected = new \stdClass;
$expected->somedata = 123;
$expected->moredata = '456';
$expected->httpstatus = 409;
$expected->rate = new \stdClass;
$expected->rate->field1 = 180;
$expected->rate->field2 = 177;
$this->assertEquals(
$expected,
$cb->call('_appendHttpStatusAndRate', [$reply, 409, $rate])
);
// array
$reply = (array) $reply;
$rate = (array) $rate;
$expected = (array) $expected;
$expected['rate'] = (array) $expected['rate'];
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_ARRAY);
$this->assertEquals(
$expected,
$cb->call('_appendHttpStatusAndRate', [$reply, 409, $rate])
);
// JSON
$reply = '{"somedata":123,"moredata":"456"}';
$expected = '{"somedata":123,"moredata":"456","httpstatus":409,'
. '"rate":{"field1":180,"field2":177}}';
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_JSON);
$this->assertEquals(
$expected,
$cb->call('_appendHttpStatusAndRate', [$reply, 409, $rate])
);
}
/**
* Tests _parseApiHeaders
*/
public function testParseApiHeaders()
{
$cb = $this->getCB();
$data = $cb->getStatic('_mock_replies')['default']['reply'];
list($headers, $reply) = $cb->call('_parseApiHeaders', [$data]);
$expected_headers = [
'HTTP/1.1 404 Not Found' => '',
'content-length' => '68',
'content-type' => 'application/json;charset=utf-8',
'date' => 'Sun, 06 Dec 2015 14:43:28 GMT',
'server' => 'tsa_b',
'set-cookie' => 'guest_id=v1%3A144941300885288055; Domain=.twitter.com'
. '; Path=/; Expires=Tue, 05-Dec-2017 14:43:28 UTC',
'strict-transport-security' => 'max-age=631138519',
'x-connection-hash' => '12218aef9e9757609afb08e661fa3b9b',
'x-response-time' => '2'
];
$expected_reply = '{"errors":[{"message":"Sorry, that page does not exist","code":34}]}';
$this->assertEquals($expected_headers, $headers);
$this->assertEquals($expected_reply, $reply);
// proxy
$data = $cb->getStatic('_mock_replies')['proxy1']['reply'];
list($headers, $reply) = $cb->call('_parseApiHeaders', [$data]);
$this->assertEquals($expected_headers, $headers);
$this->assertEquals($expected_reply, $reply);
}
/**
* Tests _parseApiReplyPrefillHeaders
*/
public function testParseApiReplyPrefillHeaders()
{
$cb = $this->getCB();
$headers = [
'X-TON-Min-Chunk-Size' => '12345',
'X-TON-Max-Chunk-Size' => '23456',
'Range' => 'bytes 0-1234567/2345678'
];
// non-empty reply: no touching
$this->assertEquals(
'123',
$cb->call('_parseApiReplyPrefillHeaders', [$headers, '123'])
);
// no location header: no touching
$this->assertEquals(
'',
$cb->call('_parseApiReplyPrefillHeaders', [$headers, ''])
);
$headers['Location'] = 'https://twitter.com';
$this->assertEquals(
'{"Location":"https:\/\/twitter.com","X-TON-Min-Chunk-Size":"12345",'
. '"X-TON-Max-Chunk-Size":"23456","Range":"bytes 0-1234567\/2345678"}',
$cb->call('_parseApiReplyPrefillHeaders', [$headers, ''])
);
}
/**
* Tests _parseApiReply
*/
public function testParseApiReply1()
{
$cb = $this->getCB();
// object
$this->assertEquals(new \stdClass, $cb->call('_parseApiReply', ['[]']));
// array
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_ARRAY);
$this->assertEquals([], $cb->call('_parseApiReply', ['[]']));
// JSON
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_JSON);
$this->assertEquals('{}', $cb->call('_parseApiReply', ['[]']));
}
/**
* Tests _parseApiReply
*/
public function testParseApiReply2()
{
$cb = $this->getCB();
$reply = '{"id_str":"6253282","profile_location":null,'
. '"status":{"created_at":"Tue Nov 24 08:56:07 +0000 2015","id":669077021138493440}}';
// object
$expected = new \stdClass;
$expected->id_str = '6253282';
$expected->profile_location = null;
$expected->status = new \stdClass;
$expected->status->created_at = 'Tue Nov 24 08:56:07 +0000 2015';
$expected->status->id = 669077021138493440;
$result = $cb->call('_parseApiReply', [$reply]);
$this->assertEquals($expected, $result);
$this->assertSame($expected->status->id, $result->status->id);
// array
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_ARRAY);
$expected = (array) $expected;
$expected['status'] = (array) $expected['status'];
$this->assertEquals($expected, $cb->call('_parseApiReply', [$reply]));
// JSON
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_JSON);
$this->assertEquals($reply, $cb->call('_parseApiReply', [$reply]));
// query-string format
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_ARRAY);
$this->assertEquals(
[
'oauth_token' => 'ABC',
'oauth_token_secret' => 'def',
'oauth_callback_confirmed' => 'true'
],
$cb->call(
'_parseApiReply',
['oauth_token=ABC&oauth_token_secret=def&oauth_callback_confirmed=true']
)
);
// message
$this->assertEquals(
['message' => 'This is just a message.'],
$cb->call('_parseApiReply', ['This is just a message.'])
);
}
}

View File

@ -0,0 +1,212 @@
<?php
namespace Codebird;
require_once ('test/codebirdm.php');
/**
* A Twitter library in PHP.
*
* @package codebird-test
* @author Jublo Limited <support@jublo.net>
* @copyright 2010-2018 Jublo Limited <support@jublo.net>
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* @link https://github.com/jublonet/codebird-php
*/
/**
* Request parsing tests
*
* @package codebird-test
*/
class Requestparse_Test extends \PHPUnit\Framework\TestCase
{
/**
* Initialise Codebird class
*
* @return \Codebird\Codebird The Codebird class
*/
protected function getCB()
{
Codebird::setConsumerKey('123', '456');
$cb = new CodebirdM();
$cb->setToken('234', '567');
return $cb;
}
/**
* Tests _parseApiParams
*/
public function testParseApiParams()
{
$cb = $this->getCB();
// empty list
$this->assertEquals([], $cb->call('_parseApiParams', [[]]));
// arrays
$this->assertEquals(['test' => 1], $cb->call('_parseApiParams', [[['test' => 1]]]));
$this->assertEquals(
['media[]' => '123'],
$cb->call('_parseApiParams', [[['media[]' => 123]]])
);
// urlencoded strings
$this->assertEquals(['testdata' => ''], $cb->call('_parseApiParams', [['testdata']]));
$this->assertEquals(
['param1' => '12', 'param2' => 'ab'],
$cb->call('_parseApiParams', [['param1=12&param2=ab']])
);
$this->assertEquals(
['media' => ['123', '456']],
$cb->call('_parseApiParams', [['media[]=123&media[]=456']])
);
}
/**
* Tests _stringifyNullBoolParams
*/
public function testStringifyNullBoolParams()
{
$cb = $this->getCB();
$result = $cb->call(
'_stringifyNullBoolParams',
[['a' => 123, 'b' => null, 'c' => true, 'd' => false, 'e' => 'x']]
);
$this->assertEquals('123', $result['a']);
$this->assertNull($result['b']);
$this->assertEquals('true', $result['c']);
$this->assertEquals('false', $result['d']);
}
/**
* Tests _mapFnToApiMethod
*/
public function testMapFnToApiMethod()
{
$cb = $this->getCB();
$apiparams = [
'test' => 1,
'account_id' => '1234'
];
$result = $cb->call(
'_mapFnToApiMethod',
'ads_accounts_ACCOUNT_ID_cards_appDownload',
$apiparams
);
$this->assertEquals([
'ads/accounts/1234/cards/app_download',
'ads/accounts/:account_id/cards/app_download'
], $result);
// check that inline parameter was removed from array
$this->assertArrayNotHasKey('account_id', $apiparams);
}
/**
* Tests _mapFnInsertSlashes
*/
public function testMapFnInsertSlashes()
{
$cb = $this->getCB();
$result = $cb->call(
'_mapFnInsertSlashes',
['ads_accounts_ACCOUNT_ID_cards_appDownload']
);
$this->assertEquals(
'ads/accounts/ACCOUNT/ID/cards/appDownload',
$result
);
}
/**
* Tests _mapFnRestoreParamUnderscores
*/
public function testMapFnRestoreParamUnderscores()
{
$cb = $this->getCB();
$params_underscore = [
'screen_name', 'place_id',
'account_id', 'campaign_id', 'card_id', 'line_item_id',
'tweet_id', 'web_event_tag_id'
];
$params_slash = [];
foreach ($params_underscore as $param) {
$params_slash[] = str_replace('_', '/', $param);
}
for ($i = 0; $i < count($params_underscore); $i++) {
$result = $cb->call(
'_mapFnRestoreParamUnderscores',
['ads/accounts/' . strtoupper($params_slash[$i]) . '/cards/appDownload']
);
$this->assertEquals(
'ads/accounts/' . strtoupper($params_underscore[$i]) . '/cards/appDownload',
$result
);
}
}
/**
* Tests _mapFnInlineParams
*/
public function testMapFnInlineParams()
{
$cb = $this->getCB();
// normal parameters
$apiparams = [
'test' => 1,
'account_id' => '1234'
];
$result = $cb->call(
'_mapFnInlineParams',
'ads/accounts/ACCOUNT_ID/cards/app_download',
$apiparams
);
$this->assertEquals([
'ads/accounts/1234/cards/app_download',
'ads/accounts/:account_id/cards/app_download'
],
$result
);
// check that inline parameter was removed from array
$this->assertArrayNotHasKey('account_id', $apiparams);
// special parameters (TON API)
$apiparams = [
'test' => 1,
'bucket' => 'ta_partner',
'file' => 'test_Ab.mp4',
'resumeId' => '56789'
];
$result = $cb->call(
'_mapFnInlineParams',
'ton/bucket/BUCKET/FILE?resumable=true&resumeId=RESUMEID',
$apiparams
);
$this->assertEquals([
'ton/bucket/ta_partner/test_Ab.mp4?resumable=true&resumeId=56789',
'ton/bucket/:bucket/:file?resumable=true&resumeId=:resumeId'
],
$result
);
$this->assertArrayNotHasKey('bucket', $apiparams);
$this->assertArrayNotHasKey('file', $apiparams);
$this->assertArrayNotHasKey('resumeId', $apiparams);
$this->assertEquals(['test' => 1], $apiparams);
}
/**
* Tests _json_decode
*/
public function testJsonDecode()
{
$json = '{"id": 123456789123456789, "id_str": "123456789123456789"}';
$array = [
'id' => 123456789123456789,
'id_str' => '123456789123456789'
];
$object = (object) $array;
$cb = $this->getCB();
$result = $cb->call('_json_decode', [$json]);
$this->assertEquals($object, $result);
$result = $cb->call('_json_decode', [$json, true]);
$this->assertEquals($array, $result);
}
}

View File

@ -0,0 +1,70 @@
<?php
namespace Codebird;
require_once ('test/codebirdm.php');
/**
* A Twitter library in PHP.
*
* @package codebird-test
* @author Jublo Limited <support@jublo.net>
* @copyright 2010-2018 Jublo Limited <support@jublo.net>
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* @link https://github.com/jublonet/codebird-php
*/
/**
* Return format tests
*
* @package codebird-test
*/
class Returnformat_Test extends \PHPUnit\Framework\TestCase
{
/**
* Initialise Codebird class
*
* @return \Codebird\Codebird The Codebird class
*/
protected function getCB()
{
Codebird::setConsumerKey('123', '456');
$cb = new CodebirdM();
$cb->setToken('234', '567');
return $cb;
}
/**
* Tests array return format
*/
public function testArrayFormat()
{
$cb = $this->getCB();
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_ARRAY);
$reply = $cb->users_show(['screen_name' => 'TwitterAPI']);
$this->assertTrue(is_array($reply));
}
/**
* Tests object return format
*/
public function testObjectFormat()
{
$cb = $this->getCB();
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_OBJECT);
$reply = $cb->users_show(['screen_name' => 'TwitterAPI']);
$this->assertInstanceOf('stdClass', $reply);
}
/**
* Tests JSON return format
*/
public function testJsonFormat()
{
$cb = $this->getCB();
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_JSON);
$reply = $cb->users_show(['screen_name' => 'TwitterAPI']);
$data = json_decode($reply);
$this->assertNotFalse($data);
}
}

View File

@ -0,0 +1,253 @@
<?php
namespace Codebird;
require_once ('test/codebirdt.php');
/**
* A Twitter library in PHP.
*
* @package codebird-test
* @author Jublo Limited <support@jublo.net>
* @copyright 2010-2018 Jublo Limited <support@jublo.net>
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* @link https://github.com/jublonet/codebird-php
*/
/**
* Setter function tests
*
* @package codebird-test
*/
class Setter_Test extends \PHPUnit\Framework\TestCase
{
/**
* Tests setConsumerKey
*/
public function testSetConsumerKey()
{
$cb = new CodebirdT();
$cb->setConsumerKey('123', '456');
$this->assertEquals('123', $cb->getStatic('_consumer_key'));
$this->assertEquals('456', $cb->getStatic('_consumer_secret'));
}
/**
* Tests setBearerToken
*/
public function testSetBearerToken()
{
$cb = new CodebirdT();
$cb->setBearerToken('789');
$this->assertEquals('789', $cb->getStatic('_bearer_token'));
}
/**
* Tests getVersion
*/
public function testGetVersion()
{
$cb = new CodebirdT();
$version = $cb->getVersion();
$this->assertEquals($version, $cb->getStatic('_version'));
$this->assertRegexp('/^[1-9]\d*\.\d+\.\d+(-([a-z]+\.[1-9]\d*|dev))?$/', $version);
}
/**
* Tests setToken
*/
public function testSetToken()
{
$cb = new CodebirdT();
$cb->setToken('123', '456');
$this->assertEquals('123', $cb->get('_oauth_token'));
$this->assertEquals('456', $cb->get('_oauth_token_secret'));
}
/**
* Tests logout
*/
public function testLogout()
{
$cb = new CodebirdT();
$cb->setToken('123', '456');
$cb->logout();
$this->assertNull($cb->get('_oauth_token'));
$this->assertNull($cb->get('_oauth_token_secret'));
}
/**
* Tests setUseCurl
*/
public function testSetUseCurl()
{
$cb = new CodebirdT();
$cb->setUseCurl(true);
$this->assertTrue($cb->get('_use_curl'));
$cb->setUseCurl(false);
$this->assertFalse($cb->get('_use_curl'));
$cb->setUseCurl('123');
$this->assertTrue($cb->get('_use_curl'));
}
/**
* Tests setTimeout
*/
public function testSetTimeout()
{
$cb = new CodebirdT();
$cb->setTimeout(123);
$this->assertEquals(123, $cb->get('_timeouts')['request']);
$cb->setTimeout(0);
$this->assertEquals(0, $cb->get('_timeouts')['request']);
$cb->setTimeout(-123);
$this->assertEquals(0, $cb->get('_timeouts')['request']);
}
/**
* Tests setConnectionTimeout
*/
public function testSetConnectionTimeout()
{
$cb = new CodebirdT();
$cb->setConnectionTimeout(123);
$this->assertEquals(123, $cb->get('_timeouts')['connect']);
$cb->setConnectionTimeout(0);
$this->assertEquals(0, $cb->get('_timeouts')['connect']);
$cb->setConnectionTimeout(-123);
$this->assertEquals(0, $cb->get('_timeouts')['connect']);
}
/**
* Tests setConnectionTimeout
*/
public function testSetRemoteDownloadTimeout()
{
$cb = new CodebirdT();
$cb->setRemoteDownloadTimeout(123);
$this->assertEquals(123, $cb->get('_timeouts')['remote']);
$cb->setRemoteDownloadTimeout(0);
$this->assertEquals(0, $cb->get('_timeouts')['remote']);
$cb->setRemoteDownloadTimeout(-123);
$this->assertEquals(0, $cb->get('_timeouts')['remote']);
}
/**
* Tests setReturnFormat
*/
public function testSetReturnFormat()
{
$cb = new CodebirdT();
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_JSON);
$this->assertEquals($cb->get('_return_format'), CODEBIRD_RETURNFORMAT_JSON);
}
/**
* Tests setProxy
*/
public function testSetProxy()
{
$cb = new CodebirdT();
$cb->setProxy('127.0.0.1', '8888');
$this->assertEquals('127.0.0.1', $cb->get('_proxy')['host']);
$this->assertEquals('8888', $cb->get('_proxy')['port']);
$this->assertEquals(CURLPROXY_HTTP, $cb->get('_proxy')['type']);
$cb->setProxy('127.0.0.1', '8888', CURLPROXY_SOCKS5);
$this->assertEquals('127.0.0.1', $cb->get('_proxy')['host']);
$this->assertEquals('8888', $cb->get('_proxy')['port']);
$this->assertEquals(CURLPROXY_SOCKS5, $cb->get('_proxy')['type']);
}
/**
* Tests setProxy
* @expectedException \Exception
* @expectedExceptionMessage Invalid proxy type specified.
*/
public function testSetProxy2()
{
$cb = new CodebirdT();
$cb->setProxy('127.0.0.1', '8888', 1);
}
/**
* Tests setProxyAuthentication
*/
public function testSetProxyAuthentication()
{
$cb = new CodebirdT();
$cb->setProxyAuthentication('ABCDEF');
$this->assertEquals('ABCDEF', $cb->get('_proxy')['authentication']);
}
/**
* Tests setStreamingCallback
*/
public function testSetStreamingCallback1()
{
$callback = ['\Codebird\CodebirdT', 'streamingCallbackTest'];
$cb = new CodebirdT();
$cb->setStreamingCallback($callback);
$this->assertSame(
array_diff($callback, $cb->get('_streaming_callback')),
array_diff($cb->get('_streaming_callback'), $callback)
);
}
/**
* Tests setStreamingCallback
* @expectedException \Exception
* @expectedExceptionMessage This is not a proper callback.
*/
public function testSetStreamingCallback2()
{
$cb = new CodebirdT();
$cb->setStreamingCallback(['\Codebird\CodebirdTX', 'somewhere']);
}
/**
* Tests getApiMethods
*/
public function testGetApiMethods()
{
$cb = new CodebirdT();
$methods = $cb->getApiMethods();
$this->assertArrayHasKey('GET', $cb->getStatic('_api_methods'));
$this->assertArrayHasKey('POST', $cb->getStatic('_api_methods'));
$this->assertArrayHasKey('PUT', $cb->getStatic('_api_methods'));
$this->assertArrayHasKey('DELETE', $cb->getStatic('_api_methods'));
$this->assertEquals($methods, $cb->getStatic('_api_methods'));
}
/**
* Tests hasProxy
*/
public function testHasProxy()
{
$cb = new CodebirdT();
$this->assertFalse($cb->call('_hasProxy'));
$cb->setProxy('127.0.0.1', '8888');
$this->assertTrue($cb->call('_hasProxy'));
}
/**
* Tests getProxyHost
*/
public function testGetProxyHost()
{
$cb = new CodebirdT();
$this->assertNull($cb->call('_getProxyHost'));
$cb->setProxy('127.0.0.1', '8888');
$this->assertEquals('127.0.0.1', $cb->call('_getProxyHost'));
}
/**
* Tests getProxyPort
*/
public function testGetProxyPort()
{
$cb = new CodebirdT();
$this->assertNull($cb->call('_getProxyPort'));
$cb->setProxy('127.0.0.1', '8888');
$this->assertEquals('8888', $cb->call('_getProxyPort'));
}
}

View File

@ -0,0 +1,166 @@
<?php
namespace Codebird;
require_once ('test/codebirdm.php');
/**
* A Twitter library in PHP.
*
* @package codebird-test
* @author Jublo Limited <support@jublo.net>
* @copyright 2010-2018 Jublo Limited <support@jublo.net>
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* @link https://github.com/jublonet/codebird-php
*/
/**
* OAuth signing tests
*
* @package codebird-test
*/
class Signing_Test extends \PHPUnit\Framework\TestCase
{
/**
* Initialise Codebird class
*
* @return \Codebird\Codebird The Codebird class
*/
protected function getCB()
{
Codebird::setConsumerKey('123', '456');
$cb = new CodebirdM();
return $cb;
}
/**
* Tests _url
*/
public function testUrl()
{
$cb = $this->getCB();
// string
$this->assertEquals(
'q%20%2B%20b%21%22%C2%A7%24%25%26%2F%28%29%3D%3F%23%2A13%2C3%C3%A4.',
$cb->call('_url', ['q + b!"§$%&/()=?#*13,3ä.'])
);
// array
$this->assertEquals(
[
'q%20%2B%20b%21%22%C2%A7%24%25%26%2F%28%29%3D%3F%23%2A13%2C3%C3%A4.',
'test123'
],
$cb->call('_url', [[
'q + b!"§$%&/()=?#*13,3ä.',
'test123'
]])
);
}
/**
* Tests _sha1
*/
public function testSha1()
{
$cb = $this->getCB();
$this->assertEquals(
'ydAlpYjrGHU7psDQ9HPgHTcwEuw=',
$cb->call('_sha1', ['q + b!"§$%&/()=?#*13,3ä.'])
);
// with access token secret
$cb->setToken('678', '789');
$this->assertEquals(
'CtivZhAHiX49ZMUuHXtKabLAuo0=',
$cb->call('_sha1', ['q + b!"§$%&/()=?#*13,3ä.'])
);
}
/**
* Tests _nonce
*/
public function testNonce1()
{
$cb = $this->getCB();
// default length
$this->assertEquals(
'4247c524',
$cb->call('_nonce', [])
);
// custom length
$this->assertEquals(
'4247c5248da',
$cb->call('_nonce', [11])
);
}
/**
* Tests _nonce
* @expectedException \Exception
* @expectedExceptionMessage Invalid nonce length.
*/
public function testNonce2()
{
$cb = $this->getCB();
// invalid length
$cb->call('_nonce', [0]);
}
/**
* Tests _getSignature
*/
public function testGetSignature()
{
$cb = $this->getCB();
$base_params = [
'oauth_consumer_key' => '123',
'oauth_nonce' => '12345678',
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => '1400000000',
'oauth_token' => '567',
'oauth_version' => '1.0',
'q' => 'Test search.'
];
$this->assertEquals(
'ZON/m9bHvciPdtyK9BlokjeiW4M=',
$cb->call('_getSignature', ['GET', 'search/tweets', $base_params])
);
}
/**
* Tests _sign
* @expectedException \Exception
* @expectedExceptionMessage To generate a signature, the consumer key must be set.
*/
public function testSign1()
{
$cb = $this->getCB();
$cb->setConsumerKey(null, null);
$params = ['q' => 'Test search.'];
$cb->call('_sign', ['GET', 'search/tweets', $params]);
}
/**
* Tests _sign
*/
public function testSign2()
{
$cb = $this->getCB();
$params = ['q' => 'Test search.'];
$this->assertEquals(
'OAuth oauth_consumer_key="123", oauth_nonce="4247c524", oauth_signature'
. '="lOLNd5l6cGB9kWACxWLNKJwSD%2FI%3D", oauth_signature_method="HMAC-SHA'
. '1", oauth_timestamp="1412345678", oauth_version="1.0"',
$cb->call('_sign', ['GET', 'search/tweets', $params])
);
// with oauth token
$cb->setToken('678', '789');
$this->assertEquals(
'OAuth oauth_consumer_key="123", oauth_nonce="4247c524", oauth_signature'
. '="XzegzFKEqs2PpUMym5T%2BwhEmTz4%3D", oauth_signature_method="HMAC-SHA'
. '1", oauth_timestamp="1412345678", oauth_token="678", oauth_version="1.0"',
$cb->call('_sign', ['GET', 'search/tweets', $params])
);
}
}

View File

@ -0,0 +1,31 @@
<?php
namespace Codebird;
require_once ('test/codebirdt.php');
/**
* A Twitter library in PHP.
*
* @package codebird-test
* @author Jublo Limited <support@jublo.net>
* @copyright 2010-2018 Jublo Limited <support@jublo.net>
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* @link https://github.com/jublonet/codebird-php
*/
/**
* Singleton tests
*
* @package codebird-test
*/
class Singleton_Test extends \PHPUnit\Framework\TestCase
{
/**
* Tests getInstance
*/
public function testGetInstance()
{
$cb = CodebirdT::getInstance();
$this->assertInstanceOf('\Codebird\Codebird', $cb);
}
}