]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - extlib/facebook/facebookapi_php5_restlib.php
take an argument for fixup_utf8
[quix0rs-gnu-social.git] / extlib / facebook / facebookapi_php5_restlib.php
1 <?php
2 //
3 // +---------------------------------------------------------------------------+
4 // | Facebook Platform PHP5 client                                             |
5 // +---------------------------------------------------------------------------+
6 // | Copyright (c) 2007-2008 Facebook, Inc.                                    |
7 // | All rights reserved.                                                      |
8 // |                                                                           |
9 // | Redistribution and use in source and binary forms, with or without        |
10 // | modification, are permitted provided that the following conditions        |
11 // | are met:                                                                  |
12 // |                                                                           |
13 // | 1. Redistributions of source code must retain the above copyright         |
14 // |    notice, this list of conditions and the following disclaimer.          |
15 // | 2. Redistributions in binary form must reproduce the above copyright      |
16 // |    notice, this list of conditions and the following disclaimer in the    |
17 // |    documentation and/or other materials provided with the distribution.   |
18 // |                                                                           |
19 // | THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR      |
20 // | IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES |
21 // | OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.   |
22 // | IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,          |
23 // | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT  |
24 // | NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
25 // | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY     |
26 // | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT       |
27 // | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF  |
28 // | THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.         |
29 // +---------------------------------------------------------------------------+
30 // | For help with this library, contact developers-help@facebook.com          |
31 // +---------------------------------------------------------------------------+
32 //
33
34 include_once 'jsonwrapper/jsonwrapper.php';
35 class FacebookRestClient {
36   public $secret;
37   public $session_key;
38   public $api_key;
39   // to save making the friends.get api call, this will get prepopulated on
40   // canvas pages
41   public $friends_list;
42   public $user;
43   // to save making the pages.isAppAdded api call, this will get prepopulated
44   // on canvas pages
45   public $added;
46   public $is_user;
47   // we don't pass friends list to iframes, but we want to make
48   // friends_get really simple in the canvas_user (non-logged in) case.
49   // So we use the canvas_user as default arg to friends_get
50   public $canvas_user;
51   public $batch_mode;
52   private $batch_queue;
53   private $call_as_apikey;
54
55   const BATCH_MODE_DEFAULT = 0;
56   const BATCH_MODE_SERVER_PARALLEL = 0;
57   const BATCH_MODE_SERIAL_ONLY = 2;
58
59   /**
60    * Create the client.
61    * @param string $session_key if you haven't gotten a session key yet, leave
62    *                            this as null and then set it later by just
63    *                            directly accessing the $session_key member
64    *                            variable.
65    */
66   public function __construct($api_key, $secret, $session_key=null) {
67     $this->secret       = $secret;
68     $this->session_key  = $session_key;
69     $this->api_key      = $api_key;
70     $this->batch_mode = FacebookRestClient::BATCH_MODE_DEFAULT;
71     $this->last_call_id = 0;
72     $this->call_as_apikey = '';
73       $this->server_addr  = Facebook::get_facebook_url('api') . '/restserver.php';
74
75     if (!empty($GLOBALS['facebook_config']['debug'])) {
76       $this->cur_id = 0;
77       ?>
78 <script type="text/javascript">
79 var types = ['params', 'xml', 'php', 'sxml'];
80 function getStyle(elem, style) {
81   if (elem.getStyle) {
82     return elem.getStyle(style);
83   } else {
84     return elem.style[style];
85   }
86 }
87 function setStyle(elem, style, value) {
88   if (elem.setStyle) {
89     elem.setStyle(style, value);
90   } else {
91     elem.style[style] = value;
92   }
93 }
94 function toggleDisplay(id, type) {
95   for (var i = 0; i < types.length; i++) {
96     var t = types[i];
97     var pre = document.getElementById(t + id);
98     if (pre) {
99       if (t != type || getStyle(pre, 'display') == 'block') {
100         setStyle(pre, 'display', 'none');
101       } else {
102         setStyle(pre, 'display', 'block');
103       }
104     }
105   }
106   return false;
107 }
108 </script>
109 <?php
110     }
111   }
112
113   /**
114    * Set the default user id for methods that allow the caller
115    * to pass an uid parameter to identify the target user
116    * instead of a session key. This currently applies to
117    * the user preferences methods.
118    *
119    * @param $uid int the user id
120    */
121   public function set_user($uid) {
122     $this->user = $uid;
123   }
124
125   /**
126    * Start a batch operation.
127    */
128   public function begin_batch() {
129     if($this->batch_queue !== null) {
130       $code = FacebookAPIErrorCodes::API_EC_BATCH_ALREADY_STARTED;
131       throw new FacebookRestClientException($code,
132         FacebookAPIErrorCodes::$api_error_descriptions[$code]);
133     }
134
135     $this->batch_queue = array();
136   }
137
138   /*
139    * End current batch operation
140    */
141   public function end_batch() {
142     if($this->batch_queue === null) {
143       $code = FacebookAPIErrorCodes::API_EC_BATCH_NOT_STARTED;
144       throw new FacebookRestClientException($code,
145       FacebookAPIErrorCodes::$api_error_descriptions[$code]);
146     }
147
148     $this->execute_server_side_batch();
149
150     $this->batch_queue = null;
151   }
152
153   private function execute_server_side_batch() {
154     $item_count = count($this->batch_queue);
155     $method_feed = array();
156     foreach($this->batch_queue as $batch_item) {
157       $method_feed[] = $this->create_post_string($batch_item['m'],
158                                                  $batch_item['p']);
159     }
160
161     $method_feed_json = json_encode($method_feed);
162
163     $serial_only =
164       ($this->batch_mode == FacebookRestClient::BATCH_MODE_SERIAL_ONLY);
165     $params = array('method_feed' => $method_feed_json,
166                     'serial_only' => $serial_only);
167     if ($this->call_as_apikey) {
168       $params['call_as_apikey'] = $this->call_as_apikey;
169     }
170
171     $xml = $this->post_request('batch.run', $params);
172
173     $result = $this->convert_xml_to_result($xml, 'batch.run', $params);
174
175
176     if (is_array($result) && isset($result['error_code'])) {
177       throw new FacebookRestClientException($result['error_msg'],
178                                             $result['error_code']);
179     }
180
181     for($i = 0; $i < $item_count; $i++) {
182       $batch_item = $this->batch_queue[$i];
183       $batch_item_result_xml = $result[$i];
184       $batch_item_result = $this->convert_xml_to_result($batch_item_result_xml,
185                                                         $batch_item['m'],
186                                                         $batch_item['p']);
187
188       if (is_array($batch_item_result) &&
189           isset($batch_item_result['error_code'])) {
190         throw new FacebookRestClientException($batch_item_result['error_msg'],
191                                               $batch_item_result['error_code']);
192       }
193       $batch_item['r'] = $batch_item_result;
194     }
195   }
196
197   public function begin_permissions_mode($permissions_apikey) {
198     $this->call_as_apikey = $permissions_apikey;
199   }
200
201   public function end_permissions_mode() {
202     $this->call_as_apikey = '';
203   }
204
205   /**
206    * Returns public information for an application (as shown in the application
207    * directory) by either application ID, API key, or canvas page name.
208    *
209    * @param int $application_id              (Optional) app id
210    * @param string $application_api_key      (Optional) api key
211    * @param string $application_canvas_name  (Optional) canvas name
212    *
213    * Exactly one argument must be specified, otherwise it is an error.
214    *
215    * @return array  An array of public information about the application.
216    */
217   public function application_getPublicInfo($application_id=null,
218                                             $application_api_key=null,
219                                             $application_canvas_name=null) {
220     return $this->call_method('facebook.application.getPublicInfo',
221         array('application_id' => $application_id,
222               'application_api_key' => $application_api_key,
223               'application_canvas_name' => $application_canvas_name));
224   }
225
226   /**
227    * Creates an authentication token to be used as part of the desktop login
228    * flow.  For more information, please see
229    * http://wiki.developers.facebook.com/index.php/Auth.createToken.
230    *
231    * @return string  An authentication token.
232    */
233   public function auth_createToken() {
234     return $this->call_method('facebook.auth.createToken', array());
235   }
236
237   /**
238    * Returns the session information available after current user logs in.
239    *
240    * @param string $auth_token             the token returned by
241    *                                       auth_createToken or passed back to
242    *                                       your callback_url.
243    * @param bool $generate_session_secret  whether the session returned should
244    *                                       include a session secret
245    *
246    * @return array  An assoc array containing session_key, uid
247    */
248   public function auth_getSession($auth_token, $generate_session_secret=false) {
249     //Check if we are in batch mode
250     if($this->batch_queue === null) {
251       $result = $this->call_method('facebook.auth.getSession',
252           array('auth_token' => $auth_token,
253                 'generate_session_secret' => $generate_session_secret));
254       $this->session_key = $result['session_key'];
255
256     if (!empty($result['secret']) && !$generate_session_secret) {
257       // desktop apps have a special secret
258       $this->secret = $result['secret'];
259     }
260       return $result;
261     }
262   }
263
264   /**
265    * Generates a session-specific secret. This is for integration with
266    * client-side API calls, such as the JS library.
267    *
268    * @return array  A session secret for the current promoted session
269    *
270    * @error API_EC_PARAM_SESSION_KEY
271    *        API_EC_PARAM_UNKNOWN
272    */
273   public function auth_promoteSession() {
274       return $this->call_method('facebook.auth.promoteSession', array());
275   }
276
277   /**
278    * Expires the session that is currently being used.  If this call is
279    * successful, no further calls to the API (which require a session) can be
280    * made until a valid session is created.
281    *
282    * @return bool  true if session expiration was successful, false otherwise
283    */
284   public function auth_expireSession() {
285       return $this->call_method('facebook.auth.expireSession', array());
286   }
287
288   /**
289    * Revokes the user's agreement to the Facebook Terms of Service for your
290    * application.  If you call this method for one of your users, you will no
291    * longer be able to make API requests on their behalf until they again
292    * authorize your application.  Use with care.  Note that if this method is
293    * called without a user parameter, then it will revoke access for the
294    * current session's user.
295    *
296    * @param int $uid  (Optional) User to revoke
297    *
298    * @return bool  true if revocation succeeds, false otherwise
299    */
300   public function auth_revokeAuthorization($uid=null) {
301       return $this->call_method('facebook.auth.revokeAuthorization',
302           array('uid' => $uid));
303   }
304
305   /**
306    * Returns the number of unconnected friends that exist in this application.
307    * This number is determined based on the accounts registered through
308    * connect.registerUsers() (see below).
309    */
310   public function connect_getUnconnectedFriendsCount() {
311     return $this->call_method('facebook.connect.getUnconnectedFriendsCount',
312         array());
313   }
314
315  /**
316   * This method is used to create an association between an external user
317   * account and a Facebook user account, as per Facebook Connect.
318   *
319   * This method takes an array of account data, including a required email_hash
320   * and optional account data. For each connected account, if the user exists,
321   * the information is added to the set of the user's connected accounts.
322   * If the user has already authorized the site, the connected account is added
323   * in the confirmed state. If the user has not yet authorized the site, the
324   * connected account is added in the pending state.
325   *
326   * This is designed to help Facebook Connect recognize when two Facebook
327   * friends are both members of a external site, but perhaps are not aware of
328   * it.  The Connect dialog (see fb:connect-form) is used when friends can be
329   * identified through these email hashes. See the following url for details:
330   *
331   *   http://wiki.developers.facebook.com/index.php/Connect.registerUsers
332   *
333   * @param mixed $accounts A (JSON-encoded) array of arrays, where each array
334   *                        has three properties:
335   *                        'email_hash'  (req) - public email hash of account
336   *                        'account_id'  (opt) - remote account id;
337   *                        'account_url' (opt) - url to remote account;
338   *
339   * @return array  The list of email hashes for the successfully registered
340   *                accounts.
341   */
342   public function connect_registerUsers($accounts) {
343     return $this->call_method('facebook.connect.registerUsers',
344         array('accounts' => $accounts));
345   }
346
347  /**
348   * Unregisters a set of accounts registered using connect.registerUsers.
349   *
350   * @param array $email_hashes  The (JSON-encoded) list of email hashes to be
351   *                             unregistered.
352   *
353   * @return array  The list of email hashes which have been successfully
354   *                unregistered.
355   */
356   public function connect_unregisterUsers($email_hashes) {
357     return $this->call_method('facebook.connect.unregisterUsers',
358         array('email_hashes' => $email_hashes));
359   }
360
361   /**
362    * Returns events according to the filters specified.
363    *
364    * @param int $uid            (Optional) User associated with events. A null
365    *                            parameter will default to the session user.
366    * @param array $eids         (Optional) Filter by these event ids. A null
367    *                            parameter will get all events for the user.
368    * @param int $start_time     (Optional) Filter with this unix time as lower
369    *                            bound.  A null or zero parameter indicates no
370    *                            lower bound.
371    * @param int $end_time       (Optional) Filter with this UTC as upper bound.
372    *                            A null or zero parameter indicates no upper
373    *                            bound.
374    * @param string $rsvp_status (Optional) Only show events where the given uid
375    *                            has this rsvp status.  This only works if you
376    *                            have specified a value for $uid.  Values are as
377    *                            in events.getMembers.  Null indicates to ignore
378    *                            rsvp status when filtering.
379    *
380    * @return array  The events matching the query.
381    */
382   public function &events_get($uid=null,
383                               $eids=null,
384                               $start_time=null,
385                               $end_time=null,
386                               $rsvp_status=null) {
387     return $this->call_method('facebook.events.get',
388         array('uid' => $uid,
389               'eids' => $eids,
390               'start_time' => $start_time,
391               'end_time' => $end_time,
392               'rsvp_status' => $rsvp_status));
393   }
394
395   /**
396    * Returns membership list data associated with an event.
397    *
398    * @param int $eid  event id
399    *
400    * @return array  An assoc array of four membership lists, with keys
401    *                'attending', 'unsure', 'declined', and 'not_replied'
402    */
403   public function &events_getMembers($eid) {
404     return $this->call_method('facebook.events.getMembers',
405       array('eid' => $eid));
406   }
407
408   /**
409    * RSVPs the current user to this event.
410    *
411    * @param int $eid             event id
412    * @param string $rsvp_status  'attending', 'unsure', or 'declined'
413    *
414    * @return bool  true if successful
415    */
416   public function &events_rsvp($eid, $rsvp_status) {
417     return $this->call_method('facebook.events.rsvp',
418         array(
419         'eid' => $eid,
420         'rsvp_status' => $rsvp_status));
421   }
422
423   /**
424    * Cancels an event. Only works for events where application is the admin.
425    *
426    * @param int $eid                event id
427    * @param string $cancel_message  (Optional) message to send to members of
428    *                                the event about why it is cancelled
429    *
430    * @return bool  true if successful
431    */
432   public function &events_cancel($eid, $cancel_message='') {
433     return $this->call_method('facebook.events.cancel',
434         array('eid' => $eid,
435               'cancel_message' => $cancel_message));
436   }
437
438   /**
439    * Creates an event on behalf of the user is there is a session, otherwise on
440    * behalf of app.  Successful creation guarantees app will be admin.
441    *
442    * @param assoc array $event_info  json encoded event information
443    *
444    * @return int  event id
445    */
446   public function &events_create($event_info) {
447     return $this->call_method('facebook.events.create',
448         array('event_info' => $event_info));
449   }
450
451   /**
452    * Edits an existing event. Only works for events where application is admin.
453    *
454    * @param int $eid                 event id
455    * @param assoc array $event_info  json encoded event information
456    *
457    * @return bool  true if successful
458    */
459   public function &events_edit($eid, $event_info) {
460     return $this->call_method('facebook.events.edit',
461         array('eid' => $eid,
462               'event_info' => $event_info));
463   }
464
465   /**
466    * Fetches and re-caches the image stored at the given URL, for use in images
467    * published to non-canvas pages via the API (for example, to user profiles
468    * via profile.setFBML, or to News Feed via feed.publishUserAction).
469    *
470    * @param string $url  The absolute URL from which to refresh the image.
471    *
472    * @return bool  true on success
473    */
474   public function &fbml_refreshImgSrc($url) {
475     return $this->call_method('facebook.fbml.refreshImgSrc',
476         array('url' => $url));
477   }
478
479   /**
480    * Fetches and re-caches the content stored at the given URL, for use in an
481    * fb:ref FBML tag.
482    *
483    * @param string $url  The absolute URL from which to fetch content. This URL
484    *                     should be used in a fb:ref FBML tag.
485    *
486    * @return bool  true on success
487    */
488   public function &fbml_refreshRefUrl($url) {
489     return $this->call_method('facebook.fbml.refreshRefUrl',
490         array('url' => $url));
491   }
492
493   /**
494    * Lets you insert text strings in their native language into the Facebook
495    * Translations database so they can be translated.
496    *
497    * @param array $native_strings  An array of maps, where each map has a 'text'
498    *                               field and a 'description' field.
499    *
500    * @return int  Number of strings uploaded.
501    */
502   public function &fbml_uploadNativeStrings($native_strings) {
503     return $this->call_method('facebook.fbml.uploadNativeStrings',
504         array('native_strings' => json_encode($native_strings)));
505   }
506
507   /**
508    * Associates a given "handle" with FBML markup so that the handle can be
509    * used within the fb:ref FBML tag. A handle is unique within an application
510    * and allows an application to publish identical FBML to many user profiles
511    * and do subsequent updates without having to republish FBML on behalf of
512    * each user.
513    *
514    * @param string $handle  The handle to associate with the given FBML.
515    * @param string $fbml    The FBML to associate with the given handle.
516    *
517    * @return bool  true on success
518    */
519   public function &fbml_setRefHandle($handle, $fbml) {
520     return $this->call_method('facebook.fbml.setRefHandle',
521         array('handle' => $handle, 'fbml' => $fbml));
522   }
523
524   /**
525    * Register custom tags for the application. Custom tags can be used
526    * to extend the set of tags available to applications in FBML
527    * markup.
528    *
529    * Before you call this function,
530    * make sure you read the full documentation at
531    *
532    * http://wiki.developers.facebook.com/index.php/Fbml.RegisterCustomTags
533    *
534    * IMPORTANT: This function overwrites the values of
535    * existing tags if the names match. Use this function with care because
536    * it may break the FBML of any application that is using the
537    * existing version of the tags.
538    *
539    * @param mixed $tags an array of tag objects (the full description is on the
540    *   wiki page)
541    *
542    * @return int  the number of tags that were registered
543    */
544   public function &fbml_registerCustomTags($tags) {
545     $tags = json_encode($tags);
546     return $this->call_method('facebook.fbml.registerCustomTags',
547                               array('tags' => $tags));
548   }
549
550   /**
551    * Get the custom tags for an application. If $app_id
552    * is not specified, the calling app's tags are returned.
553    * If $app_id is different from the id of the calling app,
554    * only the app's public tags are returned.
555    * The return value is an array of the same type as
556    * the $tags parameter of fbml_registerCustomTags().
557    *
558    * @param int $app_id the application's id (optional)
559    *
560    * @return mixed  an array containing the custom tag  objects
561    */
562   public function &fbml_getCustomTags($app_id = null) {
563     return $this->call_method('facebook.fbml.getCustomTags',
564                               array('app_id' => $app_id));
565   }
566
567
568   /**
569    * Delete custom tags the application has registered. If
570    * $tag_names is null, all the application's custom tags will be
571    * deleted.
572    *
573    * IMPORTANT: If your application has registered public tags
574    * that other applications may be using, don't delete those tags!
575    * Doing so can break the FBML ofapplications that are using them.
576    *
577    * @param array $tag_names the names of the tags to delete (optinal)
578    * @return bool true on success
579    */
580   public function &fbml_deleteCustomTags($tag_names = null) {
581     return $this->call_method('facebook.fbml.deleteCustomTags',
582                               array('tag_names' => json_encode($tag_names)));
583   }
584
585
586
587   /**
588    * This method is deprecated for calls made on behalf of users. This method
589    * works only for publishing stories on a Facebook Page that has installed
590    * your application. To publish stories to a user's profile, use
591    * feed.publishUserAction instead.
592    *
593    * For more details on this call, please visit the wiki page:
594    *
595    * http://wiki.developers.facebook.com/index.php/Feed.publishTemplatizedAction
596    */
597   public function &feed_publishTemplatizedAction($title_template,
598                                                  $title_data,
599                                                  $body_template,
600                                                  $body_data,
601                                                  $body_general,
602                                                  $image_1=null,
603                                                  $image_1_link=null,
604                                                  $image_2=null,
605                                                  $image_2_link=null,
606                                                  $image_3=null,
607                                                  $image_3_link=null,
608                                                  $image_4=null,
609                                                  $image_4_link=null,
610                                                  $target_ids='',
611                                                  $page_actor_id=null) {
612     return $this->call_method('facebook.feed.publishTemplatizedAction',
613       array('title_template' => $title_template,
614             'title_data' => $title_data,
615             'body_template' => $body_template,
616             'body_data' => $body_data,
617             'body_general' => $body_general,
618             'image_1' => $image_1,
619             'image_1_link' => $image_1_link,
620             'image_2' => $image_2,
621             'image_2_link' => $image_2_link,
622             'image_3' => $image_3,
623             'image_3_link' => $image_3_link,
624             'image_4' => $image_4,
625             'image_4_link' => $image_4_link,
626             'target_ids' => $target_ids,
627             'page_actor_id' => $page_actor_id));
628   }
629
630   /**
631    * Registers a template bundle.  Template bundles are somewhat involved, so
632    * it's recommended you check out the wiki for more details:
633    *
634    *  http://wiki.developers.facebook.com/index.php/Feed.registerTemplateBundle
635    *
636    * @return string  A template bundle id
637    */
638   public function &feed_registerTemplateBundle($one_line_story_templates,
639                                                $short_story_templates = array(),
640                                                $full_story_template = null,
641                                                $action_links = array()) {
642
643     $one_line_story_templates = json_encode($one_line_story_templates);
644
645     if (!empty($short_story_templates)) {
646       $short_story_templates = json_encode($short_story_templates);
647     }
648
649     if (isset($full_story_template)) {
650       $full_story_template = json_encode($full_story_template);
651     }
652
653     if (isset($action_links)) {
654       $action_links = json_encode($action_links);
655     }
656
657     return $this->call_method('facebook.feed.registerTemplateBundle',
658         array('one_line_story_templates' => $one_line_story_templates,
659               'short_story_templates' => $short_story_templates,
660               'full_story_template' => $full_story_template,
661               'action_links' => $action_links));
662   }
663
664   /**
665    * Retrieves the full list of active template bundles registered by the
666    * requesting application.
667    *
668    * @return array  An array of template bundles
669    */
670   public function &feed_getRegisteredTemplateBundles() {
671     return $this->call_method('facebook.feed.getRegisteredTemplateBundles',
672         array());
673   }
674
675   /**
676    * Retrieves information about a specified template bundle previously
677    * registered by the requesting application.
678    *
679    * @param string $template_bundle_id  The template bundle id
680    *
681    * @return array  Template bundle
682    */
683   public function &feed_getRegisteredTemplateBundleByID($template_bundle_id) {
684     return $this->call_method('facebook.feed.getRegisteredTemplateBundleByID',
685         array('template_bundle_id' => $template_bundle_id));
686   }
687
688   /**
689    * Deactivates a previously registered template bundle.
690    *
691    * @param string $template_bundle_id  The template bundle id
692    *
693    * @return bool  true on success
694    */
695   public function &feed_deactivateTemplateBundleByID($template_bundle_id) {
696     return $this->call_method('facebook.feed.deactivateTemplateBundleByID',
697         array('template_bundle_id' => $template_bundle_id));
698   }
699
700   const STORY_SIZE_ONE_LINE = 1;
701   const STORY_SIZE_SHORT = 2;
702   const STORY_SIZE_FULL = 4;
703
704   /**
705    * Publishes a story on behalf of the user owning the session, using the
706    * specified template bundle. This method requires an active session key in
707    * order to be called.
708    *
709    * The parameters to this method ($templata_data in particular) are somewhat
710    * involved.  It's recommended you visit the wiki for details:
711    *
712    *  http://wiki.developers.facebook.com/index.php/Feed.publishUserAction
713    *
714    * @param int $template_bundle_id  A template bundle id previously registered
715    * @param array $template_data     See wiki article for syntax
716    * @param array $target_ids        (Optional) An array of friend uids of the
717    *                                 user who shared in this action.
718    * @param string $body_general     (Optional) Additional markup that extends
719    *                                 the body of a short story.
720    * @param int $story_size          (Optional) A story size (see above)
721    *
722    * @return bool  true on success
723    */
724   public function &feed_publishUserAction(
725       $template_bundle_id, $template_data, $target_ids='', $body_general='',
726       $story_size=FacebookRestClient::STORY_SIZE_ONE_LINE) {
727
728     if (is_array($template_data)) {
729       $template_data = json_encode($template_data);
730     } // allow client to either pass in JSON or an assoc that we JSON for them
731
732     if (is_array($target_ids)) {
733       $target_ids = json_encode($target_ids);
734       $target_ids = trim($target_ids, "[]"); // we don't want square brackets
735     }
736
737     return $this->call_method('facebook.feed.publishUserAction',
738         array('template_bundle_id' => $template_bundle_id,
739               'template_data' => $template_data,
740               'target_ids' => $target_ids,
741               'body_general' => $body_general,
742               'story_size' => $story_size));
743   }
744
745   /**
746    * For the current user, retrieves stories generated by the user's friends
747    * while using this application.  This can be used to easily create a
748    * "News Feed" like experience.
749    *
750    * @return array  An array of feed story objects.
751    */
752   public function &feed_getAppFriendStories() {
753     return $this->call_method('facebook.feed.getAppFriendStories', array());
754   }
755
756   /**
757    * Makes an FQL query.  This is a generalized way of accessing all the data
758    * in the API, as an alternative to most of the other method calls.  More
759    * info at http://developers.facebook.com/documentation.php?v=1.0&doc=fql
760    *
761    * @param string $query  the query to evaluate
762    *
763    * @return array  generalized array representing the results
764    */
765   public function &fql_query($query) {
766     return $this->call_method('facebook.fql.query',
767       array('query' => $query));
768   }
769
770   /**
771    * Returns whether or not pairs of users are friends.
772    * Note that the Facebook friend relationship is symmetric.
773    *
774    * @param array $uids1  array of ids (id_1, id_2,...) of some length X
775    * @param array $uids2  array of ids (id_A, id_B,...) of SAME length X
776    *
777    * @return array  An array with uid1, uid2, and bool if friends, e.g.:
778    *   array(0 => array('uid1' => id_1, 'uid2' => id_A, 'are_friends' => 1),
779    *         1 => array('uid1' => id_2, 'uid2' => id_B, 'are_friends' => 0)
780    *         ...)
781    */
782   public function &friends_areFriends($uids1, $uids2) {
783     return $this->call_method('facebook.friends.areFriends',
784         array('uids1' => $uids1, 'uids2' => $uids2));
785   }
786
787   /**
788    * Returns the friends of the current session user.
789    *
790    * @param int $flid  (Optional) Only return friends on this friend list.
791    *
792    * @return array  An array of friends
793    */
794   public function &friends_get($flid=null) {
795     if (isset($this->friends_list)) {
796       return $this->friends_list;
797     }
798     $params = array();
799     if (isset($this->canvas_user)) {
800       $params['uid'] = $this->canvas_user;
801     }
802     if ($flid) {
803       $params['flid'] = $flid;
804     }
805     return $this->call_method('facebook.friends.get', $params);
806
807   }
808
809   /**
810    * Returns the set of friend lists for the current session user.
811    *
812    * @return array  An array of friend list objects
813    */
814   public function &friends_getLists() {
815     return $this->call_method('facebook.friends.getLists', array());
816   }
817
818   /**
819    * Returns the friends of the session user, who are also users
820    * of the calling application.
821    *
822    * @return array  An array of friends also using the app
823    */
824   public function &friends_getAppUsers() {
825     return $this->call_method('facebook.friends.getAppUsers', array());
826   }
827
828   /**
829    * Returns groups according to the filters specified.
830    *
831    * @param int $uid     (Optional) User associated with groups.  A null
832    *                     parameter will default to the session user.
833    * @param array $gids  (Optional) Group ids to query. A null parameter will
834    *                     get all groups for the user.
835    *
836    * @return array  An array of group objects
837    */
838   public function &groups_get($uid, $gids) {
839     return $this->call_method('facebook.groups.get',
840         array('uid' => $uid,
841               'gids' => $gids));
842   }
843
844   /**
845    * Returns the membership list of a group.
846    *
847    * @param int $gid  Group id
848    *
849    * @return array  An array with four membership lists, with keys 'members',
850    *                'admins', 'officers', and 'not_replied'
851    */
852   public function &groups_getMembers($gid) {
853     return $this->call_method('facebook.groups.getMembers',
854       array('gid' => $gid));
855   }
856
857   /**
858    * Returns cookies according to the filters specified.
859    *
860    * @param int $uid     User for which the cookies are needed.
861    * @param string $name (Optional) A null parameter will get all cookies
862    *                     for the user.
863    *
864    * @return array  Cookies!  Nom nom nom nom nom.
865    */
866   public function data_getCookies($uid, $name) {
867     return $this->call_method('facebook.data.getCookies',
868         array('uid' => $uid,
869               'name' => $name));
870   }
871
872   /**
873    * Sets cookies according to the params specified.
874    *
875    * @param int $uid       User for which the cookies are needed.
876    * @param string $name   Name of the cookie
877    * @param string $value  (Optional) if expires specified and is in the past
878    * @param int $expires   (Optional) Expiry time
879    * @param string $path   (Optional) Url path to associate with (default is /)
880    *
881    * @return bool  true on success
882    */
883   public function data_setCookie($uid, $name, $value, $expires, $path) {
884     return $this->call_method('facebook.data.setCookie',
885         array('uid' => $uid,
886               'name' => $name,
887               'value' => $value,
888               'expires' => $expires,
889               'path' => $path));
890   }
891
892   /**
893    * Permissions API
894    */
895
896   /**
897    * Checks API-access granted by self to the specified application.
898    *
899    * @param string $permissions_apikey  Other application key
900    *
901    * @return array  API methods/namespaces which are allowed access
902    */
903   public function permissions_checkGrantedApiAccess($permissions_apikey) {
904     return $this->call_method('facebook.permissions.checkGrantedApiAccess',
905         array('permissions_apikey' => $permissions_apikey));
906   }
907
908   /**
909    * Checks API-access granted to self by the specified application.
910    *
911    * @param string $permissions_apikey  Other application key
912    *
913    * @return array  API methods/namespaces which are allowed access
914    */
915   public function permissions_checkAvailableApiAccess($permissions_apikey) {
916     return $this->call_method('facebook.permissions.checkAvailableApiAccess',
917         array('permissions_apikey' => $permissions_apikey));
918   }
919
920   /**
921    * Grant API-access to the specified methods/namespaces to the specified
922    * application.
923    *
924    * @param string $permissions_apikey  Other application key
925    * @param array(string) $method_arr   (Optional) API methods/namespaces
926    *                                    allowed
927    *
928    * @return array  API methods/namespaces which are allowed access
929    */
930   public function permissions_grantApiAccess($permissions_apikey, $method_arr) {
931     return $this->call_method('facebook.permissions.grantApiAccess',
932         array('permissions_apikey' => $permissions_apikey,
933               'method_arr' => $method_arr));
934   }
935
936   /**
937    * Revoke API-access granted to the specified application.
938    *
939    * @param string $permissions_apikey  Other application key
940    *
941    * @return bool  true on success
942    */
943   public function permissions_revokeApiAccess($permissions_apikey) {
944     return $this->call_method('facebook.permissions.revokeApiAccess',
945         array('permissions_apikey' => $permissions_apikey));
946   }
947
948   /**
949    * Returns the outstanding notifications for the session user.
950    *
951    * @return array An assoc array of notification count objects for
952    *               'messages', 'pokes' and 'shares', a uid list of
953    *               'friend_requests', a gid list of 'group_invites',
954    *               and an eid list of 'event_invites'
955    */
956   public function &notifications_get() {
957     return $this->call_method('facebook.notifications.get', array());
958   }
959
960   /**
961    * Sends a notification to the specified users.
962    *
963    * @return A comma separated list of successful recipients
964    */
965   public function &notifications_send($to_ids, $notification, $type) {
966     return $this->call_method('facebook.notifications.send',
967         array('to_ids' => $to_ids,
968               'notification' => $notification,
969               'type' => $type));
970   }
971
972   /**
973    * Sends an email to the specified user of the application.
974    *
975    * @param array $recipients  id of the recipients
976    * @param string $subject    subject of the email
977    * @param string $text       (plain text) body of the email
978    * @param string $fbml       fbml markup for an html version of the email
979    *
980    * @return string  A comma separated list of successful recipients
981    */
982   public function &notifications_sendEmail($recipients,
983                                            $subject,
984                                            $text,
985                                            $fbml) {
986     return $this->call_method('facebook.notifications.sendEmail',
987         array('recipients' => $recipients,
988               'subject' => $subject,
989               'text' => $text,
990               'fbml' => $fbml));
991   }
992
993   /**
994    * Returns the requested info fields for the requested set of pages.
995    *
996    * @param array  $page_ids  an array of page ids
997    * @param array  $fields    an array of strings describing the info fields
998    *                          desired
999    * @param int    $uid       (Optional) limit results to pages of which this
1000    *                          user is a fan.
1001    * @param string type       limits results to a particular type of page.
1002    *
1003    * @return array  An array of pages
1004    */
1005   public function &pages_getInfo($page_ids, $fields, $uid, $type) {
1006     return $this->call_method('facebook.pages.getInfo',
1007         array('page_ids' => $page_ids,
1008               'fields' => $fields,
1009               'uid' => $uid,
1010               'type' => $type));
1011   }
1012
1013   /**
1014    * Returns true if the given user is an admin for the passed page.
1015    *
1016    * @param int $page_id  target page id
1017    * @param int $uid      (Optional) user id (defaults to the logged-in user)
1018    *
1019    * @return bool  true on success
1020    */
1021   public function &pages_isAdmin($page_id, $uid = null) {
1022     return $this->call_method('facebook.pages.isAdmin',
1023         array('page_id' => $page_id,
1024               'uid' => $uid));
1025   }
1026
1027   /**
1028    * Returns whether or not the given page has added the application.
1029    *
1030    * @param int $page_id  target page id
1031    *
1032    * @return bool  true on success
1033    */
1034   public function &pages_isAppAdded($page_id) {
1035     return $this->call_method('facebook.pages.isAppAdded',
1036         array('page_id' => $page_id));
1037   }
1038
1039   /**
1040    * Returns true if logged in user is a fan for the passed page.
1041    *
1042    * @param int $page_id target page id
1043    * @param int $uid user to compare.  If empty, the logged in user.
1044    *
1045    * @return bool  true on success
1046    */
1047   public function &pages_isFan($page_id, $uid = null) {
1048     return $this->call_method('facebook.pages.isFan',
1049         array('page_id' => $page_id,
1050               'uid' => $uid));
1051   }
1052
1053   /**
1054    * Adds a tag with the given information to a photo. See the wiki for details:
1055    *
1056    *  http://wiki.developers.facebook.com/index.php/Photos.addTag
1057    *
1058    * @param int $pid          The ID of the photo to be tagged
1059    * @param int $tag_uid      The ID of the user being tagged. You must specify
1060    *                          either the $tag_uid or the $tag_text parameter
1061    *                          (unless $tags is specified).
1062    * @param string $tag_text  Some text identifying the person being tagged.
1063    *                          You must specify either the $tag_uid or $tag_text
1064    *                          parameter (unless $tags is specified).
1065    * @param float $x          The horizontal position of the tag, as a
1066    *                          percentage from 0 to 100, from the left of the
1067    *                          photo.
1068    * @param float $y          The vertical position of the tag, as a percentage
1069    *                          from 0 to 100, from the top of the photo.
1070    * @param array $tags       (Optional) An array of maps, where each map
1071    *                          can contain the tag_uid, tag_text, x, and y
1072    *                          parameters defined above.  If specified, the
1073    *                          individual arguments are ignored.
1074    * @param int $owner_uid    (Optional)  The user ID of the user whose photo
1075    *                          you are tagging. If this parameter is not
1076    *                          specified, then it defaults to the session user.
1077    *
1078    * @return bool  true on success
1079    */
1080   public function &photos_addTag($pid,
1081                                  $tag_uid,
1082                                  $tag_text,
1083                                  $x,
1084                                  $y,
1085                                  $tags,
1086                                  $owner_uid=0) {
1087     return $this->call_method('facebook.photos.addTag',
1088         array('pid' => $pid,
1089               'tag_uid' => $tag_uid,
1090               'tag_text' => $tag_text,
1091               'x' => $x,
1092               'y' => $y,
1093               'tags' => json_encode($tags),
1094               'owner_uid' => $this->get_uid($owner_uid)));
1095   }
1096
1097   /**
1098    * Creates and returns a new album owned by the specified user or the current
1099    * session user.
1100    *
1101    * @param string $name         The name of the album.
1102    * @param string $description  (Optional) A description of the album.
1103    * @param string $location     (Optional) A description of the location.
1104    * @param string $visible      (Optional) A privacy setting for the album.
1105    *                             One of 'friends', 'friends-of-friends',
1106    *                             'networks', or 'everyone'.  Default 'everyone'.
1107    * @param int $uid             (Optional) User id for creating the album; if
1108    *                             not specified, the session user is used.
1109    *
1110    * @return array  An album object
1111    */
1112   public function &photos_createAlbum($name,
1113                                       $description='',
1114                                       $location='',
1115                                       $visible='',
1116                                       $uid=0) {
1117     return $this->call_method('facebook.photos.createAlbum',
1118         array('name' => $name,
1119               'description' => $description,
1120               'location' => $location,
1121               'visible' => $visible,
1122               'uid' => $this->get_uid($uid)));
1123   }
1124
1125   /**
1126    * Returns photos according to the filters specified.
1127    *
1128    * @param int $subj_id  (Optional) Filter by uid of user tagged in the photos.
1129    * @param int $aid      (Optional) Filter by an album, as returned by
1130    *                      photos_getAlbums.
1131    * @param array $pids   (Optional) Restrict to a list of pids
1132    *
1133    * Note that at least one of these parameters needs to be specified, or an
1134    * error is returned.
1135    *
1136    * @return array  An array of photo objects.
1137    */
1138   public function &photos_get($subj_id, $aid, $pids) {
1139     return $this->call_method('facebook.photos.get',
1140       array('subj_id' => $subj_id, 'aid' => $aid, 'pids' => $pids));
1141   }
1142
1143   /**
1144    * Returns the albums created by the given user.
1145    *
1146    * @param int $uid     (Optional) The uid of the user whose albums you want.
1147    *                     A null will return the albums of the session user.
1148    * @param array $aids  (Optional) A list of aids to restrict the query.
1149    *
1150    * Note that at least one of the (uid, aids) parameters must be specified.
1151    *
1152    * @returns an array of album objects.
1153    */
1154   public function &photos_getAlbums($uid, $aids) {
1155     return $this->call_method('facebook.photos.getAlbums',
1156       array('uid' => $uid,
1157             'aids' => $aids));
1158   }
1159
1160   /**
1161    * Returns the tags on all photos specified.
1162    *
1163    * @param string $pids  A list of pids to query
1164    *
1165    * @return array  An array of photo tag objects, which include pid,
1166    *                subject uid, and two floating-point numbers (xcoord, ycoord)
1167    *                for tag pixel location.
1168    */
1169   public function &photos_getTags($pids) {
1170     return $this->call_method('facebook.photos.getTags',
1171       array('pids' => $pids));
1172   }
1173
1174   /**
1175    * Returns the requested info fields for the requested set of users.
1176    *
1177    * @param array $uids    An array of user ids
1178    * @param array $fields  An array of info field names desired
1179    *
1180    * @return array  An array of user objects
1181    */
1182   public function &users_getInfo($uids, $fields) {
1183     return $this->call_method('facebook.users.getInfo',
1184         array('uids' => $uids, 'fields' => $fields));
1185   }
1186
1187   /**
1188    * Returns the requested info fields for the requested set of users. A
1189    * session key must not be specified. Only data about users that have
1190    * authorized your application will be returned.
1191    *
1192    * Check the wiki for fields that can be queried through this API call.
1193    * Data returned from here should not be used for rendering to application
1194    * users, use users.getInfo instead, so that proper privacy rules will be
1195    * applied.
1196    *
1197    * @param array $uids    An array of user ids
1198    * @param array $fields  An array of info field names desired
1199    *
1200    * @return array  An array of user objects
1201    */
1202   public function &users_getStandardInfo($uids, $fields) {
1203     return $this->call_method('facebook.users.getStandardInfo',
1204         array('uids' => $uids, 'fields' => $fields));
1205   }
1206
1207   /**
1208    * Returns the user corresponding to the current session object.
1209    *
1210    * @return integer  User id
1211    */
1212   public function &users_getLoggedInUser() {
1213     return $this->call_method('facebook.users.getLoggedInUser', array());
1214   }
1215
1216   /**
1217    * Returns 1 if the user has the specified permission, 0 otherwise.
1218    * http://wiki.developers.facebook.com/index.php/Users.hasAppPermission
1219    *
1220    * @return integer  1 or 0
1221    */
1222   public function &users_hasAppPermission($ext_perm, $uid=null) {
1223     return $this->call_method('facebook.users.hasAppPermission',
1224         array('ext_perm' => $ext_perm, 'uid' => $uid));
1225   }
1226
1227   /**
1228    * Returns whether or not the user corresponding to the current
1229    * session object has the give the app basic authorization.
1230    *
1231    * @return boolean  true if the user has authorized the app
1232    */
1233   public function &users_isAppUser($uid=null) {
1234     if ($uid === null && isset($this->is_user)) {
1235       return $this->is_user;
1236     }
1237
1238     return $this->call_method('facebook.users.isAppUser', array('uid' => $uid));
1239   }
1240
1241   /**
1242    * Sets the users' current status message. Message does NOT contain the
1243    * word "is" , so make sure to include a verb.
1244    *
1245    * Example: setStatus("is loving the API!")
1246    * will produce the status "Luke is loving the API!"
1247    *
1248    * @param string $status                text-only message to set
1249    * @param int    $uid                   user to set for (defaults to the
1250    *                                      logged-in user)
1251    * @param bool   $clear                 whether or not to clear the status,
1252    *                                      instead of setting it
1253    * @param bool   $status_includes_verb  if true, the word "is" will *not* be
1254    *                                      prepended to the status message
1255    *
1256    * @return boolean
1257    */
1258   public function &users_setStatus($status,
1259                                    $uid = null,
1260                                    $clear = false,
1261                                    $status_includes_verb = true) {
1262     $args = array(
1263       'status' => $status,
1264       'uid' => $uid,
1265       'clear' => $clear,
1266       'status_includes_verb' => $status_includes_verb,
1267     );
1268     return $this->call_method('facebook.users.setStatus', $args);
1269   }
1270
1271   /**
1272    * Sets the FBML for the profile of the user attached to this session.
1273    *
1274    * @param   string   $markup           The FBML that describes the profile
1275    *                                     presence of this app for the user
1276    * @param   int      $uid              The user
1277    * @param   string   $profile          Profile FBML
1278    * @param   string   $profile_action   Profile action FBML (deprecated)
1279    * @param   string   $mobile_profile   Mobile profile FBML
1280    * @param   string   $profile_main     Main Tab profile FBML
1281    *
1282    * @return  array  A list of strings describing any compile errors for the
1283    *                 submitted FBML
1284    */
1285   function profile_setFBML($markup,
1286                            $uid=null,
1287                            $profile='',
1288                            $profile_action='',
1289                            $mobile_profile='',
1290                            $profile_main='') {
1291     return $this->call_method('facebook.profile.setFBML',
1292         array('markup' => $markup,
1293               'uid' => $uid,
1294               'profile' => $profile,
1295               'profile_action' => $profile_action,
1296               'mobile_profile' => $mobile_profile,
1297               'profile_main' => $profile_main));
1298   }
1299
1300   /**
1301    * Gets the FBML for the profile box that is currently set for a user's
1302    * profile (your application set the FBML previously by calling the
1303    * profile.setFBML method).
1304    *
1305    * @param int $uid   (Optional) User id to lookup; defaults to session.
1306    * @param int $type  (Optional) 1 for original style, 2 for profile_main boxes
1307    *
1308    * @return string  The FBML
1309    */
1310   public function &profile_getFBML($uid=null, $type=null) {
1311     return $this->call_method('facebook.profile.getFBML',
1312         array('uid' => $uid,
1313               'type' => $type));
1314   }
1315
1316   /**
1317    * Returns the specified user's application info section for the calling
1318    * application. These info sections have either been set via a previous
1319    * profile.setInfo call or by the user editing them directly.
1320    *
1321    * @param int $uid  (Optional) User id to lookup; defaults to session.
1322    *
1323    * @return array  Info fields for the current user.  See wiki for structure:
1324    *
1325    *  http://wiki.developers.facebook.com/index.php/Profile.getInfo
1326    *
1327    */
1328   public function &profile_getInfo($uid=null) {
1329     return $this->call_method('facebook.profile.getInfo',
1330         array('uid' => $uid));
1331   }
1332
1333   /**
1334    * Returns the options associated with the specified info field for an
1335    * application info section.
1336    *
1337    * @param string $field  The title of the field
1338    *
1339    * @return array  An array of info options.
1340    */
1341   public function &profile_getInfoOptions($field) {
1342     return $this->call_method('facebook.profile.getInfoOptions',
1343         array('field' => $field));
1344   }
1345
1346   /**
1347    * Configures an application info section that the specified user can install
1348    * on the Info tab of her profile.  For details on the structure of an info
1349    * field, please see:
1350    *
1351    *  http://wiki.developers.facebook.com/index.php/Profile.setInfo
1352    *
1353    * @param string $title       Title / header of the info section
1354    * @param int $type           1 for text-only, 5 for thumbnail views
1355    * @param array $info_fields  An array of info fields. See wiki for details.
1356    * @param int $uid            (Optional)
1357    *
1358    * @return bool  true on success
1359    */
1360   public function &profile_setInfo($title, $type, $info_fields, $uid=null) {
1361     return $this->call_method('facebook.profile.setInfo',
1362         array('uid' => $uid,
1363               'type' => $type,
1364               'title'   => $title,
1365               'info_fields' => json_encode($info_fields)));
1366   }
1367
1368   /**
1369    * Specifies the objects for a field for an application info section. These
1370    * options populate the typeahead for a thumbnail.
1371    *
1372    * @param string $field   The title of the field
1373    * @param array $options  An array of items for a thumbnail, including
1374    *                        'label', 'link', and optionally 'image',
1375    *                        'description' and 'sublabel'
1376    *
1377    * @return bool  true on success
1378    */
1379   public function profile_setInfoOptions($field, $options) {
1380     return $this->call_method('facebook.profile.setInfoOptions',
1381         array('field'   => $field,
1382               'options' => json_encode($options)));
1383   }
1384
1385   /**
1386    * Get all the marketplace categories.
1387    *
1388    * @return array  A list of category names
1389    */
1390   function marketplace_getCategories() {
1391     return $this->call_method('facebook.marketplace.getCategories',
1392         array());
1393   }
1394
1395   /**
1396    * Get all the marketplace subcategories for a particular category.
1397    *
1398    * @param  category  The category for which we are pulling subcategories
1399    *
1400    * @return array A list of subcategory names
1401    */
1402   function marketplace_getSubCategories($category) {
1403     return $this->call_method('facebook.marketplace.getSubCategories',
1404         array('category' => $category));
1405   }
1406
1407   /**
1408    * Get listings by either listing_id or user.
1409    *
1410    * @param listing_ids   An array of listing_ids (optional)
1411    * @param uids          An array of user ids (optional)
1412    *
1413    * @return array  The data for matched listings
1414    */
1415   function marketplace_getListings($listing_ids, $uids) {
1416     return $this->call_method('facebook.marketplace.getListings',
1417         array('listing_ids' => $listing_ids, 'uids' => $uids));
1418   }
1419
1420   /**
1421    * Search for Marketplace listings.  All arguments are optional, though at
1422    * least one must be filled out to retrieve results.
1423    *
1424    * @param category     The category in which to search (optional)
1425    * @param subcategory  The subcategory in which to search (optional)
1426    * @param query        A query string (optional)
1427    *
1428    * @return array  The data for matched listings
1429    */
1430   function marketplace_search($category, $subcategory, $query) {
1431     return $this->call_method('facebook.marketplace.search',
1432         array('category' => $category,
1433               'subcategory' => $subcategory,
1434               'query' => $query));
1435   }
1436
1437   /**
1438    * Remove a listing from Marketplace.
1439    *
1440    * @param listing_id  The id of the listing to be removed
1441    * @param status      'SUCCESS', 'NOT_SUCCESS', or 'DEFAULT'
1442    *
1443    * @return bool  True on success
1444    */
1445   function marketplace_removeListing($listing_id,
1446                                      $status='DEFAULT',
1447                                      $uid=null) {
1448     return $this->call_method('facebook.marketplace.removeListing',
1449         array('listing_id' => $listing_id,
1450               'status' => $status,
1451               'uid' => $uid));
1452   }
1453
1454   /**
1455    * Create/modify a Marketplace listing for the loggedinuser.
1456    *
1457    * @param int              listing_id  The id of a listing to be modified, 0
1458    *                                     for a new listing.
1459    * @param show_on_profile  bool        Should we show this listing on the
1460    *                                     user's profile
1461    * @param listing_attrs    array       An array of the listing data
1462    *
1463    * @return int  The listing_id (unchanged if modifying an existing listing).
1464    */
1465   function marketplace_createListing($listing_id,
1466                                      $show_on_profile,
1467                                      $attrs,
1468                                      $uid=null) {
1469     return $this->call_method('facebook.marketplace.createListing',
1470         array('listing_id' => $listing_id,
1471               'show_on_profile' => $show_on_profile,
1472               'listing_attrs' => json_encode($attrs),
1473               'uid' => $uid));
1474   }
1475
1476   /////////////////////////////////////////////////////////////////////////////
1477   // Data Store API
1478
1479   /**
1480    * Set a user preference.
1481    *
1482    * @param  pref_id    preference identifier (0-200)
1483    * @param  value      preferece's value
1484    * @param  uid        the user id (defaults to current session user)
1485    * @error
1486    *    API_EC_DATA_DATABASE_ERROR
1487    *    API_EC_PARAM
1488    *    API_EC_DATA_QUOTA_EXCEEDED
1489    *    API_EC_DATA_UNKNOWN_ERROR
1490    *    API_EC_PERMISSION_OTHER_USER
1491    */
1492   public function &data_setUserPreference($pref_id, $value, $uid = null) {
1493     return $this->call_method('facebook.data.setUserPreference',
1494        array('pref_id' => $pref_id,
1495              'value' => $value,
1496              'uid' => $this->get_uid($uid)));
1497   }
1498
1499   /**
1500    * Set a user's all preferences for this application.
1501    *
1502    * @param  values     preferece values in an associative arrays
1503    * @param  replace    whether to replace all existing preferences or
1504    *                    merge into them.
1505    * @param  uid        the user id (defaults to current session user)
1506    * @error
1507    *    API_EC_DATA_DATABASE_ERROR
1508    *    API_EC_PARAM
1509    *    API_EC_DATA_QUOTA_EXCEEDED
1510    *    API_EC_DATA_UNKNOWN_ERROR
1511    *    API_EC_PERMISSION_OTHER_USER
1512    */
1513   public function &data_setUserPreferences($values,
1514                                            $replace = false,
1515                                            $uid = null) {
1516     return $this->call_method('facebook.data.setUserPreferences',
1517        array('values' => json_encode($values),
1518              'replace' => $replace,
1519              'uid' => $this->get_uid($uid)));
1520   }
1521
1522   /**
1523    * Get a user preference.
1524    *
1525    * @param  pref_id    preference identifier (0-200)
1526    * @param  uid        the user id (defaults to current session user)
1527    * @return            preference's value
1528    * @error
1529    *    API_EC_DATA_DATABASE_ERROR
1530    *    API_EC_PARAM
1531    *    API_EC_DATA_QUOTA_EXCEEDED
1532    *    API_EC_DATA_UNKNOWN_ERROR
1533    *    API_EC_PERMISSION_OTHER_USER
1534    */
1535   public function &data_getUserPreference($pref_id, $uid = null) {
1536     return $this->call_method('facebook.data.getUserPreference',
1537        array('pref_id' => $pref_id,
1538              'uid' => $this->get_uid($uid)));
1539   }
1540
1541   /**
1542    * Get a user preference.
1543    *
1544    * @param  uid        the user id (defaults to current session user)
1545    * @return            preference values
1546    * @error
1547    *    API_EC_DATA_DATABASE_ERROR
1548    *    API_EC_DATA_QUOTA_EXCEEDED
1549    *    API_EC_DATA_UNKNOWN_ERROR
1550    *    API_EC_PERMISSION_OTHER_USER
1551    */
1552   public function &data_getUserPreferences($uid = null) {
1553     return $this->call_method('facebook.data.getUserPreferences',
1554        array('uid' => $this->get_uid($uid)));
1555   }
1556
1557   /**
1558    * Create a new object type.
1559    *
1560    * @param  name       object type's name
1561    * @error
1562    *    API_EC_DATA_DATABASE_ERROR
1563    *    API_EC_DATA_OBJECT_ALREADY_EXISTS
1564    *    API_EC_PARAM
1565    *    API_EC_PERMISSION
1566    *    API_EC_DATA_INVALID_OPERATION
1567    *    API_EC_DATA_QUOTA_EXCEEDED
1568    *    API_EC_DATA_UNKNOWN_ERROR
1569    */
1570   public function &data_createObjectType($name) {
1571     return $this->call_method('facebook.data.createObjectType',
1572        array('name' => $name));
1573   }
1574
1575   /**
1576    * Delete an object type.
1577    *
1578    * @param  obj_type       object type's name
1579    * @error
1580    *    API_EC_DATA_DATABASE_ERROR
1581    *    API_EC_DATA_OBJECT_NOT_FOUND
1582    *    API_EC_PARAM
1583    *    API_EC_PERMISSION
1584    *    API_EC_DATA_INVALID_OPERATION
1585    *    API_EC_DATA_QUOTA_EXCEEDED
1586    *    API_EC_DATA_UNKNOWN_ERROR
1587    */
1588   public function &data_dropObjectType($obj_type) {
1589     return $this->call_method('facebook.data.dropObjectType',
1590        array('obj_type' => $obj_type));
1591   }
1592
1593   /**
1594    * Rename an object type.
1595    *
1596    * @param  obj_type       object type's name
1597    * @param  new_name       new object type's name
1598    * @error
1599    *    API_EC_DATA_DATABASE_ERROR
1600    *    API_EC_DATA_OBJECT_NOT_FOUND
1601    *    API_EC_DATA_OBJECT_ALREADY_EXISTS
1602    *    API_EC_PARAM
1603    *    API_EC_PERMISSION
1604    *    API_EC_DATA_INVALID_OPERATION
1605    *    API_EC_DATA_QUOTA_EXCEEDED
1606    *    API_EC_DATA_UNKNOWN_ERROR
1607    */
1608   public function &data_renameObjectType($obj_type, $new_name) {
1609     return $this->call_method('facebook.data.renameObjectType',
1610        array('obj_type' => $obj_type,
1611              'new_name' => $new_name));
1612   }
1613
1614   /**
1615    * Add a new property to an object type.
1616    *
1617    * @param  obj_type       object type's name
1618    * @param  prop_name      name of the property to add
1619    * @param  prop_type      1: integer; 2: string; 3: text blob
1620    * @error
1621    *    API_EC_DATA_DATABASE_ERROR
1622    *    API_EC_DATA_OBJECT_ALREADY_EXISTS
1623    *    API_EC_PARAM
1624    *    API_EC_PERMISSION
1625    *    API_EC_DATA_INVALID_OPERATION
1626    *    API_EC_DATA_QUOTA_EXCEEDED
1627    *    API_EC_DATA_UNKNOWN_ERROR
1628    */
1629   public function &data_defineObjectProperty($obj_type,
1630                                              $prop_name,
1631                                              $prop_type) {
1632     return $this->call_method('facebook.data.defineObjectProperty',
1633        array('obj_type' => $obj_type,
1634              'prop_name' => $prop_name,
1635              'prop_type' => $prop_type));
1636   }
1637
1638   /**
1639    * Remove a previously defined property from an object type.
1640    *
1641    * @param  obj_type      object type's name
1642    * @param  prop_name     name of the property to remove
1643    * @error
1644    *    API_EC_DATA_DATABASE_ERROR
1645    *    API_EC_DATA_OBJECT_NOT_FOUND
1646    *    API_EC_PARAM
1647    *    API_EC_PERMISSION
1648    *    API_EC_DATA_INVALID_OPERATION
1649    *    API_EC_DATA_QUOTA_EXCEEDED
1650    *    API_EC_DATA_UNKNOWN_ERROR
1651    */
1652   public function &data_undefineObjectProperty($obj_type, $prop_name) {
1653     return $this->call_method('facebook.data.undefineObjectProperty',
1654        array('obj_type' => $obj_type,
1655              'prop_name' => $prop_name));
1656   }
1657
1658   /**
1659    * Rename a previously defined property of an object type.
1660    *
1661    * @param  obj_type      object type's name
1662    * @param  prop_name     name of the property to rename
1663    * @param  new_name      new name to use
1664    * @error
1665    *    API_EC_DATA_DATABASE_ERROR
1666    *    API_EC_DATA_OBJECT_NOT_FOUND
1667    *    API_EC_DATA_OBJECT_ALREADY_EXISTS
1668    *    API_EC_PARAM
1669    *    API_EC_PERMISSION
1670    *    API_EC_DATA_INVALID_OPERATION
1671    *    API_EC_DATA_QUOTA_EXCEEDED
1672    *    API_EC_DATA_UNKNOWN_ERROR
1673    */
1674   public function &data_renameObjectProperty($obj_type, $prop_name,
1675                                             $new_name) {
1676     return $this->call_method('facebook.data.renameObjectProperty',
1677        array('obj_type' => $obj_type,
1678              'prop_name' => $prop_name,
1679              'new_name' => $new_name));
1680   }
1681
1682   /**
1683    * Retrieve a list of all object types that have defined for the application.
1684    *
1685    * @return               a list of object type names
1686    * @error
1687    *    API_EC_DATA_DATABASE_ERROR
1688    *    API_EC_PERMISSION
1689    *    API_EC_DATA_QUOTA_EXCEEDED
1690    *    API_EC_DATA_UNKNOWN_ERROR
1691    */
1692   public function &data_getObjectTypes() {
1693     return $this->call_method('facebook.data.getObjectTypes', array());
1694   }
1695
1696   /**
1697    * Get definitions of all properties of an object type.
1698    *
1699    * @param obj_type       object type's name
1700    * @return               pairs of property name and property types
1701    * @error
1702    *    API_EC_DATA_DATABASE_ERROR
1703    *    API_EC_PARAM
1704    *    API_EC_PERMISSION
1705    *    API_EC_DATA_OBJECT_NOT_FOUND
1706    *    API_EC_DATA_QUOTA_EXCEEDED
1707    *    API_EC_DATA_UNKNOWN_ERROR
1708    */
1709   public function &data_getObjectType($obj_type) {
1710     return $this->call_method('facebook.data.getObjectType',
1711        array('obj_type' => $obj_type));
1712   }
1713
1714   /**
1715    * Create a new object.
1716    *
1717    * @param  obj_type      object type's name
1718    * @param  properties    (optional) properties to set initially
1719    * @return               newly created object's id
1720    * @error
1721    *    API_EC_DATA_DATABASE_ERROR
1722    *    API_EC_PARAM
1723    *    API_EC_PERMISSION
1724    *    API_EC_DATA_INVALID_OPERATION
1725    *    API_EC_DATA_QUOTA_EXCEEDED
1726    *    API_EC_DATA_UNKNOWN_ERROR
1727    */
1728   public function &data_createObject($obj_type, $properties = null) {
1729     return $this->call_method('facebook.data.createObject',
1730        array('obj_type' => $obj_type,
1731              'properties' => json_encode($properties)));
1732   }
1733
1734   /**
1735    * Update an existing object.
1736    *
1737    * @param  obj_id        object's id
1738    * @param  properties    new properties
1739    * @param  replace       true for replacing existing properties;
1740    *                       false for merging
1741    * @error
1742    *    API_EC_DATA_DATABASE_ERROR
1743    *    API_EC_DATA_OBJECT_NOT_FOUND
1744    *    API_EC_PARAM
1745    *    API_EC_PERMISSION
1746    *    API_EC_DATA_INVALID_OPERATION
1747    *    API_EC_DATA_QUOTA_EXCEEDED
1748    *    API_EC_DATA_UNKNOWN_ERROR
1749    */
1750   public function &data_updateObject($obj_id, $properties, $replace = false) {
1751     return $this->call_method('facebook.data.updateObject',
1752        array('obj_id' => $obj_id,
1753              'properties' => json_encode($properties),
1754              'replace' => $replace));
1755   }
1756
1757   /**
1758    * Delete an existing object.
1759    *
1760    * @param  obj_id        object's id
1761    * @error
1762    *    API_EC_DATA_DATABASE_ERROR
1763    *    API_EC_DATA_OBJECT_NOT_FOUND
1764    *    API_EC_PARAM
1765    *    API_EC_PERMISSION
1766    *    API_EC_DATA_INVALID_OPERATION
1767    *    API_EC_DATA_QUOTA_EXCEEDED
1768    *    API_EC_DATA_UNKNOWN_ERROR
1769    */
1770   public function &data_deleteObject($obj_id) {
1771     return $this->call_method('facebook.data.deleteObject',
1772        array('obj_id' => $obj_id));
1773   }
1774
1775   /**
1776    * Delete a list of objects.
1777    *
1778    * @param  obj_ids       objects to delete
1779    * @error
1780    *    API_EC_DATA_DATABASE_ERROR
1781    *    API_EC_PARAM
1782    *    API_EC_PERMISSION
1783    *    API_EC_DATA_INVALID_OPERATION
1784    *    API_EC_DATA_QUOTA_EXCEEDED
1785    *    API_EC_DATA_UNKNOWN_ERROR
1786    */
1787   public function &data_deleteObjects($obj_ids) {
1788     return $this->call_method('facebook.data.deleteObjects',
1789        array('obj_ids' => json_encode($obj_ids)));
1790   }
1791
1792   /**
1793    * Get a single property value of an object.
1794    *
1795    * @param  obj_id        object's id
1796    * @param  prop_name     individual property's name
1797    * @return               individual property's value
1798    * @error
1799    *    API_EC_DATA_DATABASE_ERROR
1800    *    API_EC_DATA_OBJECT_NOT_FOUND
1801    *    API_EC_PARAM
1802    *    API_EC_PERMISSION
1803    *    API_EC_DATA_INVALID_OPERATION
1804    *    API_EC_DATA_QUOTA_EXCEEDED
1805    *    API_EC_DATA_UNKNOWN_ERROR
1806    */
1807   public function &data_getObjectProperty($obj_id, $prop_name) {
1808     return $this->call_method('facebook.data.getObjectProperty',
1809        array('obj_id' => $obj_id,
1810              'prop_name' => $prop_name));
1811   }
1812
1813   /**
1814    * Get properties of an object.
1815    *
1816    * @param  obj_id      object's id
1817    * @param  prop_names  (optional) properties to return; null for all.
1818    * @return             specified properties of an object
1819    * @error
1820    *    API_EC_DATA_DATABASE_ERROR
1821    *    API_EC_DATA_OBJECT_NOT_FOUND
1822    *    API_EC_PARAM
1823    *    API_EC_PERMISSION
1824    *    API_EC_DATA_INVALID_OPERATION
1825    *    API_EC_DATA_QUOTA_EXCEEDED
1826    *    API_EC_DATA_UNKNOWN_ERROR
1827    */
1828   public function &data_getObject($obj_id, $prop_names = null) {
1829     return $this->call_method('facebook.data.getObject',
1830        array('obj_id' => $obj_id,
1831              'prop_names' => json_encode($prop_names)));
1832   }
1833
1834   /**
1835    * Get properties of a list of objects.
1836    *
1837    * @param  obj_ids     object ids
1838    * @param  prop_names  (optional) properties to return; null for all.
1839    * @return             specified properties of an object
1840    * @error
1841    *    API_EC_DATA_DATABASE_ERROR
1842    *    API_EC_DATA_OBJECT_NOT_FOUND
1843    *    API_EC_PARAM
1844    *    API_EC_PERMISSION
1845    *    API_EC_DATA_INVALID_OPERATION
1846    *    API_EC_DATA_QUOTA_EXCEEDED
1847    *    API_EC_DATA_UNKNOWN_ERROR
1848    */
1849   public function &data_getObjects($obj_ids, $prop_names = null) {
1850     return $this->call_method('facebook.data.getObjects',
1851        array('obj_ids' => json_encode($obj_ids),
1852              'prop_names' => json_encode($prop_names)));
1853   }
1854
1855   /**
1856    * Set a single property value of an object.
1857    *
1858    * @param  obj_id        object's id
1859    * @param  prop_name     individual property's name
1860    * @param  prop_value    new value to set
1861    * @error
1862    *    API_EC_DATA_DATABASE_ERROR
1863    *    API_EC_DATA_OBJECT_NOT_FOUND
1864    *    API_EC_PARAM
1865    *    API_EC_PERMISSION
1866    *    API_EC_DATA_INVALID_OPERATION
1867    *    API_EC_DATA_QUOTA_EXCEEDED
1868    *    API_EC_DATA_UNKNOWN_ERROR
1869    */
1870   public function &data_setObjectProperty($obj_id, $prop_name,
1871                                          $prop_value) {
1872     return $this->call_method('facebook.data.setObjectProperty',
1873        array('obj_id' => $obj_id,
1874              'prop_name' => $prop_name,
1875              'prop_value' => $prop_value));
1876   }
1877
1878   /**
1879    * Read hash value by key.
1880    *
1881    * @param  obj_type      object type's name
1882    * @param  key           hash key
1883    * @param  prop_name     (optional) individual property's name
1884    * @return               hash value
1885    * @error
1886    *    API_EC_DATA_DATABASE_ERROR
1887    *    API_EC_PARAM
1888    *    API_EC_PERMISSION
1889    *    API_EC_DATA_INVALID_OPERATION
1890    *    API_EC_DATA_QUOTA_EXCEEDED
1891    *    API_EC_DATA_UNKNOWN_ERROR
1892    */
1893   public function &data_getHashValue($obj_type, $key, $prop_name = null) {
1894     return $this->call_method('facebook.data.getHashValue',
1895        array('obj_type' => $obj_type,
1896              'key' => $key,
1897              'prop_name' => $prop_name));
1898   }
1899
1900   /**
1901    * Write hash value by key.
1902    *
1903    * @param  obj_type      object type's name
1904    * @param  key           hash key
1905    * @param  value         hash value
1906    * @param  prop_name     (optional) individual property's name
1907    * @error
1908    *    API_EC_DATA_DATABASE_ERROR
1909    *    API_EC_PARAM
1910    *    API_EC_PERMISSION
1911    *    API_EC_DATA_INVALID_OPERATION
1912    *    API_EC_DATA_QUOTA_EXCEEDED
1913    *    API_EC_DATA_UNKNOWN_ERROR
1914    */
1915   public function &data_setHashValue($obj_type,
1916                                      $key,
1917                                      $value,
1918                                      $prop_name = null) {
1919     return $this->call_method('facebook.data.setHashValue',
1920        array('obj_type' => $obj_type,
1921              'key' => $key,
1922              'value' => $value,
1923              'prop_name' => $prop_name));
1924   }
1925
1926   /**
1927    * Increase a hash value by specified increment atomically.
1928    *
1929    * @param  obj_type      object type's name
1930    * @param  key           hash key
1931    * @param  prop_name     individual property's name
1932    * @param  increment     (optional) default is 1
1933    * @return               incremented hash value
1934    * @error
1935    *    API_EC_DATA_DATABASE_ERROR
1936    *    API_EC_PARAM
1937    *    API_EC_PERMISSION
1938    *    API_EC_DATA_INVALID_OPERATION
1939    *    API_EC_DATA_QUOTA_EXCEEDED
1940    *    API_EC_DATA_UNKNOWN_ERROR
1941    */
1942   public function &data_incHashValue($obj_type,
1943                                      $key,
1944                                      $prop_name,
1945                                      $increment = 1) {
1946     return $this->call_method('facebook.data.incHashValue',
1947        array('obj_type' => $obj_type,
1948              'key' => $key,
1949              'prop_name' => $prop_name,
1950              'increment' => $increment));
1951   }
1952
1953   /**
1954    * Remove a hash key and its values.
1955    *
1956    * @param  obj_type    object type's name
1957    * @param  key         hash key
1958    * @error
1959    *    API_EC_DATA_DATABASE_ERROR
1960    *    API_EC_PARAM
1961    *    API_EC_PERMISSION
1962    *    API_EC_DATA_INVALID_OPERATION
1963    *    API_EC_DATA_QUOTA_EXCEEDED
1964    *    API_EC_DATA_UNKNOWN_ERROR
1965    */
1966   public function &data_removeHashKey($obj_type, $key) {
1967     return $this->call_method('facebook.data.removeHashKey',
1968        array('obj_type' => $obj_type,
1969              'key' => $key));
1970   }
1971
1972   /**
1973    * Remove hash keys and their values.
1974    *
1975    * @param  obj_type    object type's name
1976    * @param  keys        hash keys
1977    * @error
1978    *    API_EC_DATA_DATABASE_ERROR
1979    *    API_EC_PARAM
1980    *    API_EC_PERMISSION
1981    *    API_EC_DATA_INVALID_OPERATION
1982    *    API_EC_DATA_QUOTA_EXCEEDED
1983    *    API_EC_DATA_UNKNOWN_ERROR
1984    */
1985   public function &data_removeHashKeys($obj_type, $keys) {
1986     return $this->call_method('facebook.data.removeHashKeys',
1987        array('obj_type' => $obj_type,
1988              'keys' => json_encode($keys)));
1989   }
1990
1991   /**
1992    * Define an object association.
1993    *
1994    * @param  name        name of this association
1995    * @param  assoc_type  1: one-way 2: two-way symmetric 3: two-way asymmetric
1996    * @param  assoc_info1 needed info about first object type
1997    * @param  assoc_info2 needed info about second object type
1998    * @param  inverse     (optional) name of reverse association
1999    * @error
2000    *    API_EC_DATA_DATABASE_ERROR
2001    *    API_EC_DATA_OBJECT_ALREADY_EXISTS
2002    *    API_EC_PARAM
2003    *    API_EC_PERMISSION
2004    *    API_EC_DATA_INVALID_OPERATION
2005    *    API_EC_DATA_QUOTA_EXCEEDED
2006    *    API_EC_DATA_UNKNOWN_ERROR
2007    */
2008   public function &data_defineAssociation($name, $assoc_type, $assoc_info1,
2009                                          $assoc_info2, $inverse = null) {
2010     return $this->call_method('facebook.data.defineAssociation',
2011        array('name' => $name,
2012              'assoc_type' => $assoc_type,
2013              'assoc_info1' => json_encode($assoc_info1),
2014              'assoc_info2' => json_encode($assoc_info2),
2015              'inverse' => $inverse));
2016   }
2017
2018   /**
2019    * Undefine an object association.
2020    *
2021    * @param  name        name of this association
2022    * @error
2023    *    API_EC_DATA_DATABASE_ERROR
2024    *    API_EC_DATA_OBJECT_NOT_FOUND
2025    *    API_EC_PARAM
2026    *    API_EC_PERMISSION
2027    *    API_EC_DATA_INVALID_OPERATION
2028    *    API_EC_DATA_QUOTA_EXCEEDED
2029    *    API_EC_DATA_UNKNOWN_ERROR
2030    */
2031   public function &data_undefineAssociation($name) {
2032     return $this->call_method('facebook.data.undefineAssociation',
2033        array('name' => $name));
2034   }
2035
2036   /**
2037    * Rename an object association or aliases.
2038    *
2039    * @param  name        name of this association
2040    * @param  new_name    (optional) new name of this association
2041    * @param  new_alias1  (optional) new alias for object type 1
2042    * @param  new_alias2  (optional) new alias for object type 2
2043    * @error
2044    *    API_EC_DATA_DATABASE_ERROR
2045    *    API_EC_DATA_OBJECT_ALREADY_EXISTS
2046    *    API_EC_DATA_OBJECT_NOT_FOUND
2047    *    API_EC_PARAM
2048    *    API_EC_PERMISSION
2049    *    API_EC_DATA_INVALID_OPERATION
2050    *    API_EC_DATA_QUOTA_EXCEEDED
2051    *    API_EC_DATA_UNKNOWN_ERROR
2052    */
2053   public function &data_renameAssociation($name, $new_name, $new_alias1 = null,
2054                                          $new_alias2 = null) {
2055     return $this->call_method('facebook.data.renameAssociation',
2056        array('name' => $name,
2057              'new_name' => $new_name,
2058              'new_alias1' => $new_alias1,
2059              'new_alias2' => $new_alias2));
2060   }
2061
2062   /**
2063    * Get definition of an object association.
2064    *
2065    * @param  name        name of this association
2066    * @return             specified association
2067    * @error
2068    *    API_EC_DATA_DATABASE_ERROR
2069    *    API_EC_DATA_OBJECT_NOT_FOUND
2070    *    API_EC_PARAM
2071    *    API_EC_PERMISSION
2072    *    API_EC_DATA_QUOTA_EXCEEDED
2073    *    API_EC_DATA_UNKNOWN_ERROR
2074    */
2075   public function &data_getAssociationDefinition($name) {
2076     return $this->call_method('facebook.data.getAssociationDefinition',
2077        array('name' => $name));
2078   }
2079
2080   /**
2081    * Get definition of all associations.
2082    *
2083    * @return             all defined associations
2084    * @error
2085    *    API_EC_DATA_DATABASE_ERROR
2086    *    API_EC_PERMISSION
2087    *    API_EC_DATA_QUOTA_EXCEEDED
2088    *    API_EC_DATA_UNKNOWN_ERROR
2089    */
2090   public function &data_getAssociationDefinitions() {
2091     return $this->call_method('facebook.data.getAssociationDefinitions',
2092        array());
2093   }
2094
2095   /**
2096    * Create or modify an association between two objects.
2097    *
2098    * @param  name        name of association
2099    * @param  obj_id1     id of first object
2100    * @param  obj_id2     id of second object
2101    * @param  data        (optional) extra string data to store
2102    * @param  assoc_time  (optional) extra time data; default to creation time
2103    * @error
2104    *    API_EC_DATA_DATABASE_ERROR
2105    *    API_EC_PARAM
2106    *    API_EC_PERMISSION
2107    *    API_EC_DATA_INVALID_OPERATION
2108    *    API_EC_DATA_QUOTA_EXCEEDED
2109    *    API_EC_DATA_UNKNOWN_ERROR
2110    */
2111   public function &data_setAssociation($name, $obj_id1, $obj_id2, $data = null,
2112                                       $assoc_time = null) {
2113     return $this->call_method('facebook.data.setAssociation',
2114        array('name' => $name,
2115              'obj_id1' => $obj_id1,
2116              'obj_id2' => $obj_id2,
2117              'data' => $data,
2118              'assoc_time' => $assoc_time));
2119   }
2120
2121   /**
2122    * Create or modify associations between objects.
2123    *
2124    * @param  assocs      associations to set
2125    * @param  name        (optional) name of association
2126    * @error
2127    *    API_EC_DATA_DATABASE_ERROR
2128    *    API_EC_PARAM
2129    *    API_EC_PERMISSION
2130    *    API_EC_DATA_INVALID_OPERATION
2131    *    API_EC_DATA_QUOTA_EXCEEDED
2132    *    API_EC_DATA_UNKNOWN_ERROR
2133    */
2134   public function &data_setAssociations($assocs, $name = null) {
2135     return $this->call_method('facebook.data.setAssociations',
2136        array('assocs' => json_encode($assocs),
2137              'name' => $name));
2138   }
2139
2140   /**
2141    * Remove an association between two objects.
2142    *
2143    * @param  name        name of association
2144    * @param  obj_id1     id of first object
2145    * @param  obj_id2     id of second object
2146    * @error
2147    *    API_EC_DATA_DATABASE_ERROR
2148    *    API_EC_DATA_OBJECT_NOT_FOUND
2149    *    API_EC_PARAM
2150    *    API_EC_PERMISSION
2151    *    API_EC_DATA_QUOTA_EXCEEDED
2152    *    API_EC_DATA_UNKNOWN_ERROR
2153    */
2154   public function &data_removeAssociation($name, $obj_id1, $obj_id2) {
2155     return $this->call_method('facebook.data.removeAssociation',
2156        array('name' => $name,
2157              'obj_id1' => $obj_id1,
2158              'obj_id2' => $obj_id2));
2159   }
2160
2161   /**
2162    * Remove associations between objects by specifying pairs of object ids.
2163    *
2164    * @param  assocs      associations to remove
2165    * @param  name        (optional) name of association
2166    * @error
2167    *    API_EC_DATA_DATABASE_ERROR
2168    *    API_EC_DATA_OBJECT_NOT_FOUND
2169    *    API_EC_PARAM
2170    *    API_EC_PERMISSION
2171    *    API_EC_DATA_QUOTA_EXCEEDED
2172    *    API_EC_DATA_UNKNOWN_ERROR
2173    */
2174   public function &data_removeAssociations($assocs, $name = null) {
2175     return $this->call_method('facebook.data.removeAssociations',
2176        array('assocs' => json_encode($assocs),
2177              'name' => $name));
2178   }
2179
2180   /**
2181    * Remove associations between objects by specifying one object id.
2182    *
2183    * @param  name        name of association
2184    * @param  obj_id      who's association to remove
2185    * @error
2186    *    API_EC_DATA_DATABASE_ERROR
2187    *    API_EC_DATA_OBJECT_NOT_FOUND
2188    *    API_EC_PARAM
2189    *    API_EC_PERMISSION
2190    *    API_EC_DATA_INVALID_OPERATION
2191    *    API_EC_DATA_QUOTA_EXCEEDED
2192    *    API_EC_DATA_UNKNOWN_ERROR
2193    */
2194   public function &data_removeAssociatedObjects($name, $obj_id) {
2195     return $this->call_method('facebook.data.removeAssociatedObjects',
2196        array('name' => $name,
2197              'obj_id' => $obj_id));
2198   }
2199
2200   /**
2201    * Retrieve a list of associated objects.
2202    *
2203    * @param  name        name of association
2204    * @param  obj_id      who's association to retrieve
2205    * @param  no_data     only return object ids
2206    * @return             associated objects
2207    * @error
2208    *    API_EC_DATA_DATABASE_ERROR
2209    *    API_EC_DATA_OBJECT_NOT_FOUND
2210    *    API_EC_PARAM
2211    *    API_EC_PERMISSION
2212    *    API_EC_DATA_INVALID_OPERATION
2213    *    API_EC_DATA_QUOTA_EXCEEDED
2214    *    API_EC_DATA_UNKNOWN_ERROR
2215    */
2216   public function &data_getAssociatedObjects($name, $obj_id, $no_data = true) {
2217     return $this->call_method('facebook.data.getAssociatedObjects',
2218        array('name' => $name,
2219              'obj_id' => $obj_id,
2220              'no_data' => $no_data));
2221   }
2222
2223   /**
2224    * Count associated objects.
2225    *
2226    * @param  name        name of association
2227    * @param  obj_id      who's association to retrieve
2228    * @return             associated object's count
2229    * @error
2230    *    API_EC_DATA_DATABASE_ERROR
2231    *    API_EC_DATA_OBJECT_NOT_FOUND
2232    *    API_EC_PARAM
2233    *    API_EC_PERMISSION
2234    *    API_EC_DATA_INVALID_OPERATION
2235    *    API_EC_DATA_QUOTA_EXCEEDED
2236    *    API_EC_DATA_UNKNOWN_ERROR
2237    */
2238   public function &data_getAssociatedObjectCount($name, $obj_id) {
2239     return $this->call_method('facebook.data.getAssociatedObjectCount',
2240        array('name' => $name,
2241              'obj_id' => $obj_id));
2242   }
2243
2244   /**
2245    * Get a list of associated object counts.
2246    *
2247    * @param  name        name of association
2248    * @param  obj_ids     whose association to retrieve
2249    * @return             associated object counts
2250    * @error
2251    *    API_EC_DATA_DATABASE_ERROR
2252    *    API_EC_DATA_OBJECT_NOT_FOUND
2253    *    API_EC_PARAM
2254    *    API_EC_PERMISSION
2255    *    API_EC_DATA_INVALID_OPERATION
2256    *    API_EC_DATA_QUOTA_EXCEEDED
2257    *    API_EC_DATA_UNKNOWN_ERROR
2258    */
2259   public function &data_getAssociatedObjectCounts($name, $obj_ids) {
2260     return $this->call_method('facebook.data.getAssociatedObjectCounts',
2261        array('name' => $name,
2262              'obj_ids' => json_encode($obj_ids)));
2263   }
2264
2265   /**
2266    * Find all associations between two objects.
2267    *
2268    * @param  obj_id1     id of first object
2269    * @param  obj_id2     id of second object
2270    * @param  no_data     only return association names without data
2271    * @return             all associations between objects
2272    * @error
2273    *    API_EC_DATA_DATABASE_ERROR
2274    *    API_EC_PARAM
2275    *    API_EC_PERMISSION
2276    *    API_EC_DATA_QUOTA_EXCEEDED
2277    *    API_EC_DATA_UNKNOWN_ERROR
2278    */
2279   public function &data_getAssociations($obj_id1, $obj_id2, $no_data = true) {
2280     return $this->call_method('facebook.data.getAssociations',
2281        array('obj_id1' => $obj_id1,
2282              'obj_id2' => $obj_id2,
2283              'no_data' => $no_data));
2284   }
2285
2286   /**
2287    * Get the properties that you have set for an app.
2288    *
2289    * @param properties  List of properties names to fetch
2290    *
2291    * @return array  A map from property name to value
2292    */
2293   public function admin_getAppProperties($properties) {
2294     return json_decode(
2295         $this->call_method('facebook.admin.getAppProperties',
2296             array('properties' => json_encode($properties))), true);
2297   }
2298
2299   /**
2300    * Set properties for an app.
2301    *
2302    * @param properties  A map from property names to values
2303    *
2304    * @return bool  true on success
2305    */
2306   public function admin_setAppProperties($properties) {
2307     return $this->call_method('facebook.admin.setAppProperties',
2308        array('properties' => json_encode($properties)));
2309   }
2310
2311   /**
2312    * Returns the allocation limit value for a specified integration point name
2313    * Integration point names are defined in lib/api/karma/constants.php in the
2314    * limit_map.
2315    *
2316    * @param string $integration_point_name  Name of an integration point
2317    *                                        (see developer wiki for list).
2318    *
2319    * @return int  Integration point allocation value
2320    */
2321   public function &admin_getAllocation($integration_point_name) {
2322     return $this->call_method('facebook.admin.getAllocation',
2323         array('integration_point_name' => $integration_point_name));
2324   }
2325
2326   /**
2327    * Returns values for the specified metrics for the current application, in
2328    * the given time range.  The metrics are collected for fixed-length periods,
2329    * and the times represent midnight at the end of each period.
2330    *
2331    * @param start_time  unix time for the start of the range
2332    * @param end_time    unix time for the end of the range
2333    * @param period      number of seconds in the desired period
2334    * @param metrics     list of metrics to look up
2335    *
2336    * @return array  A map of the names and values for those metrics
2337    */
2338   public function &admin_getMetrics($start_time, $end_time, $period, $metrics) {
2339     return $this->call_method('admin.getMetrics',
2340         array('start_time' => $start_time,
2341               'end_time' => $end_time,
2342               'period' => $period,
2343               'metrics' => json_encode($metrics)));
2344   }
2345
2346   /**
2347    * Sets application restriction info.
2348    *
2349    * Applications can restrict themselves to only a limited user demographic
2350    * based on users' age and/or location or based on static predefined types
2351    * specified by facebook for specifying diff age restriction for diff
2352    * locations.
2353    *
2354    * @param array $restriction_info  The age restriction settings to set.
2355    *
2356    * @return bool  true on success
2357    */
2358   public function admin_setRestrictionInfo($restriction_info = null) {
2359     $restriction_str = null;
2360     if (!empty($restriction_info)) {
2361       $restriction_str = json_encode($restriction_info);
2362     }
2363     return $this->call_method('admin.setRestrictionInfo',
2364         array('restriction_str' => $restriction_str));
2365   }
2366
2367   /**
2368    * Gets application restriction info.
2369    *
2370    * Applications can restrict themselves to only a limited user demographic
2371    * based on users' age and/or location or based on static predefined types
2372    * specified by facebook for specifying diff age restriction for diff
2373    * locations.
2374    *
2375    * @return array  The age restriction settings for this application.
2376    */
2377   public function admin_getRestrictionInfo() {
2378     return json_decode(
2379         $this->call_method('admin.getRestrictionInfo', array()),
2380         true);
2381   }
2382
2383   /* UTILITY FUNCTIONS */
2384
2385   /**
2386    * Calls the specified method with the specified parameters.
2387    *
2388    * @param string $method  Name of the Facebook method to invoke
2389    * @param array $params   A map of param names => param values
2390    *
2391    * @return mixed  Result of method call
2392    */
2393   public function & call_method($method, $params) {
2394     //Check if we are in batch mode
2395     if($this->batch_queue === null) {
2396       if ($this->call_as_apikey) {
2397         $params['call_as_apikey'] = $this->call_as_apikey;
2398       }
2399       $xml = $this->post_request($method, $params);
2400       $result = $this->convert_xml_to_result($xml, $method, $params);
2401
2402       if (is_array($result) && isset($result['error_code'])) {
2403         throw new FacebookRestClientException($result['error_msg'],
2404                                               $result['error_code']);
2405       }
2406     }
2407     else {
2408       $result = null;
2409       $batch_item = array('m' => $method, 'p' => $params, 'r' => & $result);
2410       $this->batch_queue[] = $batch_item;
2411     }
2412
2413     return $result;
2414   }
2415
2416   private function convert_xml_to_result($xml, $method, $params) {
2417     $sxml = simplexml_load_string($xml);
2418     $result = self::convert_simplexml_to_array($sxml);
2419
2420
2421     if (!empty($GLOBALS['facebook_config']['debug'])) {
2422       // output the raw xml and its corresponding php object, for debugging:
2423       print '<div style="margin: 10px 30px; padding: 5px; border: 2px solid black; background: gray; color: white; font-size: 12px; font-weight: bold;">';
2424       $this->cur_id++;
2425       print $this->cur_id . ': Called ' . $method . ', show ' .
2426             '<a href=# onclick="return toggleDisplay(' . $this->cur_id . ', \'params\');">Params</a> | '.
2427             '<a href=# onclick="return toggleDisplay(' . $this->cur_id . ', \'xml\');">XML</a> | '.
2428             '<a href=# onclick="return toggleDisplay(' . $this->cur_id . ', \'sxml\');">SXML</a> | '.
2429             '<a href=# onclick="return toggleDisplay(' . $this->cur_id . ', \'php\');">PHP</a>';
2430       print '<pre id="params'.$this->cur_id.'" style="display: none; overflow: auto;">'.print_r($params, true).'</pre>';
2431       print '<pre id="xml'.$this->cur_id.'" style="display: none; overflow: auto;">'.htmlspecialchars($xml).'</pre>';
2432       print '<pre id="php'.$this->cur_id.'" style="display: none; overflow: auto;">'.print_r($result, true).'</pre>';
2433       print '<pre id="sxml'.$this->cur_id.'" style="display: none; overflow: auto;">'.print_r($sxml, true).'</pre>';
2434       print '</div>';
2435     }
2436     return $result;
2437   }
2438
2439   private function create_post_string($method, $params) {
2440     $params['method'] = $method;
2441     $params['session_key'] = $this->session_key;
2442     $params['api_key'] = $this->api_key;
2443     $params['call_id'] = microtime(true);
2444     if ($params['call_id'] <= $this->last_call_id) {
2445       $params['call_id'] = $this->last_call_id + 0.001;
2446     }
2447     $this->last_call_id = $params['call_id'];
2448     if (!isset($params['v'])) {
2449       $params['v'] = '1.0';
2450     }
2451     $post_params = array();
2452     foreach ($params as $key => &$val) {
2453       if (is_array($val)) $val = implode(',', $val);
2454       $post_params[] = $key.'='.urlencode($val);
2455     }
2456     $secret = $this->secret;
2457     $post_params[] = 'sig='.Facebook::generate_sig($params, $secret);
2458     return implode('&', $post_params);
2459   }
2460
2461   public function post_request($method, $params) {
2462
2463     $post_string = $this->create_post_string($method, $params);
2464
2465     if (function_exists('curl_init')) {
2466       // Use CURL if installed...
2467       $useragent = 'Facebook API PHP5 Client 1.1 (curl) ' . phpversion();
2468       $ch = curl_init();
2469       curl_setopt($ch, CURLOPT_URL, $this->server_addr);
2470       curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
2471       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
2472       curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
2473       $result = curl_exec($ch);
2474       curl_close($ch);
2475     } else {
2476       // Non-CURL based version...
2477       $content_type = 'application/x-www-form-urlencoded';
2478       $user_agent = 'Facebook API PHP5 Client 1.1 (non-curl) '.phpversion();
2479       $context =
2480         array('http' =>
2481               array('method' => 'POST',
2482                     'header' => 'Content-type: '.$content_type."\r\n".
2483                                 'User-Agent: '.$user_agent."\r\n".
2484                                 'Content-length: ' . strlen($post_string),
2485                     'content' => $post_string));
2486       $contextid=stream_context_create($context);
2487       $sock=fopen($this->server_addr, 'r', false, $contextid);
2488       if ($sock) {
2489         $result='';
2490         while (!feof($sock))
2491           $result.=fgets($sock, 4096);
2492
2493         fclose($sock);
2494       }
2495     }
2496     return $result;
2497   }
2498
2499   public static function convert_simplexml_to_array($sxml) {
2500     $arr = array();
2501     if ($sxml) {
2502       foreach ($sxml as $k => $v) {
2503         if ($sxml['list']) {
2504           $arr[] = self::convert_simplexml_to_array($v);
2505         } else {
2506           $arr[$k] = self::convert_simplexml_to_array($v);
2507         }
2508       }
2509     }
2510     if (sizeof($arr) > 0) {
2511       return $arr;
2512     } else {
2513       return (string)$sxml;
2514     }
2515   }
2516
2517   private function get_uid($uid) {
2518     return $uid ? $uid : $this->user;
2519   }
2520 }
2521
2522
2523 class FacebookRestClientException extends Exception {
2524 }
2525
2526 // Supporting methods and values------
2527
2528 /**
2529  * Error codes and descriptions for the Facebook API.
2530  */
2531
2532 class FacebookAPIErrorCodes {
2533
2534   const API_EC_SUCCESS = 0;
2535
2536   /*
2537    * GENERAL ERRORS
2538    */
2539   const API_EC_UNKNOWN = 1;
2540   const API_EC_SERVICE = 2;
2541   const API_EC_METHOD = 3;
2542   const API_EC_TOO_MANY_CALLS = 4;
2543   const API_EC_BAD_IP = 5;
2544
2545   /*
2546    * PARAMETER ERRORS
2547    */
2548   const API_EC_PARAM = 100;
2549   const API_EC_PARAM_API_KEY = 101;
2550   const API_EC_PARAM_SESSION_KEY = 102;
2551   const API_EC_PARAM_CALL_ID = 103;
2552   const API_EC_PARAM_SIGNATURE = 104;
2553   const API_EC_PARAM_USER_ID = 110;
2554   const API_EC_PARAM_USER_FIELD = 111;
2555   const API_EC_PARAM_SOCIAL_FIELD = 112;
2556   const API_EC_PARAM_ALBUM_ID = 120;
2557   const API_EC_PARAM_BAD_EID = 150;
2558   const API_EC_PARAM_UNKNOWN_CITY = 151;
2559
2560   /*
2561    * USER PERMISSIONS ERRORS
2562    */
2563   const API_EC_PERMISSION = 200;
2564   const API_EC_PERMISSION_USER = 210;
2565   const API_EC_PERMISSION_ALBUM = 220;
2566   const API_EC_PERMISSION_PHOTO = 221;
2567   const API_EC_PERMISSION_EVENT = 290;
2568   const API_EC_PERMISSION_RSVP_EVENT = 299;
2569
2570   const FQL_EC_PARSER = 601;
2571   const FQL_EC_UNKNOWN_FIELD = 602;
2572   const FQL_EC_UNKNOWN_TABLE = 603;
2573   const FQL_EC_NOT_INDEXABLE = 604;
2574
2575   /**
2576    * DATA STORE API ERRORS
2577    */
2578   const API_EC_DATA_UNKNOWN_ERROR = 800;
2579   const API_EC_DATA_INVALID_OPERATION = 801;
2580   const API_EC_DATA_QUOTA_EXCEEDED = 802;
2581   const API_EC_DATA_OBJECT_NOT_FOUND = 803;
2582   const API_EC_DATA_OBJECT_ALREADY_EXISTS = 804;
2583   const API_EC_DATA_DATABASE_ERROR = 805;
2584
2585   /*
2586    * Batch ERROR
2587    */
2588   const API_EC_BATCH_ALREADY_STARTED = 900;
2589   const API_EC_BATCH_NOT_STARTED = 901;
2590   const API_EC_BATCH_METHOD_NOT_ALLOWED_IN_BATCH_MODE = 902;
2591
2592   public static $api_error_descriptions = array(
2593       API_EC_SUCCESS           => 'Success',
2594       API_EC_UNKNOWN           => 'An unknown error occurred',
2595       API_EC_SERVICE           => 'Service temporarily unavailable',
2596       API_EC_METHOD            => 'Unknown method',
2597       API_EC_TOO_MANY_CALLS    => 'Application request limit reached',
2598       API_EC_BAD_IP            => 'Unauthorized source IP address',
2599       API_EC_PARAM             => 'Invalid parameter',
2600       API_EC_PARAM_API_KEY     => 'Invalid API key',
2601       API_EC_PARAM_SESSION_KEY => 'Session key invalid or no longer valid',
2602       API_EC_PARAM_CALL_ID     => 'Call_id must be greater than previous',
2603       API_EC_PARAM_SIGNATURE   => 'Incorrect signature',
2604       API_EC_PARAM_USER_ID     => 'Invalid user id',
2605       API_EC_PARAM_USER_FIELD  => 'Invalid user info field',
2606       API_EC_PARAM_SOCIAL_FIELD => 'Invalid user field',
2607       API_EC_PARAM_ALBUM_ID    => 'Invalid album id',
2608       API_EC_PARAM_BAD_EID     => 'Invalid eid',
2609       API_EC_PARAM_UNKNOWN_CITY => 'Unknown city',
2610       API_EC_PERMISSION        => 'Permissions error',
2611       API_EC_PERMISSION_USER   => 'User not visible',
2612       API_EC_PERMISSION_ALBUM  => 'Album not visible',
2613       API_EC_PERMISSION_PHOTO  => 'Photo not visible',
2614       API_EC_PERMISSION_EVENT  => 'Creating and modifying events required the extended permission create_event',
2615       API_EC_PERMISSION_RSVP_EVENT => 'RSVPing to events required the extended permission rsvp_event',
2616       FQL_EC_PARSER            => 'FQL: Parser Error',
2617       FQL_EC_UNKNOWN_FIELD     => 'FQL: Unknown Field',
2618       FQL_EC_UNKNOWN_TABLE     => 'FQL: Unknown Table',
2619       FQL_EC_NOT_INDEXABLE     => 'FQL: Statement not indexable',
2620       FQL_EC_UNKNOWN_FUNCTION  => 'FQL: Attempted to call unknown function',
2621       FQL_EC_INVALID_PARAM     => 'FQL: Invalid parameter passed in',
2622       API_EC_DATA_UNKNOWN_ERROR => 'Unknown data store API error',
2623       API_EC_DATA_INVALID_OPERATION => 'Invalid operation',
2624       API_EC_DATA_QUOTA_EXCEEDED => 'Data store allowable quota was exceeded',
2625       API_EC_DATA_OBJECT_NOT_FOUND => 'Specified object cannot be found',
2626       API_EC_DATA_OBJECT_ALREADY_EXISTS => 'Specified object already exists',
2627       API_EC_DATA_DATABASE_ERROR => 'A database error occurred. Please try again',
2628       API_EC_BATCH_ALREADY_STARTED => 'begin_batch already called, please make sure to call end_batch first',
2629       API_EC_BATCH_NOT_STARTED => 'end_batch called before start_batch',
2630       API_EC_BATCH_METHOD_NOT_ALLOWED_IN_BATCH_MODE => 'This method is not allowed in batch mode',
2631   );
2632 }