161
Yahoo! Application Platform Developers Guide

Yap Dev Guide

Embed Size (px)

Citation preview

Page 1: Yap Dev Guide

Yahoo! Application Platform DevelopersGuide

Page 2: Yap Dev Guide

Yahoo! Application Platform Developers Guide

Abstract

This guide provides conceptual information, tutorials, and code examples for the Yahoo! Application Platform (YAP).It is for software developers who are familiar with technologies such as HTML, JavaScript, PHP, and Web services.To find out what's new in this release, see the YAP Release Notes1.

This guide is available in both HTML2 and PDF3.

Have a comment or question about this document? Let us know in the YDN Forum for YOS Documentation4.

1 /yap/releasenotes/2 http://developer.yahoo.com/yap/guide/3 http://developer.yahoo.com/yap/guide/yap-dev-guide.pdf4 http://developer.yahoo.net/forum/index.php?showforum=64

Page 3: Yap Dev Guide

Table of Contents1. Overview of the Yahoo! Application Platform (YAP) ............................................................... 1

What is YAP? .............................................................................................................. 1Programming Models ................................................................................................... 1

Server-Side ......................................................................................................... 1Browser-Side OpenSocial JavaScript ....................................................................... 2Browser-Side Flash .............................................................................................. 3

Encoding Requirements and MIME Types ........................................................................ 4Supported Image Formats ...................................................................................... 4

Submission Guidelines ................................................................................................. 5Application Distribution and Promotion ........................................................................... 6

Publishing With the Add-to-Yahoo! Button ............................................................... 6Using the Share and Message Features ..................................................................... 8Leveraging Updates ............................................................................................. 8Using Preview ..................................................................................................... 8

2. Getting Started: Build Your First Open Application ................................................................. 9Introduction ................................................................................................................ 9Prerequisites ............................................................................................................... 9Getting the Code and Images ......................................................................................... 9Configuring Your Application ....................................................................................... 10Previewing Your Application ........................................................................................ 13Pushing Your Application Live ...................................................................................... 13Running the Canvas View ............................................................................................ 14Updating Your Application ........................................................................................... 14Submitting Your Application to Yahoo! ........................................................................... 15

3. Anatomy of an Open Application ....................................................................................... 16Introduction .............................................................................................................. 16Small View ............................................................................................................... 17Canvas View ............................................................................................................. 18Preview .................................................................................................................... 20Chrome .................................................................................................................... 21Landing Page ............................................................................................................ 21My Applications ........................................................................................................ 22Messages .................................................................................................................. 23Sharing .................................................................................................................... 24Updates .................................................................................................................... 25

4. Best Practices ................................................................................................................ 26Introduction .............................................................................................................. 26Helping Users Discover Your Application ....................................................................... 26

Do's ................................................................................................................. 26Don'ts .............................................................................................................. 27

Providing a Better Initial Experience ............................................................................. 27Do's ................................................................................................................. 27Don'ts .............................................................................................................. 27

Optimizing the Views .................................................................................................. 27Do's ................................................................................................................. 28Don'ts .............................................................................................................. 28

Making Applications Social ......................................................................................... 28Do's ................................................................................................................. 28Don'ts .............................................................................................................. 29

Respecting Your Users ................................................................................................ 29Do's ................................................................................................................. 29

February 29, 2012iiiYahoo! Developer Network

Page 4: Yap Dev Guide

Don'ts .............................................................................................................. 29Improving Performance ............................................................................................... 29

Do's ................................................................................................................. 30Don'ts .............................................................................................................. 30Image Caching .................................................................................................. 30

Optimizing Your Application for the Gallery ................................................................... 30Do's ................................................................................................................. 30Don'ts .............................................................................................................. 31

5. Setting the Small View of an Open Application ..................................................................... 32Introduction .............................................................................................................. 32Prerequisites ............................................................................................................. 32Creating the Default State ............................................................................................ 33Creating the Personalized State ..................................................................................... 36

Applications Using Private Data ........................................................................... 36Applications Using Public Data ............................................................................ 37

Source Code ............................................................................................................. 396. Yahoo! Markup Language (YML) ...................................................................................... 40

Introduction to YML ................................................................................................... 40What is YML? ................................................................................................... 40Benefits ........................................................................................................... 40Syntax Rules ..................................................................................................... 41URL Parameter Encoding and Relative Paths .......................................................... 41YML Lite ......................................................................................................... 42

yml:a ....................................................................................................................... 42Description ....................................................................................................... 42Attributes ......................................................................................................... 42Examples ......................................................................................................... 43

yml:audio ................................................................................................................. 45Description ....................................................................................................... 45Attributes ......................................................................................................... 45Examples ......................................................................................................... 45

yml:customize ........................................................................................................... 46Description ....................................................................................................... 46Attributes ......................................................................................................... 46Examples ......................................................................................................... 46

yml:form .................................................................................................................. 46Description ....................................................................................................... 46Attributes ......................................................................................................... 46Examples ......................................................................................................... 46

yml:friend-selector ..................................................................................................... 47Description ....................................................................................................... 47Attributes ......................................................................................................... 47Examples ......................................................................................................... 47

yml:if-env ................................................................................................................. 47Description ....................................................................................................... 47Attributes ......................................................................................................... 48Examples ......................................................................................................... 48

yml:include ............................................................................................................... 48Description ....................................................................................................... 48Attributes ......................................................................................................... 48Examples ......................................................................................................... 49

yml:message ............................................................................................................. 50Description ....................................................................................................... 50Attributes ......................................................................................................... 51

February 29, 2012ivYahoo! Developer Network

Yahoo! Application Platform De-velopers Guide

Page 5: Yap Dev Guide

Examples ......................................................................................................... 51yml:name ................................................................................................................. 52

Description ....................................................................................................... 52Attributes ......................................................................................................... 52Examples ......................................................................................................... 53

yml:profile-pic .......................................................................................................... 53Description ....................................................................................................... 53Attributes ......................................................................................................... 53Examples ......................................................................................................... 53

yml:pronoun ............................................................................................................. 54Description ....................................................................................................... 54Attributes ......................................................................................................... 54Examples ......................................................................................................... 54

yml:share ................................................................................................................. 54Description ....................................................................................................... 54Attributes ......................................................................................................... 55Examples ......................................................................................................... 55

yml:swf .................................................................................................................... 55Description ....................................................................................................... 55Attributes ......................................................................................................... 55Tag contents ...................................................................................................... 56Examples ......................................................................................................... 56

yml:user-badge .......................................................................................................... 56Description ....................................................................................................... 56Attributes ......................................................................................................... 56Examples ......................................................................................................... 56

7. Caja Support .................................................................................................................. 58Introduction .............................................................................................................. 58

What is Caja? .................................................................................................... 58Caja Status for This Release ................................................................................. 58Why Do We Need Caja? ...................................................................................... 59How Does Caja Work? ........................................................................................ 59

How Do I Debug My Application? ................................................................................ 61YML Alters Caja Line Numbers ........................................................................... 61

What HTML Tags are Blacklisted? ................................................................................ 62What Works in Caja? .................................................................................................. 62

Browsers Supported ........................................................................................... 62HTML and CSS ................................................................................................. 62YML ............................................................................................................... 62DOM manipulation ............................................................................................ 63Events and Timers .............................................................................................. 63OpenSocial 0.9 .................................................................................................. 63

What are Caja's Limitations? ........................................................................................ 63Server-Side vs. Client-Side Sanitization ................................................................. 63XHTML Strictness ............................................................................................. 63HTML Limitations ............................................................................................. 64CSS Limitations ................................................................................................ 65JavaScript limitations .......................................................................................... 65DOM Limitations ............................................................................................... 67Flash Restrictions ............................................................................................... 68

What Do These Messages Mean? .................................................................................. 69Compile-Time Errors .......................................................................................... 69Runtime errors .................................................................................................. 69

8. YUI Support .................................................................................................................. 70

February 29, 2012vYahoo! Developer Network

Yahoo! Application Platform De-velopers Guide

Page 6: Yap Dev Guide

Introduction .............................................................................................................. 70YUI Libraries and Utilities Available in YAP ........................................................... 70Including YUI Scripts and CSS ............................................................................. 71Support and Bugs ............................................................................................... 71

YUI Examples for YAP ............................................................................................... 72Event Handlers .................................................................................................. 72Scrolling Animation ........................................................................................... 74

9. OpenSocial 0.9 Compatibility ........................................................................................... 77Overview of OpenSocial Support .................................................................................. 77

Gadget Configuration for OpenSocial .................................................................... 77OpenSocial JavaScript Features Supported by YAP ........................................................... 78

Activity ............................................................................................................ 78Messaging ........................................................................................................ 79Person and People .............................................................................................. 79Supported DataRequest Fields .............................................................................. 80Using Environment.supportsField ......................................................................... 80Permissions ...................................................................................................... 80Gadget Core APIs .............................................................................................. 80

OpenSocial RESTful APIs Supported by YAP ................................................................. 80OpenSocial Code Samples ........................................................................................... 81

Activities Demo ................................................................................................. 81Gifts Demo ....................................................................................................... 84Yahoo! Profile Demo .......................................................................................... 91

Gadget XML Configuration File ................................................................................... 93Content Sections ................................................................................................ 97Application Categories ........................................................................................ 98Legacy Applications ........................................................................................... 99

10. OpenSocial 0.8 Compatibility ........................................................................................ 101OpenSocial 0.8 Legacy Support .................................................................................. 101OpenSocial 0.8 JavaScript Features Supported by YAP .................................................... 101

Activity .......................................................................................................... 101Messaging ...................................................................................................... 102Person and People ............................................................................................ 102Supported DataRequest Fields ............................................................................ 103Using Environment.supportsField ........................................................................ 103Permissions ..................................................................................................... 103Gadget Core APIs ............................................................................................. 103

OpenSocial RESTful APIs Supported by YAP ................................................................ 103Differences Between Versions 0.8 and 0.7 JavaScript APIs ............................................... 104

Using opensocial.IdSpec .................................................................................... 104When NOT to Use opensocial.IdSpec ................................................................... 105Retrieving Friends With NETWORK_DISTANCE ................................................. 105Activity Response Format .................................................................................. 105

OpenSocial Code Samples ......................................................................................... 106Activities Demo ............................................................................................... 106Gifts Demo ..................................................................................................... 109

Gadget Configuration for OpenSocial 0.8 ...................................................................... 11611. Code Examples ........................................................................................................... 117

Prerequisites ............................................................................................................ 117YML Code Examples ................................................................................................ 117

Tabs in the Small View ...................................................................................... 117Friend Selector ................................................................................................ 119Friend Selector With Style ................................................................................. 120Navigate from Small View to Canvas View ............................................................ 121

February 29, 2012viYahoo! Developer Network

Yahoo! Application Platform De-velopers Guide

Page 7: Yap Dev Guide

Preview Open Application Small View ................................................................. 122Links to Yahoo! Profiles .................................................................................... 123Accordion Menu for an Open Application ............................................................. 124Refreshing the Small View ................................................................................. 126Refreshing the Small View Dynamically ............................................................... 128

Caja-Ready Code Examples ....................................................................................... 130Event Handling ................................................................................................ 130JSON Conversion ............................................................................................. 132Ajax Request ................................................................................................... 134Wall-to-Wall Open Application ........................................................................... 136

Other Code Examples ............................................................................................... 138My Social PHP Application ................................................................................ 138Additional Code Examples ................................................................................. 145

A. Parameters Passed to an Open Application ........................................................................ 147B. YAP Developer Web Services .......................................................................................... 151

General Information .................................................................................................. 151Authorization .................................................................................................. 151Response Codes ............................................................................................... 151

Set Small View Web Service ....................................................................................... 151Description ..................................................................................................... 152URI ............................................................................................................... 152Methods ......................................................................................................... 152Request Body .................................................................................................. 152

February 29, 2012viiYahoo! Developer Network

Yahoo! Application Platform De-velopers Guide

Page 8: Yap Dev Guide

List of Figures1.1. Server-Side ................................................................................................................... 21.2. Browser-Side JavaScript .................................................................................................. 31.3. Browser-Side Flash ........................................................................................................ 43.1. Anatomy of an Open Application details the composition of an application with its differentViews, states, and locations. ................................................................................................. 173.2. Example Small View ..................................................................................................... 183.3. Example Canvas View ................................................................................................... 203.4. Chrome Screenshot ...................................................................................................... 213.5. Landing Page Screenshot ............................................................................................... 223.6. My Applications Screenshot ........................................................................................... 233.7. Message Screenshot ...................................................................................................... 243.8. Sharing Screenshot ....................................................................................................... 253.9. Updates Screenshot ...................................................................................................... 2511.1. Tab 2 Selected .......................................................................................................... 11811.2. Friend Selector Screenshot ......................................................................................... 11911.3. Preview of Canvas View ............................................................................................. 12211.4. Links to Yahoo! Profile With YML ............................................................................... 12311.5. Accordion Screenshot ................................................................................................ 124

February 29, 2012viiiYahoo! Developer Network

Page 9: Yap Dev Guide

List of TablesA.1. Parameters Passed to an Open Application ...................................................................... 147

February 29, 2012ixYahoo! Developer Network

Page 10: Yap Dev Guide

Chapter 1. Overview of the Yahoo!Application Platform (YAP)

In This Chapter

• “What is YAP?” [1]

• “Programming Models” [1]

• “Encoding Requirements and MIME Types” [4]

• “Submission Guidelines” [5]

• “Application Distribution and Promotion” [6]

• “Using the Share and Message Features” [8]

• “Leveraging Updates” [8]

• “Using Preview” [8]

What is YAP?The Yahoo! Application Platform (YAP) is the software and services that enable developers to build Webapplications that are available throughout Yahoo!—to the largest audience in the world. The Yahoo! Ap-plication Platform has the following components:

• Development environment: A browser-based tool that enables software developers to quickly create,preview, and publish Web applications.

• APIs and Web services: Programmatic access to OpenSocial functionality and popular Yahoo! Webservices.

• Distribution and discovery infrastructure: Built-in features for publishing applications in Yahoo! galleriesand properties, including Yahoo! Toolbar and My Yahoo!. End users can discover applications bysearching or browsing within application galleries.

• Runtime and rendering environment: The backend servers and software that run applications and convertthe code into HTML.

Programming ModelsYAP offers several programming models for the development of Open Applications [16]. The diagramsthat follow show a simplified view of the runtime components for each model.

Server-SideIn this model, the code for your Canvas View [18] is a Web application that is hosted by and runs on yourservers. You can write the code in the language of your choice, such as Python, Java, or PHP. To make it

February 29, 20121Yahoo! Developer Network

Page 11: Yap Dev Guide

easier to perform authorization and access Yahoo! social data, several Yahoo! Social API SDKs1 areavailable. At runtime, the YAP engine proxies requests to your server, adding the additional informationlisted in Parameters Passed to an Open Application [147]. The Canvas View of your application can accessthis additional information programmatically. For example, a Canvas View coded in PHP can access theuser's GUID from the $_REQUEST superglobal. YAP saves the Small View [17] code in a cache. Tospecify the default Small View code, you enter HTML and YML [40] statements on the Project Detailspage. To personalize the Small View to each user, your application can call the setSmallView methodof the Yahoo! Social SDK for PHP2.

YAP takes several measures to protect the user's private data. When the application accesses data throughthe Yahoo! Social API3, OAuth verifies that the access is authorized. The YAP engine sanitizes the HTMLand processes the JavaScript with Caja [58] before sending the content back to the browser.

Figure 1.1. Server-Side

Browser-Side OpenSocial JavaScriptMost OpenSocial applications are written in JavaScript, which runs on the browser. When a Canvas Viewmakes an OpenSocial io.dataRequest, the YAP engine retrieves the data by calling the correspondingYahoo! Social API. For a io.makeRequest, the YAP engine fetches content from a third-party site,sanitizes the HTML, and then sends the content back to the browser.

1 /social/sdk/index.html2 /social/sdk/php/3 /social/index.html

February 29, 20122Yahoo! Developer Network

Overview of the Yahoo! ApplicationPlatform (YAP)

Page 12: Yap Dev Guide

Figure 1.2. Browser-Side JavaScript

Browser-Side FlashWith the ActionScript 3 Social APIs4, you can create Flash modules in a Canvas View. The Flash modulehas access to the viewer's session information and can obtain social information by making calls to theYahoo! Social API. To include a Flash Module in the Canvas View, insert a Yahoo! Markup Language [40](YML) tag such as the following:

<yml:swf src="http://example.com/app.swf" width="750" height="1000"/>

4 ../../flash/yos/classreference/

February 29, 20123Yahoo! Developer Network

Overview of the Yahoo! ApplicationPlatform (YAP)

Page 13: Yap Dev Guide

Figure 1.3. Browser-Side Flash

Encoding Requirements and MIME TypesThe character encoding for YAP is UTF-8 for both requests and responses. Invalid input will be rejected.UTF-8 control characters are not allowed.

Supported Image FormatsFor most purposes, YAP supports standard image formats including GIF, PNG, JPEG, BMP, and ICO.File-name extensions should match the format, as should the MIME type specified in the HTTP header.

HTTP headers should specify one of the following types: image/gif, image/png, image/jpeg, image/jpg,image/pjpeg, image/pjpg, image/bmp, image/ico, image/x-ico, image/x-icon, or image/vnd.microsoft.icon.

The image displayed on the Yahoo.com homepage is specified by the <Icon> element in the GadgetXML [93] configuration file. If this image is not a GIF, it will be converted to a GIF for use on thehomepage.

The image specified by the "YahooComIconUrl" Extension in Gadget XML [93] must be a GIF andits file name must end with the gif extension. Example: <yap:Extension name="yap.gadgets.Ya-hooComIconUrl">http://my_domain.com/my_icon-20X20.gif</yap:Extension>.

Finally, pay attention to the image dimensions specified in the table here [95]. If we ask for a 20x20-pixelimage, be sure to supply a 20x20-pixel image.

February 29, 20124Yahoo! Developer Network

Overview of the Yahoo! ApplicationPlatform (YAP)

Page 14: Yap Dev Guide

See also “Image Caching” [30].

Submission GuidelinesYahoo! selects a limited number of high-quality Open Applications to feature in the application galleriesof our properties, including:

• My Yahoo!5

• Yahoo! Toolbar6

• Yahoo! Pulse7

Yahoo! selects these applications from the pool that have been reviewed and approved. If an applicationhas been approved, it does not automatically appear in Yahoo! galleries.

To submit an application for inclusion in Yahoo! galleries, click the Submit to Publish button on the ProjectDetails page in My Projects8. Further instructions are available in the tutorial section “Submitting YourApplication to Yahoo!” [15].

Once an application has been submitted, it is added to the review queue for the Open Application Repositoryand Toolbar; applications published in the Repository and Toolbar are later considered, using additonalcriteria, for My Yahoo!. This is an automatic process that does not require further action from the developer.If you want to get information about the status of an application, you can post a message to the Yahoo!Application Platform9 YDN forum.

Broadly speaking, Open Applications can be classified as fully featured or feed based. Fully featured appsare self-contained interactive programs whose core functionality resides in the app itself. Feed-based appsare essentially RSS/XML feeds displayed in a YAP container. In evaluating submissions for the My Yahoo!and Yahoo! homepage galleries, there is a preference for fully featured applications.

If your application conforms to the following guidelines, it has a better chance of being selected for Yahoo!galleries.

Using the Small and Canvas Views

• The application includes a distinct Small [17] View and Canvas [18] View.

• Both views use a fluid layout.

• The views do not simply duplicate each other's content; the Canvas View provides a richer experiencewith extra features (such as configuration options and alternate functionality).

• The Small View is compelling and useful in itself; it is not simply a tag line that links to the Canvasview. (Many apps use yml:include [48] to pull fresh content directly into the Small View.)

It's About the App

• The application offers users an engaging experience with your content while on Yahoo!.

5 http://my.yahoo.com/6 http://toolbar.yahoo.com/7 http://pulse.yahoo.com/y/apps/find8 http://developer.yahoo.com/dashboard9 http://developer.yahoo.net/forum/?showforum=40

February 29, 20125Yahoo! Developer Network

Overview of the Yahoo! ApplicationPlatform (YAP)

Page 15: Yap Dev Guide

• Links in the Small View go to the Canvas View or to some functionality that keeps the user within theOpen Application. The Small View does not contain links to an external site; it does not, for example,simply link headlines to your company's website. (Instead of linking to your site, you can link to theCanvas View and pull in information from your site.) There are exceptions to this rule, as when a linkin the Small View sends the user to your website to link the Open Application with the user's account.

• More than 25% of the links in the Canvas View perform actions with the Open Application. For example,links can display a partial news article (which might then link to a full article on your website), loadanother page in the application, or configure the content being displayed.

Configuration and Metadata

• The application has all the required metadata, including title, description, short description, locale, cat-egories, application icon, favicon, Yahoo.com icon, and screenshot. For instructions on setting thismetadata, see “Configuring Your Application” [10] and “Gadget XML Configuration File” [93].

• The value of the description ModulePrefs attribute is less than 43 characters long.

• The pixel dimensions are correct for all required images, such as the Application Icon. See OptimizingYour Application for the Gallery [30].

• The contact information for the application's developer is accurate and current. To check this information,go to Yahoo! Pulse10 and select the Account Info tab.

Using Yahoo! Social Features

• The application creates or displays Yahoo! Updates [25].

• The application has viral features for distribution. For suggestions, see Application Distribution [6].

• The Small View displays up-to-date information relevant to the user or the application. For example,the Small View might display the top scores of friends, the latest news item, or dashboard information.(You can create dynamic Small Views with the yml:a [42] and yml:include [48] tags.)

Good Citizenship

• The application follows the Yahoo! Terms of Use11 and Yahoo! Guidelines12.

Application Distribution and PromotionWith the features described in this section, you can help users to find, explore, and share your application.

Publishing With the Add-to-Yahoo! ButtonThe "Add to Yahoo!" button is the simplest way to publish your Open Application anywhere on the Web.By clicking the button, users can add your application to My Yahoo! or Yahoo! Homepage:

In a Web page, the "Add to Yahoo!" button might look like this:

10 http://pulse.yahoo.com/11 http://info.yahoo.com/legal/us/yahoo/api/api-2140.html12 http://info.yahoo.com/guidelines/us/

February 29, 20126Yahoo! Developer Network

Overview of the Yahoo! ApplicationPlatform (YAP)

Page 16: Yap Dev Guide

To create the "Add to Yahoo!" button, perform the following steps:

1. From the Project Details page, push your application live. (For instructions, see the tutorial section“Pushing Your Application Live” [13].)

2. Note the Application ID displayed by the Project Details page.

3. Link the required CSS and JavaScript files to your application:

<link rel="stylesheet" href="http://l.yimg.com/a/lib/addtoyahoo/addtoyahoo_1.0.2.css"/>

<script src="http://l.yimg.com/a/lib/addtoyahoo/addtoyahoo_1.0.5.js"></script>

Your page must have an HTML doctype to use these libraries.

4. On the page where you want the "Add to Yahoo!" button, instantiate AddToYahoo. For example:

<script>var button1 = new YAHOO.one.AddToYahoo({ id:"add_button_1", intl:"en-US", typeToAdd: ["app","your_app_ID"], dropdownNetworks: ["yCom","yMy"], newWindow: true});</script>

You can publish RSS feeds as well as YAP applications. For example:

<script>var button2 = new YAHOO.one.AddToYahoo({ id:"add_button_2", intl:"en-US", typeToAdd: ["url","http://feeds.someserver.com/rss/..."], dropdownNetworks: ["yCom","yMy"], newWindow: true});</script>

For more information about the properties of AddToYahoo, see below.

5. Place an empty element, such as a div or span, on the page where you want to create the button. Includethe id of your AddToYahoo object and specify class="addToYButton". For example:

<div id="add_button_1" class="addToYButton"></div>

You can assign the following properties to AddToYahoo:

DescriptionProperty

The id of the element where the button is to appear. Must be unique.id

February 29, 20127Yahoo! Developer Network

Overview of the Yahoo! ApplicationPlatform (YAP)

Page 17: Yap Dev Guide

DescriptionProperty

Options include "en-US", "es-ES", "fr-FR", "it-IT", "de-DE", "pt-BR", "en-SG", "es-AR", "en-AU", "fr-CA", "es-CL", "es-CO", "da-DK", "es-US", "el-GR", "zh-Hant-

intl

HK", "id-ID", "en-IN", "ko-KR", "es-MX", "nb-NO", "en-NZ", "es-PE", "en-PH","pl-PL", "ru-RU", "sv-SE", "th-TH", "tr-TR", "zh-Hant-TW", "en-GB", "es-VE",and "vi-VN".

An array consisting of "app" followed by a YAP application ID, or "url" followedby the URL of an RSS feed.

typeToAdd

Optional. Creates a pull-down menu. An array containing "yMy" (My Yahoo!).dropdownNetworks

Optional. Boolean (defaults to false). Specify true to open a new window whenthe button is clicked.

newWindow

Using the Share and Message FeaturesThe Canvas View [18] of an Open Application has a Share widget in the upper right corner. By selectingthe Share widget, the user can send an email message to Yahoo! Connections about the application. Theemail contains the application's link and screenshot. Also, you can create a user-to-user sharing form inthe Canvas View with the yml:share [54] tag.

The yml:message [50] tag also helps to spread applications across Yahoo!. With the yml:message [50]tag, you can customize the messages sent by users to their Connections. For example, you can change thesubject, body, image, and the call-to-action URL.

Leveraging UpdatesYahoo! Updates [25] appear on many Yahoo! sites, Yahoo! Messenger13, Yahoo! Mail14, Yahoo! Pulse15,and Yahoo! TV16. When a user installs an application on Yahoo! Toolbar or My Yahoo!, an update isgenerated. To propagate even more viral hooks throughout Yahoo!'s sites, your application should generateadditional updates. For information on creating updates, see the Yahoo! Updates API17 and Yahoo! SocialAPI SDKs18.

Using PreviewPreview [20] allows you to present substantive content to users who are not signed in or have not installedyour application. In preview content, encourage users to install and customize the app.

13 http://messenger.yahoo.com/14 http://mail.yahoo.com/15 http://pulse.yahoo.com/16 http://tv.yahoo.com/17 /social/updates/18 /social/sdk/

February 29, 20128Yahoo! Developer Network

Overview of the Yahoo! ApplicationPlatform (YAP)

Page 18: Yap Dev Guide

Chapter 2. Getting Started: Build YourFirst Open Application

In this Chapter

• “Introduction” [9]

• “Prerequisites” [9]

• “Getting the Code and Images” [9]

• “Configuring Your Application” [10]

• “Previewing Your Application” [13]

• “Pushing Your Application Live” [13]

• “Running the Canvas View” [14]

• “Updating Your Application” [14]

• “Submitting Your Application to Yahoo!” [15]

IntroductionThis tutorial provides step-by-step instructions for creating an Open Application. The code for this tutorialis a simple PHP script named weather.php1. This script calls YQL with cURL and then displays the inform-ation returned: the current weather for zip code 90210. (To learn about YQL, see the YQL Guide2.)

Prerequisites• To understand this material, you must be familiar with PHP, XML, HTML/XHTML, and Web application

development.

• You will need a Web server that can be accessed outside of your local network. You cannot use localhostfor an Open Application.

• Your Web server must be running PHP 5.2 or later.

Getting the Code and ImagesThe files used in this tutorial are available in a single archive called weather.zip3. You can also downloadthese files individually (see below).

1. Copy the weather.php4 script to your Web server. (Change the file name extension from "phps" to "php"after downloading.)

1 examples/weather.phps2 http://developer.yahoo.com/yql/guide/3 examples/weather.zip4 examples/weather.phps

February 29, 20129Yahoo! Developer Network

Page 19: Yap Dev Guide

2. Copy the following image files to your Web server:

• weather-16X16.gif5(favicon)

• weather-20X20.gif6(additional icon)

• weather-300X250.gif7(screenshot)

• weather-64X64.gif8(application icon)

You will specify the URLs to these images when you configure your application in the next step [10].

Configuring Your Application1. In your browser, go to My Projects9, which is shown in the following figure.

2. Click New Project.

3. Select YAP.

4. Click Continue.

5. Verify that you have created a new application by looking at the figure below.

5 images/weather-16X16.gif6 images/weather-20X20.gif7 images/weather-300X250.gif8 images/weather-64X64.gif9 http://developer.yahoo.com/dashboard

February 29, 201210Yahoo! Developer Network

Getting Started: Build Your First OpenApplication

Page 20: Yap Dev Guide

6. Click Download XML and save the generated Gadget XML file on your computer. The file is calledygadget_appID.xml, where appID is the application's ID (e.g. gadget_9g2QuE6o.xml).

The file you've just downloaded is a template that provides a starting point for your application. It isfully functional, with all required elements and attributes as well as default content; it defines an applic-ation that you can run in Preview mode. In the next step, you'll modify this file to create the Weathersample app.

7. Open the Gadget XML file in a text editor and edit the following fields:

• In the ModulePrefs element:

• Set the title attribute to "Weather".

• Set the description attribute to "Weather Forecast Sample Application".

• Set the category attribute to "Information-Weather".

• In the Icon subelement, type the URL of the weather-16X16.gif favicon that you copiedin the previous step [9]—e.g. <Icon>http://your-domain.com/weather-16X16.gif</Icon>.

• In the Extension named "yap.gadgets.ShortDescription", type "Weather Test App". (See theexample below.)

• In the Extension named "ApplicationIconUrl", type the URL of the weather-64X64.gifapplication icon that you copied in the previous step [9].

• In the Extension named "YahooComIconUrl", type the URL of the weather-20X20.gificon that you copied in the previous step [9].

• In the Extension named "ScreenshotUrl", type the URL of the weather-300X250.gifscreenshot that you copied in the previous step [9].

• In the first Content element, change the text to "Weather Forecast".

• In the second Content element, set the href attribute to the URL of the weather.php file thatyou copied in the previous step [9] (http://your-domain.com/weather.php).

February 29, 201211Yahoo! Developer Network

Getting Started: Build Your First OpenApplication

Page 21: Yap Dev Guide

You can fill in additional fields if you want:

• For an explanation of Gadget XML and its contents, see “Gadget XML Configuration File” [93].

• For guidelines on image files, see “Optimizing Your Application for the Gallery” [30] and “SupportedImage Formats” [4].

Save the file.

When you are done, the Gadget XML file should include the following (where your-domain.comis replaced with the address of your Web server):

<?xml version="1.0" encoding="UTF-8"?><Module xmlns:yap="http://www.yahoo.com/ns/yap">

<ModulePrefs title="Weather" description="Weather Forecast Sample Application" category="Information-Weather"> <Icon>http://your-domain.com/weather-16X16.gif</Icon> <Locale lang="en" country="us"/>

<yap:Extension name="yap.gadgets.ShortDescription">Weather Test App</yap:Extension> <yap:Extension name="yap.gadgets.ApplicationIconUrl">http://your-domain.com/weather-64X64.gif</yap:Extension>

<yap:Extension name="yap.gadgets.YahooComIconUrl">http://your-domain.com/weather-20X20.gif</yap:Extension>

<yap:Extension name="yap.gadgets.ScreenshotUrl">http://your-domain.com/weather-300X250.gif</yap:Extension>

</ModulePrefs>

<Content type="html" view="YahooSmallView, default"> <h1>Weather Forecast</h1> </Content>

<Content type="html" view="YahooFullView, canvas" href="http://your-domain.com/weather.php"> </Content>

<!-- The content of this CDATA will render if no other content sections are applicable. --> <Content type="html"> <![CDATA[ Hello World, my name is <yml:name uid="viewer" linked="true" capitalize="true"/>. ]]> </Content></Module>

8. Copy the edited Gadget XML file to your Web server.

February 29, 201212Yahoo! Developer Network

Getting Started: Build Your First OpenApplication

Page 22: Yap Dev Guide

9. Click Import New XML and specify the URL for the Gadget XML file on your Web server.

Click Import. YAP will validate the Gadget XML file and report errors. If there are errors, fix themand reimport the file.

Previewing Your ApplicationIn the Project Details page, select the Open Application tab and click the Preview button. Your application'sSmall View appears in a new window. You can display different views by choosing from the Render Viewpull-down list at the top of the window.

Pushing Your Application LiveOnce you've provided a valid Gadget XML file (by clicking Import New XML on the Project Details page),you can push your application live. When an application is live, it can be run on YAP. Be sure to test yourapp in Preview mode before pushing it live.

To make an application live, follow these steps:

1. In the Project Details page, select the Open Application tab and click the Load from DevelopmentGadget button.

2. Verify that the Load from Development Gadget button now reads Launch. You can now launch yourWeather application.

February 29, 201213Yahoo! Developer Network

Getting Started: Build Your First OpenApplication

Page 23: Yap Dev Guide

Running the Canvas View1. To run the Canvas View [18] of your application, click the Launch button. Your application will open

in a new page that has a URL in the following format, where your_app_id is the ID of your OpenApplication:

http://pulse.yahoo.com/y/apps/your_app_id/

2. Verify that the Canvas View of the weather application appears. It should look something like this:

Updating Your ApplicationWhen you change the HTML or PHP code on your Web server, there is no need to update your YDNproject; YAP fetches new files from your server every time your application is accessed. (Note, however,that YAP caches image files from third-party servers. See “Image Caching” [30] for more information.)Changes to the Gadget XML file, on the other hand, require a project refresh before they can take effect.The refresh is required because YAP always uses a copy of the Gadget XML file stored on a Yahoo!server.

There are three buttons on the Project Details page that update the Gadget XML file. Each has a distinctfunction:

• Import New XML tells YAP to fetch the Gadget XML file using a specified URL. You need to clickthis button the first time you tell YAP about your project's Gadget XML file and any time you changethe name or location of the file.

• Reload tells YAP to fetch a new version of your Gadget XML file from your server, using the same filename and URL as last time. Click this button when you've modified your Gadget XML file and want tosee the results in Preview mode.

• Update from Development Gadget tells YAP to use the most recently updated version of Gadget XMLof the Development Gadget for the "live" app. Click this button after you've tested your changes inPreview mode and are ready to push the new version.

February 29, 201214Yahoo! Developer Network

Getting Started: Build Your First OpenApplication

Page 24: Yap Dev Guide

These buttons are meant to be used in order. Reload fetches the Gadget file using the last URL specifiedwith Import New XML; you can't click Reload until you've used Import New XML at least once. Updatefrom Development Gadget switches the "live" version of your app to the most recently updated Gadgetfile; you can't refresh your app with Update from Development Gadget until you've used Refresh (orImport New XML) to upload the modified Gadget file.

Submitting Your Application to Yahoo!If you're trying to attract users, you may want to submit your app for inclusion in Yahoo!'s galleries. (Ob-viously, you wouldn't do this with the Weather sample app.) See “Submission Guidelines” [5] for moreinformation.

1. Make sure that your application conforms to the “Submission Guidelines” [5].

2. Include all the required fields in your Gadget XML file. The requirements for publishing are morestringent than for previewing or pushing live; see “Gadget XML Configuration File” [93].

3. Follow the recommendations in Chapter 4, Best Practices [26].

4. In the Project Details page, on the Open Application tab, click Submit to Publish.

February 29, 201215Yahoo! Developer Network

Getting Started: Build Your First OpenApplication

Page 25: Yap Dev Guide

Chapter 3. Anatomy of an OpenApplication

In this Chapter

• “Introduction” [16]

• “Small View” [17]

• “Canvas View” [18]

• “Preview” [20]

• “Chrome” [21]

• “Landing Page” [21]

• “My Applications” [22]

• “Messages” [23]

• “Sharing” [24]

• “Updates” [25]

IntroductionAn Open Application is a Web application that has been registered on the Yahoo! Development Network1

(YDN) and runs on the Yahoo! Application Platform (YAP). An Open Application is defined by a GadgetXML [93] file.

As seen by the end user, an Open Application has multiple views, integration points, and components.

1 http://developer.yahoo.com

February 29, 201216Yahoo! Developer Network

Page 26: Yap Dev Guide

Figure 3.1. Anatomy of an Open Application details the composition of an applicationwith its different Views, states, and locations.

Click to see a larger image2 or PDF3 of this figure.

Small ViewImportant Notice

YAP will stop supporting Small View from 15th April 2012 onwards.

The Small View of an application appears to end users as a module contained within a Web page. As theapplication's teaser, the purpose of the Small View is to draw end users into the Canvas View [18], whichprovides a richer interaction.

The content of the Small View is up to you, but usually a Small View contains information such as thefollowing:

• One or more triggers to launch the Canvas View.

• A representation of the user, such as a name and an image. Your application can get this informationfrom the user's Yahoo! Profile.

• Status or Updates [25] about other end users that will encourage the user running the Small View toopen the Canvas View.

A Small View has two states:

• Default: In this state, the Small View should encourage the user to customize the application.

2 images/anatomy_big.png3 images/anatomy_big.pdf

February 29, 201217Yahoo! Developer Network

Anatomy of an Open Application

Page 27: Yap Dev Guide

To define the default state, in the Gadget XML file create a Content element whose view attribute isset to "YahooSmallView". The Content element must contain HTML or YML [40]; other markup orprogramming languages are ignored. At runtime, YAP renders the Small View's default code if a per-sonalized state for the end user is not available.

• Personalized: The end user is signed in to Yahoo! and has installed the application. Yahoo! maintainsper-user, per-application customization data on its own servers.

To personalize the Small View, an application calls the setSmallView method of the Yahoo! SocialSDK for PHP4. This method enables you to tailor the Small View for each end user (identified by GUID)and to dynamically update the Small View. You can use this method wherever you can run the PHPSDK, for example, in the Canvas View and back-end processes. For more information, see “Creatingthe Personalized State” [36].

Small Views have the following constraints:

• The size of a Small View must not be fixed. Be sure to use a fluid layout so that the view will be properlydisplayed on different Yahoo! sites. A vertical scroll bar appears when necessary.

• Unlike the Canvas View, advertisements and promotions cannot be served in a Small View.

• In the Small View, the code is restricted to HTML or YML [40]. You cannot specify JavaScript, PHP,or other languages for the Small View.

Figure 3.2. Example Small View

Canvas ViewThe Canvas View is the application's largest and richest interface for the end user. Usually, the CanvasView is rendered within a Yahoo! landing page, surrounded by a Yahoo! header, footer, and an advertisementunit. End users access a Canvas View from a variety of locations: the Small View, links for user Up-dates [25], email links, and Web links. Unlike the Small View, the Canvas View supports third-party ad-vertisements and promotions. The size of a Canvas View must not be fixed. Be sure to use a fluid layoutso that the view will be properly displayed on different Yahoo! sites. A vertical scroll bar appears whennecessary.

4 /social/sdk/php/

February 29, 201218Yahoo! Developer Network

Anatomy of an Open Application

Page 28: Yap Dev Guide

The application code for the Canvas View is hosted on a server outside of YAP. To specify the code'slocation, in the Project Details page, enter the URL in the Application URL field.

The Canvas View code can be HTML, YML [40], CSS, and the subset of JavaScript allowed by Caja.This code can be generated by a variety of languages, such as PHP, XML/XSLT, and Ruby on Rails.

To protect the private information of end users, YAP applies the following security mechanisms to theCanvas View:

• The Canvas View is presented within an iframe.

• HTML is sanitized to remove unsafe code.

• JavaScript is translated by Caja.

You should design the Canvas View so that it has the following two states:

• Uninstalled: The user is visiting your application but has not customized it or given it permission to accessYahoo! user data; the user's identity (GUID) is unknown to the application. In this state, the CanvasView should encourage the user to customize the application.

• Personalized: The user has installed your application, his or her identity is known, and the full function-ality of the Canvas view is available.

February 29, 201219Yahoo! Developer Network

Anatomy of an Open Application

Page 29: Yap Dev Guide

Figure 3.3. Example Canvas View

PreviewImportant Notice

YAP will stop supporting Preview View from 15th April 2012 onwards.

Preview content is shown to users who are not signed in to Yahoo!, have not installed your application, orhave not given permission for your app to access their data. Preview content may also appear in othercontexts—for example, when a user browses for apps in a Yahoo! gallery, or when a third-party app isfeatured on a Yahoo! site. If your app does not provide Preview content, users in these contexts will see asimple request to sign in or install your app.

To define Preview content, create a Content element in the Gadget XML [97] file whose view attributeis set to "preview".

Preview content is subject to certain limitations. YML is supported, but tags cannot retrieve informationabout the user. For example, the following tag works:

February 29, 201220Yahoo! Developer Network

Anatomy of an Open Application

Page 30: Yap Dev Guide

<yml:name uid="QPR12345" />

But the following tag does not work in preview content:

<yml:name uid="viewer" /> <!-- don't use in preview -->

When creating Preview content:

• Try to include substantive content that is interesting to most users. For example, a non-customizedweather app could include information about one or two popular travel destinations.

• Design the page for display in various widths. Content may appear in containers of different sizes.

• Encourage the user to install and customize the application. You can use the yml:customize [46] tagfor this purpose.

ChromeYAP may provide navigation aids around the border of an application. These items, which vary dependingon the container and context in which the app appears, require no input from the developer.

Figure 3.4. Chrome Screenshot

Landing PageThe Landing Page is the default location where an Open Application's Canvas View is presented. Endusers can access the Landing Page via a proxied URL (http://apps.yahoo.com/-your_app_id). On a LandingPage, the Canvas View is enclosed by Yahoo!'s standard header and footer, and in some cases by an ad-vertisement unit.

February 29, 201221Yahoo! Developer Network

Anatomy of an Open Application

Page 31: Yap Dev Guide

Figure 3.5. Landing Page Screenshot

My ApplicationsMy Applications lists all Open Applications installed by an end user. When an application is installed, itis added to My Applications regardless of where the installation took place. In My Applications, everyapplication is represented by its icon and name. Clicking on an application sends the end user to the applic-ation's Landing Page, displaying the Canvas View of the App. My Applications can be accessed at ht-tp://pulse.yahoo.com/y/apps, and will be promoted around the Yahoo! network in future releases.

February 29, 201222Yahoo! Developer Network

Anatomy of an Open Application

Page 32: Yap Dev Guide

Figure 3.6. My Applications Screenshot

MessagesYAP allows users to send messages to each other through Open Applications. See “Using the Share andMessage Features” [8] and “yml:message” [50] for more information.

February 29, 201223Yahoo! Developer Network

Anatomy of an Open Application

Page 33: Yap Dev Guide

Figure 3.7. Message Screenshot

SharingA sharing request is a special message [23] that invites the recipient to install an Open Application. Theseinvitations are initiated by an end user who as already installed the application in question. See “Using theShare and Message Features” [8] and “yml:share” [54] for more information.

February 29, 201224Yahoo! Developer Network

Anatomy of an Open Application

Page 34: Yap Dev Guide

Figure 3.8. Sharing Screenshot

UpdatesUpdates are Yahoo!'s user event stream. When an end user installs an Open Application, the Applicationmay be granted rights to read from and write to the user's Updates. For more information see the Yahoo!Updates API5.

Figure 3.9. Updates Screenshot

5 /social/updates/

February 29, 201225Yahoo! Developer Network

Anatomy of an Open Application

Page 35: Yap Dev Guide

Chapter 4. Best PracticesIntroduction

Yahoo! recommends a number of best practices you can follow to create a better and more successful ap-plication. The best practices fall into these categories:

• “Helping Users Discover Your Application” [26]

• “Providing a Better Initial Experience” [27]

• “Optimizing the Views” [27]

• “Making Applications Social” [28]

• “Respecting Your Users” [29]

• “Improving Performance” [29]

• “Optimizing Your Application for the Gallery” [30]

Helping Users Discover Your ApplicationHelping users find your application can aid in the application's success. Don't assume users will seek outyour application. Leverage the Yahoo! network and user Connections to attract users to your application.Design an experience that appeals to users regardless of their level of expertise and let users explore,sample, and share the application with friends. Make sure users can easily identify your application andassociate it with your business. The following guidelines can make your application easier to discover andcan help increase traffic to your application.

Do's• Provide a clear and distinguishable application name, description, and recognizable icons in all sizes [30].

• For users that are not signed in to Yahoo!, present the application in a way that encourages them to installyour application (example: Flood-it1). Consider using preview [20] for this purpose.

• Publish your application using a business account rather than your personal Yahoo! account to correctlydescribe your application’s ownership to your users. (Example: Target2)

• Allow users to share your application with their Connections. Also, let them send messages within yourapplication at relevant moments to drive more traffic. (Example: Mafia Wars3)

• Add an "Add to Yahoo!" [6] link to your site to drive traffic to your application from Yahoo!.

• Highlight your application through your product's existing channels, such as site promotion, emails, andadvertising.

1 http://apps.yahoo.com/-Mvp8tE30/2 http://profiles.yahoo.com/u/FNO6VTJ4N2OGURW33TTQRV6DEY3 http://apps.yahoo.com/-yNmsEV4q/

February 29, 201226Yahoo! Developer Network

Page 36: Yap Dev Guide

Don'ts• Don't use your personal Yahoo! account because your application will be attributed accordingly (Example:

"by Jane Doe").

• Don't ignore the potential for converting signed-out users into signed-in users. An undeveloped signed-out state can make your application look broken or unavailable.

Providing a Better Initial ExperienceThe user experience begins as soon as a user adds your application. Remember, you only get one chanceto make a first impression. Make a great one, so that users will continue to run your application. Offer a"smart" initial experience to your users by adhering to the general principles:

• Ensure your application is up and running when the user adds it.

• Take advantage of defaults, and infer values from the user's Profile information.

• Localize your application and provide content relevant to the user's locale.

Do's• Look up the user's location data in the Profile. (Example: Social Weather4)

• Use GeoPlanet5 to convert user-submitted locations into usable data such as latitude/longitude coordinatesand city name. GeoPlanet is also available through YQL6.

• Reference yap_jurisdiction (an ISO 3166 country code passed as a post parameter to YAP ap-plications) and Accept-Language (an RFC 2616 section 14.4 language priority list passed as aheader to YAP applications).

Don'ts• Don't ask users to provide information they have already provided through Yahoo!, such as Profile data,

interests, or location. (Example: "Enter your nickname:")

• Don't ask the user for their location unless there is no logical way of inferring it. For example, you maynot be able to determine the location if the available information is abstract. (Example: "out in thecountry")

Optimizing the ViewsYou should take advantage of the two different application views: Small7 and Canvas8. Design each viewuniquely. Keep in mind that each view has a variety of states that can appear across the Yahoo! networkin different contexts. Use a lightweight Small View to entice the user into running the application withinthe rich and interactive Canvas View. Don’t assume the dimensions of the container, as they might change.

4 http://apps.yahoo.com/-2Khf0X4k/5 http://developer.yahoo.com/geo/geoplanet/6 http://developer.yahoo.com/yql/console/?q=select%20*%20from%20geo.places%20where%20text%20IN%20%28select%20location%20from%0Aso-cial.profile%20where%20guid%3Dme%297 http://developer.yahoo.com/yap/guide/anatomy-small-view.html8 http://developer.yahoo.com/yap/guide/anatomy-canvas-view.html

February 29, 201227Yahoo! Developer Network

Best Practices

Page 37: Yap Dev Guide

Do's• Create a widget-like Small View and a rich, interactive Canvas View. (Example: Addicted to Chappelle's

Show9)

• Allow fluid dimensions for different sizes in different places around Yahoo!. Use a width of 100% foryour applications so that its width adjusts if the window size changes. (Example: Flixter10)

• Ensure that the fluid dimensions of your application enable it to display properly within the smallestavailable container. Factor in the width of a scrollbar, which is about 20 pixels wide, as well as the fixedheight of the window on the Yahoo! homepage (www.yahoo.com). If your window extends below thisfixed height, it may not appear without scrolling.

Don'ts• Don't create a Small View that merely duplicates the Canvas View.

• Don' t res t r ic t an appl icat ion to a fixed width (Example: <divstyle="width:478px;">...</div>).

• Don’t assume you know the size of the application container. There is currently no method you can callto obtain the container's dimensions. That said, please note the rough dimensions of the Yahoo!homepage's Small View (400 pixels wide by 460 pixels high) and Canvas View (750 pixels wide by460 pixels high).

Making Applications SocialAn effective way to drive traffic to your application is by making it social.

By leveraging the Yahoo! Social Directory API11, you should be able to:

• Take advantage of existing social Connections within Yahoo! instead of establishing your own graphfrom scratch.

• Show user activities that encourage interaction with your application.

• Make your application spread virally by letting people share [8] it in different ways at Yahoo!.

• Use Yahoo! as your megaphone to showcase user activity.

Do's• Surface a user's friends inside your application to encourage competition and interaction. (Example:

Hey Einstein12)

• Write informative, inviting messages that encourage other users to click. (Example: "Mark has rated thebook Adventures of Huckleberry Finn: 4/5 stars" via Books weRead13)

9 http://apps.yahoo.com/-Hj113a6u/10 http://apps.yahoo.com/-vj42yE6u/11 http://developer.yahoo.com/social/socialdir/12 http://apps.yahoo.com/-mnHRuo76/YahooFullView/?tabNum=4&yap_lang=en-US&yap_tz=America%2FLos_Angeles&yap_js=us13 http://apps.yahoo.com/-Ku3UzX36/

February 29, 201228Yahoo! Developer Network

Best Practices

Page 38: Yap Dev Guide

• Advertise user activity through Yahoo! Updates14 (activity stream).

Don'ts• Don't ask users to create an entirely new set of relationships inside your application.

Respecting Your UsersUser trust is essential for an application to be successful. Be respectful to your users. Design an experiencethat engages novices as they gain confidence with your application.

Take advantage of Yahoo!'s tools for getting user feedback, bug reports, and feature requests.

Do's• Before pushing your application live, test the different states of each view, ensure that Updates are

posted properly, and test that sharing works. Use A-Grade browsers15 for testing.

• Ensure that Updates are posted correctly and sharing works.

• Allow users to submit bug reports and feature requests easily in your application through links in thebottom right of your application (Example: Lexolous16)

• Request only those permissions that your application needs to access user data (such as Contacts).

Don'ts• Don't display sensitive or private information to others. (Example: "Mark just bought 4 shares of AAPL

stock at $93.14/share.)

• Don't display user-specific data to users who are not connected to a user. For example, identify userswith nicknames instead of full names or other information that your application obtains.

• Don't force users into submitting comments about your application through the Yahoo! "Report Abuse"link available in each application.

• Don't request redundant permissions to access user content (such as Contacts) if your application doesn'tneed it to operate.

Improving PerformanceResponse time plays a key role in how users perceive your application; nobody likes a slow application.By tracking your application's usage and adjusting its performance, you can dramatically improve thequality of your application's user experience.

There are two approaches to improving your application's performance. First, you can improve the actualresponse time by optimizing the application logic. Second, you can enhance the perceived performanceby adjusting the order in which you load resources.

14 http://developer.yahoo.com/social/updates/15 http://developer.yahoo.com/yui/articles/gbs/index.html16 http://apps.yahoo.com/-hzlnyP38

February 29, 201229Yahoo! Developer Network

Best Practices

Page 39: Yap Dev Guide

The following guidelines discuss both approaches:

Do's• Use YQL17 to cache queries. Combine multiple queries into one call.

• Use unique URLs for resources such as images or media files. When you update the content of a resource,you should update the URL so that the cache is flushed with the updated content.

• Write modular code and reuse it as much as possible. Reuse is especially important because Caja [58]18,the technology used by Yahoo! to ensure the security of user data, can increase the size of your JavaScriptcode by 2-3 times because it adds a series of checks and verification steps.

• To improve perceived response time, defer loading resources until your application has launched. Also,load resources after fully rendering the page.

• Present a progress indicator while resources are being loaded.

• Monitor the response time of your server. If your application takes more than 9 seconds to load, YAPdisplays an error message to the user. If an image request takes longer than 3 seconds, the request isterminated and the image will not be available for your application.

Don'ts• Don't use multiple, sequential calls if they can be combined into a single call.

• Don't overload your front-end with unnecessary JavaScript code if the same functionality can be achievedin the back-end.

Image CachingYAP caches images from third-party servers, usually for a day or so. You can control this behavior by in-cluding the standard Cache-Control19 header in your HTTP responses.

Optimizing Your Application for the GalleryApplications featured in the Apps Gallery gain more visibility with users and will potentially gain moretraffic. Your application may be recommended in the My Favorites section or featured in the Apps Galleryon the Yahoo! homepage (www.yahoo.com).

Do's• Provide a 20x20-pixel icon in GIF format. The file name must end in .gif.

• Provide a recognizable 64x64-pixel icon for your Gallery/My Apps buttons.

• Provide a 16x16-pixel favicon. This will be used on the Yahoo.com homepage and for Updates events.

• Provide a 300x250-pixel screenshot that helps users see what your application offers.

17 http://developer.yahoo.com/yql18 http://developer.yahoo.com/yap/guide/caja-support.html19 http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9

February 29, 201230Yahoo! Developer Network

Best Practices

Page 40: Yap Dev Guide

Don'ts• Don't leave your first name, last name, nickname, and profile picture empty in your Yahoo! Profile. This

information will help identify you and your application to users.

• Do not leave the application's icon, image, name, and description fields empty.

February 29, 201231Yahoo! Developer Network

Best Practices

Page 41: Yap Dev Guide

Chapter 5. Setting the Small View of anOpen Application

Important Notice

YAP will stop supporting Small View from 15th April 2012 onwards.

In this Chapter

• “Introduction” [32]

• “Prerequisites” [32]

• “Creating the Default State” [33]

• “Creating the Personalized State” [36]

• “Applications Using Private Data” [36]

• “Applications Using Public Data” [37]

• “Source Code” [39]

IntroductionThis tutorial shows you how to set the contents of the Small View [17] of an Open Application. In thefirst part of the tutorial, you will set the Small View's default state [17] by entering HTML and YML asinlined text in a Content element of the the Gadget XML file. The second part of the tutorial shows youhow to set the personalized state [18] of the Small View by calling the setSmallView method of theYahoo! Social SDK for PHP1.

PrerequisitesImportant Notice

YAP will stop supporting Small View from 15th April 2012 onwards.

• To understand this material, you must be familiar with PHP, HTML/XHTML, and Web applicationdevelopment.

• You will need a Web server with PHP (version 5.2 or later) installed.

• On your Web server, install the Yahoo! Social SDK for PHP2. You can download this SDK from github3.

• You should already be familiar with the step-by-step process described in the Getting Started [9] section.

• You must have a Yahoo! Profile4.

1 http://developer.yahoo.com/social/sdk/php/2 http://developer.yahoo.com/social/sdk/php/3 http://github.com/yahoo/yos-social-php/tree/master4 http://profiles.yahoo.com

February 29, 201232Yahoo! Developer Network

Page 42: Yap Dev Guide

Creating the Default StateImportant Notice

YAP will stop supporting Small View from 15th April 2012 onwards.

The default state appears to the end user only if the personalized state is not set. You set the default stateby specifying HTML or YML in the Application Editor. To create a default state for a Small View, performthe following steps:

1. Go to the Project Details page, as described in “Configuring Your Application” [10].

2. Open your project's Gadgdet XML file in an editor.

3. Make sure the Gadgdet XML file contains the following lines:

<Require feature="yap.feature.classic"/><Require feature="opensocial-0.8"/>

4. In the Gadgdet XML file, you can see the Small View content. It might look like this:

<Content type="html" view="YahooSmallView, default"> <![CDATA[ Hello World, my name is <yml:name uid="viewer" linked="true" capitalize="true"/>.

]]></Content>

5. In the Project Details Page, select the Open Application tab and click the Preview button to see theSmall View in the default state.

February 29, 201233Yahoo! Developer Network

Setting the Small View of an Open Ap-plication

Page 43: Yap Dev Guide

6. Close the Preview window and return to the Gadget XML file. Copy the HTML span element shownbelow and paste it into the Small View default Content.

<Content type="html" view="YahooSmallView, default"> <![CDATA[ <span style="background-color: #FFFF00; color: red; font=">You can use HTML, but you can't add links or user info.</span> ]]></Content>

Save the Gadget XML file and re-upload it, if necessary, to your Web server.

7. Click Preview again to see the figure below. Although you can format the Small View with HTML andinline CSS, adding user information is not possible. This is where YML [40] becomes important.

February 29, 201234Yahoo! Developer Network

Setting the Small View of an Open Ap-plication

Page 44: Yap Dev Guide

8. Close the Preview window. This time copy the YML below and paste it into the Small View defaultContent element.

<Content type="html" view="YahooSmallView, default"> <![CDATA[ <yml:user-badge uid="viewer" linked="true" width="55" reflexive="false" useyou="false" capitalize="true" /> ]]></Content>

9. The YML tag user-badge creates a default state that displays the user name and image. Try experimentingwith other YML Code Examples [117].

February 29, 201235Yahoo! Developer Network

Setting the Small View of an Open Ap-plication

Page 45: Yap Dev Guide

Creating the Personalized StateImportant Notice

YAP will stop supporting Small View from 15th April 2012 onwards.

In this section, you use the setSmallView method of the PHP SDK to create the personalized state ofthe Small View for your application. The setSmallView method is found in two classes in the PHPSDK: YahooUser and YahooApplication. The two versions of the method both create personalizedstates for the Small view, but which one you use depends on the type of data (public or private) that yourapplication is accessing. For more information, see Private Data v. Public Data5.

Applications Using Private DataTo access private data, your application is required to get the end user's authorization. To create an applic-ation that uses private data, you will use the YahooSession and YahooUser classes of the PHP SDK.You use the YahooSession class to get authorization from the end user and the YahooUser class toget user data and set the personalized state of the Small View.

5 ../../oauth/guide/about.html#oauth-private_public_data

February 29, 201236Yahoo! Developer Network

Setting the Small View of an Open Ap-plication

Page 46: Yap Dev Guide

The following steps show how to call the setSmallView with the YahooSession class. These stepsare included in the set_small_view.php 6 script provided with this tutorial.

1. The $yahoo_session object is returned from the method requireSession. If $yahoo_sessionis not NULL, your user has authorized your application to access private data.

$yahoo_session = YahooSession::requireSession(CONSUMER_KEY, CON-SUMER_SECRET);

2. From the YahooSession object named $yahoo_session, you call the method getSessioned-User to obtain a YahooUserobject. The YahooUser object will allow your application to set theSmall View and get the user's social data.

$yahoo_user = $yahoo_session->getSessionedUser();

3. Before calling the method setSmallView from $yahoo_user, create content for your Small View.The YML below will show the end user's Profile photo and name.

// Using YML gives you options for including user information in your content. Be sure to escape quotation marks.$small_view_content = "<yml:name uid=\"viewer\" linked=\"true\" capitalize=\"true\" useyou=\"false\"/>'s photo:" . "<yml:profile-pic uid=\"owner\" width=\"48\" linked=\"true\" />"

4. The method setSmallView in the YahooUser class only takes one parameter (content of SmallView) and returns a boolean. Call the method from $yahoo_user, checking if the Small View wasset. If the Small View was not set, record an error in the Web server's error log with YahooLogger::er-ror.

if(! $yahoo_user->setSmallView($small_view_content)){ YahooLogger::error("Could not set Small View.");}

Applications Using Public DataThe YahooApplication class is for applications that do NOT need user authorization, such as applic-ations that access public data from Web services or RSS feeds. A simple example would be an applicationthat gets public photos from the Flickr API. The application exchanges a Consumer Key and ConsumerSecret with the Flickr API, but no user authorization is required.

The following steps show how to call the setSmallView with the YahooApplication class. Thesesteps are included in the set_small_view_public.php 7 script provided with this tutorial.

1. Create a PHP script with an editor and include the PHP SDK.

<?php include_once("change-this-path/Yahoo.inc");?>

6 ./examples/set_small_view.phps7 ./examples/set_small_view_public.phps

February 29, 201237Yahoo! Developer Network

Setting the Small View of an Open Ap-plication

Page 47: Yap Dev Guide

2. Define constants to store the Consumer Key and Consumer Secret that Yahoo! provides when you createan application.

define('CONSUMER_KEY',"your_Consumer_Key_goes_here");define('CONSUMER_SECRET',"your_Consumer_Secret_goes_here");

3. Pass the constants CONSUMER_KEY and CONSUMER_SECRET to the YahooApplication constructorto create the object $yahoo_two_legged_app.

// You are performing the two-legged OAuth authorization here$yahoo_two_legged_app = new YahooApplication(CONSUMER_KEY,CONSUMER_SECRET);

4. Enter the HTML link to set the Small View.

// Link the original photo on Flickr to a Flickr user's photo for the Small View$small_view_content = "<a href=\"http://www.flickr.com/photos/flickr_user/2947006845\"> The Rabbit: <img src=\"http://farm4.static.flickr.com/9821/rabbit.jpg\"></a>";

5. Pass the $small_view_content and the end user's GUID to the setSmallView. The GUID ishardcoded in this example, but you can obtain the GUID from several different sources: from a databasewhere you store user information, from a three-legged session, or from an authorized REST call to theIntrospective GUID8 resource.

// The GUID in your application will most likely obtained from a database query$guid = "your_GUID_goes_here";

// Set the Small View content$yahoo_two_legged_app->setSmallView($guid,$small_view_content);

6. The Small View you set should look similar to the figure below.

8 /social/rest_api_guide/introspective-guid-resource.html

February 29, 201238Yahoo! Developer Network

Setting the Small View of an Open Ap-plication

Page 48: Yap Dev Guide

Source CodeImportant Notice

YAP will stop supporting Small View from 15th April 2012 onwards.

The set_small_view.php script is for accessing private data:

<xi:include></xi:include>

The set_small_view_public.php script is for accessing public data:

<xi:include></xi:include>

February 29, 201239Yahoo! Developer Network

Setting the Small View of an Open Ap-plication

Page 49: Yap Dev Guide

Chapter 6.Yahoo! Markup Language(YML)

In this Chapter

• “Introduction to YML” [40]

• “yml:a” [42]

• “yml:audio” [45]

• “yml:customize” [46]

• “yml:form” [46]

• “yml:friend-selector” [47]

• “yml:if-env” [47]

• “yml:include” [48]

• “yml:message” [50]

• “yml:name” [52]

• “yml:profile-pic” [53]

• “yml:pronoun” [54]

• “yml:share” [54]

• “yml:swf” [55]

• “yml:user-badge” [56]

Introduction to YML

What is YML?Similar in format to XML, Yahoo! Markup Language (YML) provides functionality to Open Applicationsin a safe and standardized fashion. You include YML tags in the HTML code of an Open Application. Atruntime, YAP processes YML tags and converts them into HTML. If necessary, JavaScript libraries onthe endpoints attach dynamic behaviors in the user's browser.

BenefitsYML offers the following benefits:

• Social data: YML tags make it easy for you to create applications that access social data, such as a listof the user's friends.

February 29, 201240Yahoo! Developer Network

Page 50: Yap Dev Guide

• Dynamic and secure interactions: Several YML tags provide UI widgets and and rich interactions thatnormally require untrusted JavaScript.

• Data encapsulation: YML tags allow sensitive and timely data to be presented to end users in a uniformmanner. The YML interpreter will replace tags with data only if the viewer has the proper access.

Syntax RulesYML tags must conform to the following rules:

• YML tags are namespaced with yml:. However, since YML documents are not actually XML, noformal namespace declaration is required.

• All attributes must be enclosed in double quotes. To specify double quotes within an attribute value,enter the &quot; character reference.

• If the data type of an attribute is boolean, allowed values are "true" and "false", which must be enclosedin double quotes.

• Singleton tags (that is, tags with no closing tags) must end with /> .

• White space and indentations are passed through, but ignored in the interpretation phase.

• YML tags accept and produce characters in UTF-8 only.

URL Parameter Encoding and Relative PathsSome YML tags (including “yml:a” [42], “yml:form” [46], “yml:include” [48], and “yml:message” [50])have an attribute called params. The value of this attribute must conform to RFC 39861. Avoid commonmistakes such as unescaped spaces, entities (e.g. &amp;), and reverse encoding (percent-encoding of re-served characters used as delimiters or failure to percent-encode reserved characters used as data). Noncon-forming syntax can cause runtime errors.

Unless otherwise documented, the params attribute specifies a path relative to your application's full-view URL, subject to the following rules:

• If the first character in the value of params is "?", the value of params is simply appended to theURL.

• If the value of params begins with any character other than "?", the URL is truncated to the last slash;then the value of params is appended.

• If the URL ends with a trailing slash, it is not truncated.

The following examples illustrate how relative paths are constructed from params and the applicationURL.

ResultSpecified ParametersFull-View URL

http://example.com/my-full-view?x=1params="?x=1"http://example.com/my-full-view

http://example.com/fetch-abc?x=1params="fetch-abc?x=1"http://example.com/my-full-view

http://example.com/my-full-view/fetch-abc?x=1

params="fetch-abc?x=1"http://example.com/my-full-view/

1 http://www.ietf.org/rfc/rfc3986.txt

February 29, 201241Yahoo! Developer Network

Yahoo! Markup Language (YML)

Page 51: Yap Dev Guide

YML LiteYML Lite is a subset of YML designed for improved performance. The Small View of an Open Applicationcan contain only HTML or YML Lite tags, which are:

• yml:a

• yml:audio

• yml:form

• yml:if-env

• yml:include

• yml:name

• yml:profile-pic

• yml:pronoun

• yml:swf

• yml:user-badge

yml:a

DescriptionCreates a link to a different Open Application view, which can either be loaded in a new page view orDOM node.

Attributes

DescriptionRequired/OptionalTypeName

Name of application view linked to. The allowed values for applicationview are "YahooFullView" and "YahooSmallView".

optionalstringview

Parameters that are passed to the linked view. For YahooFullView,the params string is appended to the URL. See “URL Parameter En-coding and Relative Paths” [41].

optionalstringparams

The ID of a DOM node that will be replaced with the output of theview or params specified. The entire node is replaced.

optional*stringreplace

The ID of a DOM node where the contents will be substituted withthe output of the view or params specified. Although the contents ofthe node are substituted, the node itself remains.

optional*stringinsert

*Do not specify both replace and insert in the same element. If either of these attributes is used, theincluded content is filtered; specifically, JavaScript is removed and CSS is moved to the head of thedocument (where it can have global effects).

February 29, 201242Yahoo! Developer Network

Yahoo! Markup Language (YML)

Page 52: Yap Dev Guide

ExamplesThe following example creates a link in the small view that enables the user to navigate to the canvas (full)view. Include this code in the small view.

<yml:a view="YahooFullView">Click here to navigate to canvas view</yml:a>

The next example displays the content of the small view in the canvas view. Include this code in the canvasview.

<div id="content">You are currently viewing this page in canvas mode. <yml:a view="YahooSmallView">Click here to see your smallview content</yml:a></div>

The following example shows how to use the insert parameter to place content in the canvas view. Inthis case, the content is from the small view. When the user clicks the "InsertContent" link, the content inthis area disappears and the content from the small view is inserted in its place.

<!-- Include the following code in the small view --><div id="mysvcontent"><b> This content appears in the small view </b></div>

<!-- Include the following code in the canvas view --><div id="myfvcontent"><yml:a view="YahooSmallView" insert="insertContent">InsertContent</yml:a></div><div id="insertContent"></div>

The following example shows how to use the replace parameter to place content from the small viewin the canvas view. The replace parameter removes the div element, which cannot be referenced again.(In contrast, the insert parameter keeps div element, substituting only the content of the element.) Includethe following code in the small view.

<div id="mysvcontent"><b> This content is to be displayed in the smallView </b></div>

<!-- Include the following code in the canvas view -->

February 29, 201243Yahoo! Developer Network

Yahoo! Markup Language (YML)

Page 53: Yap Dev Guide

<div id="myfvcontent"><yml:a view="YahooSmallView" replace="insertContent">ReplaceContent</yml:a></div><div id="insertContent">When the user clicks the "ReplaceContent" link,the content in this area disappears and the content from thesmall view is inserted in its place.</div>

The next example passes parameters to the canvas view. The first time the user sees the canvas view, theparameters are not passed. When the user clicks the link created by yml:a, parameters (such as nameand perf are passed to the canvas view and displayed by the echo statements. Include the followingcode in the canvas view.

<b> This Page is served by Welcome3.php <b> <br><br><br>

<yml:a view="YahooFullView" params="Welcome3.php?name=kid&perf=good&work=yahoo&loc=us"> Click here to pass params </yml:a>

Welcome <?php echo $_REQUEST["name"]; ?>.<br>You are <?php echo $_REQUEST["perf"]; ?>.<br>You work for <?php echo $_REQUEST["work"]; ?>.<br>You are located in <?php echo $_REQUEST["loc"]; ?>.<br>

Like the preceding example, the following example passes parameters to the canvas view. However, theyml:a tag in the following example includes the insert attribute, which inserts the response into thediv element of the canvas view. Include the following code in the canvas view.

<div id="insertarea"><b> This Page is served by Welcome3.php <b> <br><br><br>

<yml:a view="YahooFullView" params="Welcome3.php?name=kid&perf=good&work=yahoo&loc=us" insert="insertarea"> Click here to pass params </yml:a>

Welcome <?php echo $_REQUEST["name"]; ?>.<br>You are <?php echo $_REQUEST["perf"]; ?>.<br>You work for <?php echo $_REQUEST["work"]; ?>.<br>You are located in <?php echo $_REQUEST["loc"]; ?>.<br></div>

The next example also passes parameters to the canvas view. When the user clicks the link created byyml:a, the response from folder2/folder3/file2.html is inserted into the div element "in-sertarea". Include the following code in the canvas view.

February 29, 201244Yahoo! Developer Network

Yahoo! Markup Language (YML)

Page 54: Yap Dev Guide

<div id="insertarea"><b> This Page is served by Welcome3.php <b> <br><br><br>

<yml:a view="YahooFullView" params="folder2/folder3/file2.html" insert="insertarea"> Click here to pass params </yml:a>

</div>

More Examples:

• Navigate from Small View to Canvas View [121]

• HTML Form in a Canvas View

• Tabs in the Small View [117]

• Accordion Menu for an Open Application [124]

• Refreshing the Small View [126]

yml:audio

DescriptionCreates an audio media player that plays MP3 files. The contents of the tag may define a playlist in anXML format.

Attributes

DescriptionRequired/OptionalTypeName

Full URL path to the MP3 file.requiredstringsrc

Sets the player to auto start on load. Default is "false". Autostartis not available in a small view.

optionalbooleanautostart

Sets the volume to mute. Default is "false".optionalbooleanmute

Defines the volume level. Default is "0.7".optionalstringvolume

Allows the audio track to loop. Default is "false".optionalbooleanloop

Defines the artist name. Default is "Unknown Artist".optionalstringartist

Defines the track name. Default is "Unknown Track".optionalstringtitle

Examples

<yml:audio src="http://www.yourdomain.com/file.mp3" title="My Car is Faster than Your Car" artist="Sammy Speedo" />

February 29, 201245Yahoo! Developer Network

Yahoo! Markup Language (YML)

Page 55: Yap Dev Guide

yml:customize

DescriptionCreates a link to an installation screen for your app. Use in Preview [20] content.

AttributesNone

Examples<yml:customize>Click here to customize this app!</yml:customize>

yml:form

DescriptionCreates a form that posts to a different Open Application view, which can either be loaded in a new pageview or a DOM node. Any form controls inside the yml:form will be posted as params to the view.

Attributes

DescriptionRequired/OptionalTypeName

Name of application view to link to. Allowed values are "Ya-hooFullView" and "YahooSmallView".

optionalstringview

Parameters to pass to the view being linked to. For "YahooFullView",the params string is appended to the URL. See “URL Parameter En-coding and Relative Paths” [41].

optionalstringparams

The name of the form.optionalstringname

The HTTP method, for example, POST.optionalstringmethod

The ID of a DOM node that will be replaced with the output of theview or params specified. The entire node is replaced.

optionalstringreplace

The ID of a DOM node where the contents will be substituted withthe output of the view or params specified. Although the contents ofthe node are substituted, the node itself remains.

optionalstringinsert

Examples

<yml:form name="myform" params="add.php" method="GET"> <fieldset> Symbol: <input type="text" name="symbol"/> Shares: <input type="text" name="shares"/> <input type="hidden" name="user" value="<?php echo $profile->guid;

February 29, 201246Yahoo! Developer Network

Yahoo! Markup Language (YML)

Page 56: Yap Dev Guide

?>"/> </fieldset> <input type="submit" value="Buy" /></yml:form>

See also HTML Form in a Canvas View.

yml:friend-selector

DescriptionDisplays an HTML select list of the user's friends. In a Yahoo! Profile, friends are called "Connections."Note: If the viewer (person running the application) and the target user (specified by uid attribute) are notthe same, the friends list is available only if the viewer and the target user are friends.

Attributes

DescriptionRequired/OptionalTypeName

The ID of the user to build a friends list for. Allowed values area GUID, the string "viewer", and the string "owner". Default is"viewer".

optionalstringuid

Allows multiple selections. Default is "false".optionalbooleanmultiple

Name of the form element that is generated. Default is "selected-Friend".

optionalstringname

Size of HTML select element. If "multiple" is set, then this de-faults to 10. Otherwise, it's ignored.

optionalnumericsize

A comma-delimited list of user IDs (uid) that will be pre-selected.Default is nothing selected.

optionalstringselected

Examples <yml:friend-selector uid="viewer"/>

<yml:friend-selector uid="PQ12345"/>

<yml:friend-selector uid="viewer" multiple="true" selected="PQ12345,AF34291,XP2qaAf3,owner"/>

See also Friend Selector [119] and Friend Selector With Style [120].

yml:if-env

DescriptionIncludes content or blocks of application code dynamically, based on the user's browser, version, operatingsystem, or if the browser is considered A-grade2 by Yahoo!.

2 http://developer.yahoo.com/yui/articles/gbs/index.html

February 29, 201247Yahoo! Developer Network

Yahoo! Markup Language (YML)

Page 57: Yap Dev Guide

Attributes

DescriptionRequired/OptionalTypeName

Specifies the browser user agent. Allowed values: "firefox", "sa-fari", "ie", "opera"

optionalstringua

Shows the content if the user's browser version is at least the givenvalue.

optionalstringminver

Shows the content if the user's browser version is at most the givenvalue.

optionalstringmaxver

Specifies the user's operating system. Allowed values: "macosx","winvista", "winxp", "win2000"

optionalstringos

Specifies the current view being displayed.optionalstringview

Specifies that the browser and operating system must be an A-grade3 browser.

optionalbooleanagrade

Examples<yml:if-env agrade ="true">You are browsing with an A-grade browser</yml:if-env><yml:if-env ua="firefox">You are browsing with Firefox</yml:if-env><yml:if-env ua="ie" minver="6">IE greater than or equal to version 6</yml:if-env><yml:if-env view="myview">Showing the "myview" view.</yml:if-env>

yml:include

DescriptionIncludes content from the specified source. This tag also allows an application to refresh data in the SmallView periodically.

Content fetched by yml:include is filtered:

• HTML markup is passed through without modification.

• CSS is moved to the head of the document; it is never kept in the body. This means that styles infetched content can affect the document globally.

• JavaScript is always removed.

Attributes

DescriptionRequired/Op-tional

TypeName

The relative path to the content, including any required parameters. See“URL Parameter Encoding and Relative Paths” [41].

requiredstringparams

3 http://developer.yahoo.com/yui/articles/gbs/index.html

February 29, 201248Yahoo! Developer Network

Yahoo! Markup Language (YML)

Page 58: Yap Dev Guide

DescriptionRequired/Op-tional

TypeName

The ID of the DOM node to replace with the output specified by theparams attribute. The entire node is replaced.

optional*stringreplace

The ID of a DOM node whose contents will be replaced with the outputspecified by the params attribute. Only the node's contents are replaced.

optional*stringinsert

The number of milliseconds to wait before YAP gets the content specifiedby the params attribute. The content will not be loaded any sooner thanthe number of milliseconds specified. The default value is 0.

optionalintegerdelay

The yml:include tag allows a maximum of five requests to run con-currently. If a page has more than five yml:include tags, and if thesetags do not specify a delay, then an 400 error will occur. To avoid thiserror, specify the delay attribute to group the requests, as shown by thesecond yml:include example below.

The delay attribute is not a strict contract. The YAP engine guaranteesthat the new content will not be loaded any sooner than the number ofmilliseconds specified by the delay attribute. However, it may takeseveral seconds longer, depending on several factors. For example, if thevalue of delay is 5000, the new content may be inserted anywhere from5 to 10 seconds after the content is loaded.

*Specify either replace or insert, but not both. Earlier implementations allowed yml:includeelements with neither replace nor insert attributes, but this usage is deprecated.

ExamplesIn the following example, the yml:include tag initially provides the string "some text here". After await of 5000 milliseconds, the content from myprog.php is fetched to replace the string "some text here".

<yml:include params="myprog.php?a=b" insert="xyz" delay="5000">some text here</yml:include>

A maximum of five yml:include requests can run concurrently. The next example shows how to workaround this limitation by setting the delay attribute to a different values in each group of five tags.

<yml:include params="http://example.com" insert="target" delay="1000"/><yml:include params="http://example.com" insert="target" delay="1000"/><yml:include params="http://example.com" insert="target" delay="1000"/><yml:include params="http://example.com" insert="target" delay="1000"/><yml:include params="http://example.com" insert="target" delay="1000"/>

<yml:include params="http://example.com" insert="target" delay="2000"/><yml:include params="http://example.com" insert="target" delay="2000"/><yml:include params="http://example.com" insert="target" delay="2000"/><yml:include params="http://example.com" insert="target" delay="2000"/><yml:include params="http://example.com" insert="target" delay="2000"/>

In the next example, the content from myprog.php replaces the DOM node that has the div ID acct.

<yml:include params="myprog.php" insert="acct" />. . .

February 29, 201249Yahoo! Developer Network

Yahoo! Markup Language (YML)

Page 59: Yap Dev Guide

<div id="acct"> <p>This text will be replaced by the output of myprog.php.</p></div>

The following example shows how the yml:include tag can help engage your users by keeping thedata in the Small View up to date. When a user first installs this application, the Small View shows thefollowing: "I am loading right now. Click here to load latest prices." The yml:include tag in the SmallView gets data by calling the prices.php program. When prices.php returns the data, the SmallView shows a string such as: "Prices as of Wed, 01 Jul 2009 17:51:01 -0600 Reloadget_the_prices_or_whatever_it_is_you_do". The yml:include tag in prices.php refreshes the dataevery 5 minutes (30000 milliseconds). The user can force a refresh by clicking the "Reload" link providedby the yml:a tag of prices.php.

<!-- The following code (the div with id="loading") goes into the Small View. -->

<div id="loading"> <yml:include replace="loading" params="prices.php">I am loading right now.</yml:include> <yml:a params="prices.php" replace="loading">Click here to load latest prices.</yml:a></div>

. . .

<!-- The next div belongs in the prices.php file, which is installed on your web server. -->

<div id="prices"> <yml:include delay="30000" params="prices.php" replace="prices" /> Prices as of <?php echo date('r'); ?> <yml:a params="prices.php" replace="prices">Reload</yml:a> <?php echo get_the_prices_or_whatever_it_is_you_do; ?></div>

For another examle, see Refreshing the Small View Dynamically [128].

yml:message

DescriptionCreates a form that opens a message dialog for the user. With the dialog, the user can send a message toYahoo! Connections (friends) or other users to tell them about the application. Those connections andusers receiving the message will get the message in the form of an email and a notification4.

The message element contains HTML form controls, each of which must have one of the followingnames (e.g. <input name="subject" ...>):

4 http://developer.yahoo.com/social/rest_api_guide/notifications_api.html

February 29, 201250Yahoo! Developer Network

Yahoo! Markup Language (YML)

Page 60: Yap Dev Guide

UseName

GUID(s) of message recipient(s)to

subject of messagesubject

content of messagebody

image that appears with messageimage

target of link that appears with messagelink_href

link text of link that appears with messagelink_label

label of "Submit" button in dialog that sender sees (defaults to "Send")submit

See “Examples” [51].

Attributes

DescriptionRequired/OptionalTypeName

Name of application view, for example, YahooFullView.optionalstringview

Path to a program, relative to the application containing theyml:message tag. (See “URL Parameter Encoding and Relative

optionalstringparams

Paths” [41].) The DOM node specified by the insert or replaceattribute is inserted into or replaced by the output of the programspecified by the params attribute.

The ID of a DOM node to replace with the output of the paramsspecified.

optionalstringreplace

The ID of a DOM node whose contents will be replaced with theoutput of the params specified.

optionalstringinsert

ExamplesThe yml:message and div tags in the following listing are in the code of the Canvas View (Ya-hooFullView). When the yml:message tag is executed, a form in a message dialog appears to the user.The message dialog is prepopulated with the form controls to, subject, and body, which the user canmodify. The value of the to control is the GUID of a Yahoo! user. (You can specify multiple GUIDs,separated by commas.) In the message dialog, the "To" field contains the display name of the recipient.When the user clicks the submit button, an email is sent to the user specified by the to form control. Theoutput of myprog.php is inserted into the DOM node of the div with the ID sect1, replacing thecontents of the div.

In Yahoo! Mail, the message appears as an email in the recepient's inbox. The text in the email's subjectand body correspond to the values specified by the form controls in the yml:message tag. The emailcontains three other elements: an "Add" button, an image, and a link. By clicking the "Add" button, therecipient can install the application run by the sending user (that is, the application containing theyml:message tag). The image in the email is specified by the image form control of the yml:messagetag. The link in the email is labelled "Click me", as specified by the link_label form control. Thedestination of the link is click_from_email.php, as indicated by link_href.

. . .

<yml:message

view="YahooFullView"

February 29, 201251Yahoo! Developer Network

Yahoo! Markup Language (YML)

Page 61: Yap Dev Guide

params="myprog.php" insert="sect1">

<!-- GUID of the Yahoo Connection who is the message recipient. --> <input name="to" type="hidden" value="MHT5XY4FBG2OXXHQYWVPOF4A2E">

<!-- Subject of message. --> <input type="text" name="subject" value="an app you will like">

<!-- Body of message. --> <textarea name="body">This is a really funny app.</textarea>

<!-- Image for message that appears to the recipient. --> <input type="text" name="image" value="http://host.domain/pic.jpg">

<!-- Target of link that appears to the recipient. --> <input type="hidden" name="link_href" value="click_from_email.php">

<!-- Label of link that appears to the recipient. --> <input type="hidden" name="link_label" value="Click me">

<!-- Label of submit button in the message dialog that appears to the sender. --> <input type="submit" name="submit" value="Send message now">

</yml:message>

. . .<div id="sect1"> <p>This paragraph is replaced by the output of myprog.php.</p></div>. . .

yml:name

DescriptionDisplays the name of the specified person. Optionally, links to the person's Yahoo! Profile page.

Attributes

DescriptionRequired/OptionalTypeName

If true, the name displayed links to the Yahoo! Profile page ofthe user. Default is "false".

optionalbooleanlinked

Display the word "you" instead of the user's actual name if theuser is the viewer. Default is "false".

optionalbooleanuseyou

Used in conjunction with the useyou="true" attribute. If true,shows "yourself" instead of "you". Default is "false".

optionalbooleanreflexive

If true, capitalizes the first letter of the user's name. Default is"false".

optionalbooleancapitalize

February 29, 201252Yahoo! Developer Network

Yahoo! Markup Language (YML)

Page 62: Yap Dev Guide

DescriptionRequired/OptionalTypeName

The ID of the user whose name is displayed. Allowed values area GUID, "viewer", and "owner". Default is "viewer".

optionalstringuid

Examples

<yml:name uid="viewer" linked="true" capitalize="true" />

<yml:name uid="QPR12345" />

See also Links to Yahoo! Profile [123].

yml:profile-pic

DescriptionDisplays the user's Yahoo! Profile picture. Optionally, links to the user's Yahoo! Profile page.

Attributes

DescriptionRequired/OptionalTypeName

If true, the picture displayed links to the user's Yahoo! Profile page.Default: false.

optionalbooleanlinked

The width and height in pixels of the picture. The maximum size is48. Default: 48.

optionalintwidth

The ID of the user whose picture is to be displayed. Allowed valuesare a specific user ID, the string "viewer", and the string "owner".Default: "viewer"

optionalstringuid

Examples <yml:profile-pic uid="viewer" width="48" linked="false" />

<yml:profile-pic uid="PA385037" width="24" linked="true" />

<yml:profile-pic uid="owner" width="48" linked="true" />

See also Links to Yahoo! Profile [123].

February 29, 201253Yahoo! Developer Network

Yahoo! Markup Language (YML)

Page 63: Yap Dev Guide

yml:pronoun

DescriptionDisplays a pronoun appropriate for the user ID and specified parameters. Note: Only define one of thetense-related attributes (possessive, reflexive, objective) at a time. If more than one is specified, one willtake precedence over the rest.

Attributes

DescriptionRequired/OptionalTypeName

User ID of the pronoun to render. Allowed values include anID, the string "viewer", and the string "owner".

requiredstringuid

Display "you" instead of a personal pronoun. Default is "true".Only applicable when uid="viewer".

optionalbooleanuseyou

Display the possessive form of the pronoun (your, her, his,their). Default is "false".

optionalbooleanpossessive

Display the reflexive form of the pronoun (yourself, himself,herself, themselves). Default is "false".

optionalbooleanreflexive

Display the objective form of the pronoun (you, her, him, them).Default is "false".

optionalbooleanobjective

Display "they" if the gender cannot be determined. Default is"true".

optionalbooleanusethey

Capitalize the first letter of the pronoun. Default is "false".optionalbooleancapitalize

Examples<yml:pronoun uid="viewer" useyou="true"/><yml:pronoun uid="viewer" useyou="true" capitalize="true"/> <yml:pronoun uid="12345" possessive="true"/><yml:pronoun uid="viewer" obj="true"/><yml:pronoun uid="viewer" reflexive="true" capitalize="true"/><yml:pronoun uid="owner"/><yml:pronoun uid="viewer" usethey="true"/>

yml:share

DescriptionCreates a form that will open a "message" dialog for the user. It's just like yml:message, except that themessage itself is not customizable, and you cannot specify a view where the user will "land" when they'vesent the message. Also, the user has two allotments of messages that they can send per day: one for genericmessages and another for sharing messages. Users receiving the message will get the message in the formof an email and a notification5.

5 http://developer.yahoo.com/social/rest_api_guide/notifications_api.html

February 29, 201254Yahoo! Developer Network

Yahoo! Markup Language (YML)

Page 64: Yap Dev Guide

AttributesNone

Examples <yml:share> <!-- this is a list of guids, or just one guid --> <yml:friend-selector name="to" multiple="true" size="10" /> <input type="submit" value="Share with your friends!"></yml:share>

yml:swf

DescriptionIncludes a Shockware Flash (SWF) object in an Open Application.

Note

Caja imposes security restrictions [68] on the use of Flash code.

Attributes

DescriptionRequired/OptionalTypeName

The full path URL to the SWF file.requiredstringsrc

The width of the SWF object in pixels.requiredintwidth

The height of the SWF object in pixels.requiredintheight

Autoplay when the SWF loads. Default is "true".optionalbooleanplay

Play the SWF continuously. Default is "false".optionalbooleanloop

Display a context menu when the user right-clicks the SWF ob-ject. Default is "false".

optionalbooleanmenu

Quality of the object. Allowed values: "high", "medium", "low".Default is "high".

optionalstringquality

Scaling of the SWF object. Allowed values: "showall", "nobor-der", "exactfit", and "default". Default is "default".

optionalstringscale

Alignment of the SWF object within the DOM object. Default isnull.

optionalstringalign

Alignment of the SWF movie within the SWF object. Allowedvalues: "t" (top), "b" (bottom), "l" (left), "r" (right). Also allowed

optionalstringsalign

are the following combinations: "tl", "tr", "bl", "br". Default is"tl".

Opacity setting. Allowed values: "transparent", "opaque", "win-dow". Default is "transparent".

optionalstringwmode

Hexadecimal SWF background color. Default is "#FFFFFF".optionalstringbgcolor

February 29, 201255Yahoo! Developer Network

Yahoo! Markup Language (YML)

Page 65: Yap Dev Guide

DescriptionRequired/OptionalTypeName

Developer-supplied flashvars. The values must be HTML en-coded. Default is null.

optionalstringflashvars

Tag contentsIf the user does not have a high enough version of Flash, they'll see the contents of the tag. If you don't putanything here, then they'll see a default message with a link to download the latest version of Flash.

If play is not set to "true", then the user will have to click the fallback content to activate the Flash movie.

Examples

<yml:swf src="http://example.com/app.swf" width="780" height="1000"/>

<yml:swf src="http://example.com/app.swf" height="780" width="1000" flashvars="foo=bar"/>

yml:user-badge

DescriptionDisplays the user badge, which is the name and picture of the user's Yahoo! Profile. Optionally, links tothe person's Yahoo! Profile page.

Attributes

DescriptionRequired/OptionalTypeName

If true, the badge displayed links to the user's Yahoo!Profile page. Default is "true".

optionalbooleanlinked

The width in pixels of the badge with a max of 48. De-fault is "48".

optionalstring (numerical)width

If true, shows "yourself" if useyou="true", otherwiseit's ignored. Default is "false".

optionalbooleanreflexive

If true, capitalize the first letter of the user's name. De-fault is "true".

optionalbooleancapitalize

If true, and the user is the viewer, it'll show "you" in-stead of the name. Default is "false".

optionalbooleanuseyou

The ID of the user whose badge is displayed. Allowedvalues are "viewer", "owner", or id. Default is "viewer".

optionalstringuid

Examples <yml:user-badge uid="viewer" linked="true" width="48" reflexive="false" useyou="false" capitalize="true" />

February 29, 201256Yahoo! Developer Network

Yahoo! Markup Language (YML)

Page 66: Yap Dev Guide

See also Links to Yahoo! Profiles [123].

February 29, 201257Yahoo! Developer Network

Yahoo! Markup Language (YML)

Page 67: Yap Dev Guide

Chapter 7. Caja SupportIn this Chapter

• “Introduction” [58]

• “What is Caja?” [58]

• “Caja Status for This Release” [58]

• “Why Do We Need Caja?” [59]

• “How Does Caja Work?” [59]

• “How Do I Debug My Application?” [61]

• “What HTML Tags are Blacklisted?” [62]

• “What Works in Caja?” [62]

• “What are Caja's Limitations?” [63]

• “What Do These Messages Mean?” [69]

Introduction

What is Caja?Caja is a system that transforms ordinary HTML and JavaScript into a restricted form of JavaScript. Thetransformation is called "cajoling", and the result is "cajoled script". The cajoled script is then run withina security sandbox created in your browser. This provides a way to safely include arbitrary third-partycontent on any Web page.

In principle, Caja should be transparent. Most JavaScript behaves the same whether it's run directly or ca-joled. However, since Caja is currently evolving and incomplete, there are some noticeable differences.

Caja is an Open Source project sponsored by Google and hosted at Google Code1.

Caja Status for This ReleaseSince Caja is used to transform an application's HTML and JavaScript into a restricted form that preventsmalicious applications from doing damage, applications cannot contain arbitrary ActiveX objects, useeval to get around the ActiveX restriction, or use iframes to get around the eval restriction.

Other than that, most JavaScript application elements should work. Our goal is to make Caja as unobtrusiveas possible for ordinary applications. However, we're not there yet. Caja still has some rough edges, andyou may experience mysterious Caja behavior. This document will describe some of those mysteries indetail.

1 http://code.google.com/p/google-caja/

February 29, 201258Yahoo! Developer Network

Page 68: Yap Dev Guide

To get started right away, use a browser that supports console.log(), such as Firefox with the Firebug2

add-on, IE 8, or Safari 4.x.

Note the following restrictions that apply to this release:

• Calls to alert() are redirected to console.log().

• You can't use external scripts or external stylesheets yet. Inline them instead.

• Complex libraries such as YUI, jQuery, and Prototype might partially work if you inline them, but theyare not seamless yet.

• The document.write method is subject to restrictions described in “DOM Limitations” [67].However, innerHTML and many commonly-used DOM interfaces are supported.

Why Do We Need Caja?When a website wants to include arbitrary third-party content, it needs to consider many potential securityproblems. One of the harder problems is "drive-by downloads": an attacker inserts malicious HTML thattries to install malware when you view the page.

A typical vector is an <iframe src=...> tag pointing at the attacker's website. Your browser automat-ically loads the iframe, which runs a script that figures out what browser and extensions you have, thendownloads malware targeted specifically at the vulnerabilities known for your system.

The traditional solution to this problem is to aggressively sanitize third-party content by removing iframes,removing scripts, etc. That works well in many cases, but aggressive sanitization makes it difficult to createinteresting applications.

Today, we want to allow anybody to create interesting applications that can appear on our site, but we alsowant to limits our users' exposure to scripts that install malware.

Sanitizing JavaScript is difficult, and that's what Caja is about.

How Does Caja Work?Caja has two main parts:

• server-side translator

• client-side runtime support

The Server-Side Translator

The Caja translator rewrites arbitrary HTML and JavaScript into safe HTML and JavaScript, using white-list security principles, by

• Removing anything it doesn't understand

• Removing HTML and CSS that isn't on a white-list

• Modifying CSS rules, limiting them to a sandbox <div>

2 http://getfirebug.com/

February 29, 201259Yahoo! Developer Network

Caja Support

Page 69: Yap Dev Guide

• Transforming JavaScript into forms known to be safe

The JavaScript transformation is the complicated part. It's basically a form of virtualization:

• Replaces references to real global variables with references to per-sandbox globals

• Rewrites references to this to prevent access to the real global scope

• Replaces most JavaScript code with semantically similar code that has runtime checks for security

• Rejects some JavaScript code early, such as with(obj){...}.

Here's an example transformation. This JavaScript source code:

size = 3; function arf(geo, out) { var s4 = geo.compute(4 * size); var s5 = geo.compute(5 * size); out.value = (s4+s5)/2; return this; };

is cajoled into something like this:

$v.so('arf', (function () { function arf$_caller($dis, geo, out) { var s4 = $v.cm(geo, 'compute', [ 4 * $v.ro('size') ]); var s5 = $v.cm(geo, 'compute', [ 5 * $v.ro('size') ]); $v.s(out, 'value', (s4+s5)/2); return $dis; } ___.markFuncOnly(arf$_caller, 'arf$_caller'); return $v.dis(___.primFreeze(arf$_caller), 'arf'); })()); $v.so('size', 3);

Note

The actual Caja transformation is slightly different. This example has been simplified to makeit easier to see what Caja is doing under the hood.

Simple operations on local variables, such as (s4+s5)/2, are left alone.

Some operations on local variables, such as geo.compute(), are rewritten to call $v functions.

References to globals, such as size, are rewritten to call $v functions.

References to this are rewritten to $dis.

For more details about the JavaScript transformation, see the Google Caja page3.

3 http://code.google.com/p/google-caja/

February 29, 201260Yahoo! Developer Network

Caja Support

Page 70: Yap Dev Guide

The client-side runtime

Cajoled script can't access any real global objects without help, and that's what the Caja runtime systemis for. The runtime system creates a useful sandbox environment by importing objects into the sandbox'sglobals, which is called "outers" or IMPORTS___.

Some of the imported objects are the real thing. For example, IMPORTS___.Array is identical to thebrowser's Array.

Some of the imported objects are proxies. For example, IMPORTS___.document is a proxy object thatexposes a safe subset of the DOM interface.

The proxy function document.getElementById will return objects that are also proxies. You won'tget direct access to a real DOM object, but that doesn't matter, because the proxy objects are similar enoughto the actual objects .

The runtime system also enforces the Caja security model, by checking that objects and functions wereproperly tagged before they're used. You can see Caja's internal tagging when you examine objects in adebugger. Most objects will have properties that end with triple-underbar, such as length_canRead___,FROZEN___, etc.

How Do I Debug My Application?Caja's runtime library writes errors and diagnostics with console.log(), so it's probably easier to workin a browser that supports console.log(), such as Firefox+Firebug, Safari 4, or IE 8.

First, if you're getting weird error messages, check if they're explained here.

Most LINT and WARNING messages are harmless and can be ignored. However, there's one WARNINGthat's important:

WARNING: failed to load external url ...

The reason that's important: External scripts are not currently supported, but Caja doesn't flag that as afatal error. If you see that warning for a <script> tag, then your application probably won't work. Fixthat problem first. Either inline the external script, or modify your code to eliminate the external dependency.

alert() works, but the messages are redirected to Firebug's console.

Always check your JavaScript console for messages, even if you aren't getting JavaScript errors. SometimesCaja's runtime will print an error message without throwing or re-throwing an exception, so tools likeFirebug will not notice it's an error and will not notify you.

YML Alters Caja Line NumbersThe line numbers in Caja's error messages are line numbers that Caja sees, which is not necessarily thesame as the line numbers in your source code. In particular, YML transformation happens before Caja, soif you use any YML tags, the line numbers reported by Caja might be offset by an arbitrary amount.

At the moment, there isn't an easy way to determine the original line number.

For compile-time errors, Caja will print the source line text for each error, and hopefully that's enough toidentify the actual location.

February 29, 201261Yahoo! Developer Network

Caja Support

Page 71: Yap Dev Guide

For run-time errors, you can sometimes figure out the real location by looking at the JavaScript that Cajagenerates.

What HTML Tags are Blacklisted?Caja does not allow the following HTML tags:

<applet><base><basefont><embed><frame><frameset><iframe><isindex><meta><noframes><noscript><object><param><title>

What Works in Caja?This is a brief overview of what's expected to work in Caja currently.

Browsers Supported• Firefox 3.0 and 3.5 work pretty well.

• Safari 3 and 4 work pretty well.

• IE 7 and 8 work ok.

• IE 6 is a little flaky.

• Opera 9 and 10 probably work, but are not tested much.

HTML and CSSCaja supports most of the HTML 4.01 and CSS 2.1 specs, as well as some common browser extensions.Caja tends to adhere more closely to the specs than browsers do, so it may warn about or reject nonstandardextensions that would normally work in browsers.

YMLAll YML tags work with Caja.

February 29, 201262Yahoo! Developer Network

Caja Support

Page 72: Yap Dev Guide

DOM manipulationCaja provides proxied access to the DOM. If you look under the hood, you can see that you're actuallymanipulating instances of TameDocument, TameNode, etc.

Many of the common DOM operations work, such as document.getElementById, document.cre-ateElement, node.firstChild, etc. However, Caja does not implement the complete DOM spec,so uncommon operations may not work yet.

The document.write method is subject to restrictions described in “DOM Limitations” [67]. Settingand getting innerHTML is supported.

Events and TimersMost event handlers work. You can attach handlers with HTML onevent= attributes, or with the DOMaddEventListener method, or by assigning to the node.onevent property.

Note: node.onevent='...' will not work. The value must be a function.

the window.setTimeout and window.setInterval methods both work.

Note: event.fromElement is IE specific and is not supported by Caja. Instead, use event.targetor event.relatedTarget, depending on the event type.

OpenSocial 0.9Most of our OpenSocial 0.9 support is explicitly whitelisted for use in Caja. If you get runtime "Not readable"errors related to OpenSocial objects, check if you're using an older interface that is no longer part of thestandard. You might also be using an OpenSocial 0.9 feature that is not supported by YAP; see Chapter 9,OpenSocial 0.9 Compatibility [77].

What are Caja's Limitations?This section describes various things that don't work in Caja, along with some workarounds. Some of theseare deliberately not supported, some are accidentally not supported. The following material is specific toour Caja instance. Caja has a flexible configuration, so you might not see exactly the same behavior else-where.

Server-Side vs. Client-Side SanitizationCaja has two similar but distinct HTML sanitization processes:

• Server-side sanitization is the full cajoler transformation applied to your application. Server-side sanit-ization supports complex features like scripts and stylesheets.

• Client-side sanitization happens when you set innerHTML in your application. Client-side sanitizationis more restrictive, and will silently strip out scripts and stylesheets.

XHTML StrictnessIf your application starts with an <?xml> tag or a <!DOCTYPE> that isn't HTML, then Caja will parseyour application as XML, which is stricter than HTML, and stricter than what browsers will usually do.

February 29, 201263Yahoo! Developer Network

Caja Support

Page 73: Yap Dev Guide

Most of the time, it's easier to tell Caja that your app is HTML. Either omit <!DOCTYPE>, or use someHTML doctype, such as <!DOCTYPE html>.

However, if you do want XHTML strictness, here are some common problems you might encounter:

• Unclosed tags or unbalanced tags are fatal errors, which will prevent your application from renderingat all.

• The <script> elements are not special. In HTML, a <script> element will read everything as lit-eral text until a closing </script> tag, so you don't have to do anything about "<" or "&" charactersin your script. In XML, a <script> element is parsed like any other tag, and the contents must bewell-formed XML. So, you will usually want to quote your script bodies with <![CDATA[...]>.

HTML Limitations<a target=...> We allow target=_blank and tar-

get=_top. Other values are deleted with awarning. Omitting target is the same astarget=_top.

<embed> For Flash, use <yml:swf> instead. Otherembeds are not supported.

<head> All contents of the head element are stripped.Use plain HTML starting from inside thebody.

<iframe> Not supported yet. Workaround depends onwhat you're trying to do.

<link rel=stylesheet> External stylesheets are not supported yet.Workaround is to inline the stylesheet.

<object> For Flash, use <yml:swf> instead. Otherembeds are not supported.

<script> Inline scripts are supported by the server-sidecajoler, but they're stripped by the client-sidesanitizer. Workaround depends on what you'retrying to do.

<script src=...> External scripts are not supported yet. Work-around is to inline the script.

<style> Stylesheets are supported by the server-sidecajoler, but they're stripped by the client-sidesanitizer. Workaround depends on what you'retrying to do.

javascript:void(0) Caja currently rejects any javascript:URLs.

If you're trying to use javas-cript:void(0) to make <a> buttons, try

February 29, 201264Yahoo! Developer Network

Caja Support

Page 74: Yap Dev Guide

using an onclick handler instead, somethinglike this:

<a href="#" onclick="click(); return false">click</a>

URL policy We currently allow http, https, andmailto URLs.

This applies to any use of URLs, such as <a>,<img>, etc.

CSS Limitations[] selectors A subset of [] selectors are supported, but

only to the extent that the browser supportsthem. For example, IE7 will still ignore []selectors.

expression() Not supported. Workaround depends on whatyou're trying to do.

@import Not supported yet. Workaround is to inlinethe stylesheet.

:visited The text-decoration property of:visited is not supported. The followingproperties are supported: color, back-ground-color, cursor.

JavaScript limitationseval() Not supported. Workaround depends on what

you're trying to do.

new Function() Not supported. This is similar to eval.Workaround depends on what you're tryingto do.

Assigning strings as event handlers Code like this is not supported:

node.onclick = '...';

That's an implicit eval, and has the sameproblem as explicit eval.

Instead, put your event-handling code in afunction, and assign the function to the eventhandler:

function handle_click() { ...

February 29, 201265Yahoo! Developer Network

Caja Support

Page 75: Yap Dev Guide

} node.onclick = handle_click;

Names ending with underscore You can't use names ending with triple-under-score. Those are reserved for Caja's internalbookkeeping.

You can't use names ending with double-un-derscore. Those are reserved for browser ex-tensions.

with (obj) { ... } This is not allowed since the dynamic behaviorof with makes it difficult to analyze its secur-ity implications. The workaround is to removethe with statement and write obj.foo in-stead of just foo.

Calling a method as a function If obj.foo is a method that refers to this,then peeling it off as a function and calling itdirectly will cause a runtime error:

<script> var get = document.getElementById; get('x'); // fails </script>

That doesn't really work in raw JavaScripteither, but instead of silently doing the wrongthing, Caja will throw an error:

Can't call .getElementById on a non function () { throw "This constructor cannot be called directly";}: USELESS

The reason is, JavaScript doesn't have boundmethods, so that code probably doesn't dowhat you want. The code is saying to callgetElementById with this bound to theglobal object, which is window. So if it suc-ceeded, getElementById would getthis===window, instead ofthis===document.

The usual way of capturing a method as afunction is to wrap the method call in a func-tion:

<script>

February 29, 201266Yahoo! Developer Network

Caja Support

Page 76: Yap Dev Guide

var get = function(el) { return document.getElementById(el); }; get('x'); // works </script>

And that will work with or without Caja.

DOM LimitationsSome limitations in the DOM interface result from missing implementation rather than security concerns.If the function or property you're trying to use isn't available, you may be able to do the same thing usingcurrently supported interfaces.

document.write The document.write method is subjectto the following restrictions:

• Prohibited tags and attributes, includingscript, are silently removed. (The samefiltering rules apply to innerHTML.)

• Incomplete tags are prohibited. For ex-ample, document.write('<divclass="'); will not work, nor willdocument.write(className); ordocument.write('">');. Instead,concatenate the parts and write the result inone piece.

Unbalanced tags, however, are allowed. Forexample, the following will work:

document.write('<b>'); document.write('hello'); document.write('</b>');

• You can't change the nesting structure ofstatic HTML. Consider this example:

<div id="div1"> <script> document.write('</div>'); </script> <div id="div2"> </div> </div>

A browser would interpret this code byclosing div1, making div2 a sibling ofdiv1. In Caja, however, the full structureis created before any scripts are executed,making div2 a child of div1; there is noway to change this with docu-ment.write.

• You can't use document.write to erasea document. In a browser, if a document is"closed", document.write erases it andstarts a new document. This typically hap-pens when document.write is calledfrom an event listener. In Caja, however,

February 29, 201267Yahoo! Developer Network

Caja Support

Page 77: Yap Dev Guide

document.write always appends to thevirtual document without erasing anything.

As an alternative to document.write, youcan use innerHTML:

<div id="x"></div> <script> var x = document.getElementById('x'); x.innerHTML = 'abc'; </script>

You can also build up a DOM tree in piecesusing document.createElement andso forth.

window.event window.event isn't supported. This prob-lem shows up if you have event-handling codelike this:

<a onclick="click()">click</a> <script> function click() { alert(window.event); } </script>

When you click on the text, the value you getwill be undefined.

The workaround is to pass in the event as anargument. Caja always binds event withinonevent= handlers, so you can rewrite theexample this way:

<a onclick="click(event||window.event)">click</a>

<script> function click(event) { alert(event); } </script>

Another workaround is to use addEventL-istener instead.

Flash RestrictionsIf your application serves Flash code, it should specify allowNetworking="internal" in its <ob-ject> and <embed> tags. This prevents Flash from fetching external pages, images, or JavaScript

February 29, 201268Yahoo! Developer Network

Caja Support

Page 78: Yap Dev Guide

routines (which may violate Caja restrictions). For more information about allowNetworking, see theActionScript Developer's Guide4 and Flex documentation5 from Adobe.

What Do These Messages Mean?

Compile-Time ErrorsCompile-time errors show up as messages at the end of your application preview, and look something likethis:

stdin:stdin:1: <div id='x' foo='hi'></div> ^^^WARNING: stdin:stdin:1+13 - 16: removing unknown attribute foo on div

Most LINT and WARNING messages are harmless and can be ignored, but pay attention to any "failed toload external url" warnings.

Here are some of the common errors:

WARNING: ...: failed to load externalurl ...

External scripts and stylesheets are currentlynot supported. Note, failure to load a script isnot a fatal error, so Caja will keep processingyour application, and it will probably fail onsome issue that's a side effect of the load fail-ure. Subsequent error messages are misleadingin this case. The real problem is the load fail-ure.

Inline the external content to get around this.

ERROR: ...: css property color has badvalue: ==>...<==

Caja is pretty strict about color names in CSSrules. Only the 16 standard color names arerecognized. Use hexadecimal colors to getaround this.

Runtime errorsRuntime errors usually show up as plain messages in the JavaScript console. Sometimes a runtime errorwill raise an exception that will be reported as an error, but these exceptions are often unrelated to the ac-tual error.

4 http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS1EFE2EDA-026D-4d14-864E-79DFD56F87C6.html#WS5b3ccc516d4fbf351e63e3d118a9b90204-7c5b5 http://help.adobe.com/en_US/flex/using/WS2db454920e96a9e51e63e3d11c0bf69084-7f18.html

February 29, 201269Yahoo! Developer Network

Caja Support

Page 79: Yap Dev Guide

Chapter 8.YUI SupportIn this Chapter

• “Introduction” [70]

• “YUI Examples for YAP” [72]

IntroductionNote

In this release, YUI on YAP is a beta feature providing limited YUI library support.

Caja [58], the YAP front-end securer, restricts the use of certain insecure JavaScript features within theCanvas view of a YAP Open application. However, several YUI utilities have been integrated with YAP,enabling you to include YUI functionality in a Canvas View.

To understand this chapter, you should already be familiar with YUI. For more information, see the YUILibrary sites on YDN1 and yuilibrary.com2.

YUI Libraries and Utilities Available in YAPYAP supports a subset of the YUI 2.8.0 libraries and utilities. Other releases of YUI are not supported.The specific YUI libraries and utilities that YAP supports are listed in the following sections:

YUI Core

• YAHOO Global Object (base requirement for all YUI components)

• DOM Collection (convenience methods for DOM interactions)

• Event Utility (event normalization and custom events)

YUI Library Utilities

• Animation Utility

• Connection Manager (for XHR / AJAX)

• DataSource Utility

• Drag and Drop Utility

• Element Utility

• ImageLoader Utility

• Resize Utility

1 http://developer.yahoo.com/yui2 http://yuilibrary.com/

February 29, 201270Yahoo! Developer Network

Page 80: Yap Dev Guide

• Selector Utility

YUI Library Controls / Widgets

• AutoComplete

• Button

• Container (including Module, Overlay, Panel, Tooltip, Dialog, SimpleDialog)

• Menu

• TabView

• TreeView

Including YUI Scripts and CSSTo include YUI in your Canvas View, follow the procedures described in the "Start building" step on thepage YUI 2 - Yahoo! User Interface Library3. If you include YUI directly from the Yahoo! servers, theYUI JavaScript libraries are interpreted by the cajoler and swapped with a Caja-safe version on the Yahoo!servers. If you include YUI by inserting the contents inline onto your page, the inlined script is interpretedby the cajoler and rewritten to its Caja-safe equivalent.

To determine which YUI scripts and CSS need to be included in your application, use the YUI DependencyConfigurator4. However, YAP currently supports only YUI 2.8.0; do not be misled by the Configuratorinto importing unsupported versions. For example, the Configurator might supply a script that pulls in2.8.2 libraries, like this:

<script type="text/javascript" src="http://yui.yahooapis.com/2.8.2r1/build/yahoo-dom-event/yahoo-dom-event.js"></script>

To avoid errors, you would replace the Configurator-supplied script with this:

<script type="text/javascript" src="http://yui.yahooapis.com/2.8.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>

Support and BugsTo report a bug or ask a question about YUI on YAP, post to the YAP Forum5. For support on YUI withoutYAP, see the yuilibrary.com site6. When posting, please provide the following information:

• The YUI libraries that you are using.

• A description of the problem you are encountering.

• A code snippet that illustrates the problem.

• Applicable error messages or logs.

3 http://developer.yahoo.com/yui/2/4 http://developer.yahoo.com/yui/articles/hosting/5 http://developer.yahoo.net/forum/index.php?showforum=406 http://yuilibrary.com

February 29, 201271Yahoo! Developer Network

YUI Support

Page 81: Yap Dev Guide

YUI Examples for YAPThe following examples show the CSS, HTML, and JavaScript code needed for implementing YUI in theCanvas View of an Open Application.

Event HandlersThis example shows how to set up a simple rating widget in an Open Application using the YUI eventhandler utilities.

Style Block

The CSS defines the core visualization of the rating widget. This style block should be placed within thesame file as the widget, not included in an external style sheet.

<style type="text/css"> div#ratings{ position:relative; border:1px solid rgb(204, 204, 204);

padding:15px; color:rgb(89, 89, 89); width:275px; background-color:rgb(248, 248, 248); } div#ratings div{ width:25px; height:25px; float:left; margin:10px; border:1px solid #4891e9; } div#ratings div.normal{ background-color:#c4d8f0; } div#ratings div.hover{ background-color:#ebc357; } div#ratings div.clicked{ background-color:#4891e9; } div#ratings br.clear{ clear:both; height:1px; }</style>

HTML Block

The HTML of the ratings widget specifies a unique ID for each selectable option.

<div id="ratings"> <div class="normal" id="star1"></div> <div class="normal" id="star2"></div> <div class="normal" id="star3"></div> <div class="normal" id="star4"></div> <div class="normal" id="star5"></div> <br class="clear" /> </div>

JavaScript Block

The JavaScript code defines the event handlers and attaches the event listeners that will handle the mouseevents.

The ids array contains the unique IDs defined in the preceding HTML Block section. Later in the code,this array will be referenced when adding event listeners.

February 29, 201272Yahoo! Developer Network

YUI Support

Page 82: Yap Dev Guide

<script type="text/javascript"> //create the id array for all nodes which will be assigned YUI events

var ids = ['star1', 'star2', 'star3', 'star4', 'star5'];

The next code snippet sets up the event handlers for the mouseover and mouseout events. The code usesthe YUI Event utility to get the DOM node that generated the action. If the DOM node has not alreadybeen set to a clicked state, the class of the node is set to hover for the mouseover or to normal for themouseout.

//handle the hover state by changing the class of the hover target //do not change the class if the target has already been clicked function fnOver(e){ var target = YAHOO.util.Event.getTarget(e, 1); if (! YAHOO.util.Dom.hasClass(target.id, 'clicked')){ target.className = 'hover'; } }

//handle the out state by changing the class of the hover target //do not change the class if the target has already been clicked function fnOut(e){ var target = YAHOO.util.Event.getTarget(e, 1); if (! YAHOO.util.Dom.hasClass(target.id, 'clicked')){ target.className = 'normal'; } }

The next code snippet defines a handler for the click event. First, the code gets the DOM node that wasclicked and determines the number that was clicked based on the ID of the node. Next, the getElements-ByClassName utility gets all nodes that have a clicked state. The first for loop iterates through thosenodes, setting them back to a normal class. The second for loop goes through all clickable nodes, fromthe first node to the node that was clicked, and sets their class to clicked.

//handle the click event function fnClick(e){ //get the node that was clicked var target = YAHOO.util.Event.getTarget(e, 1); var itmNum = target.id[target.id.length - 1];

//purge all clicked states for each previously selected node (reset class tonormal) var clickedEls = YAHOO.util.Dom.getElementsByClassName('clicked', 'div'); for (var i = 0; i < clickedEls.length; i++){ clickedEls[i].className = 'normal';

February 29, 201273Yahoo! Developer Network

YUI Support

Page 83: Yap Dev Guide

}

//set the class for the current and lower nodes to a clicked state for (i = 1; i <= itmNum; i++){ document.getElementById('star' + i).className = 'clicked'; } }

Finally, the code calls the YUI addListener method to add the mouseover, mouseout, and click eventlisteners. These listeners are added to the nodes of the IDs in the array defined at the top of the JavaScriptblock.

//attach the YUI event handlers to all provided nodes YAHOO.util.Event.addListener(ids, "mouseover", fnOver); YAHOO.util.Event.addListener(ids, "mouseout", fnOut); YAHOO.util.Event.addListener(ids, "click", fnClick); </script>

Scrolling AnimationThis example shows how to create an end-user license agreement (EULA) section scroller in an OpenApplication.

Style Block

The CSS defines a few simple styles to build out the EULA scroll container. These styles define visualrepresentation of the widget and are independent of the actual animation effects.

<style type="text/css"> #eulaScroll { height:6em; width:20em; overflow:auto; margin-bottom:1em; font:13px arial,helvetica,sans-serif; }</style>

The HTML Block

The HTML defines eulaScroll, a div container with two content sections. Below this container arethe two buttons that control the scrolling animation between sections.

<div id="eulaScroll"> <p><b>Section 1</b><br />

February 29, 201274Yahoo! Developer Network

YUI Support

Page 84: Yap Dev Guide

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin a ante non sapien vestibulum ullamcorper eu a elit. Maecenas pretium, magna sit amet volutpat aliquam, elit turpis sollicitudin velit, vel.</p>

<p><b>Section 2</b><br /> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin a ante non sapien vestibulum ullamcorper eu a elit. Maecenas pretium, magna sit amet volutpat aliquam, elit turpis sollicitudin velit, vel.

</p> </div> <button id="btnSec1">Section 1</button> <button id="btnSec2">Section 2</button>

JavaScript Block

The JavaScript code defines the scrolling animations and button events.

First, the code instantiates the two variables used in controlling the animation effects:

• scrollSections - An array that contains a scroll definition for each section that we wish to scrollto. The numeric identifiers defined by "to" are the left and top pixel locations to scroll to.

• anim - The variable for defining the animation effects on the eulaScroll node.

<script type="text/javascript"> (function(){ //variable instantiation var scrollSections = [{scroll: { to: [0, 0] }}, {scroll: { to: [0, 140] }}]; var anim;

The next code snippet uses the YUI Event utility to attach click events to both buttons defined in the HTMLblock. When a button is clicked, the code calls the runScrollAnim function, passing the array locationof the scroll arguments for that section.

YAHOO.util.Event.on('btnSec1', 'click', function(){ runScrollAnim(0); }); YAHOO.util.Event.on('btnSec2', 'click', function(){ runScrollAnim(1); });

The following code defines runScrollAnim, the scrolling animation function that runs when eitherbutton is clicked. The function uses the YUI Animation Scroll utility and the scroll definition specify theanimation configuration. Finally, the function animates the scrolling effect.

February 29, 201275Yahoo! Developer Network

YUI Support

Page 85: Yap Dev Guide

//run animation effects var runScrollAnim = function(sectionRef){ anim = new YAHOO.util.Scroll('eulaScroll', scrollSections[sectionRef]); anim.animate(); }; })(); </script>

February 29, 201276Yahoo! Developer Network

YUI Support

Page 86: Yap Dev Guide

Chapter 9. OpenSocial 0.9 CompatibilityIn this Chapter

• “Overview of OpenSocial Support” [77]

• “Gadget Configuration for OpenSocial” [77]

• “OpenSocial JavaScript Features Supported by YAP” [78]

• “OpenSocial RESTful APIs Supported by YAP” [80]

• “OpenSocial Code Samples” [81]

• “Gadget XML Configuration File” [93]

Overview of OpenSocial SupportYAP supports the OpenSocial 0.9 JavaScript APIs and OpenSocial 0.8.1 RESTful API. The code for yourCanvas View can include calls to the OpenSocial JavaScript APIs; YAP filters all JavaScript with Caja [58].Small View does not support JavaScript.

This chapter covers OpenSocial support for YAP, but does not discuss OpenSocial in general. For moreinformation on OpenSocial, see the following documentation:

• OpenSocial Specification v0.91 (includes JavaScript API Reference)

• OpenSocial 0.8.1 RESTful API Reference2

• OpenSocial Gadgets API Specification v0.93

Note

As a charter member of the OpenSocial Foundation, Yahoo! is committed to supportingOpenSocial specifications and continues to work with the Foundation on new features suchas OSML and OpenSocial Templates. However, only the OpenSocial specifications docu-mented here should be regarded as fully compatible with YAP; support for other specificationsis provisional or "beta".

For information about OpenSocial 0.8 support, see Chapter 10, OpenSocial 0.8 Compatibility [101].

Gadget Configuration for OpenSocialOpenSocial 0.9 is supported by default, but can be specified explicitly in your project's Gadget XML [93]file:

<Require feature="opensocial-0.9"/>

Do not attempt to mix support for different OpenSocial versions in the same application.

1 http://www.opensocial.org/Technical-Resources/opensocial-spec-v09/OpenSocial-Specification.html2 http://www.opensocial.org/Technical-Resources/opensocial-spec-v081/restful-protocol3 http://www.opensocial.org/Technical-Resources/opensocial-spec-v09/Gadgets-API-Specification.html

February 29, 201277Yahoo! Developer Network

Page 87: Yap Dev Guide

The following OpenSocial features are enabled by specific Require elements in Gadget XML [93]:

• Lightweight Javascript API (OS Lite)4

<Require feature="osapi"/>

• Data Pipelining5

<Require feature="opensocial-data"/>

• Templating6

<Require feature="opensocial-templates"/>

OpenSocial JavaScript Features Supported byYAP

Activity

Supported Activity Fields

YAP supports opensocial.CreateActivityPriority.LOW for requestCreateActivitybut does not support opensocial.CreateActivityPriority.HIGH. Requests for HIGH aretreated the same as LOW.

Because OpenSocial does not specify ActivityRequestFields, offsets and limits (using "first" and"max") are not supported.

YAP supports the following Activity fields:

• opensocial.Activity.Field.TITLE 7

• opensocial.Activity.Field.BODY 8

• opensocial.Activity.Field.URL 9

• opensocial.Activity.Field.USER_ID 10

• opensocial.Activity.Field.APP_ID 11

• opensocial.Activity.Field.STREAM_FAVICON_URL 12

• opensocial.Activity.Field.STREAM_SOURCE_URL 13

4 http://www.opensocial.org/Technical-Resources/opensocial-spec-v09/OpenSocial-Specification.html#LightweightJSAPI5 http://www.opensocial.org/Technical-Resources/opensocial-spec-v09/OpenSocial-Data-Pipelining.html6 http://www.opensocial.org/Technical-Resources/opensocial-spec-v09/OpenSocial-Templating.html7 http://wiki.opensocial.org/index.php?title=Opensocial.Activity_%28v0.9%29#opensocial.Activity.Field.TITLE8 http://wiki.opensocial.org/index.php?title=Opensocial.Activity_%28v0.9%29#opensocial.Activity.Field.BODY9 http://wiki.opensocial.org/index.php?title=Opensocial.Activity_%28v0.9%29#opensocial.Activity.Field.URL10 http://wiki.opensocial.org/index.php?title=Opensocial.Activity_%28v0.9%29#opensocial.Activity.Field.USER_ID11 http://wiki.opensocial.org/index.php?title=Opensocial.Activity_%28v0.9%29#opensocial.Activity.Field.APP_ID12 http://wiki.opensocial.org/index.php?title=Opensocial.Activity_%28v0.9%29#opensocial.Activity.Field.STREAM_FAVICON_URL13 http://wiki.opensocial.org/index.php?title=Opensocial.Activity_%28v0.9%29#opensocial.Activity.Field.STREAM_SOURCE_URL

February 29, 201278Yahoo! Developer Network

OpenSocial 0.9 Compatibility

Page 88: Yap Dev Guide

• opensocial.Activity.Field.STREAM_TITLE 14

Application Data

YAP supports up to 1,024 bytes of data per key and up to 1 MB per application.

MessagingYAP does not support requestSendMessage and requestShareApp.

Person and People

Supported Person Fields

The following fields are in every response:

• opensocial.Person.Field.ID 15

• opensocial.Person.Field.NAME 16

• opensocial.Person.Field.THUMBNAIL_URL 17

If the information for the following fields is in the Yahoo! Social Directory, then they are in the response:

• opensocial.Person.Field.DISPLAY_NAME

• opensocial.Person.Field.NICKNAME 18

• opensocial.Person.Field.AGE 19

• opensocial.Person.Field.GENDER 20

• opensocial.Person.Field.STATUS 21

• opensocial.Person.Field.CURRENT_LOCATION 22

• opensocial.Person.Field.UTC_OFFSET

• opensocial.Person.Field.PROFILE_URL 23

• opensocial.Name.UNSTRUCTURED 24

• opensocial.Address.UNSTRUCTURED_ADDRESS 25

14 http://wiki.opensocial.org/index.php?title=Opensocial.Activity_%28v0.9%29#opensocial.Activity.Field.STREAM_TITLE15 http://wiki.opensocial.org/index.php?title=Opensocial.Person_%28v0.9%29#opensocial.Person.Field.ID16 http://wiki.opensocial.org/index.php?title=Opensocial.Person_%28v0.9%29#opensocial.Person.Field.NAME17 http://wiki.opensocial.org/index.php?title=Opensocial.Person_%28v0.9%29#opensocial.Person.Field.THUMBNAIL_URL18 http://wiki.opensocial.org/index.php?title=Opensocial.Person_%28v0.9%29#opensocial.Person.Field.NICKNAME19 http://wiki.opensocial.org/index.php?title=Opensocial.Person_%28v0.9%29#opensocial.Person.Field.AGE20 http://wiki.opensocial.org/index.php?title=Opensocial.Person_%28v0.9%29#opensocial.Person.Field.GENDER21 http://wiki.opensocial.org/index.php?title=Opensocial.Person_%28v0.9%29#opensocial.Person.Field.STATUS22 http://wiki.opensocial.org/index.php?title=Opensocial.Person_%28v0.9%29#opensocial.Person.Field.CURRENT_LOCATION23 http://wiki.opensocial.org/index.php?title=Opensocial.Person_%28v0.9%29#opensocial.Person.Field.PROFILE_URL24 http://wiki.opensocial.org/index.php?title=Opensocial.Name_%28v0.9%29#opensocial.Name.Field.UNSTRUCTURED25 http://wiki.opensocial.org/index.php?title=Opensocial.Address_%28v0.9%29#opensocial.Address.Field.UNSTRUCTURED_ADDRESS

February 29, 201279Yahoo! Developer Network

OpenSocial 0.9 Compatibility

Page 89: Yap Dev Guide

Supported PeopleRequest Fields

YAP supports only the following PeopleRequest fields:

• opensocial.DataRequest.PeopleRequestFields.FIRST 26

• opensocial.DataRequest.PeopleRequestFields.MAX 27

YAP does not support other PeopleRequest fields, including FILTER, PROFILE_DETAILS, andSORT_ORDER.YAP behaves as if these fields are set to ALL.

Supported DataRequest FieldsYAP supports only the ESCAPE_TYPE DataRequest field. All requests behave as if ESCAPE_TYPEis set to NONE.

Using Environment.supportsFieldThe Environment.supportsField method returns true if the specified field is supported by theOpenSocial container. The method does not check to see if the field value exists for a given user.

A user might not provide information such as age, gender, and time zone. If this information is not provided,it is not returned in the response.

The supportsField method is useful for checking if the container stores data for a certain field, forexample, location. If the container does not support location, then the application must store the locationdata. If the container does support location, but location is undefined, then the application can prompt theuser to update location in the container's preferences.

PermissionsIf your Yahoo! Open Application makes OpenSocial calls, on the Project Details page specify Read (orRead/Write) for the following data:

• Yahoo! Profiles

• Yahoo! Updates

Gadget Core APIsYAP supports gadgets.io.makeRequest28. Support for other Gadget Core APIs is not guaranteed.

OpenSocial RESTful APIs Supported by YAPImportant Notice

YAP will stop supporting OpenSocial RESTful APIs from 15th April 2012 onwards. We recommend usingYahoo! Social Profile APIs for OpenSocial People REST endpoints (/people) and Yahoo! Social UpdatesAPIs for Opensocial Activity endpoints (/activities).

26 http://wiki.opensocial.org/index.php?title=Opensocial.DataRequest_%28v0.9%29#opensocial.DataRequest.PeopleRequestFields.FIRST27 http://wiki.opensocial.org/index.php?title=Opensocial.DataRequest_%28v0.9%29#opensocial.DataRequest.PeopleRequestFields.MAX28 http://wiki.opensocial.org/index.php?title=Gadgets.io_%28v0.9%29#gadgets.io.makeRequest

February 29, 201280Yahoo! Developer Network

OpenSocial 0.9 Compatibility

Page 90: Yap Dev Guide

The YAP supports the OpenSocial 0.8.1 RESTful API29. The details of this support follow.

OpenSocial REST Endpoint: http://appstore.apps.yahooapis.com/social/rest

Authentication: 3 Legged OAuth. For more information, see Yahoo! OAuth30 and OAuth AuthorizationFlow31.

Supported APIs: People, Friends

Supported Data formats: JSON

Supported People Endpoints:

• /people/{guid}/@all- Collection of all people connected to user {guid}.

• /people/{guid}/@self- Profile record for user {guid}.

• /people/@me/@self- Profile record for requester.

Supported Activities Endpoints:

• /activities/{guid}/@self- Collection of activities generated by given user.

• /activities/{guid}/@self- Collection of activities generated by an app for a given user

• /activities/{guid}/@self/{appid}/{activityid}- Individual activity resource, usuallydiscovered from a collection.

If you want to use the OpenSocial APIs in languages other than JavaScript, see the OpenSocial REST/RPCclient libraries32.

OpenSocial Code SamplesThe following code samples demonstrate how you might make OpenSocial calls in the Canvas View of aYahoo! Open Application.

Activities Demo

<!-- YAP OpenSocial Activities Demo Reid Burke 10 Sep 2008--><script type="text/javascript">

function getViewerActivities() {

var idSpec = opensocial.newIdSpec(); idSpec.setField(opensocial.IdSpec.Field.USER_ID,

29 http://www.opensocial.org/Technical-Resources/opensocial-spec-v081/restful-protocol30 http://developer.yahoo.com/oauth/31 http://developer.yahoo.com/oauth/guide/oauth-auth-flow.html32 http://wiki.opensocial.org/index.php?title=Client_Libraries

February 29, 201281Yahoo! Developer Network

OpenSocial 0.9 Compatibility

Page 91: Yap Dev Guide

opensocial.IdSpec.PersonId.VIEWER);

var req = opensocial.newDataRequest(); req.add(req.newFetchActivitiesRequest(idSpec), 'activities'); req.add(req.newFetchPeopleRequest(idSpec), 'people'); req.send(onLoadViewerActivities);

}

function getViewerFriendsActivities() {

var idSpec = opensocial.newIdSpec(); idSpec.setField(opensocial.IdSpec.Field.USER_ID, opensocial.IdSpec.PersonId.VIEWER); idSpec.setField(opensocial.IdSpec.Field.NETWORK_DISTANCE, 1);

var req = opensocial.newDataRequest(); req.add(req.newFetchActivitiesRequest(idSpec), 'activities'); req.add(req.newFetchPeopleRequest(idSpec), 'people'); req.send(onLoadViewerFriendsActivities);

}

function onLoadViewerFriendsActivities(response) {

var html = processResponse(response);

document.getElementById('yap-activity-viewer-friends').innerHTML = html;

}

function onLoadViewerActivities(response) {

var html = processResponse(response);

document.getElementById('yap-activity-viewer').innerHTML = html;

}

function processResponse(response) {

var activities = response.get('activities').getData(); var people = response.get('people').getData();

var peopleNames = {}; var peopleLink = {}; var peoplePic = {}; people.each(function(person) { peopleNames[person.getId()] = person.getDisplayName(); peopleLink[person.getId()] = person.getField(opensocial.Person.Field.PROFILE_URL); peoplePic[person.getId()] = person.getField(opensocial.Person.Field.THUMBNAIL_URL);

February 29, 201282Yahoo! Developer Network

OpenSocial 0.9 Compatibility

Page 92: Yap Dev Guide

});

var html = new Array(); var size = activities.getTotalSize(); if (size > 0) { var what = ' activities'; if (size == 1) what = ' activity'; html.push('<p>You have ' + size + what + ':</p>'); html.push('<ul>'); activities.each(function(activity) { var userId = activity.getField(opensocial.Activity.Field.USER_ID); var title = activity.getField(opensocial.Activity.Field.TITLE); html.push('<li><img src="' + peoplePic[userId] + '" height="32" width="32"><b>' + title + '</b> from <a href="' + peopleLink[userId] + '">' + peopleNames[userId] + '</a></li>'); }); html.push('</ul>'); } else { html.push('<div class="yap-error">No activities yet!</div>'); }

return html.join('');

}

function postActivity() { var params = {}; params[opensocial.Activity.Field.TITLE] = 'J. Hacker bookmarked the Yahoo! Application Platform'; params[opensocial.Activity.Field.BODY] = 'The Yahoo! Application Platform allows you to create social applications. Check it out!'; var activity = opensocial.newActivity(params); opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.LOW, function() { document.getElementById('yap-status').innerHTML = '<div>Activity created!</div>'; });}

gadgets.util.registerOnLoadHandler(function() { postActivity(); getViewerActivities(); getViewerFriendsActivities();});

</script>

<style type="text/css">#yap-app { font-family: Arial, sans-serif; padding: 5px;}

February 29, 201283Yahoo! Developer Network

OpenSocial 0.9 Compatibility

Page 93: Yap Dev Guide

#yap-status div, .yap-notice, .yap-error { background: #ffc; padding: 5px 15px 5px; margin-bottom: 3px;}

.yap-error { font-style: italic; background: #fcc;}

ul { list-style: none;}

li { padding: 3px; border: 1px solid #ccc; margin-bottom: 3px;}</style>

<div id="yap-app">

<h1>YAP OpenSocial Activities Demo</h1>

<div id="yap-status"><div>Posting a sample activity...</div></div>

<h3>Your Recent Updates</h3><div id="yap-activity-viewer"><div class="yap-notice">Loading...</div></div>

<h3>Your Friend's Recent Updates</h3><div id="yap-activity-viewer-friends"><div class="yap-notice">Loading...</div></div>

</div>

Gifts Demo

<!-- A sample YAP 1.0 ready OpenSocial application. Adapted from http://code.google.com/apis/opensocial/articles/tutorial/tutorial-0.7.html

February 29, 201284Yahoo! Developer Network

OpenSocial 0.9 Compatibility

Page 94: Yap Dev Guide

Updated for OpenSocial 0.8 and the Yahoo! Application Platform by Reid Burke 5 Sep 2008 YAP or 0.8 specific comments are annotated with YAPNOTE Updated 27 Oct 2008

Updated for OpenSocial 0.9 22 Oct 2010--><script type="text/javascript">

// Original JS code: http://opensocial-resources.googlecode.com/svn/samples/tutorial/tags/api-0.7/gifts_5_streams.js

var globalGivenGifts = {};var globalViewer = {};var globalFriends = {};

// YAPNOTE: You may store up to 1K of data per AppData key, up to 1MB total.// Currently, using gadgets.json.stringify will include properties attached to objects used by Caja// which take up several hundred bytes. This is a known issue we are working on.// In this example, we will use a simple comma-seperated format for storing data in a// single AppData key to save storage space.function serializeGifts(obj) { var out = new Array(); for (var id in obj) { out.push(id); out.push(obj[id]); } return out.join(',');}

function unserializeGifts(str) { var out = new Object(); var arr = str.split(','); var name = false; for (var i in arr) { if (!name) { name = arr[i]; continue; } out[name] = arr[i]; name = false; } return out;}

function postActivity(nut, friend) { var options = ['a cashew nut', 'a peanut', 'a hazelnut', 'a red pistachio nut'];

var title = globalViewer.getDisplayName() + ' gave ' +

February 29, 201285Yahoo! Developer Network

OpenSocial 0.9 Compatibility

Page 95: Yap Dev Guide

globalFriends[friend] + ' ' + options[nut]; var params = {}; params[opensocial.Activity.Field.TITLE] = title; var activity = opensocial.newActivity(params); // YAPNOTE: HIGH priority events are treated the same as LOW priority activities in YAP v1.0 // The callback here is specified as an empty function opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH, function() {});}

function updateReceivedList(viewer, data, friends) { var viewerId = viewer.getId();

var options = ['a cashew nut', 'a peanut', 'a hazelnut', 'a red pistachio nut'];

var html = new Array(); html.push('You have received:<ul>'); friends.each(function(person) { var personData = data[person.getId()]; if (personData) { var json = data[person.getId()]['gifts'];

// YAPNOTE: You must be very careful to create well-formed JavaScript when working with Caja. // Missing semicolons are a source of common problems, such as this line: // var gifts = {} // should be var gifts = {};

if (!json) { gifts = {}; } try { gifts = unserializeGifts(gadgets.util.unescapeString(json)); } catch (e) { gifts = {}; }

// YAPNOTE: Be sure to use 'var' whenever appropiate when working in Caja // Therefore, this code: // for (i in gifts) { // should be: for (var i in gifts) { // YAPNOTE: We use alphanumeric GUIDs, so the +i > 0 check should be removed // This line: // if (+(i) > 0 && i == viewerId) { // should be simply: if (i == viewerId) { html.push('<li>' + options[gifts[i]] + ' from ' +

February 29, 201286Yahoo! Developer Network

OpenSocial 0.9 Compatibility

Page 96: Yap Dev Guide

person.getDisplayName() + '</li>'); } } } }); html.push('</ul>'); document.getElementById('received').innerHTML = html.join('');}

function updateGiftList(viewer, data, friends) { var json = data[viewer.getId()]['gifts'];

if (!json) { globalGivenGifts = {}; } try { globalGivenGifts = unserializeGifts(gadgets.util.unescapeString(json)); } catch (e) { globalGivenGifts = {}; }

console.log(globalGivenGifts);

var options = ['a cashew nut', 'a peanut', 'a hazelnut', 'a red pistachio nut'];

var html = new Array(); html.push('You have given:'); html.push('<ul>'); // YAPNOTE: Be sure to use 'var' whenever appropiate when working in Caja // Therefore, this code: // for (i in globalGivenGifts) { // should be: for (var i in globalGivenGifts) { // YAPNOTE: We use alphanumeric GUIDs, so this check should be removed: //if (+(i) > 0) { html.push('<li>' + friends[i] + ' received ' + options[globalGivenGifts[i]] + '</li>'); //} } html.push('</ul>'); document.getElementById('given').innerHTML = html.join('');}

function giveGift() { var nut = document.getElementById('nut').value; var friend = document.getElementById('person').value;

globalGivenGifts[friend] = nut; var json = serializeGifts(globalGivenGifts);

February 29, 201287Yahoo! Developer Network

OpenSocial 0.9 Compatibility

Page 97: Yap Dev Guide

var req = opensocial.newDataRequest();

// YAPNOTE: DataRequest.PersonId was changed to IdSpec.PersonId in 0.8; hence this code: // req.add(req.newUpdatePersonAppDataRequest(opensocial.DataRequest.PersonId.VIEWER, 'gifts', json)); // became: // req.add(req.newUpdatePersonAppDataRequest(opensocial.IdSpec.PersonId.VIEWER, 'gifts', json)); // In 0.9, the first parameter was eliminated (the ID is always VIEWER), so the call is now: req.add(req.newUpdatePersonAppDataRequest('gifts', json));

// YAPNOTE: For Person requests, specify a string ID as the first argument: // req.add(req.newFetchPersonRequest('VIEWER'), 'viewer'); // Although that code would work, the semantically correct way is to use IdSpec.PersonId when possible: req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer');

// YAPNOTE: For fetch People and AppData requests, specify an IdSpec object (not a string ID) as the first argument. // In 0.7, VIEWER_FRIENDS is no longer available. Instead, use NETWORK_DISTANCE // Therefore, this code: // req.add(req.newFetchPeopleRequest('VIEWER_FRIENDS'), 'viewerFriends'); // req.add(req.newFetchPersonAppDataRequest('VIEWER', 'gifts'), 'data'); // req.add(req.newFetchPersonAppDataRequest('VIEWER_FRIENDS', 'gifts'), 'viewerFriendData'); // is now: var idSpec = opensocial.newIdSpec(); idSpec.setField(opensocial.IdSpec.Field.USER_ID, opensocial.IdSpec.PersonId.VIEWER); var idSpecFriends = opensocial.newIdSpec(); idSpecFriends.setField(opensocial.IdSpec.Field.USER_ID, opensocial.IdSpec.PersonId.VIEWER); idSpecFriends.setField(opensocial.IdSpec.Field.NETWORK_DISTANCE, 1); // YAPNOTE: Groups aren't supported in YAP v1. If you don't specify one, we assume you want friends

req.add(req.newFetchPeopleRequest(idSpecFriends), 'viewerFriends'); req.add(req.newFetchPersonAppDataRequest(idSpec, 'gifts'), 'data'); req.add(req.newFetchPersonAppDataRequest(idSpecFriends, 'gifts'), 'viewerFriendData');

req.send(onLoadFriends);

February 29, 201288Yahoo! Developer Network

OpenSocial 0.9 Compatibility

Page 98: Yap Dev Guide

postActivity(nut, friend);}

function makeOptionsMenu() { var options = ['a cashew nut', 'a peanut', 'a hazelnut', 'a red pistachio nut'];

var html = new Array(); html.push('<select id="nut">'); for (var i = 0; i < options.length; i++) { html.push('<option value="' + i + '">' + options[i] + '</option>');

} html.push('</select>'); document.getElementById('gifts').innerHTML = html.join('');}

function loadFriends() { var req = opensocial.newDataRequest();

// YAPNOTE: For Person requests, specify a string ID as the first argument: // req.add(req.newFetchPersonRequest('VIEWER'), 'viewer'); // Although that code would work, the semantically correct way is to use IdSpec.PersonId when possible: req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer');

// YAPNOTE: For fetch People and AppData requests, specify an IdSpec object (not a string ID) as the first argument. // In 0.7, VIEWER_FRIENDS is no longer available. Instead, use NETWORK_DISTANCE // Therefore, this code: // req.add(req.newFetchPeopleRequest('VIEWER_FRIENDS'), 'viewerFriends'); // req.add(req.newFetchPersonAppDataRequest('VIEWER', 'gifts'), 'data'); // req.add(req.newFetchPersonAppDataRequest('VIEWER_FRIENDS', 'gifts'), 'viewerFriendData'); // is now: var idSpec = opensocial.newIdSpec(); idSpec.setField(opensocial.IdSpec.Field.USER_ID, opensocial.IdSpec.PersonId.VIEWER); var idSpecFriends = opensocial.newIdSpec(); idSpecFriends.setField(opensocial.IdSpec.Field.USER_ID, opensocial.IdSpec.PersonId.VIEWER); idSpecFriends.setField(opensocial.IdSpec.Field.NETWORK_DISTANCE, 1); // YAPNOTE: Groups aren't supported in YAP v1. If you don't specify one, we assume you want friends

req.add(req.newFetchPeopleRequest(idSpecFriends), 'viewerFriends'); req.add(req.newFetchPersonAppDataRequest(idSpec, 'gifts'), 'data'); req.add(req.newFetchPersonAppDataRequest(idSpecFriends, 'gifts'),

February 29, 201289Yahoo! Developer Network

OpenSocial 0.9 Compatibility

Page 99: Yap Dev Guide

'viewerFriendData');

req.send(onLoadFriends);}

function onLoadFriends(data) { var viewer = globalViewer = data.get('viewer').getData(); var viewerFriends = data.get('viewerFriends').getData(); var giftData = data.get('data').getData(); var viewerFriendData = data.get('viewerFriendData').getData(); var friends = new Array();

// YAPNOTE: Be sure to use 'var' whenever appropiate when working in Caja // Therefore, this code: // html = new Array(); // should be: var html = new Array(); html.push('<select id="person">'); viewerFriends.each(function(person) { html.push('<option value="' + person.getId() + '">' + person.getDisplayName() + "</option>");

friends[person.getId()] = person.getDisplayName(); }); html.push('</select>'); document.getElementById('friends').innerHTML = html.join('');

globalFriends = friends; updateGiftList(viewer, giftData, friends); updateReceivedList(viewer, viewerFriendData, viewerFriends);}

function init() { loadFriends(); makeOptionsMenu();}

gadgets.util.registerOnLoadHandler(init);</script>

<style type="text/css">#yap-app { font-family: Arial, sans-serif; padding: 5px;}

#yap-status div, .yap-notice, .yap-error { background: #ffc; padding: 5px 15px 5px; margin-bottom: 3px;}

.yap-error {

February 29, 201290Yahoo! Developer Network

OpenSocial 0.9 Compatibility

Page 100: Yap Dev Guide

font-style: italic; background: #fcc;}

ul { list-style: none;}

li { padding: 3px; border: 1px solid #ccc; margin-bottom: 3px;}</style>

<!-- HTML that would be within the <Content> gadget XML: --><div id='yap-app'><h1>Gift Giving!</h1><div id='give'><form id='gift_form'><!-- YAPNOTE: You can't link to javascript:void in Caja. Use '#' instead --><!-- This is invalid:Give <span id='gifts'></span> to <span id='friends'></span>. <a href="javascript:void(0);" onclick='giveGift();'>Give!</a>-->Give <span id='gifts'></span> to <span id='friends'></span>. <a href="#" onclick='giveGift();'>Give!</a></form></div><div id='given'></div><!-- YAPNOTE: You must also be careful to create well-formed HTML markup when working with Caja --><!-- This is invalid:<div id='received'</div>--><div id='received'></div></div>

Yahoo! Profile Demo<html> <div id="result-cell"></div> <style> div#result-cell { font-size:11px; padding:10px; } .wrap-in {float:left; width:100px; height:100px; background-color:#CCC; border:1px solid #999; padding:15px;margin-right:10px; margin-bottom:10px; text-align:center;

} </style> <script type="text/javascript">

February 29, 201291Yahoo! Developer Network

OpenSocial 0.9 Compatibility

Page 101: Yap Dev Guide

try {function request() { // Prepare array with key value pair var params = {}; params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED; params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT; params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET; // makeRequest call var url = "http://query.yahooapis.com/v1/yql?q=select%20givenName%2C%20familyName%2C%20image%20from%20social.profile%20where%20guid%20in%20(select%20guid%20from%20social.connections%20where%20owner_guid%3Dme)&format=json";

gadgets.io.makeRequest(url, response, params); }; function response(obj) { /** obj.text contains the text of the page that was requested **/ var responseData =obj.text; var jsonTextData = gadgets.json.parse(responseData); var markUp = ''; var connectionCount = parseInt(jsonTextData.query.count); if(connectionCount > 1) { for(var i in jsonTextData.query.results.profile) { if(jsonTextData.query.results.profile[i].givenName == undefined) continue; markUp += '<div class="wrap-in"><imgsrc="' + jsonTextData.query.results.profile[i].image.imageUrl +'" width="70px" height="70px" /><h4>' +jsonTextData.query.results.profile[i].givenName + ' ' + jsonTextData.query.results.profile[i].familyName +'</h4></div>';

} } else { markUp += '<div class="wrap-in"><img src="' +jsonTextData.query.results.profile.image.imageUrl +'" width="70px" height="70px" /><h4>' +jsonTextData.query.results.profile.givenName + ' ' + jsonTextData.query.results.profile.familyName +'</h4></div>'; } document.getElementById("result-cell").innerHTML = markUp; }; request(); } catch(e) { document.getElementById("result-cell").innerHTML = e.toString();

} </script></html>

February 29, 201292Yahoo! Developer Network

OpenSocial 0.9 Compatibility

Page 102: Yap Dev Guide

Gadget XML Configuration FileAn Open Application is configured through a Gadget XML file that conforms to the schema in theOpenSocial Gadgets API Specification33. However, YAP supports only the fields and values documentedhere.

YAP limits the size of Gadget XML files to 500KB.

When you set up your application in My Projects, YAP can generate a sample Gadget XML file for you,as described in “Configuring Your Application” [10]. This is the easiest way to get an application up andrunning. The generated file is called ygadget_appID.xml, where appID is the application's ID. Later,you can edit this file (or write your own from scratch) and upload the modified version as described in“Updating Your Application” [14].

A simple Gadget XML file looks like this:

<?xml version="1.0" encoding="utf-8"?><Module xmlns:yap="http://www.yahoo.com/ns/yap">

<ModulePrefs title="MyApp" title_url="http://example.com/" description="awesome app" author="John Doe" category="Entertainment-Games" category2="Sports">

<Icon>http://example.com/my_icon-16X16.gif</Icon> <Locale lang="en" country="us"/> </ModulePrefs>

<Content type="html" view="YahooSmallView, default"><![CDATA[ This is the default Small View content. ]]></Content>

<!-- Canvas View content --> <Content type="html" view="canvas" href="http://example.com/myApp/" ></Content>

<!-- Preview content --> <Content type="html" view="preview" href="http://example.com/myApp/preview/" ></Content>

<Content type="html"><![CDATA[ Default content ... ]]></Content>

</Module>

The enclosing element, called Module, contains a ModulePrefs element and one or more Contentelements. ModulePrefs contains an Icon element and at least one Locale element. A file like theone above could be used for testing an Open Application.

Before an app can be published, several Extension elements must be added to ModulePrefs toprovide YAP-specific metadata. ModulePrefs can also contain optional Extension elements as wellas Required elements to indicate special dependencies. For example:

33 http://www.opensocial.org/Technical-Resources/opensocial-spec-v09/Gadgets-API-Specification.html#gadgetsExtendedXSD

February 29, 201293Yahoo! Developer Network

OpenSocial 0.9 Compatibility

Page 103: Yap Dev Guide

<?xml version="1.0" encoding="utf-8"?><Module xmlns:yap="http://www.yahoo.com/ns/yap">

<ModulePrefs title="MyApp" title_url="http://example.com/" description="awesome app" author="John Doe" category="Entertainment-Games" category2="Sports">

<Require feature="yap.feature.classic"/> <Require feature="opensocial-0.8"/> <Icon>http://example.com/my_icon-16X16.gif</Icon> <Locale lang="en" country="us"/> <yap:Extension name="yap.gadgets.ShortDescription">An Awesome App</yap:Extension> <yap:Extension name="yap.gadgets.allow.SignOutRender">false</yap:Extension> <yap:Extension name="yap.gadgets.CreatorImageUrl">http://example.com/my_icon-256X256.gif</yap:Extension>

<yap:Extension name="yap.gadgets.ApplicationIconUrl">http://example.com/my_icon-64X64.gif</yap:Extension>

<yap:Extension name="yap.gadgets.YahooComIconUrl">http://example.com/my_icon-20X20.gif</yap:Extension>

<yap:Extension name="yap.gadgets.ScreenshotUrl">http://example.com/my_screenshot-300X250.gif</yap:Extension>

<yap:Extension name="yap.gadgets.TouUrl">http://example.com/tou.html</yap:Extension> <yap:Extension name="yap.gadgets.PrivacyUrl">http://example.com/privacy.html</yap:Extension>

<yap:Extension name="yap.gadgets.Tag">games,sports,awesome</yap:Extension> </ModulePrefs>

<Content type="html" view="YahooSmallView, default"><![CDATA[ This is the default Small View content. ]]></Content>

<Content type="html" view="canvas" href="http://example.com/myApp/" ></Content>

<Content type="html" view="preview" href="http://example.com/myApp/preview/" ></Content>

<Content type="html"><![CDATA[ Default content ... ]]></Content>

</Module>

February 29, 201294Yahoo! Developer Network

OpenSocial 0.9 Compatibility

Page 104: Yap Dev Guide

The outline below shows the structure of a Gadget XML file, with elements in bold and attributes initalics. Items marked with an asterisk (*) are required for publication; the title attribute is required foran app to be pushed live.

<Module yap*>*<ModulePrefs title*, title_url, description*, author, category*, category2>*<Require feature*> } ... } for legacy apps <Require feature*> } <Icon>*<Locale lang*, country>* ... <Locale lang*, country><Extension name*>* } ... } YAP-specific parameters** <Extension name*> } <Content type*, view*, href>* Small View content <Content type*, view*, href>* Canvas View content ... <Content type*> fallback/default content **The ShortDescription, ApplicationIconUrl, YahooComIconUrl, and ScreenshotUrl Extensions are required for publication.

The fields in the Gadget XML file are documented in greater detail below.

Note

XML element and attribute names are case-sensitive.

While some fields are not currently utilized, you should assume that information in theGadget XML file will be made public when you publish your app.

Gadget XML Fields

DescriptionRe-quired

forPublic-ation?

Attrib-ute

Ele-ment

Enclosing element for configuration settings.r e -quired

Mod-ule

Use the default setting provided by Yahoo! (xmlns:yap="http://www.yahoo.com/ns/yap")r e -quired

yap

Application metadata.r e -quired

Mod-u l e -Prefs

Title for the Open Application.r e -quired

title

( f o rpublica-t i o na n dl i v et e s t -ing)

A URL that the gadget title links to.option-al

title_url

Description of your app (max 512 characters).r e -quired

descrip-tion

Developer's name.option-al

author

Application category. One of the strings listed in “Application Categories” [98].r e -quired

c a t -egory

Additional application category. One of the strings listed in “Application Categories” [98].option-al

c a t -egory2

Dependencies.option-al

R e -quire

February 29, 201295Yahoo! Developer Network

OpenSocial 0.9 Compatibility

Page 105: Yap Dev Guide

DescriptionRe-quired

forPublic-ation?

Attrib-ute

Ele-ment

Specifies a required feature. Unmodified legacy (pre-2.0) applications may need:r e -quired

feature

<Require feature="yap.feature.classic"/> <Require feature="opensocial-0.8"/>

These elements are supplied by Yahoo! in generated Gadget XML files. For other Require parameters, see Ap-pendix A, Parameters Passed to an Open Application [147], “Gadget Configuration for OpenSocial” [77], and“Gadget Configuration for OpenSocial 0.8” [116].

URL that returns a 16x16-pixel favicon for your application. Used for Yahoo! Updates34 and on the Yahoo.comhomepage. See “Supported Image Formats” [4] for more information.

r e -quired

Icon

The link associated with the Lifecycle events defined in OpenSocial 8.035. YAP currently only supports the remove-app event. Example: <Link rel="event.removeapp" href="http://www.example.com/re-move?eventtype=removeapp&id=<guid>" />

option-al

Link

The lifecycle event type. Currently, the following is the only allowed value: event.removeapp. Theevent.removeapp type is intended to help developers track uninstalls of their applications.

r e -quired

rel

The endpoint that is called when the lifecycle event is triggered. When the event type is removeapp, the endpointshould include the GUID of the user uninstalling the application. For example: http://www.example.com/re-move?eventtype=removeapp&id=<guid>

r e -quired

href

Supported languages. Use one Locale element for each supported language.r e -quired

Loc-ale

ISO 639-1 two-letter language code.r e -quired

lang

ISO 3166-1 two-letter country code.option-al

country

URL that returns a file conforming to the Message Bundle Schema36.option-al

m e s -sage

YAP-specific parameters, e.g. <yap:Extension name="yap.gadgets.Tags">. Some are required (seename below).

r e -quired( s e e

E x -t e n -sion

D e -scr ip-tion)

Name of parameter. The following parameters are supported:r e -quired

name

• allow.SignOutRender (optional) - boolean determining if a user who is not signed in can install and access theappplication

• ApplicationIconUrl (required) - URL returning a 64x64-pixel image

• CreatorImageUrl (optional) - URL returning a 256x256-pixel image of your company logo

• CreatorWebsiteUrl (optional) - URL of your website

34 http://developer.yahoo.com/social/updates/35 http://www.opensocial.org/Technical-Resources/opensocial-spec-v081#TOC-Lifecycle-events36 http://www.opensocial.org/Technical-Resources/opensocial-spec-v09/Gadgets-API-Specification.html#messageBundleSchema

February 29, 201296Yahoo! Developer Network

OpenSocial 0.9 Compatibility

Page 106: Yap Dev Guide

DescriptionRe-quired

forPublic-ation?

Attrib-ute

Ele-ment

• PrivacyUrl (optional) - URL of your privacy policy

• ScreenshotUrl (required) - URL returning a 300x250-pixel preview image, used in "About" box and other dialogs

• ShortDescription (required) - max 128 characaters

• Tags (optional) - keywords for indexing, comma separated

• TouUrl (optional) - URL of your terms of use

• YahooComIconUrl (required) - URL returning a 20x20-pixel GIF (must end in .gif)

See “Supported Image Formats” [4] for more information about image files.

Content for your Open Application. Can specify a URL (through the href attribute) or contain a CDATA section.r e -quired

Con-tent

Always specify "html" (<Content type="html">).r e -quired

type

Specifies the container in which content is displayed. See “Content Sections” [97].option-al

view

URL that returns HTML content. See “Content Sections” [97].option-al

href

Content SectionsA Content element can provide content in two ways: Through a URL specified by the href attribute(<Content href="http://...">) or inlined in a CDATA section. If an href value is specified ina Content that also includes a CDATA section, the href attribute takes precedence and the inlined contentis ignored.

There is no limit to the number of Content elements in a Gadget XML file, but a typical Open Applicationuses three: one for the nonpersonalized (default) Small View, one for Canvas View, and one providingfallback content. An Open Application can also have Preview content for anonymous or unidentified users.The view attribute, which determines when content is displayed, can contain multiple comma-separatedstrings. Certain view values—"YahooSmallView", "YahooFullView", "canvas", "home", "preview", and"default"—have special meanings. You can combine these with identifying strings of your own. For example:

<Content view="YahooSmallView, default" ...> <Content view="YahooSmallView, preview, view001" ...> <Content view="YahooFullView, canvas" ...>

A Content that doesn't specify a view attribute is automatically assigned view="default".

Which Content is Displayed?

YAP uses the following algorithm to select content for display based on view values:

• For default Small View, YAP looks for a Content element with view value "YahooSmallView"; if itdoesn't find "YahooSmallView", it looks for the value "home"; if it doesn't find "home", it looks for"default". (For signed-in users, you can present a personalized Small View, as described in “SmallView” [17] and “Creating the Personalized State” [36].)

February 29, 201297Yahoo! Developer Network

OpenSocial 0.9 Compatibility

Page 107: Yap Dev Guide

• For Canvas View, YAP looks for a Content element with view value "YahooFullView"; if it doesn'tfind "YahooFullView", it looks for the value "canvas"; if it doesn't find "canvas", it looks for "default".

• If the user is not signed in or is unidentified, YAP looks for a Content element with view value "pre-view". (See “Preview” [20].)

• If multiple Content elements meet the applicable criterion (e.g. if there is more than one "YahooS-mallView"):

• If there is an element that specifies an href attribute, it is preferred over elements with inline content.

• If more than one element specifies an href attribute, YAP uses the last processed element (usually thelast one in the Gadget XML file).

• If none of the elements specifes an href attribute but there is more than one element with inline content,it concatenates the inline content of all the applicable elements.

For fallback/default content, to be used when no other source is available, include a Content elementthat specifes view="default" or does not have a view attribute.

Limitations on Preview Content

Preview content is subject to certain limitations because users are assumed to be anonymous. See “Pre-view” [20].

Resolving Links in Inlined Content

If a yml:a [42] link occurs in inlined content, the view attribute determines the base URL for the link.Specifically, the link's view attribute should match the view attribute of a Content element that specifiesan href. For example, suppose that these two Content elements occur in a Gadget XML file:

<Content type="html" view="YahooSmallView"><![CDATA[ <yml:a view="canvas" params="xyzw/info.php">Click Here</yml:a> ]]></Content> <Content type="html" view="canvas" href="http://my_url/"></Content>

To resolve the yml:a link in the first Content, "xyzw/info.php" is appended to "http://my_url/" to get"http://my_url/xyzw/info.php".

If a yml:a link doesn't have a view attribute, its base URL is taken from the most recently processed"YahooFullView" Content element.

Application CategoriesThe category and category2 attributes can take any of the values listed below.

SportsSports-Basketball

InformationInformation-Blogs

BusinessAndFinanceBusinessAndFinance-Classifieds

Sports-FantasyInformation-BusinessAndFinance-Sports-Football CalendarsAndAlerts JobsAndEmploymentSports-GolfInformation-EducationBusinessAndFinance-PersonalFinanceSports-LocalInformation-LocalAndMapsBusinessAndFinance-RealEstateSports-SoccerInformation-PoliticsBusinessAndFinance-StockMarketSports-TennisSports-OtherSports

Information-ReferenceInformation-VideosAndImages

BusinessAndFinance- OtherBusinessAndFinance

Information-WeatherInformation-OtherInformation

February 29, 201298Yahoo! Developer Network

OpenSocial 0.9 Compatibility

Page 108: Yap Dev Guide

TechTech-ComputersAndSoftware

LifestyleLifestyle-Autos

CommunicationCommunication-ChatAndMessaging

Tech-ConsumerElectronicsLifestyle-FashionCommunication-DatingTech-HealthLifestyle-GardeningCommunication-MobileTech-InternetLifestyle-HealthCommunication-PublicService

Communication-OtherCommunication Tech-ScienceTech-TechnologyTech-OtherTech

Lifestyle-HobbiesLifestyle- HomeImprovementsLifestyle-HoroscopeLifestyle-ParentingLifestyle-PetsLifestyle-RelationshipsLifestyle-OtherLifestyle

TravelTravel-Deals

NewsNews-Blogs

EntertainmentEntertainment-Celebrity

Travel-LocationsNews-InternationalEntertainment-ComedyTravel-TripsTravel-OtherTravel

News-LocalNews-RegionalNews-OtherNews

Entertainment-GamesEntertainment-MoviesEntertainment-MusicEntertainment-TVEntertainment-VideosAndImagesEntertainment-OtherEntertainment

ShoppingShopping-Deals

FoodFood-HealthAndResearch

Shopping-Food-Local ProductDescriptionsFood-Recipes

Food-OtherFood Shopping-ProductReviewsShopping-OtherShopping

Legacy ApplicationsIf you are updating an application originally published under YAP 2.0 or earlier, you need to set up aGadget XML file on your Web server and import it by clicking Import New XML on the Projects Detailspage. Because the old Details tab no longer exists on the Project Details page, you won't be able to changeyour application's metadata or default Small View content without editing this file.

YAP automatically generates a Gadget XML file based on your app's existing configuration data. You candownload the generated file, modify it, install it on your Web server, and import the new version:

1. In your browser, go to My Projects37.

2. Click the project you want to update, opening the Project Details page.

3. Click Download XML to retrieve the generated Gadget XML file.

4. Save the file to your computer and modify it if desired.

5. Copy the file to a directory on your Web server.

37 http://developer.yahoo.com/dashboard

February 29, 201299Yahoo! Developer Network

OpenSocial 0.9 Compatibility

Page 109: Yap Dev Guide

6. On the Project Details page, click Import New XML.

7. Enter the URL of the Gadget XML file on your Web server and click Import.

For more information about this process, see “Configuring Your Application” [10] and “Updating YourApplication” [14].

For legacy applications, the YAP-generated Gadget XML file may contain special Require elements,including <Require feature="yap.feature.classic"/> and <Require fea-ture="opensocial-0.8"/>, that you can remove when you are sure your app is compliant with thelatest YAP standards. (See Appendix A, Parameters Passed to an Open Application [147] and “GadgetConfiguration for OpenSocial 0.8” [116].) We recommend testing your application carefully before publishingit without these Require elements.

The text strings used to identify application categories have changed. For example, "Technology & Sci-ence:Computers / Software" has become "Tech-ComputersAndSoftware". See “Application Categories” [98]for a list of supported categories.

Previously, applications were configured from the Project Details page under My Projects. The followingtable shows the correspondence between old Project Details configuration fields and the fields in a GadgetXML file.

Gadget XML FieldOld Configuration Field

Content element ("YahooFullView" or "canvas")Application URL

Content element ("YahooSmallView" or "home")Small View Default Content

title (ModulePrefs attribute)Project Name

description (ModulePrefs attribute)Description

yap.gadgets.ShortDescription (Extensionname)Short Description

author (ModulePrefs attribute)Creator Name

yap.gadgets.CreatorImage (Extensionname)Creator Image

yap.gadgets.CreatorWebsiteURL (Extensionname)Creator Website

yap.gadgets.ApplicationIconUrl (Extensionname)Application Icon

Icon (element)Favicon

Icon (element)Yahoo.com Icon

yap.gadgets.ScreenshotUrl (Extensionname)Screenshot

title_url (ModulePrefs attribute)Yahoo.com "My Favorites" Link

yap.gadgets.TouUrl (Extensionname)Terms of Use

yap.gadgets.PrivacyUrl (Extensionname)Privacy Policy

Locale (elements)Suppoted Languages

category and category2 (ModulePrefs attributes)Categories

yap.gadgets.Tag (Extensionname)Tags

February 29, 2012100Yahoo! Developer Network

OpenSocial 0.9 Compatibility

Page 110: Yap Dev Guide

Chapter 10. OpenSocial 0.8 CompatibilityIn this Chapter

• “OpenSocial 0.8 Legacy Support” [101]

• “OpenSocial 0.8 JavaScript Features Supported by YAP” [101]

• “OpenSocial RESTful APIs Supported by YAP” [103]

• “Differences Between Versions 0.8 and 0.7 JavaScript APIs” [104]

• “OpenSocial Code Samples” [106]

• “Gadget Configuration for OpenSocial 0.8” [116]

OpenSocial 0.8 Legacy SupportYAP continues to support version 0.8 of the OpenSocial JavaScript APIs. To enable OpenSocial 0.8compatibility, see “Gadget Configuration for OpenSocial 0.8” [116].

For information about OpenSocial 0.9 support, see Chapter 9, OpenSocial 0.9 Compatibility [77]. Do notmix 0.8 and 0.9 JavaScript API calls in the same application.

The code for your Canvas View can include calls to the OpenSocial JavaScript APIs; YAP filters allJavaScript with Caja [58]. Small View does not support JavaScript.

For more information on OpenSocial 0.8, see the following documentation:

• OpenSocial 0.8 JavaScript API Reference1

• OpenSocial 0.8.1 RESTful API Reference2

• OpenSocial 0.8 Gadgets Core API Reference3

OpenSocial 0.8 JavaScript Features Supportedby YAP

Activity

Supported Activity Fields

YAP supports opensocial.CreateActivityPriority.LOW for requestCreateActivitybut does not support opensocial.CreateActivityPriority.HIGH. Requests for HIGH aretreated the same as LOW.

Because OpenSocial 0.8 does not specify ActivityRequestFields, offsets and limits (using "first"and "max") are not supported.

1 http://www.opensocial.org/Technical-Resources/opensocial-spec-v08/opensocial-reference082 http://www.opensocial.org/Technical-Resources/opensocial-spec-v081/restful-protocol3 http://www.opensocial.org/Technical-Resources/opensocial-spec-v08/gadgets-reference08

February 29, 2012101Yahoo! Developer Network

Page 111: Yap Dev Guide

YAP supports the following Activity fields:

• opensocial.Activity.Field.ID

• opensocial.Activity.Field.TITLE

• opensocial.Activity.Field.BODY

• opensocial.Activity.Field.URL

• opensocial.Activity.Field.USER_ID

• opensocial.Activity.Field.POSTED_TIME

Application Data

YAP supports up to 1,024 bytes of data per key and up to 1 MB per application.

MessagingYAP does not support requestSendMessage and requestShareApp.

Person and People

Supported Person Fields

The following fields are in every response:

• opensocial.Person.Field.ID

• opensocial.Person.Field.NAME

• opensocial.Person.Field.THUMBNAIL_URL

If the information for the following fields is in the Yahoo! Social Directory, then they are in the response:

• opensocial.Name.UNSTRUCTURED

• opensocial.Person.Field.PROFILE_URL

• opensocial.Address.UNSTRUCTURED_ADDRESS

• opensocial.Person.Field.AGE

• opensocial.Person.Field.GENDER

Supported PeopleRequest Fields

YAP supports only the following PeopleRequest fields:

• opensocial.DataRequest.PeopleRequestFields.FIRST

• opensocial.DataRequest.PeopleRequestFields.MAX

February 29, 2012102Yahoo! Developer Network

OpenSocial 0.8 Compatibility

Page 112: Yap Dev Guide

YAP does not support other PeopleRequest fields, including FILTER, PROFILE_DETAILS, andSORT_ORDER.YAP behaves as if these fields are set to ALL.

Supported DataRequest FieldsYAP supports only the ESCAPE_TYPE DataRequest field. All requests behave as if ESCAPE_TYPEis set to NONE.

Using Environment.supportsFieldThe Environment.supportsField method returns true if the specified field is supported by theOpenSocial container. The method does not check to see if the field value exists for a given user.

A user might not provide information such as age, gender, and time zone. If this information is not provided,it is not returned in the response.

The supportsField method is useful for checking if the container stores data for a certain field, forexample, location. If the container does not support location, then the application must store the locationdata. If the container does support location, but location is undefined, then the application can prompt theuser to update location in the container's preferences.

PermissionsIf your Yahoo! Open Application makes OpenSocial calls, on the Project Details page specify Read (orRead/Write) for the following data:

• Yahoo! Profiles

• Yahoo! Updates

Gadget Core APIsYAP supports the Gadget Core APIs, except for Prefs, Views, and the Feature-SpecificAPI.

OpenSocial RESTful APIs Supported by YAPImportant Notice

YAP will stop supporting OpenSocial RESTful APIs from 15th April 2012 onwards. We recommend usingYahoo! Social Profile APIs for OpenSocial People REST endpoints (/people) and Yahoo! Social UpdatesAPIs for Opensocial Activity endpoints (/activities).

The YAP supports the OpenSocial 0.8.1 RESTful API4. The details of this support follow.

OpenSocial REST Endpoint: http://appstore.apps.yahooapis.com/social/rest

Authentication: 3 Legged OAuth. For more information, see Yahoo! OAuth5 and OAuth AuthorizationFlow6.

4 http://www.opensocial.org/Technical-Resources/opensocial-spec-v081/restful-protocol5 http://developer.yahoo.com/oauth/6 http://developer.yahoo.com/oauth/guide/oauth-auth-flow.html

February 29, 2012103Yahoo! Developer Network

OpenSocial 0.8 Compatibility

Page 113: Yap Dev Guide

Supported APIs: People, Friends

Supported Data formats: JSON

Supported People Endpoints:

• /people/{guid}/@all- Collection of all people connected to user {guid}.

• /people/{guid}/@self- Profile record for user {guid}.

• /people/@me/@self- Profile record for requester.

Supported Activities Endpoints:

• /activities/{guid}/@self- Collection of activities generated by given user.

• /activities/{guid}/@self- Collection of activities generated by an app for a given user.

• /activities/{guid}/@self/{appid}/{activityid}- Individual activity resource, usuallydiscovered from a collection.

If you want to use the OpenSocial APIs in languages other than JavaScript, see the OpenSocial REST/RPCclient libraries7.

Differences Between Versions 0.8 and 0.7JavaScript APIs

This section describes some important differences between versions 0.8 and 0.7 of the OpenSocial JavaScriptAPIs. For more information, see the OpenSocial Release Notes for v0.88.

Using opensocial.IdSpecWhen making some data requests, such as Activity,People, and newFetchPersonAppDataRe-quest, you must use an IdSpec object instead of specifying opensocial.IdSpec.PersonIdby itself.

Change the following 0.7 code:

var req = opensocial.newDataRequest();req.add(req.newFetchPeopleRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer');

To the following 0.8 code:

var idSpec = opensocial.newIdSpec(); idSpec.setField(opensocial.IdSpec.Field.USER_ID, opensocial.IdSpec.PersonId.VIEWER);

7 http://wiki.opensocial.org/index.php?title=Client_Libraries8 http://www.opensocial.org/Technical-Resources/opensocial-release-notes

February 29, 2012104Yahoo! Developer Network

OpenSocial 0.8 Compatibility

Page 114: Yap Dev Guide

var req = opensocial.newDataRequest();req.add(req.newFetchPeopleRequest(idSpec), 'viewer');

When NOT to Use opensocial.IdSpecThe newFetchPersonRequest method requires a string ID as the first argument, not an openso-cial.IdSpec object. The newUpdatePersonAppDataRequest and newRemovePersonApp-DataRequest methods have the same requirement. Specifying opensocial.IdSpec as the first ar-gument results in an error. Therefore, code such as the following is correct and does not need to be changedfor 0.8:

var req = opensocial.newDataRequest();req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer');

Retrieving Friends With NETWORK_DISTANCEBecause DataRequest.Group was removed after 0.7, VIEWER_FRIENDS and OWNER_FRIENDSare no longer available. Use IdSpec.Field.NETWORK_DISTANCE instead of DataRequest.Group.

Change the following 0.7 code:

var req = opensocial.newDataRequest();req.add(req.newFetchPeopleRequest(opensocial.DataRequest.Group.VIEWER_FRIENDS), 'viewerFriends');

To the following 0.8 code:

var idSpec = opensocial.newIdSpec();idSpec.setField(opensocial.IdSpec.Field.NETWORK_DISTANCE, 1); // Greater than 1 is not supported.idSpec.setField(opensocial.IdSpec.Field.USER_ID, opensocial.IdSpec.PersonId.VIEWER);// Specifying a GROUP_ID is unnecessary and is not supported. Our container assumes you always want friends. var req = opensocial.newDataRequest(); req.add(req.newFetchPeopleRequest(idSpec), 'viewerFriends');

Activity Response FormatIn 0.7, an Activity request returned a wrapper object whose activities property contained the ac-tual response. This wrapper is no longer used; the response is returned directly.

Change the following 0.7 code:

var activities = response.get('myActivityKey').getData()['activities'];

To the following 0.8 code:

February 29, 2012105Yahoo! Developer Network

OpenSocial 0.8 Compatibility

Page 115: Yap Dev Guide

var activities = response.get('myActivityKey').getData();

OpenSocial Code SamplesThe following code samples demonstrate how you might make OpenSocial calls in the Canvas View of aYahoo! Open Application.

Activities Demo

<!-- YAP OpenSocial Activities Demo Reid Burke 10 Sep 2008--><script type="text/javascript">

function getViewerActivities() {

var idSpec = opensocial.newIdSpec(); idSpec.setField(opensocial.IdSpec.Field.USER_ID, opensocial.IdSpec.PersonId.VIEWER);

var req = opensocial.newDataRequest(); req.add(req.newFetchActivitiesRequest(idSpec), 'activities'); req.add(req.newFetchPeopleRequest(idSpec), 'people'); req.send(onLoadViewerActivities);

}

function getViewerFriendsActivities() {

var idSpec = opensocial.newIdSpec(); idSpec.setField(opensocial.IdSpec.Field.USER_ID, opensocial.IdSpec.PersonId.VIEWER); idSpec.setField(opensocial.IdSpec.Field.NETWORK_DISTANCE, 1);

var req = opensocial.newDataRequest(); req.add(req.newFetchActivitiesRequest(idSpec), 'activities'); req.add(req.newFetchPeopleRequest(idSpec), 'people'); req.send(onLoadViewerFriendsActivities);

}

function onLoadViewerFriendsActivities(response) {

var html = processResponse(response);

document.getElementById('yap-activity-viewer-friends').innerHTML = html;

February 29, 2012106Yahoo! Developer Network

OpenSocial 0.8 Compatibility

Page 116: Yap Dev Guide

}

function onLoadViewerActivities(response) {

var html = processResponse(response);

document.getElementById('yap-activity-viewer').innerHTML = html;

}

function processResponse(response) {

var activities = response.get('activities').getData(); var people = response.get('people').getData();

var peopleNames = {}; var peopleLink = {}; var peoplePic = {}; people.each(function(person) { peopleNames[person.getId()] = person.getDisplayName(); peopleLink[person.getId()] = person.getField(opensocial.Person.Field.PROFILE_URL); peoplePic[person.getId()] = person.getField(opensocial.Person.Field.THUMBNAIL_URL); });

var html = new Array(); var size = activities.getTotalSize(); if (size > 0) { var what = ' activities'; if (size == 1) what = ' activity'; html.push('<p>You have ' + size + what + ':</p>'); html.push('<ul>'); activities.each(function(activity) { var userId = activity.getField(opensocial.Activity.Field.USER_ID); var title = activity.getField(opensocial.Activity.Field.TITLE); html.push('<li><img src="' + peoplePic[userId] + '" height="32" width="32"><b>' + title + '</b> from <a href="' + peopleLink[userId] + '">' + peopleNames[userId] + '</a></li>'); }); html.push('</ul>'); } else { html.push('<div class="yap-error">No activities yet!</div>'); }

return html.join('');

}

function postActivity() { var params = {}; params[opensocial.Activity.Field.TITLE] = 'J. Hacker bookmarked the

February 29, 2012107Yahoo! Developer Network

OpenSocial 0.8 Compatibility

Page 117: Yap Dev Guide

Yahoo! Application Platform'; params[opensocial.Activity.Field.BODY] = 'The Yahoo! Application Platform allows you to create social applications. Check it out!'; var activity = opensocial.newActivity(params); opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.LOW, function() { document.getElementById('yap-status').innerHTML = '<div>Activity created!</div>'; });}

gadgets.util.registerOnLoadHandler(function() { postActivity(); getViewerActivities(); getViewerFriendsActivities();});

</script>

<style type="text/css">#yap-app { font-family: Arial, sans-serif; padding: 5px;}

#yap-status div, .yap-notice, .yap-error { background: #ffc; padding: 5px 15px 5px; margin-bottom: 3px;}

.yap-error { font-style: italic; background: #fcc;}

ul { list-style: none;}

li { padding: 3px; border: 1px solid #ccc; margin-bottom: 3px;}</style>

<div id="yap-app">

<h1>YAP OpenSocial Activities Demo</h1>

<div id="yap-status"><div>Posting a sample activity...</div></div>

February 29, 2012108Yahoo! Developer Network

OpenSocial 0.8 Compatibility

Page 118: Yap Dev Guide

<h3>Your Recent Updates</h3><div id="yap-activity-viewer"><div class="yap-notice">Loading...</div></div>

<h3>Your Friend's Recent Updates</h3><div id="yap-activity-viewer-friends"><div class="yap-notice">Loading...</div></div>

</div>

Gifts Demo

<!-- A sample YAP 1.0 ready OpenSocial application. Adapted from http://code.google.com/apis/opensocial/articles/tutorial/tutorial-0.7.html

Updated for OpenSocial 0.8 and the Yahoo! Application Platform by Reid Burke 5 Sep 2008 YAP or 0.8 specific comments are annotated with YAPNOTE Updated 27 Oct 2008--><script type="text/javascript">

// Original JS code: http://opensocial-resources.googlecode.com/svn/samples/tutorial/tags/api-0.7/gifts_5_streams.js

var globalGivenGifts = {};var globalViewer = {};var globalFriends = {};

// YAPNOTE: You may store up to 1K of data per AppData key, up to 1MB total.// Currently, using gadgets.json.stringify will include properties attached to objects used by Caja// which take up several hundred bytes. This is a known issue we are working on.// In this example, we will use a simple comma-seperated format for storing data in a// single AppData key to save storage space.function serializeGifts(obj) { var out = new Array(); for (var id in obj) { if (id.substr(-3) === '___') { continue; // YAPNOTE: Skip Caja properties, which always end with a triple underscore }

February 29, 2012109Yahoo! Developer Network

OpenSocial 0.8 Compatibility

Page 119: Yap Dev Guide

out.push(id); out.push(obj[id]); } return out.join(',');}

function unserializeGifts(str) { var out = new Object(); var arr = str.split(','); var name = false; for (var i in arr) { if (!name) { name = arr[i]; continue; } out[name] = arr[i]; name = false; } return out;}

function postActivity(nut, friend) { var options = ['a cashew nut', 'a peanut', 'a hazelnut', 'a red pistachio nut'];

var title = globalViewer.getDisplayName() + ' gave ' + globalFriends[friend] + ' ' + options[nut]; var params = {}; params[opensocial.Activity.Field.TITLE] = title; var activity = opensocial.newActivity(params); // YAPNOTE: HIGH priority events are treated the same as LOW priority activities in YAP v1.0 // The callback here is specified as an empty function opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH, function() {});}

function updateReceivedList(viewer, data, friends) { var viewerId = viewer.getId();

var options = ['a cashew nut', 'a peanut', 'a hazelnut', 'a red pistachio nut'];

var html = new Array(); html.push('You have received:<ul>'); friends.each(function(person) { var personData = data[person.getId()]; if (personData) { var json = data[person.getId()]['gifts'];

// YAPNOTE: You must be very careful to create well-formed JavaScript when working with Caja. // Missing semicolons are a source of common problems, such as this line:

February 29, 2012110Yahoo! Developer Network

OpenSocial 0.8 Compatibility

Page 120: Yap Dev Guide

// var gifts = {} // should be var gifts = {};

if (!json) { gifts = {}; } try { gifts = unserializeGifts(gadgets.util.unescapeString(json)); } catch (e) { gifts = {}; }

// YAPNOTE: Be sure to use 'var' whenever appropiate when working in Caja // Therefore, this code: // for (i in gifts) { // should be: for (var i in gifts) { // YAPNOTE: We use alphanumeric GUIDs, so the +i > 0 check should be removed // This line: // if (+(i) > 0 && i == viewerId) { // should be simply: if (i == viewerId) { html.push('<li>' + options[gifts[i]] + ' from ' + person.getDisplayName() + '</li>'); } } } }); html.push('</ul>'); document.getElementById('received').innerHTML = html.join('');}

function updateGiftList(viewer, data, friends) { var json = data[viewer.getId()]['gifts'];

if (!json) { globalGivenGifts = {}; } try { globalGivenGifts = unserializeGifts(gadgets.util.unescapeString(json)); } catch (e) { globalGivenGifts = {}; }

console.log(globalGivenGifts);

var options = ['a cashew nut', 'a peanut', 'a hazelnut', 'a red pistachio nut'];

var html = new Array();

February 29, 2012111Yahoo! Developer Network

OpenSocial 0.8 Compatibility

Page 121: Yap Dev Guide

html.push('You have given:'); html.push('<ul>'); // YAPNOTE: Be sure to use 'var' whenever appropiate when working in Caja // Therefore, this code: // for (i in globalGivenGifts) { // should be: for (var i in globalGivenGifts) { // YAPNOTE: We use alphanumeric GUIDs, so this check should be removed: //if (+(i) > 0) { html.push('<li>' + friends[i] + ' received ' + options[globalGivenGifts[i]] + '</li>'); //} } html.push('</ul>'); document.getElementById('given').innerHTML = html.join('');}

function giveGift() { var nut = document.getElementById('nut').value; var friend = document.getElementById('person').value;

globalGivenGifts[friend] = nut; var json = serializeGifts(globalGivenGifts);

var req = opensocial.newDataRequest();

// YAPNOTE: DataRequest.PersonId is now IdSpec.PersonId in 0.8 // Therefore, this code: // req.add(req.newUpdatePersonAppDataRequest(opensocial.DataRequest.PersonId.VIEWER, 'gifts', json)); // is now:

req.add(req.newUpdatePersonAppDataRequest(opensocial.IdSpec.PersonId.VIEWER, 'gifts', json));

// YAPNOTE: For Person requests, specify a string ID as the first argument: // req.add(req.newFetchPersonRequest('VIEWER'), 'viewer'); // Although that code would work, the semantically correct way is to use IdSpec.PersonId when possible: req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer');

// YAPNOTE: For fetch People and AppData requests, specify an IdSpec object (not a string ID) as the first argument. // In 0.7, VIEWER_FRIENDS is no longer available. Instead, use NETWORK_DISTANCE // Therefore, this code: // req.add(req.newFetchPeopleRequest('VIEWER_FRIENDS'),

February 29, 2012112Yahoo! Developer Network

OpenSocial 0.8 Compatibility

Page 122: Yap Dev Guide

'viewerFriends'); // req.add(req.newFetchPersonAppDataRequest('VIEWER', 'gifts'), 'data'); // req.add(req.newFetchPersonAppDataRequest('VIEWER_FRIENDS', 'gifts'), 'viewerFriendData'); // is now: var idSpec = opensocial.newIdSpec(); idSpec.setField(opensocial.IdSpec.Field.USER_ID, opensocial.IdSpec.PersonId.VIEWER); var idSpecFriends = opensocial.newIdSpec(); idSpecFriends.setField(opensocial.IdSpec.Field.USER_ID, opensocial.IdSpec.PersonId.VIEWER); idSpecFriends.setField(opensocial.IdSpec.Field.NETWORK_DISTANCE, 1); // YAPNOTE: Groups aren't supported in YAP v1. If you don't specify one, we assume you want friends

req.add(req.newFetchPeopleRequest(idSpecFriends), 'viewerFriends'); req.add(req.newFetchPersonAppDataRequest(idSpec, 'gifts'), 'data'); req.add(req.newFetchPersonAppDataRequest(idSpecFriends, 'gifts'), 'viewerFriendData');

req.send(onLoadFriends);

postActivity(nut, friend);}

function makeOptionsMenu() { var options = ['a cashew nut', 'a peanut', 'a hazelnut', 'a red pistachio nut'];

var html = new Array(); html.push('<select id="nut">'); for (var i = 0; i < options.length; i++) { html.push('<option value="' + i + '">' + options[i] + '</option>');

} html.push('</select>'); document.getElementById('gifts').innerHTML = html.join('');}

function loadFriends() { var req = opensocial.newDataRequest();

// YAPNOTE: For Person requests, specify a string ID as the first argument: // req.add(req.newFetchPersonRequest('VIEWER'), 'viewer'); // Although that code would work, the semantically correct way is to use IdSpec.PersonId when possible: req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer');

// YAPNOTE: For fetch People and AppData requests, specify an IdSpec object (not a string ID) as the first argument.

February 29, 2012113Yahoo! Developer Network

OpenSocial 0.8 Compatibility

Page 123: Yap Dev Guide

// In 0.7, VIEWER_FRIENDS is no longer available. Instead, use NETWORK_DISTANCE // Therefore, this code: // req.add(req.newFetchPeopleRequest('VIEWER_FRIENDS'), 'viewerFriends'); // req.add(req.newFetchPersonAppDataRequest('VIEWER', 'gifts'), 'data'); // req.add(req.newFetchPersonAppDataRequest('VIEWER_FRIENDS', 'gifts'), 'viewerFriendData'); // is now: var idSpec = opensocial.newIdSpec(); idSpec.setField(opensocial.IdSpec.Field.USER_ID, opensocial.IdSpec.PersonId.VIEWER); var idSpecFriends = opensocial.newIdSpec(); idSpecFriends.setField(opensocial.IdSpec.Field.USER_ID, opensocial.IdSpec.PersonId.VIEWER); idSpecFriends.setField(opensocial.IdSpec.Field.NETWORK_DISTANCE, 1); // YAPNOTE: Groups aren't supported in YAP v1. If you don't specify one, we assume you want friends

req.add(req.newFetchPeopleRequest(idSpecFriends), 'viewerFriends'); req.add(req.newFetchPersonAppDataRequest(idSpec, 'gifts'), 'data'); req.add(req.newFetchPersonAppDataRequest(idSpecFriends, 'gifts'), 'viewerFriendData');

req.send(onLoadFriends);}

function onLoadFriends(data) { var viewer = globalViewer = data.get('viewer').getData(); var viewerFriends = data.get('viewerFriends').getData(); var giftData = data.get('data').getData(); var viewerFriendData = data.get('viewerFriendData').getData(); var friends = new Array();

// YAPNOTE: Be sure to use 'var' whenever appropiate when working in Caja // Therefore, this code: // html = new Array(); // should be: var html = new Array(); html.push('<select id="person">'); viewerFriends.each(function(person) { html.push('<option value="' + person.getId() + '">' + person.getDisplayName() + "</option>");

friends[person.getId()] = person.getDisplayName(); }); html.push('</select>'); document.getElementById('friends').innerHTML = html.join('');

globalFriends = friends; updateGiftList(viewer, giftData, friends); updateReceivedList(viewer, viewerFriendData, viewerFriends);

February 29, 2012114Yahoo! Developer Network

OpenSocial 0.8 Compatibility

Page 124: Yap Dev Guide

}

function init() { loadFriends(); makeOptionsMenu();}

gadgets.util.registerOnLoadHandler(init);</script>

<style type="text/css">#yap-app { font-family: Arial, sans-serif; padding: 5px;}

#yap-status div, .yap-notice, .yap-error { background: #ffc; padding: 5px 15px 5px; margin-bottom: 3px;}

.yap-error { font-style: italic; background: #fcc;}

ul { list-style: none;}

li { padding: 3px; border: 1px solid #ccc; margin-bottom: 3px;}</style>

<!-- HTML that would be within the <Content> gadget XML: --><div id='yap-app'><h1>Gift Giving!</h1><div id='give'><form id='gift_form'><!-- YAPNOTE: You can't link to javascript:void in Caja. Use '#' instead --><!-- This is invalid:Give <span id='gifts'></span> to <span id='friends'></span>. <a href="javascript:void(0);" onclick='giveGift();'>Give!</a>-->Give <span id='gifts'></span> to <span id='friends'></span>. <a href="#" onclick='giveGift();'>Give!</a></form></div><div id='given'></div>

February 29, 2012115Yahoo! Developer Network

OpenSocial 0.8 Compatibility

Page 125: Yap Dev Guide

<!-- YAPNOTE: You must also be careful to create well-formed HTML markup when working with Caja --><!-- This is invalid:<div id='received'</div>--><div id='received'></div></div>

Gadget Configuration for OpenSocial 0.8To use OpenSocial 0.8 JavaScript APIs, add the following line to your project's Gadget XML [93] file:

<Require feature="opensocial-0.8"/>

OpenSoocial 0.9 is supported by default, but can be specified explicitly:

<Require feature="opensocial-0.9"/>

Do not include both of these Require elements in your Gadget XML file. Do not attempt to mix 0.8 and0.9 JavaScript API calls in the same application.

February 29, 2012116Yahoo! Developer Network

OpenSocial 0.8 Compatibility

Page 126: Yap Dev Guide

Chapter 11. Code ExamplesIn this Chapter

• “Prerequisites” [117]

• “YML Code Examples” [117]

• “Caja-Ready Code Examples” [130]

• “Other Code Examples” [138]

PrerequisitesBefore trying out the following code examples, you should already know how to create and run OpenApplications. The following tutorials will show you the basics:

• Getting Started [9]

• Setting the Small View [32]

You must also have the following:

• A Web server accessible outside of your local network. You cannot use localhost.

• An installation of the Yahoo! Social SDK for PHP1 on your Web server.

• Your own Yahoo! Profile2.

YML Code Examples

Tabs in the Small ViewBy Jonathan LeBlanc3

Summary

This example shows how to create dynamic tabs in the small view of a Yahoo! Open Application. Specific-ally, it demonstrates the yml:a tag and the setSmallView method of the Yahoo! Social SDK for PHP.

Implementation Notes

The Small View in this example displays a set of three tabs. In the following screenshot of the Small View,the user has selected Tab 2, which shows the user's badge.

1 http://developer.yahoo.com/social/sdk/php/2 http://pulse.yahoo.com3 http://www.nakedtechnologist.com

February 29, 2012117Yahoo! Developer Network

Page 127: Yap Dev Guide

Figure 11.1. Tab 2 Selected

The tabs_smallview.php script shown in this example is a Canvas View application that builds thetabs in the Small View. The tabs_smallview.php script constructs the HTML for the tabs with thebuild_tabs function. Then, it it passes the constructed HTML to the setSmallView method:

. . .$tabCode .= "<div class='pad5'>" . build_tabs($tabNum) . '</div>';. . .if (!$yahooSession->setSmallView($guid, $tabCode)){ echo "UNABLE TO SET SMALL VIEW";}. . .

The build_tabs function constructs each tab with the following yml:a tag:

<yml:a params=\"?tabNum=$i\" replace=\"tabContainer\">Tab $i</yml:a>

This yml:a tag creates a link, calls tabs_smallview.php with the tab number as the parameter, andreplaces the tab contents into the tabContainer element.

Setting Up this Example

To set up and run tabs_smallview.php:

1. Copy tabs_smallview.php4 to your Web server.

2. In your project's Gadget XML file, find the Content element that provides the Canavas View content;set its href attribute to the URL that returns tabs_smallview.php. Example: <Contenttype="html" view="YahooFullView" href="http://my_do-main.com/tabs_smallview.php"></Content>.

3. Make sure the Gadgdet XML file contains the following lines:

<Require feature="yap.feature.classic"/><Require feature="opensocial-0.8"/>

4. When you run the Canvas View, it should display the string "LARGE VIEW CONTENT". The URLof the Canvas View has the following format, where your_app_id is the ID of your Open Application:

http://apps.yahoo.com/-your_app_id

5. To view the Small View, append YahooSmallView to the URL:

4 examples/tabs_smallview.phps

February 29, 2012118Yahoo! Developer Network

Code Examples

Page 128: Yap Dev Guide

http://apps.yahoo.com/-your_app_id/YahooSmallView

The dynamic tabs should appear.

Source Code

<xi:include></xi:include>

Friend Selector

Summary

This example shows how to use the yml:friend-selector tag to create an HTML select elementthat contains a list of the user's friends.

The yml:friend-selector Tag

In a Yahoo! Open Application, the yml:friend-selector tag creates an HTML select elementthat contains a list of a user's friends. On the Yahoo! Pulse5 Profile page, the friends are called "Connections."The yml:friend-selector tag in this example follows. The uid parameter indicates that the friendslisted belong to the viewer (user running the application).

<yml:friend-selector uid="viewer" size="6" multiple="true" />

The following figure shows this example at runtime. When you click "Submit", the application runs theJavaScript showSelected function, which displays the GUID6 of the selected user.

Figure 11.2. Friend Selector Screenshot

For the full syntax of this tag, see the YML Reference7.

Source Code

<script language="JavaScript" type="text/javascript">

function showSelected(){ var fsdiv = document.getElementById('fsdiv'); var fssel = fsdiv.getElementsByTagName('select')[0]; alert(fssel.value); document.getElementById("displayarea").innerHTML = fssel.value;}

</script>

5 http://pulse.yahoo.com6 ../../yos/glossary/gloss-entries.html#guid7 ../../yap/guide/friend-selector.html

February 29, 2012119Yahoo! Developer Network

Code Examples

Page 129: Yap Dev Guide

<form> <p>Select a user from the Friend Selector <br /> and then click Submit to see the user's GUID.</p> <p>Friend Selector:</p> <div id='fsdiv'> <yml:friend-selector uid="viewer" size="6" multiple="true"/> </div> <br /> <input type="button" value="Submit" onclick="showSelected();" /> <p>GUID:</p> <div id='displayarea' style="border: 2px solid black"> </div><br /></form>

Friend Selector With Style

Summary

This example shows how you might style the yml:friend-selector tag to be more visually appealing.

Styling the Friend Selector With CSS

First you need to create a yml:friend-selector. The one we are using here allows people to selectmultiple friends:

<yml:friend-selector multiple="true" />

Next we can style it using a CSS block. We are using the .friend-selector class to select thefriend-selector control (and all other friend-selector controls on the page) and add a funkydesign. This one looks kinda like a barcode. If you have an existing <style> block on your page youmight want to reuse that.

<style type="text/css">.friend-selector { margin: 1em; border: 2px dashed #fff; padding: 0.2em; color: white; background: black; font-family:Ariel,Helvetica,sans-serif;

}

February 29, 2012120Yahoo! Developer Network

Code Examples

Page 130: Yap Dev Guide

</style>

Source Code

<style type="text/css">.friend-selector { margin: 1em; border: 2px dashed #fff; padding: 0.2em; color: white; background: black; font-family:Ariel,Helvetica,sans-serif;

}</style><yml:friend-selector multiple="true" />

Navigate from Small View to Canvas View

Summary

This example shows how to navigate from the Small View of a Yahoo! Open Application to the CanvasView. The yml:a tag shown in this example creates a link that takes the user from one view to another.

The yml:a Tag

This example is simple. To try it out, perform the following steps:

1. In your project's Gadget XML file, find the Content element that provides the Small View content;make sure it does not have an href attribute. Then replace its inline content with <yml:aview="YahooFullView">Click here to go to the Canvas View</yml:a>. Forexample:

<Content type="html" view="YahooSmallView, default"><![CDATA[ <yml:a view="YahooFullView">Click here to go to the Canvas View</yml:a> ]]></Content>

2. In the Project Details page, click "Preview". A window appears with a single link, "Click here to go tothe Canvas View."

3. Click the link. The Canvas View should appear.

For the full syntax of this tag, see the YML Reference8.

8 ../../yap/guide/a.html

February 29, 2012121Yahoo! Developer Network

Code Examples

Page 131: Yap Dev Guide

Source Code

<yml:a view="YahooFullView">Click here to go to the Canvas View</yml:a>

Preview Open Application Small View

Summary

This example shows how use the yml:a tag to preview the Small View content while in the canvas view.Here's a scenario for this type of preview: In the canvas view, the user can customize the Small View.Before saving the customization changes, the user can preview the rendered code of the Small View .

Insert With the yml:a Tag

The example code has two main components: an HTML div element with the id="preview" attribute,and the following YML tag:

<yml:a view="YahooSmallView" insert="preview">Click to insert Small View.</yml:a>

In the canvas view, when you select "Click to insert Small View", the contents of the div is replaced withthe contents of the Small View.

To set up this example:

1. Copy the source code to an HTML file on your Web server.

2. In your project's Gadget XML file, find the Content element that provides the Canavas View content;set its href attribute to the URL that returns the HTML file. Example: <Content type="html"view="YahooFullView" href="http://my_domain.com/my_file.html"></Con-tent>.

3. In the Project Details page, select the URL next to "Live Application". The following screenshot showsthe canvas view for this example.

Figure 11.3. Preview of Canvas View

Source Code

Top of canvas view.<div style="margin:20px"> <div id="preview" style="border: 1px dashed #bbb;width:300px;margin-bottom:20px;"> The Small View will appear here. </div> <yml:a view="YahooSmallView" insert="preview">Click to insert Small View.</yml:a></div>

February 29, 2012122Yahoo! Developer Network

Code Examples

Page 132: Yap Dev Guide

Bottom of canvas view.

Links to Yahoo! Profiles

Summary

This example shows how to create links to Yahoo! Pulse9 Profiles with the name, profile-pic, anduser-badgeYML tags.

YML Tags

A Yahoo! Profile10 is where a Yahoo! user specifies identity information such as name, location, andgender. Additionally, a Yahoo! Profile contains social data such as a user's Connections (friends). SeveralYML tags enable you to create links to a user's Yahoo! Profile page.

The yml:name tag shows displays the specified user's name. (On the Yahoo! Profile page, it's the DisplayName.) In the following tag, the specified user is viewer, the person running the application. Becausethe linked attribute is true, the Display Name links to the Yahoo! Profile page.

<yml:name uid="viewer" linked="true" />

The yml:profile-pic tags displays the photo of the user's Yahoo! Profile page. Again, linked isset to true. If you click the photo, the browser displays the Yahoo! Profile page.

<yml:profile-pic uid="viewer" width="25" linked="true" />

The yml:user-badge displays the name and photo of the user's Yahoo! Profile page.

<yml:user-badge uid="viewer" width="20" linked="true" />

For details on the syntax of these tags, see the YML Reference11.

The following screenshot shows the three links generated by the YML tags of this example:

Figure 11.4. Links to Yahoo! Profile With YML

9 http://pulse.yahoo.com10 http://pulse.yahoo.com11 ../../yap/guide/yapdev-yml.html

February 29, 2012123Yahoo! Developer Network

Code Examples

Page 133: Yap Dev Guide

Source Code

Hello, my name is <yml:name uid="viewer" linked="true" /><hr>

Click the below photo:<br><yml:profile-pic uid="viewer" width="25" linked="true" /> <hr>

Click the below user badge:<br><yml:user-badge uid="viewer" width="20" linked="true" />

Accordion Menu for an Open Application

Summary

This example shows how to create an accordian menu in the canvas and small views. The accordian menuis implemented with PHP and YML.

Implementation Notes

The accordion menu in this example is an HTML unordered list. Each item in the list is a link, created bya yml:a tag. When the user selects a link, the item is expanded and additional content appears. In thefollowing screenshot, the Fruits item has been selected, so the following words are displayed: apples, oranges,pears.

Figure 11.5. Accordion Screenshot

The following code snippet shows how the accordian is implemented with a yml:a tag and the displaystyle property. When the user clicks a list item, the ID of the item is passed to accordion.php as theparameter named expand. The yml:a tag replaces the content of the food element (the unordered list)with the output generated by the accordion.php script. In the foreach loop, if the value of expandmatches the current item processed, that item is expanded by setting the display value to block. If thevalue does not match, display is set to none, hiding the contents.

<ul id="food"><? foreach($items as $index => $item): ?><li> <yml:a view="YahooFullView" params="accordion.php?expand=<?= $index ?>" replace="food"><?= $item['header'] ?></yml:a> <div style="display:<?= $index == $expand ? 'block' : 'none' ?>"> <?= $item['content'] ?> </div></li>

February 29, 2012124Yahoo! Developer Network

Code Examples

Page 134: Yap Dev Guide

<? endforeach ?></ul>

Source Code

<?php

// Put the 3 elements of the accordion in an array.$items = array( array( 'header' => 'Fruits', 'content' => 'apples<br>oranges<br>pears' ), array( 'header' => 'Vegetables', 'content' => 'green beans<br>celery<br>carrots' ), array( 'header' => 'Grains', 'content' => 'rice<br>wheat' ));

// Get the id of the accordion item to expand.$expand = $_GET['expand'];

?>

<!-- The food list is replaced each time the user clicks an item in the accordion. -->

<ul id="food"><? foreach($items as $index => $item): ?><li>

<!-- The yml:a tag creates a clickable link for each accordion header. --> <yml:a view="YahooFullView" params="accordion.php?expand=<?= $index ?>" replace="food"><?= $item['header'] ?></yml:a>

<!-- If the user clicked this item in the accordion, then expand it.

Otherwise, hide it. --> <div style="display:<?= $index == $expand ? 'block' : 'none' ?>"> <?= $item['content'] ?> </div>

</li><?php endforeach ?>

February 29, 2012125Yahoo! Developer Network

Code Examples

Page 135: Yap Dev Guide

</ul>

Refreshing the Small Viewby Jonathan LeBlanc12

Summary

This code example shows how to use the yml:a tag to refresh content for the Small View of an OpenApplication. The yml:a tag creates a hyperlink that when clicked triggers an AJAX request for the Updatesof the logged-in Yahoo! user. The default Small View of the Open Application is then replaced with thenew content (the user's Updates).

Creating the Small View with the yml:a Tag

The content of the Small View for an Open Application is generally static. One way to make the SmallView more dynamic is to use the yml:a tag, which creates a hyperlink. The user can then click on thelink to trigger an event that makes an AJAX call to get fresh content for the Small View.

The yml:a tag in this code sample creates a hyperlink that calls the script refresh_smallview.phpto insert new contents into a div tag:

// The link calls the script with a query string that// defines the key 'uid' and inserts content into the// div tag with the id 'containerHolder'$yml = "<yml:a params=\"refresh_smallview.php?uid=" . $uid . "\" insert=\"containerHolder\">Click Here to Refresh Small View!</yml:a>";

$yml .= "<div id='containerHolder'></div>";

To set the Small View, you use the method setSmallView from the Yahoo! Social SDK for PHP. Thecode below sets the Small View with the yml:a tag that was assigned to $yml.

. . .$yahoo_session = YahooSession::requireSession(CONSUMER_KEY, CONSUMER_SECRET);$yahoo_user = $yahoo_session->getSessionedUser(); . . .$yahoo_user->setSmallView($yml);

Creating New Content for the Small View

The new content for the Small View can be generated by another PHP script or the same script that createdthe original Small View. The latter requires checking for a condition that determines whether the scriptdisplays the yml:a tag or the new content.

12 http://www.nakedtechnologist.com/

February 29, 2012126Yahoo! Developer Network

Code Examples

Page 136: Yap Dev Guide

The query string that was set in the yml:a tag earlier can be checked to determine if the link has beenclicked. If the PHP global associative array $_REQUEST contains the uid value, the new content is gen-erated, as shown in the code below:

// Check to see if the uid value has been passed// in the query stringif(isset($_REQUEST['uid'])){ // Obtain the last five updates of user $updates = $yahoo_user->listUpdates(0,5);

// If updates exist, create a list of links // to updates w/ images. if($updates) . . . }

Setting Up this Example

To set up and run refresh_smallview.php:

1. Copy refresh_smallview.php13 to your Web server.

2. In your project's Gadget XML file, find the Content element that provides the Canavas View content;set its href attribute to the URL that returns refresh_smallview.php. Example: <Contenttype="html" view="YahooFullView" href="http://my_domain.com/re-fresh_smallview.php"></Content>.

3. Make sure the Gadgdet XML file contains the following lines:

<Require feature="yap.feature.classic"/><Require feature="opensocial-0.8"/>

4. When you run the Canvas View, you should see this sentence: "This is the Canvas View!"

5. When you run the Small View, you should see a window similar to the following screenshot.

13 examples/refresh_smallview.phps

February 29, 2012127Yahoo! Developer Network

Code Examples

Page 137: Yap Dev Guide

6. In the Small View, click the link "Click Here to Refresh Small View" to get new content created by theAJAX call. You should now see your last five Updates, as shown in the figure below.

Source Code

<xi:include></xi:include>

Refreshing the Small View Dynamicallyby Jonathan LeBlanc14

Summary

This code example shows how to use the yml:include tag to dynamically refresh the content of theSmall View of an Open Application. In this example, the Small View's content is refreshed every 5 seconds.

Creating the Small View with the yml:include Tag

The following code snippet is from a PHP program named training_sdk_load.php, which callsthe setSmallView method. The content passed to the setSmallView method is a yml:includetag and a div of ID loadHere. When the yml:include tag runs, the output of the train-ing_sdk.php script replaces the contents of the loadHere div.

. . .$html = '<yml:include params="training_sdk.php" insert="loadHere"></yml:include><div id="loadHere">INSERT</div>';if (!$yahoo_user->setSmallView($html)){ echo "NO SMALL VIEW";}

14 http://www.nakedtechnologist.com/

February 29, 2012128Yahoo! Developer Network

Code Examples

Page 138: Yap Dev Guide

. . .

The training_sdk.php program contains a yml:include tag and a call to the time() function.The yml:include tag has a delay parameter of 5000 milliseconds. As a result, every 5 seconds thetime() function appears in the Small View, inserted into the loadHere div. Here is the code fortraining_sdk.php:

<yml:include params="training_sdk.php" insert="loadHere" delay="5000"></yml:include><?= time(); ?>

On some Yahoo! pages, YAP limits the number of times an application can call yml:include withina span of time. If this limit is exceeded, the following error message appears:

error-243: maxIncludes limit hit for appid XXX

If you encounter this error, reduce the number of calls to yml:include or increase the value of thedelay parameter.

Setting Up this Example

To set up and run training_sdk_load.php:

1. Copy training_sdk_load.php15 and training_sdk.php16 to your Web server.

2. In your project's Gadget XML file, find the Content element that provides the Canavas View content;set its href attribute to the URL that returns training_sdk_load.php. Example: <Contenttype="html" view="YahooFullView" href="http://my_domain.com/train-ing_sdk_load.php"></Content>.

3. Make sure the Gadgdet XML file contains the following lines:

<Require feature="yap.feature.classic"/><Require feature="opensocial-0.8"/>

4. Run the Canvas View for training_sdk_load.php.

5. When you run the Small View, you should see a timestamp, which is the output of the time() function.The value of the timestamp should automatically change every 5 seconds.

Source Code

Source for training_sdk_load.phps:

<xi:include></xi:include>

Source for training_sdk.phps:

15 examples/training_sdk_load.phps16 examples/training_sdk.phps

February 29, 2012129Yahoo! Developer Network

Code Examples

Page 139: Yap Dev Guide

<xi:include></xi:include>

Caja-Ready Code Examples

Event Handling

Summary

This code example shows how to register event handlers using the JavaScript methods addEventListen-er and attachEvent, so that the Canvas View of your Open Application will not be affected by Caja.The code example uses the event handlers to create tooltips when users click on or mouse over a DOMelement.

Caja 17is a system that transforms ordinary HTML and JavaScript into a restricted form of JavaScript. Thetransformation is called "cajoling," and the result is "cajoled script."

Registering Event Handlers

The general way of handling events is to bind a callback function to a DOM element with a JavaScriptevent handler, such as onclick, onload, onmouseover, etc. Alternatively, you can register an eventlistener on an event target using the methods addEventListener or attachEvent (for InternetExplorer).

The former method of binding event handlers is shown in the code here:

<div id="example">Clicking here will do something!</div><script language="javascript" type="text/javascript">function handler(){ document.getElementById('example').innerHTML = "I've been handled.";}document.getElementById("example").onclick=handler;</script>

To register the event and the handler with either addEventListener or attachEvent, use code likethis:

<div id="example">Clicking here will do something!</div><script language="javascript" type="text/javascript">function handler(sender){document.getElementById('example').innerHTML = "I've been handled.";}var myClickEl = document.getElementById('example');if(myClickEl.addEventListener){ myClickEl.addEventListener('click',handler,false);} else if(myClickEl.attachEvent){ myClickEl.attachEvent('click',handler);

17 http://developer.yahoo.com/yap/guide/caja-support.html

February 29, 2012130Yahoo! Developer Network

Code Examples

Page 140: Yap Dev Guide

}</script>

Setting Up this Example

To set up and run cajaready_eventhandling.html:

1. Copy cajaready_eventhandling.html18 to your Web server.

2. In your project's Gadget XML file, find the Content element that provides the Canavas View content;set its href attribute to the URL that returns cajaready_eventhandling.html. Example:<Content type="html" view="YahooFullView" href="http://my_domain.com/ca-jaready_eventhandling.html"></Content>.

3. When you run the Canvas View, you should see the below window.

4. Mouse over or click on the container to see tooltip appear to the right or above the container.

18 examples/cajaready_eventhandling.html.txt

February 29, 2012131Yahoo! Developer Network

Code Examples

Page 141: Yap Dev Guide

5. Great, you can now handle events without Caja affecting your code. To reinforce what you've learned,add code that handles double-clicking and makes the tooltip appear in a different location to the codeexample.

Source Code

<xi:include></xi:include>

JSON Conversion

Summary

This example shows how to convert a JSON object to a string and how to convert a string into JSON usingthe OpenSocial methods gadgets.json.stringify19 and gadgets.json.parse 20. Yahoo!has implemented these methods based on the OpenSocial API, so your code can safely convert JSONwithout being affected by Caja.

Caja21 is a system that transforms ordinary HTML and JavaScript into a restricted form of JavaScript. Thetransformation is called "cajoling," and the result is "cajoled script."

OpenSocial Methods: stringify and parse

To convert JSON into a string, pass the JSON to the OpenSocial method gadgets.json.stringify:

<script language="JavaScript" type="text/javascript">

19 http://code.google.com/apis/opensocial/docs/0.8/reference/gadgets/#gadgets.json20 http://code.google.com/apis/opensocial/docs/0.8/reference/gadgets/#gadgets.json21 ../../yap/guide/caja-support.html

February 29, 2012132Yahoo! Developer Network

Code Examples

Page 142: Yap Dev Guide

// Define JSON object var myJSONObject = {"bindings": [ {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},

{"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},

{"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}

] };

// Use the gadgets.json.stringify OpenSocial method // to convert the JSON object to a string var jsonAsString = gadgets.json.stringify(myJSONObject);

</script>

To convert a string into JSON, pass a string to the OpenSocial method gadgets.json.parse. Youcan then access any of the name/value pairs of the JSON object, as shown by the following code:

<script language="JavaScript" type="text/javascript">

// Define JSON text: may also be server-side // serialized JSON string var jsontext = '{"firstname":"Jonathan","surname":"LeBlanc,"phone":["111-1234","222-3456"]}';

// Use the gadgets.json.parse OpenSocial method // to convert the json string to an object // Replaces the traditional JSON.parse JavaScript method var jsonObject = gadgets.json.parse(jsontext);

// Display the value "Jonathan" alert(jsonObject.firstname);

</script>

Setting Up this Example

This example consists of one file: cajaready_jsonconv.html, which uses the OpenSocial methodsgadgets.json.stringify22 and gadgets.json.parse 23. You can get a copy of this file inthe following section, Source Code [134].

To set up this example:

1. Copy cajaready_jsonconv.html24 to your Web server.

2. In your project's Gadget XML file, find the Content element that provides the Canavas View content;set its href attribute to the URL that returns cajaready_jsonconv.html. Example: <Content

22 http://code.google.com/apis/opensocial/docs/0.8/reference/gadgets/#gadgets.json23 http://code.google.com/apis/opensocial/docs/0.8/reference/gadgets/#gadgets.json24 examples/cajaready_jsonconv.html.txt

February 29, 2012133Yahoo! Developer Network

Code Examples

Page 143: Yap Dev Guide

type="html" view="YahooFullView" href="http://my_domain.com/ca-jaready_jsonconv.html"></Content>.

3. Run the Canvas View.

Source Code

<xi:include></xi:include>

Ajax Requestby Jonathan LeBlanc25

Summary

This code example demonstrates how to use the method OpenSocial.gadgets.io.makeRequest26 to makeAjax requests to the Flickr API. Yahoo! has implemented this method based on the OpenSocial API27, soyour code can safely have Ajax functionality without being affected by Caja.

Caja28 is a system that transforms ordinary HTML and JavaScript into a restricted form of JavaScript. Thetransformation is called "cajoling," and the result is "cajoled script."

OpenSocial Method: makeRequest

Using the OpenSocial API to make an Ajax call is actually more straight forward than the standard wayof using a response object. You do not need to check for different browsers or make calls from the responseobject. Instead, you configure the request call by defining the URL, the callback function, the content type,and the HTTP method, and then make the Ajax call with gadgets.io.makeRequest29.

In the code below, the Ajax call uses the HTTP POST method and requests an XML feed (Atom or RSS).The callback function xhrCallback handles the response.

<script language="JavaScript" type="text/javascript">

// Run ajax request using OpenSocial gadgets.io.makeRequest // Define URL of a feed var url = "URL HERE";

// Define callback function var callback = xhrCallback; var params = {};

// Define content type of return value as FEED // Other possible content types: TEXT,DOM,JSON params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.FEED;

25 http://www.nakedtechnologist.com/26 http://code.google.com/apis/opensocial/articles/makerequest-0.8.html27 http://en.wikipedia.org/wiki/OpenSocial28 ../../yap/guide/caja-support.html29 http://code.google.com/apis/opensocial/articles/makerequest-0.8.html

February 29, 2012134Yahoo! Developer Network

Code Examples

Page 144: Yap Dev Guide

// Define method type (e.g. GET, POST) as POST params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;

// Run Ajax request gadgets.io.makeRequest(encodeURI(url), callback, params);

</script>

To get plain text from a response to an Ajax request, the callback function accesses the member variabletext from the response (for example, response.text).

Because the Ajax request in our example requests structured data (XML) with the keyword FEED, thecallback function accesses the response with response.data, as shown by the following code:

// Ajax request callbackfunction xhrCallback(response){

// Check if data is returned from the request if (response.data){ // Do something with response.data }}

Setting Up this Example

To set up and run cajaready_ajaxrequest.html:

1. Copy cajaready_ajaxrequest.html30 to your Web server.

2. In your project's Gadget XML file, find the Content element that provides the Canavas View content;set its href attribute to the URL that returns cajaready_ajaxrequest.html. Example: <Contenttype="html" view="YahooFullView" href="http://my_domain.com/ca-jaready_ajaxrequest.html"></Content>.

3. When you run the Canvas View, you should see a window similar to the following screenshot.

30 examples/cajaready_ajaxcall.html.txt

February 29, 2012135Yahoo! Developer Network

Code Examples

Page 145: Yap Dev Guide

4. Enter three or more characters in the text-entry field to see different photos.

Source Code

<xi:include></xi:include>

Wall-to-Wall Open Application

Summary

This code example shows you how to use the OpenSocial API31 to create an Open Application that allowsyou to add Updates to your Yahoo! Profile, much like writing on your Facebook wall. The code uses theOpenSocial API to get user and app data, extract specific information from responses, and parse strings.For explanations of these requests, see the OpenSocial Tutorial32.

The OpenSocial API is supported by many social network sites33, so this code example should also workon different application platforms such as YAP, Google (Orkut), and MySpace.

Setting Up this Example

To run the Wall-to-Wall Application:

1. Copy wall_to_wall.html 34 to your server.

2. In your project's Gadget XML file, find the Content element that provides the Canavas View content;set its href attribute to the URL that returns wall_to_wall.html. Example: <Content

31 http://wiki.opensocial.org/index.php?title=JavaScript_API_Reference32 http://wiki.opensocial.org/index.php?title=OpenSocial_Tutorial33 http://en.wikipedia.org/wiki/OpenSocial34 examples/wall_to_wall_app.html.txt

February 29, 2012136Yahoo! Developer Network

Code Examples

Page 146: Yap Dev Guide

type="html" view="YahooFullView" href="http://my_do-main.com/wall_to_wall.html"></Content>.

3. When you run the Canvas View, you should see a window similar to the figure below:

4. Choose a friend and post a message. The message will appear in the Updates stream on your Yahoo!Profile35 and on the application as seen below:

5. You can share the application by clicking the button "Send a share request!". The window below appears,allowing you to invite Connections to use your application.

35 http://profiles.yahoo.com

February 29, 2012137Yahoo! Developer Network

Code Examples

Page 147: Yap Dev Guide

Source Code

<xi:include></xi:include>

Other Code Examples

My Social PHP Application

Summary

The mysocial.php36 script performs Web authorization, calls functions of the Yahoo! Social SDK forPHP37, and displays your Yahoo! social data.

MySocial Details

The following sections describe the source code of the mysocial.php script. If you want to jump aheadand try out the script, go to Setting Up this Example [143].

Including the PHP SDK

Because mysocial.php uses the Yahoo! Social SDK for PHP, it must include the file that contains theSDK:

include_once("change-this-path/Yahoo.inc");

Authorizing With OAuth

Before calling the Social Directory APIs, mysocial.php38 authorizes with OAuth. Behind the scenes,OAuth uses an algorithm that involves passing requests, keys, and secrets between the end user (User),the hosting Web application (Service Provider), and the third-party website or application (Consumer).The Yahoo! Social SDK for PHP takes care of this complexity for you, allowing you to focus on the goalsof your application. The PHP SDK authorizes the REST request in the background and returns a YahooSes-

36 examples/mysocial.phps37 http://developer.yahoo.com/social/sdk/php/38 examples/mysocial.phps

February 29, 2012138Yahoo! Developer Network

Code Examples

Page 148: Yap Dev Guide

sion object defined in the PHP SDK. The application can then use the YahooSession to access SocialDirectory data.

Note the constants that define the application's Consumer Key and Consumer Secret. These values are re-quired for authorization with OAuth. When you register (create) your application on My Projects39, Yahoo!will create values for the Consumer Key and Consumer Secret. Then, you will insert those values in thefollowing two lines of code.

define("CONSUMER_KEY","your_Consumer_Key_goes_here"); define("CONSUMER_SECRET","your_Consumer_Secret_goes_here");

The constants CONSUMER_KEY and CONSUMER_SECRET are passed to the method requireSessionin the class YahooSession. The static method call will return the YahooSession object $yahoo_ses-sion, which is an authorized session:

$yahoo_session = YahooSession::requireSession(CONSUMER_KEY, CONSUMER_SECRET);

Debugging is very important because of the complexity of the OAuth authorization. To enable debugging,make a static call to the method setDebug from the YahooLogger class. Debugging information islogged by the PHP function error_log, which writes errors to the Web server's error log. Starting thedebugger will yield more descriptive error messages:

YahooLogger::setDebug(true);

Getting the User Profile

The Profile40 contains vital information about a user. By accessing the Profile, you can obtain user datasuch as the person's gender, location, age, and online image.

After getting the YahooSession object, you use the method getSessionedUser to return a Ya-hooUser object. To get the Profile41 of the current user, call the method loadProfile from the Ya-hooUser object $yahoo_user. The $user_profile is assigned an anonymous object that is createdfrom the JSON response. Member variables from the PHP object can then be referenced, which we willsee in the next section. Here's the code that gets the user Profile:

// Get the YahooUser object that represents the person // running this app.

$yahoo_user = $yahoo_session->getSessionedUser(); . . .

// Load the user's profile information.

$user_profile = $yahoo_user->loadProfile();

Getting a GUID

The Global User Identifier (GUID42) is a 26-byte string that identifies a user associated with his or herSocial Directory data. A GUID exists for every Yahoo! user, but is never the same as the user's Yahoo!ID. The GUID can be obtained from the user Profile or used to capture the user Profile. The GUID canalso be used to access specific user data by passing it as an argument to methods.

39 http://developer.yahoo.com/dashboard40 ../../social/rest_api_guide/social_dir_api.html41 ../../social/rest_api_guide/extended-profile-resource.html42 ../../yos/glossary/gloss-entries.html#guid

February 29, 2012139Yahoo! Developer Network

Code Examples

Page 149: Yap Dev Guide

The member variable guid belongs to the YahooUser class, so you can reference the user's GUID froma YahooUser object. You can also retrieve the YahooUser object associated with a user running yourapplication by calling the method getUser from a YahooSession object with the GUID as an argument.

// Obtain the user GUID from the member variable guid in // the YahooUser class

$guid = $user_profile->guid;

// You can get a YahooUser object by specifying the GUID$next_user = $yahoo_session->getUser($guid);

Accessing User Profile Data

With the YahooUser object $user_profile, the application can access user data by referencing themember variables of the Profile43 object. The code sample below shows how to obtain the URL of theuser's image, the status message, and the physical location of a user:

// Reference the member variable 'imageUrl' that is // embedded in the anonymous object 'image'

$imageUrl = $user_profile->image->imageUrl;

// Another embedded anonymous object used to reference the // member variable 'message'

$status = $user_profile->status->message; // Obtain the user's physical location from the class // member 'location'

$location = $user_profile->location;

Adding and Getting User Updates

Updates are records of activity for a particular user that can be shared with friends or connections. Forexample, when a user creates a new message or adds a new application, this information can be passed tothe user's connections. The PHP SDK allows you to view and create Updates. The code that follows below,adds an Update of a user and then gets a list of 20 Updates for that user.

First, let's add an Update. The method insertUpdate takes three arguments of which the source uniqueidentifier (SUID) is the most important. The SUID identifier connects a user to an action; this connectionis called an Update44. The code below shows how to title the Update and link it to a URL.

// Assign a unique values to the variable 'suid'

$suid = sprintf("%d%s",time(),$user_profile->guid);

// Create a title and link to the event $title = "My Day at Work"; $link_back_to_event = "http://yourblogsite.com/?blockID=123me";

// Pass the SUID, title and link to event to method

43 ../../social/rest_api_guide/extended-profile-resource.html44 ../../social/rest_api_guide/Single-update-resource.html

February 29, 2012140Yahoo! Developer Network

Code Examples

Page 150: Yap Dev Guide

// insertUpdate $yahoo_user->insertUpdate($suid, $title, link_back_to_event);

Next, we will get an Update. The method listUpdates takes two integers for the parameters. The twointegers represent the start and the number of Updates45 you want to retrieve. In the example below, a listof the first 20 (0-20) Updates of the user are returned. The list of Updates can then be iterated through toaccess data for each status Update. Update information, such as the user's location, URLs for the icon, andthe Update itself, can then be accessed through member variables.

// Define the beginning and ending points for the Updates to be returned

$user_updates = $yahoo_user->listUpdates(0,20); // Iterate through user updates and retrieve data from member variables

foreach($user_updates as $update) { $desc = $update->loc_longForm; $icon = $update->loc_iconURL; $link = $update->link; $update_name = $update->loc_localizedName; $image_tag = sprintf('<img src="%s" height="20" width="20" alt="%s"/>', $icon, $update_name); $link_tag = sprintf('<a href="%s">%s</a>', $link, $desc); print("<p>"); echo "$image_tag"; echo "$link_tag"; print("</p>"); }

Getting User Contacts

User Contacts represent users found in a user's Yahoo! Address Book. These Contacts have been chosenby the user, but not reciprocally confirmed as with a Connection [142]. (That is, when a user adds a Contactto his address book, the new Contact is not asked to confirm, so there is no connection made between thetwo users.) The PHP SDK has methods that allow you to obtain the entire list of user Contacts or a singleContact associated with a GUID. The code below shows how to get a list of user Contacts46 and a singleuser Contact47. The method getContacts is called from the YahooUser object $yahoo_user andreturns a list of user Contacts to the variable $user_contacts.

The method getContacts returns a list of the first ten Contacts by default, but you can specify thestarting point and number of Contacts to be returned by calling getContacts with two parameters. Ifyou wanted 12 Contacts starting from the third Contact, you would call getContacts with the values2 (offset from start) and 12 (number of Contacts): getContacts(2,12). Our example program getsthe first 20 Contacts:

$start = 0; $count = 20; $user_contacts = $yahoo_user->getContacts($start,$count);

45 ../../social/rest_api_guide/connections-resource.html46 ../../social/rest_api_guide/contacts-resource.html47 ../../social/rest_api_guide/contact-resource.html

February 29, 2012141Yahoo! Developer Network

Code Examples

Page 151: Yap Dev Guide

Getting User Connections

User connections are different than user Contacts in that the relationships have been reciprocally confirmed:Both the user and the connection have mutually agreed to form a relationship. When two users have aconnection, they have the ability to share more information. For example, if Jack becomes Jim's friend,then Jack can see Jim's photos or Jim's other friends.

Like the method listUpdates, the parameters of getConnections include a starting connectionand the number of connections to retrieve. In this example, we are asking for the first ten connections48 ofthe user; these connections are stored in the list $user_connections. The variable $total is passedby reference and is assigned the number of actual, not requested, connections returned.

// Setting $start to 0 and $count to 10, will return the // first 10 connections

// The total returned will be stored in the variable// $total, which is passed by reference to the method

$start = 0; $count = 10; $user_connections = $yahoo_user->getConnections($start,$count,$total);

By iterating through the list of connections, you can obtain specific information about an individual con-nection49.

foreach($user_updates as $update) { $desc = $update->loc_longForm; $icon = $update->loc_iconURL; $link = $update->link; $update_name = $update->loc_localizedName; $image_tag = sprintf('<img src="%s" height="20" width="20" alt="%s"/>', $icon, $update_name); $link_tag = sprintf('<a href="%s">%s</a>', $link, $desc); print("<p>"); echo "$image_tag"; echo "$link_tag"; print("</p>");}

Setting and Getting User Status

The last part of mysocial.php accesses the status (also called "presence") of the user. The status, ashort string entered by the user, typically indicates the user's current activity or location. For example, auser named Joe might want his friends to know that he's in the Bahamas on vacation. He would then enterhis status in the form of plain text: "Hi everyone, I'm in the Bahamas." His connections would be able tosee this message when visiting his Profile page or in their news feeds. In the examples below, you willupdate and retrieve the user's status.

48 ../../social/rest_api_guide/connections.html49 ../../social/rest_api_guide/connection.html

February 29, 2012142Yahoo! Developer Network

Code Examples

Page 152: Yap Dev Guide

To set the status, call the method setPresence. This method takes a string, the user's message, as anargument. Once again, you call this method from the YahooUser object $yahoo_user. The returnvalue will be an HTTP status code indicating the success or failure of the method call:

// Pass a string (user's text message) to setPresence to// change user's status (Presence)

$yahoo_user->setPresence("I'm on a raft floating down the Amazon.");

To get the status, call the method getPresence. This method is called on the YahooUser object$yahoo_user and returns the status message entered by the user (or null if there is no status):

// The method getPresence returns the user's status message $user_presence = $yahoo_user->getPresence();

Setting Up this Example

To set up this example:

1. Copy the mysocial.php50 script to your Web server.

2. Create a new Open Application named My Social.

3. In your project's Gadget XML file, find the Content element that provides the Canavas View content;set its href attribute to the URL that returns mysocial.php. Example: <Content type="html"view="YahooFullView" href="http://my_domain.com/mysocial.php"></Con-tent>.

4. Make sure the Gadgdet XML file contains the following lines:

<Require feature="yap.feature.classic"/><Require feature="opensocial-0.8"/>

5. In the Project Details page, on the APIs and Services tab, set the following Permissions:

• Read for Yahoo! Contacts

• Read for Yahoo! Profiles

• Read/Write for Yahoo! Status

• Read/Write for Yahoo! Updates

6. In the mysocial.php source code, edit the path in include_once to match the location of Ya-hoo.inc on your Web server. The Yahoo.inc file contains the libraries for the Yahoo! Social SDKfor PHP51.

include_once("change-this-path/Yahoo.inc");

50 examples/mysocial.phps51 http://developer.yahoo.com/social/sdk/php/

February 29, 2012143Yahoo! Developer Network

Code Examples

Page 153: Yap Dev Guide

7. From the APIs and Services tab of the Project Details page, copy the values of the Consumer Key52

and Consumer Secret53. Paste the values into the following lines of mysocial.php:

define("CONSUMER_KEY","your_Consumer_Key_goes_here"); define("CONSUMER_SECRET","your_Consumer_Secret_goes_here");

8. From the Project Details page, run the Canvas View. A window similar to the following figure shouldappear. If you encounter errors, see Troubleshooting Your Application [144].

Troubleshooting Your Application

This section describes some of the errors you might encounter when running the mysocial.php applic-ation.

52 ../../yos/glossary/gloss-entries.html#consumer-key53 ../../yos/glossary/gloss-entries.html#consumer-secret

February 29, 2012144Yahoo! Developer Network

Code Examples

Page 154: Yap Dev Guide

1. Error: HTTP Code 404 Not Found

Cause: The application was not found or could not be loaded.

Fix: Make sure you entered the correct URL in your project's Gadget XML file. Check that you copiedthe the mysocial.php file to the correct directory on your Web server.

2. Error: Cannot get yahoo_session.

Cause: This error message is specific to mysocial.php. It usually occurs if you have changed Per-missions in the Project Details page, but did not update the Consumer Key and Consumer Secret valuesin the PHP source code. Whenever you save a modified Permissions, the Project Details page generatesnew values for the Consumer Key and Consumer Secret.

Note

This error also occurs if you try to run mysocial.php outside of YAP (that is, by spe-cifying an URL that goes directly to your Web server and not to apps.yahoo.com).

Fix: Make sure that the values for the Consumer Key and Consumer Secret in the source code matchthose displayed by the Project Details page. Also, make sure that the URL you use for running the ap-plication refers to apps.yahoo.com.

3. Error: Class 'YahooLogger' not found in ...

Warning: include_once(.../Yahoo.inc) [function.include-once]: failed to open stream: No such file ordirectory in ...

Cause: The Yahoo.inc file, which contains the Yahoo! Social SDK for PHP, could not be found.

Fix: Make sure you installed the PHP SDK on your Web server. If the SDK is installed, check yoursource code, and make sure that the path for Yahoo.inc in the include_once or require_once statementis correct.

4. Error: Cannot get object-name, where object-name is one of the following: user_profile, user_updates,user_contacts, connections, presence.

Cause: This error message is specific to mysocial.php. It occurs if the Permissions in the ProjectDetails page are incorrect. For example, if the error message is "Cannot get user_contacts", the permissionsetting for Yahoo! Contacts is "No Access Needed", but it should be "Read".

Fix: Specify the correct Permissions in the Project Details page. Note that when you save a changedPermissions, new values for the Consumer Key and Consumer Secret are generated, so you must updatethe source code with the new values.

Source Code

<xi:include></xi:include>

Additional Code ExamplesThe following table lists third-party code examples for YAP:

February 29, 2012145Yahoo! Developer Network

Code Examples

Page 155: Yap Dev Guide

Author/SourceDescriptionReference/Resource

Jonathan LeBlanc, Yahoo!,

http://github.com

Shows you how to make a basic 3-leggedOAuth request.

basic_3_legged.php 54

Jonathan LeBlanc, Yahoo!,

http://github.com

Shows you how to send a notification.notifications_set.php55

Jonathan LeBlanc, Yahoo!,

http://github.com

Shows you how to get the profile for a user.profile_get.php 56

Jonathan LeBlanc, Yahoo!,

http://github.com

Shows you how to get the relationships ofa user and display their profiles.

relationships_get.php57

Jonathan LeBlanc, Yahoo!,

http://github.com

Shows you how to get updates for a user.updates_get.php 58

Jonathan LeBlanc, Yahoo!,

http://github.com

Shows you how to push a new update forthe user.

updates_set.php 59

Jonathan LeBlanc, Yahoo!,

http://github.com

Shows you how to make a basic YQL re-quest.

yql_get.php 60

54 https://github.com/yahoo/yap-samples/blob/master/php5_sdk/basic_3_legged.php55 https://github.com/yahoo/yap-samples/blob/master/php5_sdk/notifications_set.php56 https://github.com/yahoo/yap-samples/blob/master/php5_sdk/profile_get.php57 https://github.com/yahoo/yap-samples/blob/master/php5_sdk/relationships_get.php58 https://github.com/yahoo/yap-samples/blob/master/php5_sdk/updates_get.php59 https://github.com/yahoo/yap-samples/blob/master/php5_sdk/updates_set.php60 https://github.com/yahoo/yap-samples/blob/master/php5_sdk/yql_get.php

February 29, 2012146Yahoo! Developer Network

Code Examples

Page 156: Yap Dev Guide

Appendix A. Parameters Passed to anOpen Application

The following tables describe parameters passed by the YAP engine to an Open Application at runtime.Some of the paramters are only passed if the the project's Gadget XML [93] file contains <Requirefeature="yap.feature.classic"/>.

Table A.1. Parameters Passed to an Open Application

DescriptionR e q u i r e syap.fea-

VariableFormatSourceInformation

ture.clas-sic?

User Information

GUID of the person signed into Yahoo! in the browser.

Yesyap_viewer_guidPOSTCookie inthe session

Viewer In-formation

GUID of the person whoseidentity information is in theProfile.

Yesyap_owner_guidPOSTOwner ofthe Profile

Owner Inform-ation

Language priority list asdefined in RFC 2616 section

NoAccept-LanguageHEAD-ER

PublisherPage Lan-guage Reques-ted 14.4, with quality values as-

signed so as to maintain thepriority order of the listprovided by the publisher.

Use the lang query parameterto select the language used to

NolangPOSTPublisherPage Lan-guage Reques-ted display response data. The lang

parameter has preference overthe Accept-Language header.If the lang parameter is notpresent, the Accept-Languageheader is used.

The ISO 3166-1 alpha-2 coun-try code identifying the regionwhere the page is viewed.

NocountryPOSTPublisherPage Location

Timezone Identifier, e.g.,"Asia/Seoul".

Yesyap_tzPOSTPublisherP a g eTimezone

ISO 31661 country codeidentifying the country whose

Yesyap_jurisdictionPOSTPublisherPage Jurisdic-tion

rules should be used for con-tent moderation.

Session Information

OAuth 1.1 Access TokenNoy a p _ v i ew e r _ a c -cess_token

POSTRegistrationand YAP

Viewer's Ac-cess Token

1 http://en.wikipedia.org/wiki/ISO_3166

February 29, 2012147Yahoo! Developer Network

Page 157: Yap Dev Guide

OAuth 1.1 Token SecretNoy a p _ v i ew e r _ a c -cess_token_secret

POSTRegistrationand YAP

Viewer's Ac-cess TokenSecret

Application IDYesyap_appidPOSTYAPAppID

The ID of the Yahoo! property,such as Yahoo! Finance, where

Yesyap_dropzone_idPOSTPublisherDropzone

the application will appear.The following lists thedropzone IDs and the associ-ated Yahoo! properties:

• 852096 - My Yahoo!

• 852224 - Yahoo! Pulse

• 854272 - Yahoo! Toolbar

• 854400 - Yahoo! Messenger

• 854912 - Yahoo! Games

• 855808 - Yahoo! Sports

The URL where the applica-tion is hosted. This parameter

Yesyap_page_urlPOSTPublisherHosting PageURL

has been deprecated and willno longer be available for YAP2.6 and later versions.

YAP Authentication

OAuth 1.0a Consumer KeyYesyap_consumer_keyPOSTYAP EngineC o n s u m e rKey

Timestamp of the request inUnix time2.

Yesyap_timePOSTYAP EngineRequest Time

HMAC_SHA1 signaturemethod

Noo a u t h _ s i g n a -ture_method

POSTYAP EngineRequest Signa-ture Method

OAuth 1.0a SignatureNooauth_signaturePOSTYAP EngineRequest Signa-ture

OAuth Authorization Information

The body hash algorithm isdetermined by the OAuth sig-

Nooauth_body_hashPOSTYAP EngineOAuth HashAlgorithm

nature method used.If theOAuth signature method isHMAC-SHA1 or RSA-SHA1,SHA1 [RFC3174] 3MUST beused as the body hash al-gorithm.If the OAuth signaturemethod is PLAINTEXT, useof this specification provides

2 http://en.wikipedia.org/wiki/Unix_time3 http://tools.ietf.org/html/rfc3174

February 29, 2012148Yahoo! Developer Network

Parameters Passed to an Open Applica-tion

Page 158: Yap Dev Guide

no security benefit and is NOTRECOMMENDED.

OAuth 1.0a Consumer KeyNoo a u t h _ c o n -sumer_key

POSTYAP EngineC o n s u m e rKey

A random string used touniquely identify a request and

Nooauth_noncePOSTYAP EngineOAuth NonceValue

required by the OAuth Core1.0 Spec, Section 84.

OAuth 1.0a SignatureNooauth_signaturePOSTYAP EngineRequest Signa-ture

The signature method used tosign the request.

Noo a u t h _ s i g n a -ture_method

POSTYAP EngineRequest Signa-ture Method

Current timestamp of the re-quest. This value must be +-

Nooauth_timestampPOSTYAP EngineRequest Time

600 seconds of the currenttime.

The OAuth version being used.YAP uses OAuth 1.0 RevisionA5.

Nooauth_versionPOSTYAP EngineOAuth Ver-sion

Browser Information

NoH T -TP_USER_AGENT

HEAD-ER

BrowserUser Agent

NoHTTP_ACCEPTHEAD-ER

BrowserAccept

NoH T T P _ A C -CEPT_ENCODING

HEAD-ER

BrowserAccept Encod-ing

View Information

The request is targeted toeither the Small View or Can-vas View.

Yesyap_viewPOSTPublisherView

OpenSocial Information

The application ID that is ob-tained during application regis-tration.

Noopensocial_app_idPOSTRegistrationand YAP

ApplicationID

The absolute URL to the gad-get for the current view of theapplication.

Noopensocial_app_urlPOSTRegistrationand YAP

Gadget URL

The GUID of the applicationowner.

Noopensocial_own-er_id

POSTOwner ofthe Profile

Owner GUID

Indicates if the gadget hasproxied content. The value is

Noopensocial_prox-ied_content

POSTYAP EngineContent Proxy

1 if there is proxied contentand 0 if there is no proxiedcontent.

4 http://oauth.net/core/1.0/#nonce5 http://oauth.net/core/1.0a/

February 29, 2012149Yahoo! Developer Network

Parameters Passed to an Open Applica-tion

Page 159: Yap Dev Guide

The GUID of the user viewingthe application.

Noopensocial_view-er_id

POSTCookie inSession

User GUID

February 29, 2012150Yahoo! Developer Network

Parameters Passed to an Open Applica-tion

Page 160: Yap Dev Guide

Appendix B.YAP Developer WebServices

Important Notice

YAP will stop supporting OpenSocial RESTful APIs from 15th April 2012 onwards. We recommend usingYahoo! Social Profile APIs for OpenSocial People REST endpoints (/people) and Yahoo! Social UpdatesAPIs for Opensocial Activity endpoints (/activities).

In this Appendix

• “General Information” [151]

• “Authorization” [151]

• “Response Codes” [151]

• “Set Small View Web Service” [151]

General InformationThis appendix describes the REST web services for development on the Yahoo! Application Platform(YAP). At the time of this writing, only the Set Small View web service is available for YAP development.

AuthorizationThe calls to the web services must use OAuth 1.1, with 2-legged authorization that matches the consumerkey. Only HMAC-SHA1 signatures are supported.

Response Codes

DescriptionResponse Body ContentsResponse Code

OKNo content200

OAuth failureNo content400, 401

OAuth signature mismatchNo content403

Internal failureUnstructured body5xx

Set Small View Web ServiceImportant Notice

YAP will stop supporting OpenSocial RESTful APIs from 15th April 2012 onwards. We recommend usingYahoo! Social Profile APIs for OpenSocial People REST endpoints (/people) and Yahoo! Social UpdatesAPIs for Opensocial Activity endpoints (/activities).

February 29, 2012151Yahoo! Developer Network

Page 161: Yap Dev Guide

DescriptionReplaces the statically rendered small view for a single user.

URIThe {guid} string is the Global User ID (GUID) of the Yahoo! user whose small view is set.

http://appstore.apps.yahooapis.com/v1/cache/view/small/{guid}

Methods• POST

• PUT

Request BodyYML or HTML for the small view contents. The content-type is ignored, but content encoding is honored.

February 29, 2012152Yahoo! Developer Network

YAP Developer Web Services