Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Initial import.

  • Loading branch information...
commit 7997f2b9956413c961b17e5f5d11712f6e00dbab 1 parent 34ca5ea
@mptre authored
View
186 README.textile
@@ -1,15 +1,185 @@
-h2. SoundCloud PHP API Wrapper
+h1. SoundCloud PHP API wrapper
-h3. Introduction
+A minimalistic API wrapper for "SoundCloud":http://soundcloud.com/ written in PHP.
+Inspired by "tcdent":http://github.com/tcdent "Twitter API class":http://github.com/tcdent/php-twitter/.
-API Wrapper for SoundCloud written in PHP with support for authication using OAuth (1.0a). Based on Andy Smiths "OAuth library":http://oauth.googlecode.com/svn/code/php, inspired by Abraham Williams "twitteroauth":http://github.com/abraham/twitteroauth library and a big applause for "Hugo Wetterberg":http://github.com/hugowetterberg for helping me out big time!
+So far the supported and tested methods are comments, users and tracks.
+All methods will be supported in the near future.
-There's a simple "demo application":http://soundcloud.qvister.se available which should show how to do the "OAuth dance" with this wrapper. The code for the demo application is included in the repository. If you're new to OAuth I'd recommend to have a look at the "official docs":http://oauth.net.
+h2. Example of usage
-The old wrapper (i.e username + password method) is by now deprecated but still available in the repository for various reasons.
+All responses are XML-formated. I would recommend SimpleXMLElement to parse them.
-Got questions or need support? Don't hesitate to contact me!
+h3. Users
-h3. Getting started
+<pre>
+<code>
+<?php
+$soundcloud = new Soundcloud('username', 'password');
-See the wiki page "Getting started":http://wiki.github.com/mptre/php-soundcloud/getting-started for more information.
+// Get the authenticated user.
+$soundcloud->me->basic();
+
+// Get the authenticated user comments.
+$soundcloud->me->comments();
+
+// Get the authenticated user contacts.
+$soundcloud->me->contacts();
+
+// Add a new contact.
+$soundcloud->me->contacts(
+ array(
+ 'contact_id' => 1,
+ 'put' => TRUE
+ )
+);
+
+// Delete a contact.
+$soundcloud->me->contacts(
+ array(
+ 'contact_id' => 1,
+ 'delete' => TRUE
+ )
+);
+
+// Get the authenticated user tracks.
+$soundcloud->me->tracks();
+
+// Get the authenticated user fans.
+$soundcloud->me->fans();
+
+// Get the authenticated user favorites.
+$soundcloud->me->favorites();
+
+// Add a new favorite track.
+$soundcloud->me->favorites(
+ array(
+ 'track_id' => 1,
+ 'put' => TRUE
+ )
+);
+
+// Delete a favorite track.
+$soundcloud->me->favorites(
+ array(
+ 'track_id' => 1,
+ 'delete' => TRUE
+ )
+);
+?>
+</code>
+</pre>
+Note that you can perform most of these actions with other users.
+This is done by replacing "me" with users and simply add the key "user_id" to the array of arguments.
+Here's an example.
+<pre>
+<code>
+<?php
+$soundcloud->users->tracks(
+ array(
+ 'user_id' => 1
+ )
+);
+?>
+</code>
+</pre>
+
+h3. Tracks
+
+<pre>
+<code>
+<?php
+$soundcloud = new Soundcloud('username', 'password');
+
+// Search for tracks.
+$soundcloud->tracks->basic(
+ array(
+ 'query' => array(
+ 'filter' => 'downloadable',
+ 'orderby' => 'hotness'
+ )
+ )
+);
+
+// Get the given track.
+$soundcloud->tracks->basic(
+ array(
+ 'track_id' => 1
+ )
+);
+
+// Upload a new track.
+$soundcloud->tracks->basic(
+ array(
+ 'post' => TRUE,
+ 'fields' => array(
+ 'track[title]' => 'API calling',
+ 'track[asset_data]' => '@my_track.mp3'
+ )
+ )
+);
+
+// Update a track.
+$soundcloud->tracks->basic(
+ array(
+ 'put' => TRUE,
+ 'track_id' => 1,
+ 'fields' => array(
+ 'track[downloadable]' => 'true'
+ )
+ )
+);
+
+// Delete a track.
+$soundcloud->tracks->basic(
+ array(
+ 'delete' => TRUE,
+ 'track_id' => 1
+ )
+);
+
+// Get a track comments.
+$soundcloud->tracks->comments(
+ array(
+ 'track_id' => 1
+ )
+);
+
+// Post a new comment to the given track.
+$soundcloud->tracks->comments(
+ array(
+ 'post' => TRUE,
+ 'track_id' => 1,
+ 'fields' => array(
+ 'comment[body]' => 'Awesome track!'
+ )
+ )
+);
+?>
+</code>
+</pre>
+
+h3. Comments
+
+<pre>
+<code>
+<?php
+$soundcloud = new Soundcloud('username', 'password');
+
+// Get the given comment.
+$soundcloud->comments->basic(
+ array(
+ 'comment_id' => 1
+ )
+);
+
+// Delete the given comment.
+$soundcloud->comments->basic(
+ array(
+ 'delete' => TRUE,
+ 'comment_id' => 1
+ )
+);
+?>
+</code>
+</pre>
View
19 Rakefile
@@ -1,19 +0,0 @@
-FILES = [
- {:path => 'soundcloud.php', :search => /(\@version\s)([0-9.]+)/, :replace => "\\1%s"},
- {:path => 'soundcloud.php', :search => /(const VERSION\s=\s\')([0-9.]+)/, :replace => "\\1%s"},
-]
-
-namespace :version do
- task :bump, :version do |t, args|
- FILES.each do |file|
- contents = File.read(file[:path]).gsub(file[:search], file[:replace] % [args[:version]])
- File.open(file[:path], 'w') { |f| f.write contents }
- end
-
- print "Release message? "
- message = STDIN.gets.chomp
-
- exec "git commit -am 'Bumped version.'"
- exec "git tag -a v#{args[:version]} -m '#{message}'"
- end
-end
View
169 demo/assets/css/style.css
@@ -1,169 +0,0 @@
-html,body {
-background: #fff url(../images/body.png) repeat-x top left;
-font: normal 100% "Lucida Grande", Helvetica, Arial, sans-serif;
-color: #333;
-}
-a {
-color: #06c;
-text-decoration: none;
-}
-a:hover {
-color: #f60;
-}
-h2 {
-font-size: 1.5em;
-margin: 0 0 7px 0;
-}
-
-/* Begin content
----------------------------------------------- */
-#content {
-background: #fff;
-height: auto;
-width: 320px;
-margin: 28px auto 0 auto;
-padding: 20px;
-font-size: .75em;
-border: 1px solid #ccc;
--moz-border-radius-bottomright: 21px;
--webkit-border-bottom-right-radius: 21px;
--moz-border-radius-topleft: 21px;
--webkit-border-top-left-radius: 21px;
-}
-#content a.logout {
-float: right;
-position: relative;
-top: -18px;
-left: 15px;
-}
-#content form label {
-margin: 0 0 2px 0;
-display: block;
-cursor: pointer;
-}
-#content input.text {
-background: #fff;
-height: 20px;
-width: 316px;
-padding: 2px 2px 0 2px;
-cursor: pointer;
-border: 1px solid #ccc;
--moz-border-radius-topleft: 7px;
--webkit-border-top-left-radius: 7px;
--moz-border-radius-bottomright: 7px;
--webkit-border-bottom-right-radius: 7px;
-}
-#content input.submit {
-background: #fff url(../images/a.png) repeat-x top left;
-height: 19px;
-width: 65px;
-margin: 10px 0 0 0;
-text-align: center;
-line-height: 19px;
-color: #333;
-border: 1px solid #ccc;
--moz-border-radius: 10px;
-cursor: pointer;
-}
-#content input.submit:hover {
-background-position: bottom left;
-color: #06c;
-}
-#content p {
-margin: 0 0 7px 0;
-}
-/* End content
----------------------------------------------- */
-
-/* Begin header
----------------------------------------------- */
-#header {
-margin: 0 0 20px 0;
-border-bottom: 1px solid #ccc;
-}
-#header h1 {
-background: #fff url(../images/logo.png) no-repeat top center;
-width: 320px;
-padding: 138px 0 15px 0;
-text-align: center;
-font-size: 1.75em;
-color: #06c;
-}
-/* End header
----------------------------------------------- */
-
-/* Begin profile
----------------------------------------------- */
-#profile {
-margin: 0 0 20px 0;
-}
-#profile h2 {
-margin: 0;
-font-size: 2em;
-}
-#profile div.left {
-height: 75px;
-width: 75px;
-float: left;
-display: inline;
-}
-#profile div.left div.avatar {
-background: transparent url(../images/avatar.png) no-repeat top left;
-height: 75px;
-width: 75px;
-margin: -85px 0 0 0;
-position: absolute;
-}
-#profile div.right {
-height: 75px;
-width: 235px;
-float: right;
-display: inline;
-}
-/* End profile
----------------------------------------------- */
-
-/* Begin generic
----------------------------------------------- */
-.button {
-background: #fff url(../images/a.png) repeat-x top left;
-height: 19px;
-width: 320px;
-text-align: center;
-line-height: 19px;
-color: #333;
-border: 1px solid #ccc;
-display: block;
--moz-border-radius: 10px;
--webkit-border-radius: 10px;
-}
-.button:hover {
-background-position: bottom left;
-color: #06c;
-}
-.clear {
-clear: both;
-}
-.center {
-text-align: center;
-}
-#message {
-background: #ffeac8;
-margin: 20px 0 0 0;
-padding: 5px;
-color: #ff6600;
-border: 1px solid #ff6600;
--moz-border-radius-topleft: 7px;
--moz-border-radius-bottomright: 7px;
--webkit-border-top-left-radius: 7px;
--webkit-border-bottom-right-radius: 7px;
-}
-#message a {
-color: #ff6600;
-text-decoration: underline;
-}
-#message p {
-margin: 0;
-}
-/* End generic
----------------------------------------------- */
View
BIN  demo/assets/images/a.png
Deleted file not rendered
View
BIN  demo/assets/images/avatar.png
Deleted file not rendered
View
BIN  demo/assets/images/body.png
Deleted file not rendered
View
BIN  demo/assets/images/logo.png
Deleted file not rendered
View
187 demo/index.php
@@ -1,187 +0,0 @@
-<?php
-require_once 'oauth.php';
-require_once 'soundcloud.php';
-
-session_start();
-
-// Clear the session i.e delete all stored tokens.
-if (isset($_GET['logout'])) {
- session_destroy();
-}
-
-// Change these four variables, note the that temporary path must be writable by the server.
-$consumer_key = 'your-consumer-key';
-$consumer_secret = 'your-consumer-secret';
-$callback_url = 'your-callback-url';
-$tmp_path = '/absolute/path/to/directory/where/tracks/are/saved/temporary/';
-
-// Variables used for verifying the status of the "OAuth dance".
-$oauth_token = (isset($_GET['oauth_verifier']))
- ? $_GET['oauth_verifier']
- : ((isset($_SESSION['oauth_access_token'])) ? $_SESSION['oauth_access_token'] : NULL);
-$oauth_request_token = (isset($_SESSION['oauth_request_token']))
- ? $_SESSION['oauth_request_token']
- : NULL;
-$oauth_request_token_secret = (isset($_SESSION['oauth_request_token_secret']))
- ? $_SESSION['oauth_request_token_secret']
- : NULL;
-
-if (isset($oauth_token) && isset($oauth_request_token) && isset($oauth_request_token_secret)) {
- // Retreive access tokens if missing.
- if (!isset($_SESSION['oauth_access_token']) && !isset($_SESSION['oauth_access_token_secret'])) {
- $soundcloud = new Soundcloud(
- $consumer_key,
- $consumer_secret,
- $_SESSION['oauth_request_token'],
- $_SESSION['oauth_request_token_secret']
- );
- $token = $soundcloud->get_access_token($oauth_token);
- $_SESSION['oauth_access_token'] = $token['oauth_token'];
- $_SESSION['oauth_access_token_secret'] = $token['oauth_token_secret'];
- }
-
- // Construct a fully authicated connection with SoundCloud.
- $soundcloud = new Soundcloud(
- $consumer_key,
- $consumer_secret,
- $_SESSION['oauth_access_token'],
- $_SESSION['oauth_access_token_secret']
- );
-
- // Get basic info about the authicated visitor.
- $me = $soundcloud->request('me');
- $me = new SimpleXMLElement($me);
- $me = get_object_vars($me);
-
- // If a track is submitted.
- if (isset($_POST['submit'])) {
- // We have to make sure it's a valid and supported format by SoundCloud.
- // Note that you also can include artwork for your tracks. Use the same
- // procedure as for the tracks. PNG, JPG, GIF allowed and a max size of 5MB.
- // The artwork field is called track[artwork_data].
- $mimes = array(
- 'aac' => 'video/mp4',
- 'aiff' => 'audio/x-aiff',
- 'flac' => 'audio/flac',
- 'mp3' => 'audio/mpeg',
- 'ogg' => 'audio/ogg',
- 'wav' => 'audio/x-wav'
- );
- $extension = explode('.', $_FILES['file']['name']);
- $extension = (isset($extension[count($extension) - 1]))
- ? $extension[count($extension) - 1]
- : NULL;
- $mime = (isset($mimes[$extension])) ? $mimes[$extension] : NULL;
-
- if (isset($mime)) {
- $tmp_file = $tmp_path . $_FILES['file']['name'];
-
- // Store the track temporary.
- if (move_uploaded_file($_FILES['file']['tmp_name'], $tmp_file)) {
- $post_data = array(
- 'track[title]' => stripslashes($_POST['title']),
- 'track[asset_data]' => realpath($tmp_file),
- 'track[sharing]' => 'private'
- );
-
- if ($response = $soundcloud->upload_track($post_data, $mime)) {
- $response = new SimpleXMLElement($response);
- $response = get_object_vars($response);
- $message = 'Success! <a href="' . $response['permalink-url'] . '">Your track</a> has been uploaded!';
-
- // Delete the temporary file.
- unlink(realpath($tmp_file));
- } else {
- $message = 'Something went wrong while talking to SoundCloud, please try again.';
- }
- } else {
- $message = 'Couldn\'t move file, make sure the temporary path is writable by the server.';
- }
- } else {
- $message = 'SoundCloud support .mp3, .aiff, .wav, .flac, .aac, and .ogg files. Please select a different file.';
- }
- }
-} else {
- // This is the first step in the "OAuth dance" where we ask the visitior to authicate himself.
- $soundcloud = new Soundcloud($consumer_key, $consumer_secret);
- $token = $soundcloud->get_request_token($callback_url);
-
- $_SESSION['oauth_request_token'] = $token['oauth_token'];
- $_SESSION['oauth_request_token_secret'] = $token['oauth_token_secret'];
-
- $login = $soundcloud->get_authorize_url($token['oauth_token']);
-}
-?>
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
-<head>
- <title>SoundCloud PHP API Wrapper</title>
- <meta name="author" content="Anton Lindqvist" />
- <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
- <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.7.0/build/reset/reset-min.css" />
- <link rel="stylesheet" type="text/css" href="assets/css/style.css" />
-</head>
-<body>
- <div id="wrapper">
- <div id="content">
- <?php if (isset($me)): ?>
- <a class="logout" href="?logout=true">logout</a>
- <?php endif; ?>
- <div id="header">
- <h1>SoundCloud PHP API Wrapper</h1>
- </div>
- <?php if (isset($login)): ?>
- <h2>What is this?</h2>
- <p>This is a basic demo of the <a href="http://github.com/mptre/php-soundcloud/" rel="external">SoundCloud PHP API Wrapper</a> which lets you login to your SoundCloud account using <a href="http://oauth.net/" rel="external">OAuth</a>.</p>
- <p>Once logged in the user can view his profile and upload a new track to his account. The track will be kept private by default.</p>
- <p>Note that this demo neither save your login credentials or account information.</p>
- <p>For further reference see the documentation or take a look at code for this demo over at <a href="#" rel="external">GitHub</a>.</p>
- <p>The demo and API Wrapper is developed by <a href="http://qvister.se" rel="external">Anton Lindqvist</a>. And a big applause for <a href="http://github.com/hugowetterberg">Hugo Wetterberg</a> who help me out big time!</p>
- <h2>How to start?</h2>
- <p>
- <a class="button" href="<?php echo $login; ?>">login with your SoundCloud account</a>
- </p>
- <?php elseif (isset($me)): ?>
- <h2>Your profile</h2>
- <div id="profile">
- <div class="left">
- <p>
- <img src="<?php echo $me['avatar-url']; ?>" width="75" height="75" alt="" />
- <div class="avatar"></div>
- </p>
- </div>
- <div class="right">
- <h2>
- <a href="<?php echo $me['permalink-url']; ?>"><?php echo $me['permalink']; ?></a>
- </h2>
- <p><?php echo $me['full-name'] ?>, <?php echo $me['city']; ?>, <?php echo $me['country']; ?></p>
- <p>You have <?php echo $me['track-count']; ?> <?php echo ($me['track-count'] == 1) ? 'track' : 'tracks'; ?>.</p>
- </div>
- <div class="clear"></div>
- </div>
- <h2>Upload a new track</h2>
- <form action="" method="post" enctype="multipart/form-data">
- <p>
- <label for="title">Track title</label>
- <input class="text" type="text" name="title" id="title" />
- </p>
- <p>
- <label for="file">File</label>
- <input class="file" type="file" name="file" value="" id="file" />
- </p>
- <p class="center">
- <input class="submit" type="submit" name="submit" value="Upload" id="submit" />
- </p>
- </form>
- <?php if (isset($message)): ?>
- <div id="message">
- <p><?php echo $message; ?></p>
- </div>
- <?php endif; ?>
- <?php endif; ?>
- </div>
- </div>
-</body>
-</html>
View
185 deprecated/README.textile
@@ -1,185 +0,0 @@
-h1. SoundCloud PHP API wrapper
-
-A minimalistic API wrapper for "SoundCloud":http://soundcloud.com/ written in PHP.
-Inspired by "tcdent":http://github.com/tcdent "Twitter API class":http://github.com/tcdent/php-twitter/.
-
-So far the supported and tested methods are comments, users and tracks.
-All methods will be supported in the near future.
-
-h2. Example of usage
-
-All responses are XML-formated. I would recommend SimpleXMLElement to parse them.
-
-h3. Users
-
-<pre>
-<code>
-<?php
-$soundcloud = new Soundcloud('username', 'password');
-
-// Get the authenticated user.
-$soundcloud->me->basic();
-
-// Get the authenticated user comments.
-$soundcloud->me->comments();
-
-// Get the authenticated user contacts.
-$soundcloud->me->contacts();
-
-// Add a new contact.
-$soundcloud->me->contacts(
- array(
- 'contact_id' => 1,
- 'put' => TRUE
- )
-);
-
-// Delete a contact.
-$soundcloud->me->contacts(
- array(
- 'contact_id' => 1,
- 'delete' => TRUE
- )
-);
-
-// Get the authenticated user tracks.
-$soundcloud->me->tracks();
-
-// Get the authenticated user fans.
-$soundcloud->me->fans();
-
-// Get the authenticated user favorites.
-$soundcloud->me->favorites();
-
-// Add a new favorite track.
-$soundcloud->me->favorites(
- array(
- 'track_id' => 1,
- 'put' => TRUE
- )
-);
-
-// Delete a favorite track.
-$soundcloud->me->favorites(
- array(
- 'track_id' => 1,
- 'delete' => TRUE
- )
-);
-?>
-</code>
-</pre>
-Note that you can perform most of these actions with other users.
-This is done by replacing "me" with users and simply add the key "user_id" to the array of arguments.
-Here's an example.
-<pre>
-<code>
-<?php
-$soundcloud->users->tracks(
- array(
- 'user_id' => 1
- )
-);
-?>
-</code>
-</pre>
-
-h3. Tracks
-
-<pre>
-<code>
-<?php
-$soundcloud = new Soundcloud('username', 'password');
-
-// Search for tracks.
-$soundcloud->tracks->basic(
- array(
- 'query' => array(
- 'filter' => 'downloadable',
- 'orderby' => 'hotness'
- )
- )
-);
-
-// Get the given track.
-$soundcloud->tracks->basic(
- array(
- 'track_id' => 1
- )
-);
-
-// Upload a new track.
-$soundcloud->tracks->basic(
- array(
- 'post' => TRUE,
- 'fields' => array(
- 'track[title]' => 'API calling',
- 'track[asset_data]' => '@my_track.mp3'
- )
- )
-);
-
-// Update a track.
-$soundcloud->tracks->basic(
- array(
- 'put' => TRUE,
- 'track_id' => 1,
- 'fields' => array(
- 'track[downloadable]' => 'true'
- )
- )
-);
-
-// Delete a track.
-$soundcloud->tracks->basic(
- array(
- 'delete' => TRUE,
- 'track_id' => 1
- )
-);
-
-// Get a track comments.
-$soundcloud->tracks->comments(
- array(
- 'track_id' => 1
- )
-);
-
-// Post a new comment to the given track.
-$soundcloud->tracks->comments(
- array(
- 'post' => TRUE,
- 'track_id' => 1,
- 'fields' => array(
- 'comment[body]' => 'Awesome track!'
- )
- )
-);
-?>
-</code>
-</pre>
-
-h3. Comments
-
-<pre>
-<code>
-<?php
-$soundcloud = new Soundcloud('username', 'password');
-
-// Get the given comment.
-$soundcloud->comments->basic(
- array(
- 'comment_id' => 1
- )
-);
-
-// Delete the given comment.
-$soundcloud->comments->basic(
- array(
- 'delete' => TRUE,
- 'comment_id' => 1
- )
-);
-?>
-</code>
-</pre>
View
112 deprecated/soundcloud.php
@@ -1,112 +0,0 @@
-<?php
-/**
- * A minimalistic API wrapper for SoundCloud written in PHP.
- * For further reference and example of usage see link below.
- *
- * @link http://github.com/mptre/php-soundcloud/
- * @author Anton Lindqvist <anton@qvister.se>
- * @version 0.1.1
- */
-
-class Soundcloud {
- private $key;
- private $me;
- private $username;
- private $password;
- private $url;
-
- function __construct($username, $password, $key = NULL) {
- $this->username = $username;
- $this->password = $password;
- $this->key = $key;
- $this->me = ($key == 'me') ? TRUE : FALSE;
- $this->url = 'http://api.sandbox-soundcloud.com';
- }
-
- function __get($key) {
- return new Soundcloud($this->username, $this->password, $key);
- }
-
- function __call($method, $args) {
- $args = (count($args) && is_array($args)) ? $args[0] : array();
- $options = array(
- CURLOPT_RETURNTRANSFER => 1,
- CURLOPT_URL => sprintf('%s/%s/', $this->url, $this->key),
- CURLOPT_USERPWD => sprintf('%s:%s', $this->username, $this->password)
- );
-
- // Handle me and users method.
- if (!in_array($this->key, array('tracks'))) {
- $options[CURLOPT_URL] .= (isset($args['user_id']))
- ? $args['user_id'] .'/'
- : NULL;
- $options[CURLOPT_URL] .= ($method != 'basic')
- ? $method .'/'
- : NULL;
- }
-
- // Handle tracks search method.
- if (isset($args['query'])) {
- if (is_array($args['query'])) {
- $options[CURLOPT_URL] = preg_replace(
- '/\/$/',
- '?',
- $options[CURLOPT_URL]
- );
- $options[CURLOPT_URL] .= http_build_query($args['query']);
- }
- }
-
- // Handle POST, PUT and DELETE requests.
- foreach ($args as $key => $val) {
- if (in_array($key, array('delete', 'post', 'put'))) {
- if ($key == 'post') {
- $options[CURLOPT_POST] = 1;
- } else {
- $options[CURLOPT_CUSTOMREQUEST] = strtoupper($key);
- }
-
- $options[CURLOPT_POSTFIELDS] = (isset($args['fields']))
- ? $args['fields']
- : '';
- } elseif (preg_match('/[^[user]]{0}_id$/', $key)) {
- $options[CURLOPT_URL] .= $args[$key] .'/';
- }
- }
-
- if (in_array($this->key, array('tracks')) && $method != 'basic') {
- $options[CURLOPT_URL] .= $method;
- }
-
- $ch = curl_init();
- curl_setopt_array($ch, $options);
- $data = curl_exec($ch);
- $meta = curl_getinfo($ch);
-
- if (in_array($meta['http_code'], array(200, 201, 303))) {
- return (strlen($data) <= 1) ? TRUE : $data;
- } else {
- // Throw error.
- throw new SoundcloudException(
- sprintf(
- 'Response code: %d from %s',
- $meta['http_code'],
- $options[CURLOPT_URL]
- )
- );
- }
- }
-
- function __destruct() {
- $this->username = NULL;
- $this->password = NULL;
- $this->key = NULL;
- $this->me = NULL;
- $this->url = NULL;
- }
-}
-
-class SoundcloudException extends Exception {
- // Kthxbye.
-}
-?>
View
768 oauth.php
@@ -1,768 +0,0 @@
-<?php
-// vim: foldmethod=marker
-
-/* Generic exception class
- */
-class OAuthException extends Exception {/*{{{*/
- // pass
-}/*}}}*/
-
-class OAuthConsumer {/*{{{*/
- public $key;
- public $secret;
-
- function __construct($key, $secret, $callback_url=NULL) {/*{{{*/
- $this->key = $key;
- $this->secret = $secret;
- $this->callback_url = $callback_url;
- }/*}}}*/
-
- function __toString() {/*{{{*/
- return "OAuthConsumer[key=$this->key,secret=$this->secret]";
- }/*}}}*/
-}/*}}}*/
-
-class OAuthToken {/*{{{*/
- // access tokens and request tokens
- public $key;
- public $secret;
-
- /**
- * key = the token
- * secret = the token secret
- */
- function __construct($key, $secret) {/*{{{*/
- $this->key = $key;
- $this->secret = $secret;
- }/*}}}*/
-
- /**
- * generates the basic string serialization of a token that a server
- * would respond to request_token and access_token calls with
- */
- function to_string() {/*{{{*/
- return "oauth_token=" . OAuthUtil::urlencode_rfc3986($this->key) .
- "&oauth_token_secret=" . OAuthUtil::urlencode_rfc3986($this->secret);
- }/*}}}*/
-
- function __toString() {/*{{{*/
- return $this->to_string();
- }/*}}}*/
-}/*}}}*/
-
-class OAuthSignatureMethod {/*{{{*/
- public function check_signature(&$request, $consumer, $token, $signature) {
- $built = $this->build_signature($request, $consumer, $token);
- return $built == $signature;
- }
-}/*}}}*/
-
-class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {/*{{{*/
- function get_name() {/*{{{*/
- return "HMAC-SHA1";
- }/*}}}*/
-
- public function build_signature($request, $consumer, $token) {/*{{{*/
- $base_string = $request->get_signature_base_string();
- $request->base_string = $base_string;
-
- $key_parts = array(
- $consumer->secret,
- ($token) ? $token->secret : ""
- );
-
- $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
- $key = implode('&', $key_parts);
-
- return base64_encode( hash_hmac('sha1', $base_string, $key, true));
- }/*}}}*/
-}/*}}}*/
-
-class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {/*{{{*/
- public function get_name() {/*{{{*/
- return "PLAINTEXT";
- }/*}}}*/
-
- public function build_signature($request, $consumer, $token) {/*{{{*/
- $sig = array(
- OAuthUtil::urlencode_rfc3986($consumer->secret)
- );
-
- if ($token) {
- array_push($sig, OAuthUtil::urlencode_rfc3986($token->secret));
- } else {
- array_push($sig, '');
- }
-
- $raw = implode("&", $sig);
- // for debug purposes
- $request->base_string = $raw;
-
- return OAuthUtil::urlencode_rfc3986($raw);
- }/*}}}*/
-}/*}}}*/
-
-class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {/*{{{*/
- public function get_name() {/*{{{*/
- return "RSA-SHA1";
- }/*}}}*/
-
- protected function fetch_public_cert(&$request) {/*{{{*/
- // not implemented yet, ideas are:
- // (1) do a lookup in a table of trusted certs keyed off of consumer
- // (2) fetch via http using a url provided by the requester
- // (3) some sort of specific discovery code based on request
- //
- // either way should return a string representation of the certificate
- throw Exception("fetch_public_cert not implemented");
- }/*}}}*/
-
- protected function fetch_private_cert(&$request) {/*{{{*/
- // not implemented yet, ideas are:
- // (1) do a lookup in a table of trusted certs keyed off of consumer
- //
- // either way should return a string representation of the certificate
- throw Exception("fetch_private_cert not implemented");
- }/*}}}*/
-
- public function build_signature(&$request, $consumer, $token) {/*{{{*/
- $base_string = $request->get_signature_base_string();
- $request->base_string = $base_string;
-
- // Fetch the private key cert based on the request
- $cert = $this->fetch_private_cert($request);
-
- // Pull the private key ID from the certificate
- $privatekeyid = openssl_get_privatekey($cert);
-
- // Sign using the key
- $ok = openssl_sign($base_string, $signature, $privatekeyid);
-
- // Release the key resource
- openssl_free_key($privatekeyid);
-
- return base64_encode($signature);
- } /*}}}*/
-
- public function check_signature(&$request, $consumer, $token, $signature) {/*{{{*/
- $decoded_sig = base64_decode($signature);
-
- $base_string = $request->get_signature_base_string();
-
- // Fetch the public key cert based on the request
- $cert = $this->fetch_public_cert($request);
-
- // Pull the public key ID from the certificate
- $publickeyid = openssl_get_publickey($cert);
-
- // Check the computed signature against the one passed in the query
- $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
-
- // Release the key resource
- openssl_free_key($publickeyid);
-
- return $ok == 1;
- } /*}}}*/
-}/*}}}*/
-
-class OAuthRequest {/*{{{*/
- private $parameters;
- private $http_method;
- private $http_url;
- // for debug purposes
- public $base_string;
- public static $version = '1.0';
-
- function __construct($http_method, $http_url, $parameters=NULL) {/*{{{*/
- @$parameters or $parameters = array();
- $this->parameters = $parameters;
- $this->http_method = $http_method;
- $this->http_url = $http_url;
- }/*}}}*/
-
-
- /**
- * attempt to build up a request from what was passed to the server
- */
- public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {/*{{{*/
- $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on") ? 'http' : 'https';
- @$http_url or $http_url = $scheme . '://' . $_SERVER['HTTP_HOST'] . ':' . $_SERVER['SERVER_PORT'] . $_SERVER['REQUEST_URI'];
- @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
-
- $request_headers = OAuthRequest::get_headers();
-
- // let the library user override things however they'd like, if they know
- // which parameters to use then go for it, for example XMLRPC might want to
- // do this
- if ($parameters) {
- $req = new OAuthRequest($http_method, $http_url, $parameters);
- } else {
- // collect request parameters from query string (GET) and post-data (POST) if appropriate (note: POST vars have priority)
- $req_parameters = $_GET;
- if ($http_method == "POST" && @strstr($request_headers["Content-Type"], "application/x-www-form-urlencoded") ) {
- $req_parameters = array_merge($req_parameters, $_POST);
- }
-
- // next check for the auth header, we need to do some extra stuff
- // if that is the case, namely suck in the parameters from GET or POST
- // so that we can include them in the signature
- if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
- $header_parameters = OAuthRequest::split_header($request_headers['Authorization']);
- $parameters = array_merge($req_parameters, $header_parameters);
- $req = new OAuthRequest($http_method, $http_url, $parameters);
- } else $req = new OAuthRequest($http_method, $http_url, $req_parameters);
- }
-
- return $req;
- }/*}}}*/
-
- /**
- * pretty much a helper function to set up the request
- */
- public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) {/*{{{*/
- @$parameters or $parameters = array();
- $defaults = array("oauth_version" => OAuthRequest::$version,
- "oauth_nonce" => OAuthRequest::generate_nonce(),
- "oauth_timestamp" => OAuthRequest::generate_timestamp(),
- "oauth_consumer_key" => $consumer->key);
- $parameters = array_merge($defaults, $parameters);
-
- if ($token) {
- $parameters['oauth_token'] = $token->key;
- }
- return new OAuthRequest($http_method, $http_url, $parameters);
- }/*}}}*/
-
- public function set_parameter($name, $value) {/*{{{*/
- $this->parameters[$name] = $value;
- }/*}}}*/
-
- public function get_parameter($name) {/*{{{*/
- return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
- }/*}}}*/
-
- public function get_parameters() {/*{{{*/
- return $this->parameters;
- }/*}}}*/
-
- /**
- * Returns the normalized parameters of the request
- *
- * This will be all (except oauth_signature) parameters,
- * sorted first by key, and if duplicate keys, then by
- * value.
- *
- * The returned string will be all the key=value pairs
- * concated by &.
- *
- * @return string
- */
- public function get_signable_parameters() {/*{{{*/
- // Grab all parameters
- $params = $this->parameters;
-
- // Remove oauth_signature if present
- if (isset($params['oauth_signature'])) {
- unset($params['oauth_signature']);
- }
-
- // Urlencode both keys and values
- $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
- $values = OAuthUtil::urlencode_rfc3986(array_values($params));
- $params = array_combine($keys, $values);
-
- // Sort by keys (natsort)
- uksort($params, 'strcmp');
-
- // Generate key=value pairs
- $pairs = array();
- foreach ($params as $key=>$value ) {
- if (is_array($value)) {
- // If the value is an array, it's because there are multiple
- // with the same key, sort them, then add all the pairs
- natsort($value);
- foreach ($value as $v2) {
- $pairs[] = $key . '=' . $v2;
- }
- } else {
- $pairs[] = $key . '=' . $value;
- }
- }
-
- // Return the pairs, concated with &
- return implode('&', $pairs);
- }/*}}}*/
-
- /**
- * Returns the base string of this request
- *
- * The base string defined as the method, the url
- * and the parameters (normalized), each urlencoded
- * and the concated with &.
- */
- public function get_signature_base_string() {/*{{{*/
- $parts = array(
- $this->get_normalized_http_method(),
- $this->get_normalized_http_url(),
- $this->get_signable_parameters()
- );
-
- $parts = OAuthUtil::urlencode_rfc3986($parts);
-
- return implode('&', $parts);
- }/*}}}*/
-
- /**
- * just uppercases the http method
- */
- public function get_normalized_http_method() {/*{{{*/
- return strtoupper($this->http_method);
- }/*}}}*/
-
- /**
- * parses the url and rebuilds it to be
- * scheme://host/path
- */
- public function get_normalized_http_url() {/*{{{*/
- $parts = parse_url($this->http_url);
-
- $port = @$parts['port'];
- $scheme = $parts['scheme'];
- $host = $parts['host'];
- $path = @$parts['path'];
-
- $port or $port = ($scheme == 'https') ? '443' : '80';
-
- if (($scheme == 'https' && $port != '443')
- || ($scheme == 'http' && $port != '80')) {
- $host = "$host:$port";
- }
- return "$scheme://$host$path";
- }/*}}}*/
-
- /**
- * builds a url usable for a GET request
- */
- public function to_url() {/*{{{*/
- $out = $this->get_normalized_http_url() . "?";
- $out .= $this->to_postdata();
- return $out;
- }/*}}}*/
-
- /**
- * builds the data one would send in a POST request
- *
- * TODO(morten.fangel):
- * this function might be easily replaced with http_build_query()
- * and corrections for rfc3986 compatibility.. but not sure
- */
- public function to_postdata() {/*{{{*/
- $total = array();
- foreach ($this->parameters as $k => $v) {
- if (is_array($v)) {
- foreach ($v as $va) {
- $total[] = OAuthUtil::urlencode_rfc3986($k) . "[]=" . OAuthUtil::urlencode_rfc3986($va);
- }
- } else {
- $total[] = OAuthUtil::urlencode_rfc3986($k) . "=" . OAuthUtil::urlencode_rfc3986($v);
- }
- }
- $out = implode("&", $total);
- return $out;
- }/*}}}*/
-
- /**
- * builds the Authorization: header
- */
- public function to_header() {/*{{{*/
- $out ='Authorization: OAuth realm=""';
- $total = array();
- foreach ($this->parameters as $k => $v) {
- if (substr($k, 0, 5) != "oauth") continue;
- if (is_array($v)) throw new OAuthException('Arrays not supported in headers');
- $out .= ',' . OAuthUtil::urlencode_rfc3986($k) . '="' . OAuthUtil::urlencode_rfc3986($v) . '"';
- }
- return $out;
- }/*}}}*/
-
- public function __toString() {/*{{{*/
- return $this->to_url();
- }/*}}}*/
-
-
- public function sign_request($signature_method, $consumer, $token) {/*{{{*/
- $this->set_parameter("oauth_signature_method", $signature_method->get_name());
- $signature = $this->build_signature($signature_method, $consumer, $token);
- $this->set_parameter("oauth_signature", $signature);
- }/*}}}*/
-
- public function build_signature($signature_method, $consumer, $token) {/*{{{*/
- $signature = $signature_method->build_signature($this, $consumer, $token);
- return $signature;
- }/*}}}*/
-
- /**
- * util function: current timestamp
- */
- private static function generate_timestamp() {/*{{{*/
- return time();
- }/*}}}*/
-
- /**
- * util function: current nonce
- */
- private static function generate_nonce() {/*{{{*/
- $mt = microtime();
- $rand = mt_rand();
-
- return md5($mt . $rand); // md5s look nicer than numbers
- }/*}}}*/
-
- /**
- * util function for turning the Authorization: header into
- * parameters, has to do some unescaping
- */
- private static function split_header($header) {/*{{{*/
- $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
- $offset = 0;
- $params = array();
- while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
- $match = $matches[0];
- $header_name = $matches[2][0];
- $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
- $params[$header_name] = OAuthUtil::urldecode_rfc3986( $header_content );
- $offset = $match[1] + strlen($match[0]);
- }
-
- if (isset($params['realm'])) {
- unset($params['realm']);
- }
-
- return $params;
- }/*}}}*/
-
- /**
- * helper to try to sort out headers for people who aren't running apache
- */
- private static function get_headers() {/*{{{*/
- if (function_exists('apache_request_headers')) {
- // we need this to get the actual Authorization: header
- // because apache tends to tell us it doesn't exist
- return apache_request_headers();
- }
- // otherwise we don't have apache and are just going to have to hope
- // that $_SERVER actually contains what we need
- $out = array();
- foreach ($_SERVER as $key => $value) {
- if (substr($key, 0, 5) == "HTTP_") {
- // this is chaos, basically it is just there to capitalize the first
- // letter of every word that is not an initial HTTP and strip HTTP
- // code from przemek
- $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))));
- $out[$key] = $value;
- }
- }
- return $out;
- }/*}}}*/
-}/*}}}*/
-
-class OAuthServer {/*{{{*/
- protected $timestamp_threshold = 300; // in seconds, five minutes
- protected $version = 1.0; // hi blaine
- protected $signature_methods = array();
-
- protected $data_store;
-
- function __construct($data_store) {/*{{{*/
- $this->data_store = $data_store;
- }/*}}}*/
-
- public function add_signature_method($signature_method) {/*{{{*/
- $this->signature_methods[$signature_method->get_name()] =
- $signature_method;
- }/*}}}*/
-
- // high level functions
-
- /**
- * process a request_token request
- * returns the request token on success
- */
- public function fetch_request_token(&$request) {/*{{{*/
- $this->get_version($request);
-
- $consumer = $this->get_consumer($request);
-
- // no token required for the initial token request
- $token = NULL;
-
- $this->check_signature($request, $consumer, $token);
-
- $new_token = $this->data_store->new_request_token($consumer);
-
- return $new_token;
- }/*}}}*/
-
- /**
- * process an access_token request
- * returns the access token on success
- */
- public function fetch_access_token(&$request) {/*{{{*/
- $this->get_version($request);
-
- $consumer = $this->get_consumer($request);
-
- // requires authorized request token
- $token = $this->get_token($request, $consumer, "request");
-
-
- $this->check_signature($request, $consumer, $token);
-
- $new_token = $this->data_store->new_access_token($token, $consumer);
-
- return $new_token;
- }/*}}}*/
-
- /**
- * verify an api call, checks all the parameters
- */
- public function verify_request(&$request) {/*{{{*/
- $this->get_version($request);
- $consumer = $this->get_consumer($request);
- $token = $this->get_token($request, $consumer, "access");
- $this->check_signature($request, $consumer, $token);
- return array($consumer, $token);
- }/*}}}*/
-
- // Internals from here
- /**
- * version 1
- */
- private function get_version(&$request) {/*{{{*/
- $version = $request->get_parameter("oauth_version");
- if (!$version) {
- $version = 1.0;
- }
- if ($version && $version != $this->version) {
- throw new OAuthException("OAuth version '$version' not supported");
- }
- return $version;
- }/*}}}*/
-
- /**
- * figure out the signature with some defaults
- */
- private function get_signature_method(&$request) {/*{{{*/
- $signature_method =
- @$request->get_parameter("oauth_signature_method");
- if (!$signature_method) {
- $signature_method = "PLAINTEXT";
- }
- if (!in_array($signature_method,
- array_keys($this->signature_methods))) {
- throw new OAuthException(
- "Signature method '$signature_method' not supported try one of the following: " . implode(", ", array_keys($this->signature_methods))
- );
- }
- return $this->signature_methods[$signature_method];
- }/*}}}*/
-
- /**
- * try to find the consumer for the provided request's consumer key
- */
- private function get_consumer(&$request) {/*{{{*/
- $consumer_key = @$request->get_parameter("oauth_consumer_key");
- if (!$consumer_key) {
- throw new OAuthException("Invalid consumer key");
- }
-
- $consumer = $this->data_store->lookup_consumer($consumer_key);
- if (!$consumer) {
- throw new OAuthException("Invalid consumer");
- }
-
- return $consumer;
- }/*}}}*/
-
- /**
- * try to find the token for the provided request's token key
- */
- private function get_token(&$request, $consumer, $token_type="access") {/*{{{*/
- $token_field = @$request->get_parameter('oauth_token');
- $token = $this->data_store->lookup_token(
- $consumer, $token_type, $token_field
- );
- if (!$token) {
- throw new OAuthException("Invalid $token_type token: $token_field");
- }
- return $token;
- }/*}}}*/
-
- /**
- * all-in-one function to check the signature on a request
- * should guess the signature method appropriately
- */
- private function check_signature(&$request, $consumer, $token) {/*{{{*/
- // this should probably be in a different method
- $timestamp = @$request->get_parameter('oauth_timestamp');
- $nonce = @$request->get_parameter('oauth_nonce');
-
- $this->check_timestamp($timestamp);
- $this->check_nonce($consumer, $token, $nonce, $timestamp);
-
- $signature_method = $this->get_signature_method($request);
-
- $signature = $request->get_parameter('oauth_signature');
- $valid_sig = $signature_method->check_signature(
- $request,
- $consumer,
- $token,
- $signature
- );
-
- if (!$valid_sig) {
- throw new OAuthException("Invalid signature");
- }
- }/*}}}*/
-
- /**
- * check that the timestamp is new enough
- */
- private function check_timestamp($timestamp) {/*{{{*/
- // verify that timestamp is recentish
- $now = time();
- if ($now - $timestamp > $this->timestamp_threshold) {
- throw new OAuthException("Expired timestamp, yours $timestamp, ours $now");
- }
- }/*}}}*/
-
- /**
- * check that the nonce is not repeated
- */
- private function check_nonce($consumer, $token, $nonce, $timestamp) {/*{{{*/
- // verify that the nonce is uniqueish
- $found = $this->data_store->lookup_nonce($consumer, $token, $nonce, $timestamp);
- if ($found) {
- throw new OAuthException("Nonce already used: $nonce");
- }
- }/*}}}*/
-
-
-
-}/*}}}*/
-
-class OAuthDataStore {/*{{{*/
- function lookup_consumer($consumer_key) {/*{{{*/
- // implement me
- }/*}}}*/
-
- function lookup_token($consumer, $token_type, $token) {/*{{{*/
- // implement me
- }/*}}}*/
-
- function lookup_nonce($consumer, $token, $nonce, $timestamp) {/*{{{*/
- // implement me
- }/*}}}*/
-
- function new_request_token($consumer) {/*{{{*/
- // return a new token attached to this consumer
- }/*}}}*/
-
- function new_access_token($token, $consumer) {/*{{{*/
- // return a new access token attached to this consumer
- // for the user associated with this token if the request token
- // is authorized
- // should also invalidate the request token
- }/*}}}*/
-
-}/*}}}*/
-
-
-/* A very naive dbm-based oauth storage
- */
-class SimpleOAuthDataStore extends OAuthDataStore {/*{{{*/
- private $dbh;
-
- function __construct($path = "oauth.gdbm") {/*{{{*/
- $this->dbh = dba_popen($path, 'c', 'gdbm');
- }/*}}}*/
-
- function __destruct() {/*{{{*/
- dba_close($this->dbh);
- }/*}}}*/
-
- function lookup_consumer($consumer_key) {/*{{{*/
- $rv = dba_fetch("consumer_$consumer_key", $this->dbh);
- if ($rv === FALSE) {
- return NULL;
- }
- $obj = unserialize($rv);
- if (!($obj instanceof OAuthConsumer)) {
- return NULL;
- }
- return $obj;
- }/*}}}*/
-
- function lookup_token($consumer, $token_type, $token) {/*{{{*/
- $rv = dba_fetch("${token_type}_${token}", $this->dbh);
- if ($rv === FALSE) {
- return NULL;
- }
- $obj = unserialize($rv);
- if (!($obj instanceof OAuthToken)) {
- return NULL;
- }
- return $obj;
- }/*}}}*/
-
- function lookup_nonce($consumer, $token, $nonce, $timestamp) {/*{{{*/
- if (dba_exists("nonce_$nonce", $this->dbh)) {
- return TRUE;
- } else {
- dba_insert("nonce_$nonce", "1", $this->dbh);
- return FALSE;
- }
- }/*}}}*/
-
- function new_token($consumer, $type="request") {/*{{{*/
- $key = md5(time());
- $secret = time() + time();
- $token = new OAuthToken($key, md5(md5($secret)));
- if (!dba_insert("${type}_$key", serialize($token), $this->dbh)) {
- throw new OAuthException("doooom!");
- }
- return $token;
- }/*}}}*/
-
- function new_request_token($consumer) {/*{{{*/
- return $this->new_token($consumer, "request");
- }/*}}}*/
-
- function new_access_token($token, $consumer) {/*{{{*/
-
- $token = $this->new_token($consumer, 'access');
- dba_delete("request_" . $token->key, $this->dbh);
- return $token;
- }/*}}}*/
-}/*}}}*/
-
-class OAuthUtil {/*{{{*/
- public static function urlencode_rfc3986($input) {/*{{{*/
- if (is_array($input)) {
- return array_map(array('OAuthUtil','urlencode_rfc3986'), $input);
- } else if (is_scalar($input)) {
- return str_replace('+', ' ',
- str_replace('%7E', '~', rawurlencode($input)));
- } else {
- return '';
- }
- }/*}}}*/
-
-
- // This decode function isn't taking into consideration the above
- // modifications to the encoding process. However, this method doesn't
- // seem to be used anywhere so leaving it as is.
- public static function urldecode_rfc3986($string) {/*{{{*/
- return rawurldecode($string);
- }/*}}}*/
-}/*}}}*/
View
53 partitioned_resource.php
@@ -1,53 +0,0 @@
-<?php
-/**
- * Extension of array to allow linked partitioning.
- *
- * @package Soundcloud
- * @author Thor <thor@soundcloud.com>
- * @link http://github.com/mptre/php-soundcloud
- */
-class PartitionedResource extends ArrayObject {
-
- function __construct($string) {
- $data = $this->parse_to_array($string);
-
- parent::__construct($data);
- }
-
- function get_next_partition($soundcloud) {
- $next_partition_url = $this['@attributes']['next-partition-href'];
-
- if ($next_partition_url != '') {
- preg_match("/([a-z]+)\?/", $next_partition_url, $matches);
- $method = $matches[0];
-
- preg_match("/(\?)(.+)/", $next_partition_url, $matches);
- $param = $matches[2];
-
- $string = $soundcloud->request($method.$param);
-
- return new PartitionedResource($string);
- }
- }
-
- /// Turns the string that the main PHP API returns into an array that works with our resource.
- private function parse_to_array($string) {
- // SimpleXMLElement fails due to some of the characters in the query string, so they get stripped out here...
- if (strstr($string, 'next-partition-href')) {
- preg_match("/\/([a-z]+\?.*)\"/", $string, $matches);
-
- $queryparams = $matches[1];
- $string = str_replace($queryparams, "", $string);
- }
-
- $data = new SimpleXMLElement($string);
- $data = get_object_vars($data);
-
- // ...and replaced here.
- if ($data['@attributes']['next-partition-href']) {
- $data['@attributes']['next-partition-href'] = $data['@attributes']['next-partition-href'].$queryparams;
- }
-
- return $data;
- }
-}
View
278 soundcloud.php
@@ -1,228 +1,112 @@
<?php
/**
- * API Wrapper for SoundCloud written in PHP with support for authication using OAuth.
+ * A minimalistic API wrapper for SoundCloud written in PHP.
+ * For further reference and example of usage see link below.
*
- * @package Soundcloud
- * @version 1.2.0
- * @author Anton Lindqvist <anton@qvister.se>
* @link http://github.com/mptre/php-soundcloud/
+ * @author Anton Lindqvist <anton@qvister.se>
+ * @version 0.1.1
*/
-class Soundcloud {
-
- const VERSION = '1.2.0';
-
- public static $api_version = 1;
- public static $domains = array(
- 'development' => 'sandbox-soundcloud.com',
- 'production' => 'soundcloud.com'
- );
- public static $oauth_paths = array(
- 'access' => '/oauth/access_token',
- 'authorize' => '/oauth/authorize',
- 'request' => '/oauth/request_token'
- );
-
- public $development;
-
- function __construct($consumer_key, $consumer_secret, $oauth_token = null, $oauth_token_secret = null, $development = false) {
- if (empty($consumer_key)) {
- throw new SoundcloudException('Consumer Key required for all requests, even those to public resources.');
- }
-
- $this->development = $development;
-
- $this->sha1_method = new OAuthSignatureMethod_HMAC_SHA1();
- $this->consumer = new OAuthConsumer($consumer_key, $consumer_secret);
-
- if (!empty($oauth_token) && !empty($oauth_token_secret)) {
- $this->token = new OAuthConsumer($oauth_token, $oauth_token_secret);
- } else {
- $this->token = null;
- }
- }
-
- function get_authorize_url($token) {
- if (is_array($token)) {
- $token = $token['oauth_token'];
- }
- return $this->_get_url('authorize') . '?oauth_token=' . $token;
+class Soundcloud {
+ private $key;
+ private $me;
+ private $username;
+ private $password;
+ private $url;
+
+ function __construct($username, $password, $key = NULL) {
+ $this->username = $username;
+ $this->password = $password;
+ $this->key = $key;
+ $this->me = ($key == 'me') ? TRUE : FALSE;
+ $this->url = 'http://api.sandbox-soundcloud.com';
}
- function get_request_token($oauth_callback) {
- $request = $this->request(
- $this->_get_url('request'),
- 'POST',
- array('oauth_callback' => $oauth_callback)
- );
- $token = $this->_parse_response($request);
-
- $this->token = new OAuthConsumer(
- $token['oauth_token'],
- $token['oauth_token_secret']
- );
-
- return $token;
+ function __get($key) {
+ return new Soundcloud($this->username, $this->password, $key);
}
- function get_access_token($token) {
- $response = $this->request(
- $this->_get_url('access'),
- 'POST',
- array('oauth_verifier' => $token)
- );
- $token = $this->_parse_response($response);
- $this->token = new OAuthConsumer(
- $token['oauth_token'],
- $token['oauth_token_secret']
- );
-
- return $token;
- }
-
- function upload_track($post_data, $asset_data_mime = null, $artwork_data_mime = null) {
- $body = '';
- $boundary = '---------------------------' . md5(rand());
- $crlf = "\r\n";
- $headers = array(
- 'Content-Type' => 'multipart/form-data; boundary=' . $boundary,
- 'Content-Length' => 0
+ function __call($method, $args) {
+ $args = (count($args) && is_array($args)) ? $args[0] : array();
+ $options = array(
+ CURLOPT_RETURNTRANSFER => 1,
+ CURLOPT_URL => sprintf('%s/%s/', $this->url, $this->key),
+ CURLOPT_USERPWD => sprintf('%s:%s', $this->username, $this->password)
);
- foreach ($post_data as $key => $val) {
- if (in_array($key, array('track[asset_data]', 'track[artwork_data]'))) {
- $body .= '--' . $boundary . $crlf;
- $body .= 'Content-Disposition: form-data; name="' . $key . '"; filename="' . basename($val) . '"' . $crlf;
- $body .= 'Content-Type: ' . (($key == 'track[asset_data]') ? $asset_data_mime : $artwork_data_mime) . $crlf;
- $body .= $crlf;
- $body .= file_get_contents($val) . $crlf;
- } else {
- $body .= '--' . $boundary . $crlf;
- $body .= 'Content-Disposition: form-data; name="' . $key .'"' . $crlf;
- $body .= $crlf;
- $body .= $val . $crlf;
- }
+ // Handle me and users method.
+ if (!in_array($this->key, array('tracks'))) {
+ $options[CURLOPT_URL] .= (isset($args['user_id']))
+ ? $args['user_id'] .'/'
+ : NULL;
+ $options[CURLOPT_URL] .= ($method != 'basic')
+ ? $method .'/'
+ : NULL;
}
- $body .= '--' . $boundary . '--' . $crlf;
- $headers['Content-Length'] += strlen($body);
-
- return $this->request('tracks', 'POST', $body, $headers);
- }
-
- function request($resource, $method = 'GET', $args = array(), $headers = null) {
- if (!preg_match('/http:\/\//', $resource)) {
- $url = $this->_get_url() . $resource;
- } else {
- $url = $resource;
- }
-
- if (stristr($headers['Content-Type'], 'multipart/form-data')) {
- $body = false;
- } elseif (stristr($headers['Content-Type'], 'application/xml')) {
- $body = false;
- } else {
- $body = true;
- }
-
- $request = OAuthRequest::from_consumer_and_token(
- $this->consumer,
- $this->token,
- $method,
- $url,
- ($body === true) ? $args : null
- );
- $request->sign_request($this->sha1_method, $this->consumer, $this->token);
-
- // Formerly $url was $request->get_normalized_http_url(), which prevented params from being passed.
- return $this->_curl($url, $request, $args, $headers);
-
- }
-
- private function _build_header($headers) {
- $h = array();
-
- if (count($headers) > 0) {
- foreach ($headers as $key => $val) {
- $h[] = $key . ': ' . $val;
+ // Handle tracks search method.
+ if (isset($args['query'])) {
+ if (is_array($args['query'])) {
+ $options[CURLOPT_URL] = preg_replace(
+ '/\/$/',
+ '?',
+ $options[CURLOPT_URL]
+ );
+ $options[CURLOPT_URL] .= http_build_query($args['query']);
}
-
- return $h;
- } else {
- return $headers;
}
- }
- private function _curl($url, $request, $post_data = null, $headers = null) {
- $ch = curl_init();
- $mime = (stristr($headers['Content-Type'], 'multipart/form-data')) ? true : false;
- $headers['User-Agent'] = (isset($headers['User-Agent']))
- ? $headers['User-Agent']
- : 'PHP SoundCloud/' . self::VERSION;
- $headers['Content-Length'] = (isset($headers['Content-Length']))
- ? $headers['Content-Length']
- : 0;
- $headers = (is_array($headers)) ? $this->_build_header($headers) : array();
- $options = array(
- CURLOPT_URL => $url,
- CURLOPT_HEADER => false,
- CURLOPT_RETURNTRANSFER => true
- );
-
- if (in_array($request->get_normalized_http_method(), array('DELETE', 'PUT'))) {
- $options[CURLOPT_CUSTOMREQUEST] = $request->get_normalized_http_method();
- $options[CURLOPT_POSTFIELDS] = '';
+ // Handle POST, PUT and DELETE requests.
+ foreach ($args as $key => $val) {
+ if (in_array($key, array('delete', 'post', 'put'))) {
+ if ($key == 'post') {
+ $options[CURLOPT_POST] = 1;
+ } else {
+ $options[CURLOPT_CUSTOMREQUEST] = strtoupper($key);
+ }
+
+ $options[CURLOPT_POSTFIELDS] = (isset($args['fields']))
+ ? $args['fields']
+ : '';
+ } elseif (preg_match('/[^[user]]{0}_id$/', $key)) {
+ $options[CURLOPT_URL] .= $args[$key] .'/';
+ }
}
- if (is_array($post_data) && count($post_data) > 0 || $mime === true) {
- $options[CURLOPT_POSTFIELDS] = (is_array($post_data) && count($post_data) == 1)
- ? ((isset($post_data[key($post_data)])) ? $post_data[key($post_data)] : $post_data)
- : $post_data;
- $options[CURLOPT_POST] = true;
+ if (in_array($this->key, array('tracks')) && $method != 'basic') {
+ $options[CURLOPT_URL] .= $method;
}
- $headers[] = $request->to_header();
- $options[CURLOPT_HTTPHEADER] = $headers;
-
+ $ch = curl_init();
curl_setopt_array($ch, $options);
+ $data = curl_exec($ch);
+ $meta = curl_getinfo($ch);
- $response = curl_exec($ch);
- $this->http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
-
- curl_close($ch);
-
- return $response;
- }
-
- private function _get_url($type = null) {
- if ($type == 'authorize') {
- return 'http://'
- . (($this->development)
- ? self::$domains['development']
- : self::$domains['production'])
- . self::$oauth_paths[$type];
+ if (in_array($meta['http_code'], array(200, 201, 303))) {
+ return (strlen($data) <= 1) ? TRUE : $data;
+ } else {
+ // Throw error.
+ throw new SoundcloudException(
+ sprintf(
+ 'Response code: %d from %s',
+ $meta['http_code'],
+ $options[CURLOPT_URL]
+ )
+ );
}
-
- $url = 'http://api.';
- $url .= ($this->development)
- ? self::$domains['development']
- : self::$domains['production'];
- $url .= '/v' . self::$api_version;
- $url .= (array_key_exists($type, self::$oauth_paths))
- ? self::$oauth_paths[$type]
- : null;
- $url .= '/';
-
- return $url;
}
- private function _parse_response($response) {
- parse_str($response, $output);
-
- return (count($output) > 0) ? $output : false;
+ function __destruct() {
+ $this->username = NULL;
+ $this->password = NULL;
+ $this->key = NULL;
+ $this->me = NULL;
+ $this->url = NULL;
}
}
class SoundcloudException extends Exception {
- // kthxbye!
+ // Kthxbye.
}
+?>
Please sign in to comment.
Something went wrong with that request. Please try again.