http://wiki.developer.myspace.com/index.php?title=Category:MySpaceID_SDK
March 3, 2010
The MySpace platform is a complete platform providing the tools for developers to do just about anything within the context of MySpace. While there may not be a 1-to-1 conversion from Facebook APIs to MySpace APIs, the MySpace API is comprehensive such that for most Facebook APIs, the behavior can be mirrored through proper use of MySpace APIs.
This documentation will guide you through both authentication and RESTful APIs and how the Facebook APIs directly translate to MySpace APIs. In the case that there isn’t a direct 1-to-1 conversion, we will do our best to describe alternatives to achieving an equivalent or near equivalent result.
This documentation, in its current version, will not cover FBML-to-OSML conversion or FQL, and will not cover the complex but powerful OpenSocial Markup Language which MySpace applications can also be built with. For this information, please view the related pages on the MySpace wiki.
The Facebook platform supports a few different types of applications:
iFrame Applications - These applications live in an iFrame on the facebook site. They are not restricted in the type of HTML/JS they can use, but they can’t take advantage of the full set of FBML available.
FBML Applications - These applications also live on the facebook site, but instead of using an iFrame, the facebook servers directly load the page, convert the FBML markup to HTML and show that. The main benefit is that these applications can use the full power of FBML and FBJS to fit in with facebook, but are restricted in the set of HTML tags and JS which can be used.
External Applications - These include web and desktop applications. These use Facebook Connect for authentication and typically leave completely off the facebook site (though they may be used in conjunction with the other kinds of applications to support both). They use the RESTful API to talk with facebook.
The MySpace platform supports multiple application types as well, but their behavior is a bit different:
Fully Embedded Applications - These applications live on the MySpace site and can be compared to FBML applications for facebook. These applications use OSML, JavaScript, and AJAX calls to outside sites to handle all their logic within the MySpace website.
iFrame Applications - These applications live in an iFrame on the MySpace site. They are equivalent in almost every way to facebook iFrame applications.
External Applications - These applications live outside of the MySpace site and are either web or desktop applications. They are equivalent to facebook external applications.
In addition to the above application types, applications can further integrate with MySpace by having specific interfaces for the profile page, canvas page, and application page. These three pages are described below:
Profile Page - This places a block either in the left or right column which matches the MySpace UI which the application can use to host content for public display.
Canvas Page - This places a block either in the left or right column which matches the MySpace UI which the application can use to hose content for private (owner only) display. This is only visible by the user who installs the application.
Application Page - This is the public page which shows information about the application where users can choose to install the application.
These integration points are comparable to Facebooks integration with user profiles where applications can create tabs or their own canvas pages.
While the direct RESTful endpoints are listed throughout the document, MySpace recommends you use the official SDKs for the various languages used. These can be found at the following page:
http://wiki.developer.myspace.com/index.php?title=Category:MySpaceID_SDK
MySpace supports several languages including PHP, Ruby, Python, .NET, Java, and many more. The full list can be found on the MySpaceID SDK page above. For the remainder of the document, the PHP SDK will be used for examples, but all SDKs follow a similar format and should be easily adapted.
Authentication is the method used to identify a user and setup permissions for a specific application to request information on behalf of this user. Since all RESTful API calls require a digital signature, authentication is required prior to any API calls. This is true for both Facebook and MySpace.
To assist with the transition from Facebook authentication to MySpace authentication, this page will first have a basic overview of the technology behind both authentication systems, and finally will show some examples for transitioning the authentication from one platform to the other.
There are two main methods which Facebook applications use to authenticate:
Facebook Connect - Used by 3rd party websites to access Facebook data for a given user. The exact technology behind it is a custom protocol created by Facebook.
Using GET variables sent by Facebook - Used by embedded applications which require authentication prior to accessing certain pages of the application. This method involves sending the user to a custom generated login.php page on the Facebook servers. After a successful login, the user is redirected back to the application URL, with the signature given as a GET parameter, which can be turned into a session key for use in facebook API calls.
Despite the two different use cases, the goal of the authentication for both is the same: to retrieve the session key which is used to generate a signature which is required for all Facebook API calls. Whether you use facebook connect or login.php to authenticate, this guide will still be helpful in determining how to convert your application to the MySpace platform.
Unlike Facebook, MySpace uses a single form of authentication: MySpaceID, which is based on OAuth and OpenID. This authentication is used if your application is embedded on the site, a 3rd party website, or even an iFrame application. But depending on the location of your application, the number of steps required for the authentication will differ:
Embedded Application - No authentication is necessary! Since the application is embedded directly within MySpace, it is free to make API calls with respect to the "owner" and "viewer" (the user of the app and the current user viewing that page, which may also be the owner). MySpace handles the authentication transparent to the developer. These applications differ a bit from Facebook since Facebook doesn’t allow this sort of directly uploaded application, but this will be covered in more detail later.
iFrame Application - No authentication is necessary, but some programming must be done to calculate the signatures for the API calls based on the GET parameters passed to the application.
External Application - Complete OAuth process must occur, where the user is taken off-site to MySpace to verify that he or she wishes to connect with the application. Upon confirmation, they are redirected back to the application site, which can now generate the proper tokens to make API calls. An alternative to this is to use a pop-up (similar to how Facebook Connect works) which allows the authentication to happen all in one page.
If you’re using Facebook Connect, supporting MySpaceID is a straightforward process. The following is a quick overview of the process, before we go into detail for each step:
JavaScript is used to pop-up a window, similar to Facebook Connect to authenticate and connect the MySpace user to your site.
Once connected, MySpace redirects back to a page with GET variables which can be used to retrieve an OAuth token and secret for API access.
The first step is preparing the JavaScript and HTML for connecting with MySpace. First, setup the link for logging in with MySpaceID, like so:
<a href="#" id="myspaceid-login"> <img src="http://c3.ac-images.myspacecdn.com/images02/42/l_612a201a94ba45a4914076316fd316e6.png" alt="Login with MySpaceID!" /> </a>
This will create a link (which goes nowhere at the moment, we’ll hook it up with JavaScript next) which uses the image shown below, which is a standard MySpaceID login image.

Once the HTML is place, the JavaScript must be setup. The example below uses the jQuery JavaScript library syntax, but any JavaScript can be used. The code uses the official MySpaceID JavaScript library.
$(document).ready(function() { var msOptions = { api_base: 'http://api.myspace.com/openid', // Shouldn't have to change this server: "http://mywebsite.com", // Change to the base domain of your app realm: '/samples/myspaceid-openid-oauth-popup/', // Change to the realm (path) for access returnTo: 'finish_auth.php', // The page to return to after connecting consumer: '5fbd5254c11d49c2b7722869be87197c', // Your apps consumer key popupSize: { width:580, height:500 } // Popup options }; $("#myspaceid-login").bind("click", function() { var ms = new MySpaceID(msOptions); ms.logIn(); }); });
And that’s it! With that code in place, most of the work is already done. This will create a page with a link that when clicked will pop-up a MySpaceID login page. Upon successful login, MySpace will automatically redirect to the page you specified so you can retrieve and store the access keys, which is covered in the next section.
Once a user successfully authenticates with MySpace, they will be redirected back to the returnTo page specified. The request back will contain many GET variables which can be used to retrieve the access key and secret for API calls. Since MySpace uses OAuth + OpenID ("3 legged OAuth"), an open standard, for authentication, any OAuth library which supports it may be used in this step. For the examples below, we’ll be using the JanRain OpenID/OAuth library for PHP.
The first step is to verify that the authentication was a success, and if so, retrieve the OAuth authorized request tokens:
// First, we setup the classes required $store_path = "/tmp"; // Wherever you want to store your auth files $store = new Auth_OpenID_FileStore($store_path); $consumer = new Auth_OpenID_Consumer($store); // Then, complete the request $response = $consumer->complete("http://mywebsite.com/finish_auth.php"); if ($response->status == Auth_OpenID_SUCCESS) { // Success, now we just get the tokens and we're ready! $oauth_resp = Auth_OpenID_OAuthResponse::fromSuccessResponse($response); $authorized_request_token = $oauth_resp->authorized_request_token; $authorized_verifier = $oauth_resp->authorized_verifier; // We now have the tokens! The code samples below will continue // with code here. } else { die("You didn't authenticate!"); }
Most of the lines of code above are simply setting up classes. All the work is done by the library calls to complete the authentication request. Once we have the authorized request tokens, we can use the MySpace library to finally get our access tokens. The code samples below can be assumed to go within the success branch of the above code:
$ms = new MySpace(CONSUMER_KEY, CONSUMER_SECRET, $authorized_request_token->key, $authorized_request_token->secret, $authorized_verifier); $access_token = $ms->getAccessToken(); $ms = new MySpace(CONSUMER_KEY, CONSUMER_SECRET, $access_token->key, $access_token->secret); // We can now make any MySpace API requests! Example: $profile_data = $ms->getProfile($ms->getCurrentUserId()); print "Your name is: {$profile_data->basicprofile->name}";
With the final $ms object created, we’re ready to make any and all MySpace API requests, as the example shows.
The above example showed how to retrieve the access tokens and make a simple API call for the user’s name. But what if you wanted to simply authenticate, but make API calls on subsequent page calls? This is possible as well! The final access key and secret can be saved and reused on subsequent page calls. An example:
$_SESSION['access_key'] = $access_token->key; $_SESSION['access_secret'] = $access_token->secret; // Then on subsequent pages: $ms = new MySpace(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['access_key'], $_SESSION['access_secret']);
For Facebook applications which are embedded (as FBML or as an iFrame), the authentication method differs in that the facebook servers will send the application authentication details and keys via GET parameters. This is very similar to what MySpace does, except MySpace sends OAuth tokens which can then be used to retrieve the access tokens for API calls. There are only two steps involved in authenticating the user:
Verifying that the OpenID authentication was a success
Using the OAuth keys, retrieve the access keys needed for making API calls.
When MySpace loads your embedded page in an iFrame, it passes in GET parameters which can be used to verify and complete authentication. The first step is to verify the authentication. This step verifies the authentication and if valid, retrieves the request tokens which can be used to with the MySpace API to retrieve access tokens for the API calls.
// First, we setup the classes required $store_path = "/tmp"; // Wherever you want to store your auth files $store = new Auth_OpenID_FileStore($store_path); $consumer = new Auth_OpenID_Consumer($store); // Then, complete the request $response = $consumer->complete("http://mywebsite.com/current_page.php"); if ($response->status == Auth_OpenID_SUCCESS) { // Success, now we just get the tokens and we're ready! $oauth_resp = Auth_OpenID_OAuthResponse::fromSuccessResponse($response); $authorized_request_token = $oauth_resp->authorized_request_token; $authorized_verifier = $oauth_resp->authorized_verifier; // We now have the tokens! The code samples below will continue // with code here. } else { die("You didn't authenticate!"); }
Once the request tokens are retrieved, getting access tokens for making RESTful API calls is only a few lines away when using the MySpace SDK.
$ms = new MySpace(CONSUMER_KEY, CONSUMER_SECRET, $authorized_request_token->key, $authorized_request_token->secret, $authorized_verifier); $access_token = $ms->getAccessToken(); $ms = new MySpace(CONSUMER_KEY, CONSUMER_SECRET, $access_token->key, $access_token->secret); // We can now make any MySpace API requests! Example: $profile_data = $ms->getProfile($ms->getCurrentUserId()); print "Your name is: {$profile_data->basicprofile->name}";
With this final $ms object, it is now possible to make any requests to the MySpace API. Additionally, the access tokens can be saved (in a session) to be used on subsequent page calls.
This section will mirror the Facebook RESTful API documentation, providing details on how to convert one API call to a MySpace API equivalent. Not all API calls can be converted to the MySpace API (possibly because MySpace provides features that make it not necessary or perhaps MySpace does not support an equivalent feature from Facebook).
Note: Most of the following API calls have no MySpace equivalent due to the different nature of the authentication methods used by each platform. In these cases, we do our best to show sample code and explain how it fits into the MySpace workflow.
Facebook Description: Creates an auth_token to be passed in as a parameter to login.php and then to auth.getSession after the user has logged in. The user must log in soon after you create this token.
This API method is unnecessary with MySpace since the MySpace authentication methods are based on OAuth and OpenID. Although many "tokens" are passed during the authentication process which MySpace uses, it is not directly equivalent to the definition of "token" used here. For more information, please read the authentication section.
Facebook Description: Expires the session indicated in the API call, for your application.
Due to the nature of MySpaceID, this is also unnecessary for MySpace applications. To simulate expiring a session, simply delete all traces of the access key and token used to make API calls. These will naturally expire after a short period of time. As an example, if we’re following the format used in the authentication section of the documentation, you can invalidate a session using the following code:
unset($_SESSION['access_key']); unset($_SESSION['access_secret']);
Facebook Description: Returns the session key bound to an auth_token, as returned by auth.createToken or in the callback URL.
In terms of facebook usage, this is typically used in conjunction with auth.createToken directly after the redirect back after going to login.php to retrieve the session key used for API access. For MySpace, the equivalent would be the call to get the access token after successfully verifying credentials on the MySpace website. Example taken from the authentication section:
$ms = new MySpace(CONSUMER_KEY, CONSUMER_SECRET, $authorized_request_token->key, $authorized_request_token->secret, $authorized_verifier); $access_token = $ms->getAccessToken();
The above example assumes you have access to the authorized_request_token which is only available on the return page after successful authentication. Using these tokens, developers can retrieve the proper access tokens used to query the MySpace API.
Facebook Description: Returns a temporary session secret associated to the current existing session, for use in a client-side component to an application.
There is no equivalent to this in MySpace. Due to the different nature of the authentication system, this API is not necessary.
Facebook Description: If this method is called for the logged in user, then no further API calls can be made on that user’s behalf until the user decides to authorize the application again.
There is no equivalent to this in MySpace. Once a user installs an application, there is no way to revoke the privileges granted by that action. A way to work around this is of course to fake the authorization using software with user app data.
TODO: User app data link and example
Facebook Description: Revokes the specified extended permission for the selected user. If no user is specified, then the user of the current session is used.
There is no equivalent to this in MySpace, since MySpace doesn’t have the same notion of extended permissions. Once a user installs an application, that application has access to the full range of API calls for the user.
Facebook Description: Returns all comments for a given XID posted through fb:comments or the Comments Box (which is created with the fb:comments (XFBML) tag). This method is a wrapper for the FQL query on the comment FQL table. You can specify only one XID with this call. If you want to retrieve comments for multiple XIDs, run fql.query against the comment FQL table.
While Facebook has a single API to retrieve comments for any resource on Facebook, MySpace splits the API up to the specific resource the comment is being grabbed from. The resources which MySpace supports for commenting are profile comments, moods/status updates, media comments.
To retrieve the comments on a user’s profile, the following endpoint can be used:
GET http://opensocial.myspace.com/roa/09/profilecomments/{personId}/@self
To retrieve the comments on a person’s mood or status updates, the following endpoint can be used:
GET http://opensocial.myspace.com/roa/09/statusmoodcomments/{personId}/@self
To retrieve the comments on a person’s media items, the following endpoints can be used:
http://opensocial.myspace.com/roa/09/mediaitemcomments/{personId}/@self/{albumId}/{mediaItemId}
The parameters to each endpoint are fairly straightforward and represent simple numeric IDs to the various resources. In addition to numeric IDs, OpenSocial-style ID strings can be used, such as myspace.person.1234.
Facebook Description: This method returns all cookies for a given user and application. Cookies only apply to Web applications; they do not apply to desktop applications
There is no equivalent MySpace API for this call. Instead, applications are welcome to use JavaScript or the language they are written in to grab the cookies themselves. Of course, in the case of an iFrame or 3rd party application, it won’t be able to retrieve the MySpace cookies.
Facebook Description: Fetches and re-caches the image stored at the given URL, for use in images published to non-canvas pages via the API (for example, via stream.publish. See the FBML documentation for a description of the markup and its role in various contexts. Further, see UsageNotes/Images for more information on how Facebook handles images.
There is no MySpace equivalent for this API call. MySpace supports OSML, which is similar to FBML, but OSML has no concept of how the provider caches images, and this is generally unnecessary in a MySpace application.
Facebook Description: Fetches and re-caches the content stored at the given URL, for use in a fb:ref FBML tag. See the FBML documentation for a description of the markup and its role in various contexts.
There is no MySpace equivalent for this API call. MySpace supports OSML, which is similar to FBML, but OSML has no concept of how the provider caches images, and this is generally unnecessary in a MySpace application.
Facebook Description: Evaluates an FQL (Facebook Query Language) query. For more complex queries where you want to use the results of one query in another query without making another API call, consider using fql.multiquery.
There is no MySpace equivalent for this API call. MySpace provides no FQL-type API. Instead, multiple RESTful API calls must be used to achieve the same goal. For example, if an application wanted to emulate the following FQL query:
SELECT name, pic FROM user WHERE uid=211031 OR uid=4801660
The application could use these endpoints instead:
GET http://opensocial.myspace.com/roa/09/people/211031/@self GET http://opensocial.myspace.com/roa/09/people/4801660/@self
Of course, with more complicated FQL queries, the REST API calls required become increasingly more complex as well. Although this is not ideal, this is the only solution MySpace currently offers.
Facebook Description: Evaluates a series of FQL (Facebook Query Language) queries in one call and returns the data at one time. This method takes a JSON-encoded dictionary called queries where the individual queries use the exact same syntax as a query made with fql.query. However, this method allows for more complex queries to be made. You can fetch data from one query and use it in another query within the same call. The WHERE clause is optional in the latter query, since it references data that’s already been fetched. To reference the results of one query in another query within the same call, specify its name in the FROM clause, preceded by #.
There is no MySpace equivalent for this API call. MySpace provides no FQL-type API. Instead, multiple RESTful API calls must be used to achieve the same goal. See fql.query for more information.
Facebook Description: Returns whether or not two specified users are friends with each other. The first array specifies one half of each pair, the second array the other half; therefore, they must be of equal size.
The MySpace equivalent is the following RESTful resource:
GET http://api.myspace.com/v1/users/{userid}/friends/{friendsId}
The following are some examples using the PHP library:
// Get friendship status between our current user and a friend $friendship_result = $ms->getFriendship($ms->getCurrentUserId(), $friendsId);
Facebook Description: Returns the Facebook user IDs of the current user’s Facebook friends. The current user is determined from the session_key parameter. The values returned from this call are not storable.
The MySpace equivalent is the following RESTful resource:
GET http://opensocial.myspace.com/roa/09/people/{userId}/@friends
Optional GET params:
show - Can be any or all of the following seperated by a vertical pipe character (|)
mood - the response will indicate the mood of the friend
status - the response will indicate the status of the friend
online - the response will indicate the online status of the friend.
The following are some examples using the PHP library:
// Request a list of friends from a users top friends list // which is the 1st page of 20 and will request all info on each friend $friend_data = $ms->getFriends($ms->getCurrentUserId()); // Request a list of friends from a users top friends list which // is the 2nd page of 20 and will request all info on each friend $friend_data = $ms->getFriends($ms->getCurrentUserId(), 2); // Request a list of friends from a users top friends list // which is the 1st page of 100 and will request all info on each friend $friend_data = $ms->getFriends($ms->getCurrentUserId(), 1, 100); // Request a list of friends from a users top friends list // which is the 1st page of 100 and will request all info on each friend. // The 4th method parameter declares which friends list we are requesting // data from. Can either be 'online', 'app' or its default 'top' $friend_data = $ms->getFriends($ms->getCurrentUserId(), 1, 100, 'top'); // Request a list of friends from a users top friends list // which is the 1st page of 100 and will request all info on each friend. // The 5th method parameter declares what data we are requesting of each // friend. Can be any or all of 'online', 'mood', 'status' and are // seperated by a vertical pipe character (|) $friend_data = $ms->getFriends($ms->getCurrentUserId(), 1, 100, 'top', 'mood|status|online');
Facebook Description: Returns the user IDs of the current user’s Facebook friends who have authorized the specific calling application or who have already connected their Facebook accounts via Facebook Connect. The current user is determined from the session_key parameter. The values returned from this call are not storable.
There is no MySpace equivalent for this API call. Instead, to achieve this it can be emulated with App User Data (see section later in document). App User Data allows an application to store key/value information for a specific user on the MySpace servers. By setting appInstalled to true for example, a simple REST API call can be made to get the app user data for friends of a user, and the appInstalled key can be checked for each user. If it exists, then the user has installed the app. Likewise, if it doesn’t exist, then the user has not yet installed the application.
The following is some example code using the PHP SDK showing how to achieve this:
// For new users, mark the app as installe $myspace->putAppData($userId, array("appInstalled" => "1")); // To see which friends have the app installed: $friend_data = $myspace->getUserFriendsAppData($userId, "appInstalled"); // Now we manually filter out which friends have the key $friends = array(); foreach ($friend_data as $data) { if ($data["appInstalled"]) { // This friend has the app installed! $friends[] = $data; } }
Facebook Description: Returns the names and identifiers of any friend lists that the user has created. The current user is determined from the session_key parameter.
There is no MySpace equivalent for this API call. MySpace doesn’t support friend lists. Instead, all friends can be retrieved using friends.get.
Facebook Description: Returns the Facebook user IDs of the mutual friends between the source user and target user. For the source user, you can either specify the source’s user ID (the source_id) or use the session key of the logged-in user, but not specify both. The source user must have authorized your application.
There is no MySpace equivalent for this API call. Instead, this API call can be manually emulated within the application itself by getting the list of friend IDs for the source user and the target user, then intersecting the two sets.
The following is some code using the PHP SDK showing how this could be done:
// Get friends for each user $source_friends = $myspace->getFriends($sourceId); $target_friends = $myspace->getFriends($targetId); $mutual = array_intersect($source_friends, $target_friends);
Facebook Description: Returns all visible groups according to the filters specified.
This can be achieved using the following OpenSocial API:
GET http://opensocial.myspace.com/roa/09/groups/@supportedFields
To retrieve all the groups for the current user:
GET http://opensocial.myspace.com/roa/09/groups/@me
To retrieve all the groups of some arbitrary user:
GET http://opensocial.myspace.com/roa/09/groups/{userId}
The following is some PHP code using the OpenSocial and MySpace SDK showing how this API may be called:
$osapi = new osapi(new osapiMySpaceProvider(), new osapiOAuth2Legged($appKey, $appSecret, $userId)); $batch = $osapi->newBatch(); // Setup the API call to getGroups $user_params = array('userId' => $userId); $batch->add($osapi->groups->get($user_params), 'getGroups'); // Get the results $result = $batch->execute();
Facebook Description: Returns membership list data associated with a group.
There is no MySpace equivalent for this API call. Only groups.get is supported at the moment.
Facebook Description: Returns all links the user has posted on their profile through your application.
There is no MySpace equivalent for this API call. MySpace doesn’t have the same concept of "links" in this sense as Facebook does.
Facebook Description: Returns a list of all of the visible notes written by the specified user.
There is no MySpace equivalent for this API call. MySpace doesn’t have the same concept of "notes" in this sense as Facebook does.
Facebook Description: Returns information on outstanding Facebook notifications for current session user.
There is no MySpace equivalent for this API call. While MySpace supports the sending of "App Notifications" (which are slightly different than MySpace), getting the list of current notifications is not supported. For more information on sending App Notifications read the "App Notifications" section later in the document.
Facebook Description: Returns all the current session user’s notifications.
There is no MySpace equivalent for this API call. While MySpace supports the sending of "App Notifications" (which are slightly different than MySpace), getting the list of current notifications is not supported. For more information on sending App Notifications read the "App Notifications" section later in the document.
Facebook Description: Returns all visible pages to the filters specified.
There is no MySpace equivalent for this API call.
Facebook Description: Checks whether the logged-in user is the admin for a given Page.
There is no MySpace equivalent for this API call.
Facebook Description: Checks whether the Page has added the application.
There is no MySpace equivalent for this API call.
Facebook Description: Checks whether a user is a fan of a given Page.
There is no MySpace equivalent for this API call.
Facebook Description: Returns the user’s current and most recent statuses.
The MySpace equivalent is the following RESTful resource:
GET http://opensocial.myspace.com/roa/09/people/{userId}?fields=status
The following are some examples using the PHP library:
// Get a specific users status $user_id = $ms->getStatus($userId); // Get our current users status $user_id = $ms->getStatus($ms->getCurrentUserId());
Facebook Description: This method returns an object (in JSON-encoded or XML format) that contains the stream from the perspective of a specific viewer — a user or a Facebook Page.
The equivalent of the Facebook stream in MySpace is the "Activity Stream." A list of the activity stream items can be found at this API endpoint:
GET http://opensocial.myspace.com/roa/09/activities/{userId}/@all
The result is an array of stream items which can include any of the following:
Applications
Events
Music
Notes
People
Photos
Public
Queries
Videos
It is also possible to limit the activity stream returned to only include events from a specific application:
GET http://opensocial.myspace.com/roa/09/activities/{userId}/@all/{appId}
The following is some PHP code using the PHP SDK showing how this is done:
// Get the current user's stream $stream = $myspace->getActivities_ATOM($userId) // Get the friends streams $friend_stream = $myspace->getFriendsActivities_ATOM($userId);
Facebook Description: This method returns all comments associated with a post in a user’s stream. This method returns comments only if the user who owns the post (that is, the user published the post to his or her profile) has authorized your application.
There is no MySpace equivalent for this API call. However, there are API calls to return comments on status updates, mood updates, media items, and a user profile. More information on retrieving the comments from these resources can be found in the comments.get documentation.
Facebook Description: This method returns any filters a user has specified for his or her home page stream.
There is no MySpace equivalent for this API call.
Facebook Description: Returns a wide array of user-specific information for each user identifier passed, limited by the view of the current user.
The MySpace equivalent is the following RESTful resource:
GET http://opensocial.myspace.com/roa/09/people/{userId}/@self
The following are some examples using the PHP library:
// Get basic user information $user_id = $ms->getProfileBasic($userId);
Facebook Description: Gets the user ID (uid) associated with the current session.
The MySpace equivalent is the following RESTful resource:
GET http://opensocial.myspace.com/roa/09/people/@me/@self
The GET method will return the following information from the current user: * User ID * User URI * Web URI * Image URI * Large image URI * User type (e.g., RegularUser) * Hashed data
The following are some examples using the PHP library:
// Get our current sessions user id $user_id = $ms->getCurrentUserId();
Facebook Description: Returns an array of user-specific information for use by the application itself.
The MySpace equivalent is the following RESTful resource:
GET http://opensocial.myspace.com/roa/09/people/{userId}/@self
The following are some examples using the PHP library:
// Get full user information $user_id = $ms->getProfileFull($userId);
Facebook Description: Checks whether the user has opted in to an extended application permission.
There is no MySpace equivalent for this API call. MySpace doesn’t have "extended permissions." Instead, once a user is authenticated, the application has access to the full range of available API calls.
Facebook Description: Returns whether the user (either the session user or user specified by UID) has authorized the calling application.
There is no MySpace equivalent for this API call. An alternative to implementing this API call is to use "App User Data" which is covered in detail later in the document. As a brief overview, App User Data allows an application to store arbitrary key/value pairs for a specific user and application on the MySpace servers. By using this API, setting a key such as "appInstalled" to true upon installation, and checking that key, an application can easily determine if a user has installed the app or not.
Facebook Description: Returns whether the user is a verified Facebook user.
There is no MySpace equivalent for this API call. It can be assumed that if the MySpace user is accessing your application, then he or she is verified.
Facebook Description: Returns the file size and length limits for a video that the current user can upload through your application.
There is no MySpace equivalent for this API call. Since MySpace doesn’t support video uploads through the API, this call is not implemented.
Facebook Description: Adds a comment for a given xid on behalf of a user. Calls with a session secret may only act on behalf of the session user.
While Facebook has a single API to post comments for any resource on Facebook, MySpace only allows commenting via API to status mood comments at the moment.
POST http://opensocial.myspace.com/roa/09/statusmoodcomments/{personId}/@self?statusId={statusId}
The only parameter expected is body which is a string specifying the comment to post.
Facebook Description: Removes a comment for a given xid by comment_id. Calls with a session secret may only act on behalf of the session user.
MySpace doesn’t currently support removing comments through the API.
Facebook Description: Lets a user post a link on their Wall through your application.
There is no MySpace equivalent for this API call. MySpace doesn’t have the same concept of "links" in this sense as Facebook does.
Facebook Description: This method returns a preview of a shared link in the form of a stream attachment.
There is no MySpace equivalent for this API call. MySpace doesn’t have the same concept of "links" in this sense as Facebook does.
Facebook Description: Lets a user write a Facebook note through your application.
There is no MySpace equivalent for this API call. MySpace doesn’t have the same concept of "notes" in this sense as Facebook does.
Facebook Description: Lets a user delete a Facebook note that was written through your application.
There is no MySpace equivalent for this API call. MySpace doesn’t have the same concept of "notes" in this sense as Facebook does.
Facebook Description: Lets a user edit a Facebook note through your application.
There is no MySpace equivalent for this API call. MySpace doesn’t have the same concept of "notes" in this sense as Facebook does.
Facebook Description: Updates a user’s Facebook status through your application. This is a streamlined version of users.setStatus.
This API is equivalent to users.setStatus on the MySpace platform.
The MySpace equivalent is the following RESTful resource:
PUT http://opensocial.myspace.com/roa/09/statusmood/@me/@self
Notes:
Any Status message made up of plain text up to 140 characters is legal. Note that HTML code will be stripped out, however.
The following are some examples using the PHP library:
// Update a target users status, returns true if successful $result = $ms->updateStatus($userId, 'new status msg');
Facebook Description: This method adds a comment to a post that was already published to a user’s Wall.
MySpace doesn’t currently support adding comments through the API.
Facebook Description: This method lets a user add a like to any post the user can see. A user can like each post only once.
There is no MySpace equivalent for this API call.
Facebook Description: This method publishes a post into the stream on the user’s Wall and News Feed. This post also appears in the user’s friends' streams (their News Feeds).
There is no MySpace equivalent for this API call.
Facebook Description: This method removes a post from a user’s Wall. The post also gets removed from the user’s and the user’s friends' News Feeds. Your application may only remove posts that were created through it.
There is no MySpace equivalent for this API call.
Facebook Description: This method removes a comment from a post.
There is no MySpace equivalent for this API call.
Facebook Description: This method removes a like a user added to a post.
There is no MySpace equivalent for this API call.
Facebook Description: Updates a user’s Facebook status.
The MySpace equivalent is the following RESTful resource:
PUT http://opensocial.myspace.com/roa/09/statusmood/@me/@self
Notes:
Any Status message made up of plain text up to 140 characters is legal. Note that HTML code will be stripped out, however.
The following are some examples using the PHP library:
// Update a target users status, returns true if successful $result = $ms->updateStatus($userId, 'new status msg');
Facebook Description: Uploads a video owned by the current session user and returns the video.
There is no MySpace equivalent for this API call.
Facebook has an API for registering connected users to 3rd party websites, so that 3rd party websites can discover which users are and aren’t connected via facebook connect, since facebook connect doesn’t reveal the email information for facebook users.
MySpaceID, although similar in nature, doesn’t support the same email hashing features. 3rd party websites which need to know which MySpace users are and aren’t connected should store the user’s MySpace ID number and assume that users with ID numbers have connected, and users without have not.
More details for supporting this method can be found in the specific API calls below.
Facebook Description: Returns the number of friends of the current user who have accounts on your site, but have not yet connected their accounts. (for Facebook Connect).
While MySpace offers no direct equivalent to this method, the equivalent result can be achieved by storing the MySpace IDs of all the users who have connected on your site, then comparing them to the friend IDs of the specific user you are interested in. The intersection of these two sets would yield the users who are both registered on your site and friends of the current user.
However, the opposite cannot be easily realized (which friends are registered on your site but aren’t connected to MySpace yet), as an API for this feature does not exist.
Facebook Description: Creates an association between an existing user account on your site and that user’s Facebook account, provided the user has not connected accounts before (for Facebook Connect).
This feature is not supported by the MySpace API.
Facebook Description: Unregisters a previously registered account (using connect.registerUsers). You should call this method if the user deletes his or her account on your site. (for Facebook Connect).
This feature is not supported by the MySpace API.
Unfortunately, MySpace currently doesn’t supporting sending SMS messages through the site. If your app is dependent on such a feature, it may be worthwhile to look into using a 3rd party such as Twilio to send SMS to MySpace users and asking for their cell number manually.
Facebook Description: Adds a tag with the given information to a photo.
MySpace does not support the tagging of photos in the same way as facebook. If you wish to implement some sort of tag feature this will have to be emulated using software, unfortunately.
Facebook Description: Creates and returns a new album owned by the specified user or the current session user.
Creating an album can be done by `POST`ing to the following RESTful resource:
PUT http://opensocial.myspace.com/roa/09/albums/{userId}/@self
This call expects the caption parameter to specify the caption for the album.
The following is some example code using the PHP library of creating an album, multiple ways:
// With a simple title $album = $myspace->createAlbum($currentUserId, "My Great Adventure!"); // Specifying a location as well $album = $myspace->createAlbum($currentUserId, "My Overseas Trip!", "Japan"); // Private albums $album = $myspace->createAlbum($currentUserId, "My Girl and I", "", "FriendsOnly");
Facebook Description: Returns all visible photos according to the filters specified.
Depending on the way this API call is used in your application, there are a couple different ways to achieve the same goal with MySpace. If you are simply trying to retrieve all the photos of a specific user, you can use the following RESTful resource, which will do just that.
GET http://opensocial.myspace.com/roa/09/mediaItems/{personId}/{selector}
If instead you’re trying to just retrieve the photos within a specific album of a user, you can use the following RESTful resource:
GET http://opensocial.myspace.com/roa/09/mediaItems/{personId}/{selector}/{albumId}
To support the other options which the facebook API allows (getting photos in a specific list), this can be implemented in your application using the above API calls, but relying instead on a software search. The MySpace API currently has no built-in method of filtering the results automatically.
The following are some examples using the PHP library:
// Get all the photos for a specific user $photos = $myspace->getPhotos($userId); // Get all the photos for a specific album $photos = $myspace->getAlbum($userId, $albumId);
Facebook Description: Returns metadata about all of the photo albums uploaded by the specified user.
The MySpace equivalent is the following RESTful resource:
GET http://opensocial.myspace.com/roa/09/albums/{userId}/@self
This will return the metadata of all the users albums. MySpace has no equivalent to the parameters of the facebook API to filter the results prior to returning them to you. Therefore, if you wish to retrieve a set of only specific albums, this will have to be implemented in software. But you are able to retrieve albums one at a time by specifying an ID at the end of the resource, like so:
GET http://opensocial.myspace.com/roa/09/albums/{userId}/@self/{albumId}
The following is some example code using the MySpace PHP library to get information about albums:
// Get a user's albums $albums = $myspace->getAlbums($currentUserId); // Get a specific album $album = $myspace->getAlbumInfo($currentUserId, $albumId);
Facebook Description: Returns the set of user tags for all photos specified.
MySpace does not support the tagging of photos in the same way as facebook. If you wish to implement some sort of tag feature this will have to be emulated using software, unfortunately.
Facebook Description: Uploads a photo owned by the current session user and returns the new photo.
MySpace currently doesn’t support POST calls for photos. All user photos on MySpace must be uploaded directly by the user.
While MySpace has a rich system for browsing and posting events, the MySpace RESTful API does not yet fully support events. Events can so far only be read via the MySpace ActivityStream. This means, specifically, that there is no POST, PUT, or DELETE support for events.
Facebook Description: Cancels an event. The application must be an admin of the event.
This API call is not supported by MySpace. The user must use the UI on MySpace to cancel an event.
Facebook Description: Creates an event on behalf of the user if the application has an active session; otherwise it creates an event on behalf of the application.
This API call is not supported by MySpace. The user must use the UI on MySpace to create an event.
Facebook Description: Edits an existing event. The application must be an admin of the event.
This API call is not supported by MySpace. The user must use the UI on MySpace to edit his or her event.
Facebook Description: Returns all visible events according to the filters specified.
While there is no specific RESTful API to retrieve the events in JSON format like the other RESTful calls, it is possible to retrieve an ATOM stream of the events. While this isn’t the same as a JSON format, any regular RSS/ATOM reader code could be used to parse these results.
The following URL will return the events a user’s friends are hosting:
http://api.myspace.com/v1/users/{userId}/friends/activities.atom?
page_size=1&activityTypes=EventPosting&extensions=All
The following URL will return the events a user’s friends are attending:
http://api.myspace.com/v1/users/{userId}/friends/activities.atom?
composite=true&page_size=1&activityTypes=EventAttending&extensions=All
And the following URL will return the local band shows for a given user:
http://api.myspace.com/v1/users/{userId}/friends/activities.atom?
composite=true&page_size=1&activityTypes=PersonalBandShowUpdate
Facebook Description: Returns membership list data associated with an event.
This API call is not supported by MySpace.
Facebook Description: Lets your application invite users to an event.
This API call is not supported by MySpace.
Facebook Description: Sets the attendance option for the current user.
This API call is not supported by MySpace.
MySpace has support for a few APIs and features which Facebook either does not offer or does not support. For completion, these are included in this translation guide, so that Facebook developers can keep in mind other ways to maximize the usage of the MySpace platform.
App Data allows application developers to store key/value pairs on the MySpace servers for their application. The data can be anything, and is useful for configuration, usage tracking, and much more. The app data stored in this case is global for the entire application. This means that if you store foo with the value of bar in the app data store, then no matter what user your app is currently dealing with, bar will be returned for foo. This is the opposite of App User Data (next section).
PUT http://api.myspace.com/v1/appdata/global
The body of the PUT request should be a JSON encoded hash of keys to values. Therefore, a single PUT request can store many key/values, allowing developers to mass update app data, without having to use a single request for each key/value pair.
The following is an example of how to create or modify global app data:
// Sets the specified two keys to the two values. $myspace->putGlobalAppData(array( "foo" => "bar", "another" => "value" ));
Getting all app data:
GET http://api.myspace.com/v1/appdata/global
This will respond with an encoded hash of the key value pairs stored for the application.
Getting specific keys:
GET http://api.myspace.com/v1/appdata/global/{keys}
This will respond with an encoded hash containing only the key/value pairs for the keys specified in the keys parameter. Multiple keys should be separated by a semicolon, such as foo;bar to retrieve the value for both the foo key and the bar key.
The following is an example of how to get app data using the PHP SDK:
// Retrieve an array of all the keys $data = $myspace->getGlobalAppData(NULL); // Retrieve an array of only the specified keys $data = $myspace->getGlobalAppData("foo;bar;baz");
DELETE http://api.myspace.com/v1/appdata/global/{keys}
This will delete the keys specified by the keys parameter. Multiple keys should be separated by a semicolon, such as foo;bar to retrieve the value for both the foo key and the bar key.
This method is final. There is no way to reverse, or undo, the deletion of the app data once the request is completed.
The following is an example of how to delete global app data using the PHP SDK:
// Delete the specified keys. Note that you cannot delete all keys // in one request (unless you specify all keys explicitly) $myspace->clearGlobalAppData("foo;bar");
App User Data is the same as App Data except it is specific to the installed user. This allows application developers to store user-specific configuration, usage statistics, and more for their application, without having to use their own storage. App User Data has its own section since the URLs used are a bit different.
PUT http://opensocial.myspace.com/roa/09/appdata/{personId}/@me/{appId}
The body of the PUT request should be a JSON encoded hash of keys to values. Therefore, a single PUT request can store many key/values, allowing developers to mass update app data, without having to use a single request for each key/value pair.
// Sets the specified two keys to the two values. $myspace->putAppData($userId, array( "foo" => "bar", "another" => "value" ));
Getting all app data:
GET http://opensocial.myspace.com/roa/09/appdata/@me/@self/{appId}
This will respond with an encoded hash of the key value pairs stored for the specific application user.
Getting specific keys:
GET http://opensocial.myspace.com/roa/09/appdata/@me/@self/{appId}?fields={keys}
This will respond with an encoded hash containing only the key/value pairs for the keys specified in the keys parameter. Multiple keys should be separated by a semicolon, such as foo;bar to retrieve the value for both the foo key and the bar key.
With app user data, the app user data of friends of users can also be retrieved using the following URLs:
GET http://opensocial.myspace.com/roa/09/appdata/@me/@friends/{appId}
GET http://opensocial.myspace.com/roa/09/appdata/@me/@friends/{appId}?fields={keys}
This will return a hash of the app data for the friends of a given user.
// Retrieve an array of all the keys $data = $myspace->getAppData($userId); // Retrieve an array of only the specified keys $data = $myspace->getAppData($userId, "foo;bar;baz"); // Retrieve an array of friend app data $data = $myspace->getUserFriendsAppData($userId, "foo;bar;baz");
DELETE http://opensocial.myspace.com/roa/09/appdata/@me/@self/{appId}
This will delete the keys specified by the fields parameter. Multiple keys should be separated by a semicolon, such as foo;bar to retrieve the value for both the foo key and the bar key.
This method is final. There is no way to reverse, or undo, the deletion of the app data once the request is completed.
// Delete the specified keys. Note that you cannot delete all keys // in one request (unless you specify all keys explicitly) $myspace->clearAppData($userId, "foo;bar");
The indicators API is a simple API which returns a list of all the indicators which are currently active for a given user. Indicators identify things such as new mail, pending friend requests, etc. A complete list of the indicators can be found below:
TopFriend
NewPendingCommentApproval
NewGroupInvite
NewGroupRequest
NewMiniBlogComment
AppInvites
AppNotifications
KSoloFavNewSongFeedBack
KSoloFavNewSongFan
BulletinComments
FriendSuggestion
NewAppNotificationMail
NewMoodStatusComments
NewAppVirtualGift
NewBirthday
NewBlogComment
NewBlogSubscriptionPost
NewComment
NewEventInvitation
NewFriendRequest
NewGroupNotification
NewMail
NewPhotoTagApproval
NewPictureComment
NewRecentlyAddedFriend
NewUnreadIM
NewVideoComment
NewVideoProcess
Ksolo
GET http://api.myspace.com/v1/users/{userid}/indicators
This will return, in XML or JSON format, the list of active indicators for the given user. The format of the active indicators will be equivalent to the above list in the overview section.
The following shows how to retrieve the indicators using the PHP SDK:
// Gets the full list of active indicators $indicators = $myspace->getIndicators($userId);
The moods API allows developers to retrieve a list of available moods for a specific user or the the current mood of a specific user. The moods returned contain the mood string (such as "Happy"), the mood image url on the MySpace servers, and the mood file name.
It is possible to return a list of all available moods for a specific user. The moods returned contain the mood string, the URL to the image on the MySpace servers, and the filename of the mood.
Get all moods:
GET http://opensocial.myspace.com/roa/09/statusmood/@self/@supportedMood
Retrieving a users mood is a simple URL call:
GET http://opensocial.myspace.com/roa/09/statusmood/@me/@self
The following is an example for retrieving a user’s mood using the PHP SDK:
// Get a user's mood $mood = $myspace->getMood($userId);
The app notifications API allows developers to send notifications through the applications to users. These notifications can contain text, an image, and customized buttons. The true power of these notifications can be seen on the App Notifications page.
All notifications which are sent must use a pre-configured template built within the MySpace developer center. While this restriction may seem limiting initially, arbitrary JavaScript, OSML, and HTML can be included within the template itself. The combination of these technologies makes the notification templates quite robust.
Creating notifications is done through the following URL:
POST http://opensocial.myspace.com/roa/09/notifications/{personId}/@self
The following parameters are expected:
recipientIds - A comma separated list of MySpace user IDs.
templateParameters - A hash containing at least a content key specified which will contain the content of the notification.
mediaItems - A URL to an (optional) media item, such as an image. Only one media item may be specified at this time.
For full documentation of the parameters and all the options they may take, read the App Notifications page.
The following is some example usage of sending notifications using the PHP SDK:
// A simple notification which says "Hello, World!" sent to a user. $myspace->sendNotification($appId, $userId, array("content" => "Hello, World!"), NULL); // A notification sent to multiple recipients, containing a simple message $myspace->sendNotification($appId, array($userId, $userId2), array("content" => "Hello, folks!"), NULL); // A notification with an image attached $myspace->sendNotification($appId, $userId, array("content" => "Hello, World!"), "http://mywebsite.com/image.jpg");
Bringing the entirety of this document together, we will finally provide a step-by-step example of converting an existing Facebook application to the MySpace platform. Since this document, for now, only focuses on authentication and RESTful APIs, the example application will minimize on its usage of other features such as FBML, FBJS, and FQL.
The example application we’ll be porting over is called "Friend Shuffle." Friend shuffle allows a user to choose one of his or her friend’s photos, and solve a puzzle with that photo shuffled! A picture of what this looks like can be seen below. Once a user solves a shuffled puzzle, he or she has the option of updating his or her status to let friends know that the puzzle was completed, or to notify that friend that a puzzle of him or her was completed.

The reason this application was chosen was because it presents many of the API categories in a single application. The example application showcases the following APIs:
iFrame authentication
Photos
Albums
Status
Friends
Users
App Notifications
The code for the Facebook application was written in such a way that all the API calls are abstracted into separate functions in global.php. This allows us to simply change those functions for MySpace APIs for the MySpace application, and the rest of the application should "just work." Although this isn’t completely the case and some minor HTML tweaks must be made, its a fairly successful strategy that is highly recommended for maintaining code for multiple platforms.
Although this document contains a step-by-step guide for porting the code to the MySpace platform, the full package of both the complete Facebook and MySpace code can be downloaded here.
The remainder of this guide will assume that you’re familiar with the Facebook version of the code, pointing out ways in which the Facebook code must be changed in order to run on the MySpace platform. In most cases, the Facebook code will be reproduced next to the new MySpace code for comparison.
The first step to converting the application is to setup a new MySpace application at developer.myspace.com. This requires a MySpace developer account. If you have an existing MySpace account, this can be upgraded to a developer account with a few simple clicks. To setup your developer account, go to developer.myspace.com and click on the sign up or log in buttons. These pages will guide you through the process of setting up your account. An image below shoes where to go:

Once logged in, click on the "My Apps" then "Create New App" button. Once there, create a new on site application. This is used to create an application which resides within an iFrame on the site or with pre-uploaded templates. The other type of application, MySpaceID, is used to create a 3rd party website which uses MySpaceID for authentication.
An image below shows what this page should look like:

Once you’re on the page with the form to create a new application, fill in the appropriate details. Some important notes are that the email field must be a new and unique email for that application. The image below shows what the completed form looks like (of course email and password are up to you):

Once that is done, click "Next" and on the next page, click "Skip Step." You should now be presented with a page full of options. Fill in the required options with anything you’d like, but leave everything else for now. We’ll come back to this later.
At this point you have a new MySpace application which is in "development" mode, meaning that only the list of approved developers (only you for now) can see and test this app. Once everything is complete and setup, we’ll publish it.
The first thing we need to do is update some configuration values, since MySpace has some different keys, different URLs, etc. So the first configuration values we’re going to change are simply the API key and the secret key, which in MySpace terms are the consumer key and the oauth secret. The following, for reference, is the part of the configuration file discussed here before changing it:
/* FACEBOOK VERSION */ // Get these from http://developers.facebook.com $api_key = 'API_KEY'; $secret = 'SECRET';
Nothing needs to be changed in this case, but values need to be updated, so the resulting configuration file looks the same. The resulting configuration code is reproduced here with fake consumer and secret keys so that you can compare and see if they are similar to verify that you have the correct value:
/* MYSPACE VERSION */ // Get these from http://developer.myspace.com $api_key = 'http://www.myspace.com/524431225'; $secret = 'be5a4b8ac6404485981a9d2de3aea96df8d7508e3bc414011bbc06bc8e33562b1';
Currently, the only other configuration item is the $base_url key. In the case of a Facebook application, this needs to be known in order to generate URLs for links and so on. For a MySpace application, the domain as well as the base url need to be known for OAuth verification and for generating URLs. Therefore, we add the $base_domain configuration, and the resulting code looks like this:
/* MYSPACE VERSION */ // Appears below the api keys // Base URL of the app and the domain $base_domain = "http://mydomain.com"; $base_url = "{$base_domain}/myapp";
One last value is needed for the MySpace app, and that is the application ID. This will be used later to tell MySpace to resize our iFrame. For now, this can simply be added below the base domain and URL.
To find an application’s ID, go to developer.myspace.com, click My Apps, then click Edit Source for the application you are interested in. The ID can then be copied out of the URL. An image shows this below:

The configuration code is reproduced below:
/* MYSPACE VERSION */ // Application ID for iFrame resizing $app_id = "180479";
The final configuration file for the MySpace app is shown below:
<?php define("FRIEND_PUZZLE", 1); // Get these from http://developer.myspace.com $api_key = 'http://www.myspace.com/524431225'; $secret = 'be5a4b8ac6404485981a9d2de3aea96df8d7508e3bc414011bbc06bc8e33562b1'; // Base URL of the app and the domain $base_domain = "http://mydomain.com"; $base_url = "{$base_domain}/myapp"; $app_id = "180479"; ?>
In the global.php file, where all the library loading is done, we need to replace the Facebook library with the MySpace library. The MySpace library has a couple dependencies, namely OAuth and Auth_OpenID. These are expected to be available on the load path, so that must be setup as well. For reference, here is the piece of code from the Facebook version we’ll be replacing:
// Include the facebook PHP library require_once "lib/facebook/facebook.php";
The resulting MySpace code:
// get the currently set include path $path = ini_get('include_path'); // add the lib directory to the include path $path = "lib/" . PATH_SEPARATOR . $path; // save the new include path ini_set('include_path', $path); // Include the MySpace PHP library require_once "MySpaceID/myspace.php";
This code first uses a few lines to setup the new include path. The new include path simply has the path to where all the libraries are stored added to it. In this case, MySpaceID, Auth_OpenID, and OAuth are all in the lib/ directory.
After setting up the include path, we load the MySpace library.
Since Friend Shuffle is an iFrame application, much of the authentication heavy lifting is done for us by MySpace. When MySpace requests the app in an iFrame, it’ll pause the already-valid OAuth keys as GET parameters. Therefore, we simply need to instantiate a MySpace object. We also need to store the user ID, which is only given on the first page visited.
To instantiate the MySpace object, we’ve added a function to global.php:
function get_myspace_object() { global $api_key, $secret; $myspace = new MySpace($api_key, $secret, null, null, false); return $myspace; }
This function uses the $api_key and $secret variables from the configuration file to instantiate a MySpace object. The MySpace library transparently handles the iFrame authentication.
After writing the new function, we replace the following old Facebook-specific code:
// Setup the facebook object $facebook = new Facebook($api_key, $secret); $facebook->require_frame(); $user = $facebook->require_login("publish_stream");
With the following new MySpace object code:
// Setup the MySpace object $myspace = get_myspace_object();
The current user ID is passed in as a GET variable only on the first page request. Since Friend Shuffle is a multi-page application, we simply store it in a session for use across pages. Typically, every page call should verify that this ID is valid and is the current ID, but for the purposes of simplicity in this demo, we’ve assumed its valid.
In the Facebook version of the Friend Shuffle application, this is not necessary since all the API calls assume they’re for the current user. For MySpace, the user ID must be explicitly passed in via the URL, in a RESTful manner. This is not a limitation, since by placing other user IDs into the URL, other user information can be requested.
The following code shows the user ID being saved if it was passed in:
// Store the user ID if it was given to us if ($_GET['opensocial_owner_id']) { $_SESSION['userId'] = $_GET['opensocial_owner_id']; } // Set it as a global variable for API use later $userId = $_SESSION['userId'];
This code can be placed anywhere, as long as its before any API calls are made. In global.php, we placed it just after MySpace object instantiation.
Friend Shuffle is written in such a way that all the API calls are placed into their own functions in the global.php file. In theory then, this should allow us to just change the contents of those functions to use the MySpace API, and the rest of the application should simply work. This turns out to not be entirely true, but converting the API calls is the vast majority of the work.
For each API call, we’re going to convert it to use the MySpace API, then massage the data returned into the format used by the Facebook application. For example, if the friend select page expects the $friend array to have a name key, but MySpace returns a full_name key, then we’ll automatically setup the name key to use the full_name value for the app. This will allow us to only change the functions in global.php without having to worry about modifying the other files too much.
Description: Gets the list of friends for the current user and returns an array of their names and IDs, alphabetized.
The get_friends API is used on the initial page to show a list of all available friends. The user is then allowed to choose one of these friends. The Facebook-specific code is reproduced below:
/* FACEBOOK VERSION */ function get_friends() { global $facebook; $friends = $facebook->api_client->friends_get(); $friend_info = $facebook->api_client->users_getInfo($friends, array("name", "pic_square")); // Alphabetize usort($friend_info, "sortByName"); return $friend_info; }
Facebook requires two separate API calls for this information. The first retrieves a list of UIDs for the friends and the second returns the name and pic_square information for each user in the $friends array (which is every friend). Experienced Facebook developers may be scoffing at this code, noting that a simple FQL query can do the same thing in a single request, but the entire Friend Shuffle application explicitly uses only RESTful API calls to showcase how those can be migrated to the MySpace platform.
The equivalent MySpace code is similar, but requires only one API call. The data must then be massaged to have the same structure as the Facebook results. Note that the sorting function sortByName does not need to be modified since the data comes out in the same format:
/* MYSPACE VERSION */ function get_friends() { global $myspace, $userId; $friends = $myspace->getFriends($userId); $friend_info = array(); // Massage data into Facebook-style format foreach ($friends->Friends as $friend) { $friend_info[] = array( "uid" => $friend->userId, "name" => $friend->name, "pic_square" => $friend->image ); } // Alphabetize usort($friend_info, "sortByName"); return $friend_info; }
Description: Gets a list of all the albums for a given user. These albums are returned as an array in no specific order.
The get_albums API is used after a friend is selected to retrieve all the albums of that user so that the current user can drill down into a friend’s photos to shuffle. The Facebook version of the code is reproduced below.
/* FACEBOOK VERSION */ function get_albums() { global $facebook; return $facebook->api_client->photos_getAlbums($_GET['uid'], ''); }
As you can see, the Facebook version is a simple single API call. The MySpace call is likewise a single API, but the data must once again be massaged into the Facebook format so the rest of the app continues to work with minimal modification. The MySpace version is reproduced below:
/* MYSPACE VERSION */ function get_albums() { global $myspace; $albums = $myspace->getAlbums($_GET['uid'], 1, "all"); $return_value = array(); foreach ($albums->albums as $album) { $return_value[] = array( "aid" => $album->id, "name" => $album->title ); } return $return_value; }
Specifically, the API call specifies that it is for the $_GET[uid] user and that all albums should be returned on 1 page. This is to avoid having to paginate through the albums.
Description: Returns the photos for a given album for a given user. The photos returned are in no particular order.
After selecting both a friend and an album, the next page, specifically photo_select.php uses get_album_photos to retrieve all the photos in the selected album. The Facebook version of the code is reproduced below.
/* FACEBOOK VERSION */ function get_album_photos() { global $facebook; return $facebook->api_client->photos_get($_GET['uid'], '', ''); }
Again, the Facebook version is a single API call. And again, so is the MySpace version. The data has to be massaged a bit but all the photo information can be retrieved in a single request. The MySpace version of the code is reproduced below:
/* MYSPACE VERSION */ function get_album_photos() { global $myspace; $album = $myspace->getAlbum($_GET['uid'], $_GET['aid']); $photos = array(); foreach ($album->photos as $photo) { $photos[] = array( "aid" => $_GET['aid'], "pid" => $photo->id, "src_small" => $photo->smallImageUri ); } return $photos; }
Description: Gets the user info for a friend of the current user and returns data about their name, profile pic, etc.
Some pages display the friend’s name in contexts such as "Select one of John Doe’s photos!" This API call uses the uid given as a GET parameter and retrieves profile information about that user. The Facebook version is reproduced below:
/* FACEBOOK VERSION */ function get_friend() { global $facebook; $result = $facebook->api_client->users_getInfo(array($_GET['uid']), array("name")); return $result[0]; }
While the Facebook version is a single request, Facebook has no RESTful API to retrieve just a single user. Therefore, users.getInfo is used requesting only a single uid. After making the request, the first user is returned. MySpace, on the other hand, has a specific RESTful API which can be used to retrieve profile information for a single user. After retrieving the information, the data is massaged slightly before returning it. This code is reproduced below:
/* MYSPACE VERSION */ function get_friend() { global $myspace; $result = $myspace->getProfile($_GET['uid']); return array( "name" => $result->basicprofile->name ); }
Description: Gets metadata about a single photo within an album for a given user. The returned photo is simply a URL to the actual image.
After selecting a friend, album, and photo, get_photo is used by photo_puzzle.php to retrieve the URL for the given image so that it can be turned into a puzzle for the current user to solve. THe Facebook version is shown below:
/* FACEBOOK VERSION */ function get_photo() { global $facebook; $photo = $facebook->api_client->photos_get($_GET['uid'], $_GET['aid'], $_GET['pid']); return $photo[0]; }
Just like get_friend, Facebook has no RESTful API to retrieve a single photo from an album. Instead, photos.get is used with a single PID, and the first result is returned from the function. And again, MySpace does have an API to retrieve a single photo from an album. This is used in the MySpace version of the code, shown below:
/* MYSPACE VERSION */ function get_photo() { global $myspace; $photo = $myspace->getAlbumPhoto($_GET['uid'], $_GET['aid'], $_GET['pid']); return array( "src_big" => $photo->imageUri ); }
Description: Updates the status of the current user to the given message.
After completing a puzzle, the current user has the option of updating his or her status or sharing with friends. When updating the user’s status, this function is called with a message parameter. For Facebook, this publishes a simple text message into the user’s stream. For MySpace, it actually updates the user’s status. The Facebook version is shown below:
/* FACEBOOK VERSION */ function update_status($status) { global $facebook; $facebook->api_client->stream_publish($status); }
Just like the Facebook version, the MySpace version is also simply a single API call:
/* MYSPACE VERSION */ function update_status($status) { global $myspace, $userId; $myspace->updateStatus($userId, $status); }
Description: Notifies a friend of the current user with the given message.
Alternately, instead of updating one’s status, the current user could choose to share with friends. As of the writing of this guide, Facebook no longer supports the app notifications API and the inbox API is not yet complete. Therefore, the Facebook version uses the friend’s wall as a place to notify the friend that the puzzle was solved. MySpace has a MySpace-specific feature known as "App Notifications," covered in section 4, which will be used instead. Since share.php simply calls the notify_friend method, it doesn’t care how the friend is notified, and switching the Facebook code to the MySpace code is completely transparent.
The Facebook code is shown below:
/* FACEBOOK VERSION */ function notify_friend($friendId, $message) { global $facebook; // Simply publish on the friend's stream $facebook->api_client->stream_publish($message, NULL, NULL, $friendId); }
The MySpace code is shown below:
/* MYSPACE VERSION */ function notify_friend($friendId, $message) { global $myspace, $app_id; // Send an "App Notification" $myspace->sendNotification($app_id, $friendId, array("content" => $message), NULL); }
With the API calls in global.php converted to the MySpace platform, most of the application is already functional! There are a few minor HTML tweaks which must be made, however, due to some small differences in the way that Facebook iFrame apps and MySpace iFrame apps are handled.
The first difference which is addressed is how multi-page applications are done. In Facebook iFrame applications, the end of the Facebook URL is passed down into the iFrame. For example, if the Facebook application is at http://apps.facebook.com/myapp and the iFrame is at http://myapp.com/, then going to http://apps.facebook.com/myapp/sub/directory/foo.php would go to http://myapp.com/sub/directory/foo.php in the iFrame. Therefore, to navigate page to page, the top-level window URL is changed to some new value.
MySpace, on the other hand, has a single static canvas page for applications. In this case, multi-page apps are implemented through navigation in the iFrame itself. To address this, in the MySpace version, all links which have a target of _top must have that attribute removed. For example, the following link:
<a href="<?= $base_url ?>/puzzle_complete.php" target="_top">Complete!</a>
Must be turned into the following:
<a href="<?= $base_url ?>/puzzle_complete.php">Complete!</a>
Almost every PHP file has a link of some sort in it. A simple find-and-replace through the files should suffice.
The canvas iFrame on MySpace is 500 pixels by default. Some pages, depending on the amount of friends, photos, etc. will exceed this height. In order to tell MySpace that the iFrame needs to be resized, a few additional changes must be made.
First, the following HTML file needs to be added somewhere within the project, named ifpc_relay_external002.html:
<script type="text/javascript"> var u = location.href, h = u.substr(u.indexOf('#') + 1).split('&'), t, r; try { t = h[0] === '..' ? parent.parent : parent.frames[h[0]]; r = t.gadgets.rpc.receive; } catch (e) { } r && r(h); </script> var u = location.href, h = u.substr(u.indexOf('#') + 1).split('&'), t, r; try { t = h[0] === '..' ? parent.parent : parent.frames[h[0]]; r = t.gadgets.rpc.receive; } catch (e) { } r && r(h); </script>
This file serves as the relay file which is used for communicating to and from the iFrame. Next, the following must be added to the head of the header HTML to setup the iFrame communication:
<script type="text/javascript" src="http://js.myspacecdn.com/OpenSocial/RPC/RpcContainer.003.js"></script> <script type="text/javascript" src="http://myspace-samples.appspot.com/iframe/v5/IFPC_externalIframe006.js"></script> <script type="text/javascript"> //<![CDATA[ gadgets.rpc.setRelayUrl('..', 'http://profile.myspace.com/Modules/Applications/Pages/rpc_relay.aspx'); var container = MyOpenSpace.MySpaceContainer.get(); container.registerParam("panelId", "apppanel_<?= $app_id ?>_canvas"); container.registerParam("localRelay", "<?= $base_url ?>/ifpc_relay_external002.html"); // ]]--> </script>
Note that there is no Facebook equivalent of this, so it should simply be added anywhere in the head portion of the header file. Also, you may notice that this is the portion of the application which makes use of the $app_id configuration for setting up the panel ID. Finally, the localRelay parameter is setup to point to wherever you placed the ifpc_relay_external002.html file.
With all this in place, the following code can finally be placed in the footer, just prior to the closing body tag. This causes the iFrame to automatically resize to fit the content every half second. The timer must be placed since there is some dynamic content which changes size (the puzzle).
<script type="text/javascript"> //<![CDATA[ // Readjust MySpace iFrame height every half second setInterval(function() { MyOpenSpace.MySpaceContainer.get().adjustHeight(); }, 500); // Readjust iFrame height initially MyOpenSpace.MySpaceContainer.get().adjustHeight(); // ]]--> </script>
The code is now setup and ready to be launched! The final step is setting up the MySpace application canvas to load an iFrame pointing to the proper application files. To do this, go to the "My Apps" section of the MySpace developer center and click on "Edit Sources." An image below shoes where this is.

Once in that section, you should already be on the tab marked "Canvas Surface." If not, click on that tab to make it the focus. After selecting the tab, make sure the "App Type" selected is set to "External iFrame." Then, in the "External iFrame URL" field, place the path to the index.php page of the Friend Shuffle application. An image showing all this properly filled out is shown below:

After filling in the form properly, don’t forget to click "Save Application Source." A blue box which says "Success" should appear notifying you that it was successfully saved.
With all the settings filled out, you can now click "Dev App" on the "Canvas Surface" tab of the "Edit Sources" page to try out the application in development mode. In development mode only specified developers and testers have access to the application.

The final step for allowing your application to be used by the general public is to publish it. Before publishing however, a couple things must be done:
Update the configuration to have the proper category and subcategory
You must upload a proper small/big image.
Fill in a proper description for the profile page.
After completing the above steps, simply click the "Publish" button on the "My Apps" page and it will be live and MySpace users will begin using your application!
