3 namespace Friendica\Module;
5 use Friendica\BaseModule;
7 use Friendica\Network\HTTPException;
9 require_once __DIR__ . '/../../include/api.php';
11 class BaseApi extends BaseModule
14 * @var string json|xml|rss|atom
16 protected static $format = 'json';
20 protected static $current_user_id;
22 public static function init(array $parameters = [])
24 $arguments = DI::args();
26 if (substr($arguments->getQueryString(), -4) === '.xml') {
27 self::$format = 'xml';
29 if (substr($arguments->getQueryString(), -4) === '.rss') {
30 self::$format = 'rss';
32 if (substr($arguments->getQueryString(), -4) === '.atom') {
33 self::$format = 'atom';
37 public static function post(array $parameters = [])
40 throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
45 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
46 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
51 * Log in user via OAuth1 or Simple HTTP Auth.
53 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
55 * @return bool Was a user authenticated?
56 * @throws HTTPException\ForbiddenException
57 * @throws HTTPException\UnauthorizedException
58 * @throws HTTPException\InternalServerErrorException
59 * @hook 'authenticate'
61 * 'username' => username from login form
62 * 'password' => password from login form
63 * 'authenticated' => return status,
64 * 'user_record' => return authenticated user record
66 protected static function login()
70 self::$current_user_id = api_user();
72 return (bool)self::$current_user_id;
76 * Get user info array.
78 * @param int|string $contact_id Contact ID or URL
80 * @throws HTTPException\BadRequestException
81 * @throws HTTPException\InternalServerErrorException
82 * @throws HTTPException\UnauthorizedException
83 * @throws \ImagickException
85 protected static function getUser($contact_id = null)
87 return api_get_user(DI::app(), $contact_id);
91 * Formats the data according to the data type
93 * @param string $root_element
94 * @param array $data An array with a single element containing the returned result
95 * @return false|string
97 protected static function format(string $root_element, array $data)
99 $return = api_format_data($root_element, self::$format, $data);
101 switch (self::$format) {
103 header("Content-Type: text/xml");
106 header("Content-Type: application/json");
107 if (!empty($return)) {
108 $json = json_encode(end($return));
109 if (!empty($_GET['callback'])) {
110 $json = $_GET['callback'] . "(" . $json . ")";
116 header("Content-Type: application/rss+xml");
117 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
120 header("Content-Type: application/atom+xml");
121 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
129 * Creates the XML from a JSON style array
132 * @param $root_element
135 protected static function createXml($data, $root_element)
137 return api_create_xml($data, $root_element);