Move xml to namespace

Relocate xml from include to src
Related to #3878
This commit is contained in:
Adam Magness 2017-11-10 00:00:50 -05:00
commit f245bc8359
12 changed files with 5394 additions and 5137 deletions

View file

@ -13,6 +13,7 @@ use Friendica\Core\NotificationsManager;
use Friendica\Core\Worker; use Friendica\Core\Worker;
use Friendica\Database\DBM; use Friendica\Database\DBM;
use Friendica\Protocol\Diaspora; use Friendica\Protocol\Diaspora;
use Friendica\Util\Xml;
require_once 'include/HTTPExceptions.php'; require_once 'include/HTTPExceptions.php';
require_once 'include/bbcode.php'; require_once 'include/bbcode.php';
@ -32,7 +33,6 @@ require_once 'include/message.php';
require_once 'include/group.php'; require_once 'include/group.php';
require_once 'include/like.php'; require_once 'include/like.php';
require_once 'include/plaintext.php'; require_once 'include/plaintext.php';
require_once 'include/xml.php';
define('API_METHOD_ANY', '*'); define('API_METHOD_ANY', '*');
define('API_METHOD_GET', 'GET'); define('API_METHOD_GET', 'GET');
@ -42,7 +42,6 @@ define('API_METHOD_DELETE', 'POST,DELETE');
$API = array(); $API = array();
$called_api = null; $called_api = null;
/// @TODO Fix intending
/** /**
* @brief Auth API user * @brief Auth API user
* *
@ -50,7 +49,8 @@ $called_api = null;
* because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
* into a page, and visitors will post something without noticing it). * into a page, and visitors will post something without noticing it).
*/ */
function api_user() { function api_user()
{
if (x($_SESSION, 'allow_api')) { if (x($_SESSION, 'allow_api')) {
return local_user(); return local_user();
} }
@ -69,7 +69,8 @@ $called_api = null;
* @return string * @return string
* Client source name, default to "api" if unset/unknown * Client source name, default to "api" if unset/unknown
*/ */
function api_source() { function api_source()
{
if (requestdata('source')) { if (requestdata('source')) {
return requestdata('source'); return requestdata('source');
} }
@ -90,7 +91,8 @@ $called_api = null;
* @param string $str Source date, as UTC * @param string $str Source date, as UTC
* @return string Date in UTC formatted as "D M d H:i:s +0000 Y" * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
*/ */
function api_date($str) { function api_date($str)
{
// Wed May 23 06:01:13 +0000 2007 // Wed May 23 06:01:13 +0000 2007
return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y"); return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y");
} }
@ -104,11 +106,11 @@ $called_api = null;
* @param string $func Function name to call on path request * @param string $func Function name to call on path request
* @param bool $auth API need logged user * @param bool $auth API need logged user
* @param string $method HTTP method reqiured to call this endpoint. * @param string $method HTTP method reqiured to call this endpoint.
*
* One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST. * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
* Default to API_METHOD_ANY * Default to API_METHOD_ANY
*/ */
function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY) { function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
{
global $API; global $API;
$API[$path] = array( $API[$path] = array(
@ -133,7 +135,7 @@ $called_api = null;
* Log in user via OAuth1 or Simple HTTP Auth. * Log in user via OAuth1 or Simple HTTP Auth.
* Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
* *
* @param App $a * @param object $a App
* @hook 'authenticate' * @hook 'authenticate'
* array $addon_auth * array $addon_auth
* 'username' => username from login form * 'username' => username from login form
@ -143,7 +145,8 @@ $called_api = null;
* @hook 'logged_in' * @hook 'logged_in'
* array $user logged user record * array $user logged user record
*/ */
function api_login(App $a) { function api_login(App $a)
{
// login with oauth // login with oauth
try { try {
$oauth = new FKOAuth1(); $oauth = new FKOAuth1();
@ -207,7 +210,8 @@ $called_api = null;
$record = $addon_auth['user_record']; $record = $addon_auth['user_record'];
} else { } else {
// process normal login request // process normal login request
$r = q("SELECT * FROM `user` WHERE (`email` = '%s' OR `nickname` = '%s') $r = q(
"SELECT * FROM `user` WHERE (`email` = '%s' OR `nickname` = '%s')
AND `password` = '%s' AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` LIMIT 1", AND `password` = '%s' AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` LIMIT 1",
dbesc(trim($user)), dbesc(trim($user)),
dbesc(trim($user)), dbesc(trim($user)),
@ -231,7 +235,6 @@ $called_api = null;
$_SESSION["allow_api"] = true; $_SESSION["allow_api"] = true;
call_hooks('logged_in', $a->user); call_hooks('logged_in', $a->user);
} }
/** /**
@ -244,7 +247,8 @@ $called_api = null;
* @param string $method Required methods, uppercase, separated by comma * @param string $method Required methods, uppercase, separated by comma
* @return bool * @return bool
*/ */
function api_check_method($method) { function api_check_method($method)
{
if ($method == "*") { if ($method == "*") {
return true; return true;
} }
@ -256,10 +260,11 @@ $called_api = null;
* *
* Authenticate user, call registered API function, set HTTP headers * Authenticate user, call registered API function, set HTTP headers
* *
* @param App $a * @param object $a App
* @return string API call result * @return string API call result
*/ */
function api_call(App $a) { function api_call(App $a)
{
global $API, $called_api; global $API, $called_api;
$type = "json"; $type = "json";
@ -303,27 +308,29 @@ $called_api = null;
$duration = microtime(true)-$a->performance["start"]; $duration = microtime(true)-$a->performance["start"];
/// @TODO round() really everywhere? /// @TODO round() really everywhere?
logger(parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf("Database: %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s", logger(
parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
"Database: %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
round($a->performance["database"] - $a->performance["database_write"], 3), round($a->performance["database"] - $a->performance["database_write"], 3),
round($a->performance["database_write"], 3), round($a->performance["database_write"], 3),
round($a->performance["network"], 2), round($a->performance["network"], 2),
round($a->performance["file"], 2), round($a->performance["file"], 2),
round($duration - ($a->performance["database"] + $a->performance["network"] round($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
+ $a->performance["file"]), 2), round($duration, 2)
round($duration, 2)), ),
LOGGER_DEBUG LOGGER_DEBUG
); );
if (Config::get("rendertime", "callstack")) { if (Config::get("rendertime", "callstack")) {
$o = "Database Read:\n"; $o = "Database Read:\n";
foreach ($a->callstack["database"] AS $func => $time) { foreach ($a->callstack["database"] as $func => $time) {
$time = round($time, 3); $time = round($time, 3);
if ($time > 0) { if ($time > 0) {
$o .= $func . ": " . $time . "\n"; $o .= $func . ": " . $time . "\n";
} }
} }
$o .= "\nDatabase Write:\n"; $o .= "\nDatabase Write:\n";
foreach ($a->callstack["database_write"] AS $func => $time) { foreach ($a->callstack["database_write"] as $func => $time) {
$time = round($time, 3); $time = round($time, 3);
if ($time > 0) { if ($time > 0) {
$o .= $func . ": " . $time . "\n"; $o .= $func . ": " . $time . "\n";
@ -331,7 +338,7 @@ $called_api = null;
} }
$o .= "\nNetwork:\n"; $o .= "\nNetwork:\n";
foreach ($a->callstack["network"] AS $func => $time) { foreach ($a->callstack["network"] as $func => $time) {
$time = round($time, 3); $time = round($time, 3);
if ($time > 0) { if ($time > 0) {
$o .= $func . ": " . $time . "\n"; $o .= $func . ": " . $time . "\n";
@ -387,11 +394,11 @@ $called_api = null;
* @brief Format API error string * @brief Format API error string
* *
* @param string $type Return type (xml, json, rss, as) * @param string $type Return type (xml, json, rss, as)
* @param HTTPException $error Error object * @param object $e HTTPException Error object
* @return strin error message formatted as $type * @return strin error message formatted as $type
*/ */
function api_error($type, $e) { function api_error($type, $e)
{
$a = get_app(); $a = get_app();
$error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc); $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
@ -428,11 +435,12 @@ $called_api = null;
* *
* @param App $a * @param App $a
* @param array $arr Array to be passed to template * @param array $arr Array to be passed to template
* @param array $user_info * @param array $user_info User info
* @return array * @return array
* @todo find proper type-hints * @todo find proper type-hints
*/ */
function api_rss_extra(App $a, $arr, $user_info) { function api_rss_extra(App $a, $arr, $user_info)
{
if (is_null($user_info)) { if (is_null($user_info)) {
$user_info = api_get_user($a); $user_info = api_get_user($a);
} }
@ -459,7 +467,8 @@ $called_api = null;
* @return bool|string * @return bool|string
* Contact url or False if contact id is unknown * Contact url or False if contact id is unknown
*/ */
function api_unique_id_to_url($id) { function api_unique_id_to_url($id)
{
$r = dba::select('contact', array('url'), array('uid' => 0, 'id' => $id), array('limit' => 1)); $r = dba::select('contact', array('url'), array('uid' => 0, 'id' => $id), array('limit' => 1));
if (DBM::is_result($r)) { if (DBM::is_result($r)) {
@ -472,11 +481,12 @@ $called_api = null;
/** /**
* @brief Get user info array. * @brief Get user info array.
* *
* @param Api $a * @param object $a App
* @param int|string $contact_id Contact ID or URL * @param int|string $contact_id Contact ID or URL
* @param string $type Return type (for errors) * @param string $type Return type (for errors)
*/ */
function api_get_user(App $a, $contact_id = null, $type = "json") { function api_get_user(App $a, $contact_id = null, $type = "json")
{
global $called_api; global $called_api;
$user = null; $user = null;
@ -577,13 +587,13 @@ $called_api = null;
$user = $_SESSION['uid']; $user = $_SESSION['uid'];
$extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` "; $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
} }
} }
logger('api_user: ' . $extra_query . ', user: ' . $user); logger('api_user: ' . $extra_query . ', user: ' . $user);
// user info // user info
$uinfo = q("SELECT *, `contact`.`id` AS `cid` FROM `contact` $uinfo = q(
"SELECT *, `contact`.`id` AS `cid` FROM `contact`
WHERE 1 WHERE 1
$extra_query", $extra_query",
$user $user
@ -651,15 +661,16 @@ $called_api = null;
} }
if ($uinfo[0]['self']) { if ($uinfo[0]['self']) {
if ($uinfo[0]['network'] == "") { if ($uinfo[0]['network'] == "") {
$uinfo[0]['network'] = NETWORK_DFRN; $uinfo[0]['network'] = NETWORK_DFRN;
} }
$usr = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", $usr = q(
"SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
intval(api_user()) intval(api_user())
); );
$profile = q("SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1", $profile = q(
"SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
intval(api_user()) intval(api_user())
); );
@ -734,7 +745,7 @@ $called_api = null;
'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']), 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']), 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
'location' => ($usr) ? $usr[0]['default-location'] : $network_name, 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
'description' => (($profile) ? $profile[0]['pdesc'] : NULL), 'description' => (($profile) ? $profile[0]['pdesc'] : null),
'profile_image_url' => $uinfo[0]['micro'], 'profile_image_url' => $uinfo[0]['micro'],
'profile_image_url_https' => $uinfo[0]['micro'], 'profile_image_url_https' => $uinfo[0]['micro'],
'url' => $uinfo[0]['url'], 'url' => $uinfo[0]['url'],
@ -767,18 +778,17 @@ $called_api = null;
); );
return $ret; return $ret;
} }
/** /**
* @brief return api-formatted array for item's author and owner * @brief return api-formatted array for item's author and owner
* *
* @param App $a * @param object $a App
* @param array $item : item from db * @param array $item item from db
* @return array(array:author, array:owner) * @return array(array:author, array:owner)
*/ */
function api_item_get_user(App $a, $item) { function api_item_get_user(App $a, $item)
{
$status_user = api_get_user($a, $item["author-link"]); $status_user = api_get_user($a, $item["author-link"]);
$status_user["protected"] = (($item["allow_cid"] != "") || $status_user["protected"] = (($item["allow_cid"] != "") ||
@ -804,8 +814,8 @@ $called_api = null;
* *
* @return array the transformed array * @return array the transformed array
*/ */
function api_walk_recursive(array &$array, callable $callback) { function api_walk_recursive(array &$array, callable $callback)
{
$new_array = array(); $new_array = array();
foreach ($array as $k => $v) { foreach ($array as $k => $v) {
@ -827,12 +837,13 @@ $called_api = null;
/** /**
* @brief Callback function to transform the array in an array that can be transformed in a XML file * @brief Callback function to transform the array in an array that can be transformed in a XML file
* *
* @param variant $item Array item value * @param mixed $item Array item value
* @param string $key Array key * @param string $key Array key
* *
* @return boolean Should the array item be deleted? * @return boolean Should the array item be deleted?
*/ */
function api_reformat_xml(&$item, &$key) { function api_reformat_xml(&$item, &$key)
{
if (is_bool($item)) { if (is_bool($item)) {
$item = ($item ? "true" : "false"); $item = ($item ? "true" : "false");
} }
@ -857,7 +868,8 @@ $called_api = null;
* *
* @return string The XML data * @return string The XML data
*/ */
function api_create_xml($data, $root_element) { function api_create_xml($data, $root_element)
{
$childname = key($data); $childname = key($data);
$data2 = array_pop($data); $data2 = array_pop($data);
$key = key($data2); $key = key($data2);
@ -880,7 +892,7 @@ $called_api = null;
$data4 = array(); $data4 = array();
$i = 1; $i = 1;
foreach ($data2 AS $item) { foreach ($data2 as $item) {
$data4[$i++.":".$childname] = $item; $data4[$i++.":".$childname] = $item;
} }
@ -889,7 +901,7 @@ $called_api = null;
$data3 = array($root_element => $data2); $data3 = array($root_element => $data2);
$ret = xml::from_array($data3, $xml, false, $namespaces); $ret = Xml::from_array($data3, $xml, false, $namespaces);
return $ret; return $ret;
} }
@ -902,8 +914,8 @@ $called_api = null;
* *
* @return (string|object) XML data or JSON data * @return (string|object) XML data or JSON data
*/ */
function api_format_data($root_element, $type, $data) { function api_format_data($root_element, $type, $data)
{
$a = get_app(); $a = get_app();
switch ($type) { switch ($type) {
@ -921,7 +933,7 @@ $called_api = null;
} }
/** /**
** TWITTER API * TWITTER API
*/ */
/** /**
@ -929,7 +941,8 @@ $called_api = null;
* returns a 401 status code and an error message if not. * returns a 401 status code and an error message if not.
* http://developer.twitter.com/doc/get/account/verify_credentials * http://developer.twitter.com/doc/get/account/verify_credentials
*/ */
function api_account_verify_credentials($type) { function api_account_verify_credentials($type)
{
$a = get_app(); $a = get_app();
@ -965,16 +978,16 @@ $called_api = null;
unset($user_info["self"]); unset($user_info["self"]);
return api_format_data("user", $type, array('user' => $user_info)); return api_format_data("user", $type, array('user' => $user_info));
} }
/// @TODO move to top of file or somwhere better /// @TODO move to top of file or somwhere better
api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true); api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
/** /**
* get data from $_POST or $_GET * Get data from $_POST or $_GET
*/ */
function requestdata($k) { function requestdata($k)
{
if (x($_POST, $k)) { if (x($_POST, $k)) {
return $_POST[$k]; return $_POST[$k];
} }
@ -985,8 +998,8 @@ $called_api = null;
} }
/*Waitman Gobble Mod*/ /*Waitman Gobble Mod*/
function api_statuses_mediap($type) { function api_statuses_mediap($type)
{
$a = get_app(); $a = get_app();
if (api_user() === false) { if (api_user() === false) {
@ -1003,7 +1016,6 @@ $called_api = null;
//$txt = urldecode(requestdata('status')); //$txt = urldecode(requestdata('status'));
if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) { if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
$txt = html2bb_video($txt); $txt = html2bb_video($txt);
$config = HTMLPurifier_Config::createDefault(); $config = HTMLPurifier_Config::createDefault();
$config->set('Cache.DefinitionImpl', null); $config->set('Cache.DefinitionImpl', null);
@ -1029,7 +1041,8 @@ $called_api = null;
/// @TODO move this to top of file or somewhere better! /// @TODO move this to top of file or somewhere better!
api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST); api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
function api_statuses_update($type) { function api_statuses_update($type)
{
$a = get_app(); $a = get_app();
@ -1057,7 +1070,6 @@ $called_api = null;
$_REQUEST['body'] = html2bbcode($txt); $_REQUEST['body'] = html2bbcode($txt);
} }
} else { } else {
$_REQUEST['body'] = requestdata('status'); $_REQUEST['body'] = requestdata('status');
} }
@ -1090,9 +1102,12 @@ $called_api = null;
if ($throttle_day > 0) { if ($throttle_day > 0) {
$datefrom = date("Y-m-d H:i:s", time() - 24*60*60); $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
$r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall` $r = q(
"SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
AND `created` > '%s' AND `id` = `parent`", AND `created` > '%s' AND `id` = `parent`",
intval(api_user()), dbesc($datefrom)); intval(api_user()),
dbesc($datefrom)
);
if (DBM::is_result($r)) { if (DBM::is_result($r)) {
$posts_day = $r[0]["posts_day"]; $posts_day = $r[0]["posts_day"];
@ -1111,9 +1126,12 @@ $called_api = null;
if ($throttle_week > 0) { if ($throttle_week > 0) {
$datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7); $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
$r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall` $r = q(
"SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
AND `created` > '%s' AND `id` = `parent`", AND `created` > '%s' AND `id` = `parent`",
intval(api_user()), dbesc($datefrom)); intval(api_user()),
dbesc($datefrom)
);
if (DBM::is_result($r)) { if (DBM::is_result($r)) {
$posts_week = $r[0]["posts_week"]; $posts_week = $r[0]["posts_week"];
@ -1132,9 +1150,12 @@ $called_api = null;
if ($throttle_month > 0) { if ($throttle_month > 0) {
$datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30); $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
$r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall` $r = q(
"SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
AND `created` > '%s' AND `id` = `parent`", AND `created` > '%s' AND `id` = `parent`",
intval(api_user()), dbesc($datefrom)); intval(api_user()),
dbesc($datefrom)
);
if (DBM::is_result($r)) { if (DBM::is_result($r)) {
$posts_month = $r[0]["posts_month"]; $posts_month = $r[0]["posts_month"];
@ -1163,8 +1184,11 @@ $called_api = null;
// To-Do: Multiple IDs // To-Do: Multiple IDs
if (requestdata('media_ids')) { if (requestdata('media_ids')) {
$r = q("SELECT `resource-id`, `scale`, `nickname`, `type` FROM `photo` INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN (SELECT `resource-id` FROM `photo` WHERE `id` = %d) AND `scale` > 0 AND `photo`.`uid` = %d ORDER BY `photo`.`width` DESC LIMIT 1", $r = q(
intval(requestdata('media_ids')), api_user()); "SELECT `resource-id`, `scale`, `nickname`, `type` FROM `photo` INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN (SELECT `resource-id` FROM `photo` WHERE `id` = %d) AND `scale` > 0 AND `photo`.`uid` = %d ORDER BY `photo`.`width` DESC LIMIT 1",
intval(requestdata('media_ids')),
api_user()
);
if (DBM::is_result($r)) { if (DBM::is_result($r)) {
$phototypes = Photo::supportedTypes(); $phototypes = Photo::supportedTypes();
$ext = $phototypes[$r[0]['type']]; $ext = $phototypes[$r[0]['type']];
@ -1192,8 +1216,8 @@ $called_api = null;
api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST); api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST); api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
function api_media_upload($type) { function api_media_upload($type)
{
$a = get_app(); $a = get_app();
if (api_user() === false) { if (api_user() === false) {
@ -1230,8 +1254,8 @@ $called_api = null;
/// @TODO move to top of file or somwhere better /// @TODO move to top of file or somwhere better
api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST); api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
function api_status_show($type) { function api_status_show($type)
{
$a = get_app(); $a = get_app();
$user_info = api_get_user($a); $user_info = api_get_user($a);
@ -1245,7 +1269,8 @@ $called_api = null;
} }
// get last public wall message // get last public wall message
$lastwall = q("SELECT `item`.* $lastwall = q(
"SELECT `item`.*
FROM `item` FROM `item`
WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s'))) AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
@ -1286,7 +1311,7 @@ $called_api = null;
'in_reply_to_user_id_str' => $in_reply_to['user_id_str'], 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
'in_reply_to_screen_name' => $in_reply_to['screen_name'], 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
'user' => $user_info, 'user' => $user_info,
$geo => NULL, $geo => null,
'coordinates' => "", 'coordinates' => "",
'place' => "", 'place' => "",
'contributors' => "", 'contributors' => "",
@ -1327,7 +1352,6 @@ $called_api = null;
} }
return api_format_data("statuses", $type, array('status' => $status_info)); return api_format_data("statuses", $type, array('status' => $status_info));
} }
/** /**
@ -1335,12 +1359,13 @@ $called_api = null;
* The author's most recent status will be returned inline. * The author's most recent status will be returned inline.
* http://developer.twitter.com/doc/get/users/show * http://developer.twitter.com/doc/get/users/show
*/ */
function api_users_show($type) { function api_users_show($type)
{
$a = get_app(); $a = get_app();
$user_info = api_get_user($a); $user_info = api_get_user($a);
$lastwall = q("SELECT `item`.* $lastwall = q(
"SELECT `item`.*
FROM `item` FROM `item`
INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid` INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
@ -1383,7 +1408,7 @@ $called_api = null;
'in_reply_to_user_id' => $in_reply_to['user_id'], 'in_reply_to_user_id' => $in_reply_to['user_id'],
'in_reply_to_user_id_str' => $in_reply_to['user_id_str'], 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
'in_reply_to_screen_name' => $in_reply_to['screen_name'], 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
$geo => NULL, $geo => null,
'favorited' => $lastwall['starred'] ? true : false, 'favorited' => $lastwall['starred'] ? true : false,
'statusnet_html' => $converted["html"], 'statusnet_html' => $converted["html"],
'statusnet_conversation_id' => $lastwall['parent'], 'statusnet_conversation_id' => $lastwall['parent'],
@ -1404,7 +1429,6 @@ $called_api = null;
if (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) { if (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
$user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . network_to_name($lastwall['item_network'], $user_info['url']) . ')'); $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . network_to_name($lastwall['item_network'], $user_info['url']) . ')');
} }
} }
// "uid" and "self" are only needed for some internal stuff, so remove it from here // "uid" and "self" are only needed for some internal stuff, so remove it from here
@ -1412,15 +1436,14 @@ $called_api = null;
unset($user_info["self"]); unset($user_info["self"]);
return api_format_data("user", $type, array('user' => $user_info)); return api_format_data("user", $type, array('user' => $user_info));
} }
/// @TODO move to top of file or somewhere better /// @TODO move to top of file or somewhere better
api_register_func('api/users/show', 'api_users_show'); api_register_func('api/users/show', 'api_users_show');
api_register_func('api/externalprofile/show', 'api_users_show'); api_register_func('api/externalprofile/show', 'api_users_show');
function api_users_search($type) { function api_users_search($type)
{
$a = get_app(); $a = get_app();
$page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0); $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
@ -1436,7 +1459,7 @@ $called_api = null;
if (DBM::is_result($r)) { if (DBM::is_result($r)) {
$k = 0; $k = 0;
foreach ($r AS $user) { foreach ($r as $user) {
$user_info = api_get_user($a, $user["id"], "json"); $user_info = api_get_user($a, $user["id"], "json");
if ($type == "xml") { if ($type == "xml") {
@ -1465,8 +1488,8 @@ $called_api = null;
* TODO: Optional parameters * TODO: Optional parameters
* TODO: Add reply info * TODO: Add reply info
*/ */
function api_statuses_home_timeline($type) { function api_statuses_home_timeline($type)
{
$a = get_app(); $a = get_app();
if (api_user() === false) { if (api_user() === false) {
@ -1507,7 +1530,8 @@ $called_api = null;
$sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id); $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
} }
$r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, $r = q(
"SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`, `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
`contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`, `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
`contact`.`id` AS `cid` `contact`.`id` AS `cid`
@ -1522,14 +1546,15 @@ $called_api = null;
intval(api_user()), intval(api_user()),
dbesc(ACTIVITY_POST), dbesc(ACTIVITY_POST),
intval($since_id), intval($since_id),
intval($start), intval($count) intval($start),
intval($count)
); );
$ret = api_format_items($r, $user_info, false, $type); $ret = api_format_items($r, $user_info, false, $type);
// Set all posts from the query above to seen // Set all posts from the query above to seen
$idarray = array(); $idarray = array();
foreach ($r AS $item) { foreach ($r as $item) {
$idarray[] = intval($item["id"]); $idarray[] = intval($item["id"]);
} }
@ -1558,8 +1583,8 @@ $called_api = null;
api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true); api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true); api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
function api_statuses_public_timeline($type) { function api_statuses_public_timeline($type)
{
$a = get_app(); $a = get_app();
if (api_user() === false) { if (api_user() === false) {
@ -1593,7 +1618,8 @@ $called_api = null;
$sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id); $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
} }
$r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, $r = q(
"SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`, `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
`contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`, `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
`contact`.`id` AS `cid`, `contact`.`id` AS `cid`,
@ -1613,7 +1639,8 @@ $called_api = null;
dbesc(ACTIVITY_POST), dbesc(ACTIVITY_POST),
intval($since_id), intval($since_id),
intval($start), intval($start),
intval($count)); intval($count)
);
$ret = api_format_items($r, $user_info, false, $type); $ret = api_format_items($r, $user_info, false, $type);
@ -1634,8 +1661,8 @@ $called_api = null;
/** /**
* @TODO nothing to say? * @TODO nothing to say?
*/ */
function api_statuses_show($type) { function api_statuses_show($type)
{
$a = get_app(); $a = get_app();
if (api_user() === false) { if (api_user() === false) {
@ -1667,7 +1694,8 @@ $called_api = null;
$sql_extra .= " AND `item`.`id` = %d"; $sql_extra .= " AND `item`.`id` = %d";
} }
$r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, $r = q(
"SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`, `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
`contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`, `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
`contact`.`id` AS `cid` `contact`.`id` AS `cid`
@ -1704,8 +1732,8 @@ $called_api = null;
/** /**
* @TODO nothing to say? * @TODO nothing to say?
*/ */
function api_conversation_show($type) { function api_conversation_show($type)
{
$a = get_app(); $a = get_app();
if (api_user() === false) { if (api_user() === false) {
@ -1753,7 +1781,8 @@ $called_api = null;
// FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1` // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
// ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`) // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
$r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, $r = q(
"SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`, `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
`contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`, `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
`contact`.`id` AS `cid` `contact`.`id` AS `cid`
@ -1788,7 +1817,8 @@ $called_api = null;
/** /**
* @TODO nothing to say? * @TODO nothing to say?
*/ */
function api_statuses_repeat($type) { function api_statuses_repeat($type)
{
global $called_api; global $called_api;
$a = get_app(); $a = get_app();
@ -1813,7 +1843,8 @@ $called_api = null;
logger('API: api_statuses_repeat: '.$id); logger('API: api_statuses_repeat: '.$id);
$r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`, $r = q(
"SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
`contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`, `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
`contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`, `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
`contact`.`id` AS `cid` `contact`.`id` AS `cid`
@ -1864,8 +1895,8 @@ $called_api = null;
/** /**
* @TODO nothing to say? * @TODO nothing to say?
*/ */
function api_statuses_destroy($type) { function api_statuses_destroy($type)
{
$a = get_app(); $a = get_app();
if (api_user() === false) { if (api_user() === false) {
@ -1902,8 +1933,8 @@ $called_api = null;
* @TODO Nothing more than an URL to say? * @TODO Nothing more than an URL to say?
* http://developer.twitter.com/doc/get/statuses/mentions * http://developer.twitter.com/doc/get/statuses/mentions
*/ */
function api_statuses_mentions($type) { function api_statuses_mentions($type)
{
$a = get_app(); $a = get_app();
if (api_user() === false) { if (api_user() === false) {
@ -1943,7 +1974,8 @@ $called_api = null;
$sql_extra = ' AND `item`.`id` <= ' . intval($max_id); $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
} }
$r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, $r = q(
"SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`, `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
`contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`, `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
`contact`.`id` AS `cid` `contact`.`id` AS `cid`
@ -1963,7 +1995,8 @@ $called_api = null;
dbesc(protect_sprintf($myurl)), dbesc(protect_sprintf($myurl)),
intval(api_user()), intval(api_user()),
intval($since_id), intval($since_id),
intval($start), intval($count) intval($start),
intval($count)
); );
$ret = api_format_items($r, $user_info, false, $type); $ret = api_format_items($r, $user_info, false, $type);
@ -1983,8 +2016,8 @@ $called_api = null;
api_register_func('api/statuses/mentions', 'api_statuses_mentions', true); api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
api_register_func('api/statuses/replies', 'api_statuses_mentions', true); api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
function api_statuses_user_timeline($type) { function api_statuses_user_timeline($type)
{
$a = get_app(); $a = get_app();
if (api_user() === false) { if (api_user() === false) {
@ -1994,10 +2027,12 @@ $called_api = null;
$user_info = api_get_user($a); $user_info = api_get_user($a);
// get last network messages // get last network messages
logger("api_statuses_user_timeline: api_user: ". api_user() . logger(
"api_statuses_user_timeline: api_user: ". api_user() .
"\nuser_info: ".print_r($user_info, true) . "\nuser_info: ".print_r($user_info, true) .
"\n_REQUEST: ".print_r($_REQUEST, true), "\n_REQUEST: ".print_r($_REQUEST, true),
LOGGER_DEBUG); LOGGER_DEBUG
);
// params // params
$count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20); $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
@ -2024,7 +2059,8 @@ $called_api = null;
$sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id); $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
} }
$r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, $r = q(
"SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`, `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
`contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`, `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
`contact`.`id` AS `cid` `contact`.`id` AS `cid`
@ -2041,7 +2077,8 @@ $called_api = null;
dbesc(ACTIVITY_POST), dbesc(ACTIVITY_POST),
intval($user_info['cid']), intval($user_info['cid']),
intval($since_id), intval($since_id),
intval($start), intval($count) intval($start),
intval($count)
); );
$ret = api_format_items($r, $user_info, true, $type); $ret = api_format_items($r, $user_info, true, $type);
@ -2066,8 +2103,8 @@ $called_api = null;
* *
* api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
*/ */
function api_favorites_create_destroy($type) { function api_favorites_create_destroy($type)
{
$a = get_app(); $a = get_app();
if (api_user() === false) { if (api_user() === false) {
@ -2092,8 +2129,7 @@ $called_api = null;
$itemid = intval($_REQUEST['id']); $itemid = intval($_REQUEST['id']);
} }
$item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
$itemid, api_user());
if (!DBM::is_result($item) || count($item) == 0) { if (!DBM::is_result($item) || count($item) == 0) {
throw new BadRequestException("Invalid item."); throw new BadRequestException("Invalid item.");
@ -2110,11 +2146,9 @@ $called_api = null;
throw new BadRequestException("Invalid action ".$action); throw new BadRequestException("Invalid action ".$action);
} }
$r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d", $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
$item[0]['starred'], $itemid, api_user());
q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d", q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
$item[0]['starred'], $itemid, api_user());
if ($r === false) { if ($r === false) {
throw new InternalServerErrorException("DB error"); throw new InternalServerErrorException("DB error");
@ -2139,7 +2173,8 @@ $called_api = null;
api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST); api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE); api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
function api_favorites($type) { function api_favorites($type)
{
global $called_api; global $called_api;
$a = get_app(); $a = get_app();
@ -2176,7 +2211,8 @@ $called_api = null;
$sql_extra .= ' AND `item`.`id` <= ' . intval($max_id); $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
} }
$r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, $r = q(
"SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`, `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
`contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`, `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
`contact`.`id` AS `cid` `contact`.`id` AS `cid`
@ -2191,11 +2227,11 @@ $called_api = null;
ORDER BY `item`.`id` DESC LIMIT %d ,%d ", ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
intval(api_user()), intval(api_user()),
intval($since_id), intval($since_id),
intval($start), intval($count) intval($start),
intval($count)
); );
$ret = api_format_items($r, $user_info, false, $type); $ret = api_format_items($r, $user_info, false, $type);
} }
$data = array('status' => $ret); $data = array('status' => $ret);
@ -2211,9 +2247,10 @@ $called_api = null;
/// @TODO move to top of file or somwhere better /// @TODO move to top of file or somwhere better
api_register_func('api/favorites', 'api_favorites', true); api_register_func('api/favorites', 'api_favorites', true);
function api_format_messages($item, $recipient, $sender) { function api_format_messages($item, $recipient, $sender)
{
// standard meta information // standard meta information
$ret=Array( $ret = array(
'id' => $item['id'], 'id' => $item['id'],
'sender_id' => $sender['id'] , 'sender_id' => $sender['id'] ,
'text' => "", 'text' => "",
@ -2254,7 +2291,8 @@ $called_api = null;
return $ret; return $ret;
} }
function api_convert_item($item) { function api_convert_item($item)
{
$body = $item['body']; $body = $item['body'];
$attachments = api_get_attachments($body); $attachments = api_get_attachments($body);
@ -2322,8 +2360,8 @@ $called_api = null;
); );
} }
function api_get_attachments(&$body) { function api_get_attachments(&$body)
{
$text = $body; $text = $body;
$text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text); $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
@ -2336,7 +2374,7 @@ $called_api = null;
$attachments = array(); $attachments = array();
foreach ($images[1] AS $image) { foreach ($images[1] as $image) {
$imagedata = get_photo_info($image); $imagedata = get_photo_info($image);
if ($imagedata) { if ($imagedata) {
@ -2345,7 +2383,7 @@ $called_api = null;
} }
if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) { if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
foreach ($images[0] AS $orig) { foreach ($images[0] as $orig) {
$body = str_replace($orig, "", $body); $body = str_replace($orig, "", $body);
} }
} }
@ -2353,7 +2391,8 @@ $called_api = null;
return $attachments; return $attachments;
} }
function api_get_entitities(&$text, $bbcode) { function api_get_entitities(&$text, $bbcode)
{
/* /*
To-Do: To-Do:
* Links at the first character of the post * Links at the first character of the post
@ -2364,10 +2403,9 @@ $called_api = null;
$include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false"); $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
if ($include_entities != "true") { if ($include_entities != "true") {
preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images); preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
foreach ($images[1] AS $image) { foreach ($images[1] as $image) {
$replace = proxy_url($image); $replace = proxy_url($image);
$text = str_replace($image, $replace, $text); $text = str_replace($image, $replace, $text);
} }
@ -2393,12 +2431,18 @@ $called_api = null;
//$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode); //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
$bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode); $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
$bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism", $bbcode = preg_replace(
'[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode); "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
'[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
$bbcode
);
$bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode); $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
$bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism", $bbcode = preg_replace(
'[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode); "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
'[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
$bbcode
);
$bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode); $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
$bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode); $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
@ -2407,7 +2451,7 @@ $called_api = null;
preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls); preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
$ordered_urls = array(); $ordered_urls = array();
foreach ($urls[1] AS $id => $url) { foreach ($urls[1] as $id => $url) {
//$start = strpos($text, $url, $offset); //$start = strpos($text, $url, $offset);
$start = iconv_strpos($text, $url, 0, "UTF-8"); $start = iconv_strpos($text, $url, 0, "UTF-8");
if (!($start === false)) { if (!($start === false)) {
@ -2419,9 +2463,10 @@ $called_api = null;
$offset = 0; $offset = 0;
//foreach ($urls[1] AS $id=>$url) { //foreach ($urls[1] AS $id=>$url) {
foreach ($ordered_urls AS $url) { foreach ($ordered_urls as $url) {
if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://") && if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
!strpos($url["title"], "http://") && !strpos($url["title"], "https://")) && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
)
$display_url = $url["title"]; $display_url = $url["title"];
else { else {
$display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]); $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
@ -2444,7 +2489,7 @@ $called_api = null;
preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images); preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
$ordered_images = array(); $ordered_images = array();
foreach ($images[1] AS $image) { foreach ($images[1] as $image) {
//$start = strpos($text, $url, $offset); //$start = strpos($text, $url, $offset);
$start = iconv_strpos($text, $image, 0, "UTF-8"); $start = iconv_strpos($text, $image, 0, "UTF-8");
if (!($start === false)) if (!($start === false))
@ -2453,7 +2498,7 @@ $called_api = null;
//$entities["media"] = array(); //$entities["media"] = array();
$offset = 0; $offset = 0;
foreach ($ordered_images AS $url) { foreach ($ordered_images as $url) {
$display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url); $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
$display_url = str_replace(array("http://", "https://"), array("", ""), $display_url); $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
@ -2508,13 +2553,15 @@ $called_api = null;
return $entities; return $entities;
} }
function api_format_items_embeded_images(&$item, $text) { function api_format_items_embeded_images(&$item, $text)
{
$text = preg_replace_callback( $text = preg_replace_callback(
"|data:image/([^;]+)[^=]+=*|m", "|data:image/([^;]+)[^=]+=*|m",
function ($match) use ($item) { function ($match) use ($item) {
return System::baseUrl()."/display/".$item['guid']; return System::baseUrl()."/display/".$item['guid'];
}, },
$text); $text
);
return $text; return $text;
} }
@ -2522,12 +2569,13 @@ $called_api = null;
/** /**
* @brief return <a href='url'>name</a> as array * @brief return <a href='url'>name</a> as array
* *
* @param string $txt * @param string $txt text
* @return array * @return array
* name => 'name' * name => 'name'
* 'url => 'url' * 'url => 'url'
*/ */
function api_contactlink_to_array($txt) { function api_contactlink_to_array($txt)
{
$match = array(); $match = array();
$r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match); $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
if ($r && count($match)==3) { if ($r && count($match)==3) {
@ -2548,13 +2596,13 @@ $called_api = null;
/** /**
* @brief return likes, dislikes and attend status for item * @brief return likes, dislikes and attend status for item
* *
* @param array $item * @param array $item array
* @return array * @return array
* likes => int count * likes => int count
* dislikes => int count * dislikes => int count
*/ */
function api_format_items_activities(&$item, $type = "json") { function api_format_items_activities(&$item, $type = "json")
{
$a = get_app(); $a = get_app();
$activities = array( $activities = array(
@ -2565,10 +2613,12 @@ $called_api = null;
'attendmaybe' => array(), 'attendmaybe' => array(),
); );
$items = q('SELECT * FROM item $items = q(
'SELECT * FROM item
WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted', WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
intval($item['uid']), intval($item['uid']),
dbesc($item['uri'])); dbesc($item['uri'])
);
foreach ($items as $i) { foreach ($items as $i) {
// not used as result should be structured like other user data // not used as result should be structured like other user data
@ -2611,7 +2661,6 @@ $called_api = null;
} }
return $activities; return $activities;
} }
@ -2622,7 +2671,8 @@ $called_api = null;
* @param string $type Known types are 'atom', 'rss', 'xml' and 'json' * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
* @return array * @return array
*/ */
function api_format_items_profiles(&$profile = null, $type = "json") { function api_format_items_profiles(&$profile = null, $type = "json")
{
if ($profile != null) { if ($profile != null) {
$profile = array('profile_id' => $profile['id'], $profile = array('profile_id' => $profile['id'],
'profile_name' => $profile['profile-name'], 'profile_name' => $profile['profile-name'],
@ -2674,14 +2724,13 @@ $called_api = null;
* @param array $user_info * @param array $user_info
* @param bool $filter_user filter items by $user_info * @param bool $filter_user filter items by $user_info
*/ */
function api_format_items($r,$user_info, $filter_user = false, $type = "json") { function api_format_items($r, $user_info, $filter_user = false, $type = "json")
{
$a = get_app(); $a = get_app();
$ret = array(); $ret = array();
foreach ($r as $item) { foreach ($r as $item) {
localize_item($item); localize_item($item);
list($status_user, $owner_user) = api_item_get_user($a, $item); list($status_user, $owner_user) = api_item_get_user($a, $item);
@ -2702,7 +2751,7 @@ $called_api = null;
$status = array( $status = array(
'text' => $converted["text"], 'text' => $converted["text"],
'truncated' => False, 'truncated' => false,
'created_at'=> api_date($item['created']), 'created_at'=> api_date($item['created']),
'in_reply_to_status_id' => $in_reply_to['status_id'], 'in_reply_to_status_id' => $in_reply_to['status_id'],
'in_reply_to_status_id_str' => $in_reply_to['status_id_str'], 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
@ -2712,7 +2761,7 @@ $called_api = null;
'in_reply_to_user_id' => $in_reply_to['user_id'], 'in_reply_to_user_id' => $in_reply_to['user_id'],
'in_reply_to_user_id_str' => $in_reply_to['user_id_str'], 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
'in_reply_to_screen_name' => $in_reply_to['screen_name'], 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
$geo => NULL, $geo => null,
'favorited' => $item['starred'] ? true : false, 'favorited' => $item['starred'] ? true : false,
'user' => $status_user , 'user' => $status_user ,
'friendica_owner' => $owner_user, 'friendica_owner' => $owner_user,
@ -2786,8 +2835,8 @@ $called_api = null;
return $ret; return $ret;
} }
function api_account_rate_limit_status($type) { function api_account_rate_limit_status($type)
{
if ($type == "xml") { if ($type == "xml") {
$hash = array( $hash = array(
'remaining-hits' => '150', 'remaining-hits' => '150',
@ -2814,7 +2863,8 @@ $called_api = null;
/// @TODO move to top of file or somwhere better /// @TODO move to top of file or somwhere better
api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true); api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
function api_help_test($type) { function api_help_test($type)
{
if ($type == 'xml') { if ($type == 'xml') {
$ok = "true"; $ok = "true";
} else { } else {
@ -2827,7 +2877,8 @@ $called_api = null;
/// @TODO move to top of file or somwhere better /// @TODO move to top of file or somwhere better
api_register_func('api/help/test', 'api_help_test', false); api_register_func('api/help/test', 'api_help_test', false);
function api_lists($type) { function api_lists($type)
{
$ret = array(); $ret = array();
/// @TODO $ret is not filled here? /// @TODO $ret is not filled here?
return api_format_data('lists', $type, array("lists_list" => $ret)); return api_format_data('lists', $type, array("lists_list" => $ret));
@ -2836,7 +2887,8 @@ $called_api = null;
/// @TODO move to top of file or somwhere better /// @TODO move to top of file or somwhere better
api_register_func('api/lists', 'api_lists', true); api_register_func('api/lists', 'api_lists', true);
function api_lists_list($type) { function api_lists_list($type)
{
$ret = array(); $ret = array();
/// @TODO $ret is not filled here? /// @TODO $ret is not filled here?
return api_format_data('lists', $type, array("lists_list" => $ret)); return api_format_data('lists', $type, array("lists_list" => $ret));
@ -2850,8 +2902,8 @@ $called_api = null;
* This function is deprecated by Twitter * This function is deprecated by Twitter
* returns: json, xml * returns: json, xml
*/ */
function api_statuses_f($type, $qtype) { function api_statuses_f($type, $qtype)
{
$a = get_app(); $a = get_app();
if (api_user() === false) { if (api_user() === false) {
@ -2883,7 +2935,8 @@ $called_api = null;
$sql_extra = " AND false "; $sql_extra = " AND false ";
} }
$r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND NOT `self` AND (NOT `blocked` OR `pending`) $sql_extra ORDER BY `nick`", $r = q(
"SELECT `nurl` FROM `contact` WHERE `uid` = %d AND NOT `self` AND (NOT `blocked` OR `pending`) $sql_extra ORDER BY `nick`",
intval(api_user()) intval(api_user())
); );
@ -2903,7 +2956,8 @@ $called_api = null;
} }
function api_statuses_friends($type) { function api_statuses_friends($type)
{
$data = api_statuses_f($type, "friends"); $data = api_statuses_f($type, "friends");
if ($data === false) { if ($data === false) {
return false; return false;
@ -2911,7 +2965,8 @@ $called_api = null;
return api_format_data("users", $type, $data); return api_format_data("users", $type, $data);
} }
function api_statuses_followers($type) { function api_statuses_followers($type)
{
$data = api_statuses_f($type, "followers"); $data = api_statuses_f($type, "followers");
if ($data === false) { if ($data === false) {
return false; return false;
@ -2923,8 +2978,8 @@ $called_api = null;
api_register_func('api/statuses/friends', 'api_statuses_friends', true); api_register_func('api/statuses/friends', 'api_statuses_friends', true);
api_register_func('api/statuses/followers', 'api_statuses_followers', true); api_register_func('api/statuses/followers', 'api_statuses_followers', true);
function api_statusnet_config($type) { function api_statusnet_config($type)
{
$a = get_app(); $a = get_app();
$name = $a->config['sitename']; $name = $a->config['sitename'];
@ -2956,14 +3011,14 @@ $called_api = null;
); );
return api_format_data('config', $type, array('config' => $config)); return api_format_data('config', $type, array('config' => $config));
} }
/// @TODO move to top of file or somewhere better /// @TODO move to top of file or somewhere better
api_register_func('api/gnusocial/config', 'api_statusnet_config', false); api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
api_register_func('api/statusnet/config', 'api_statusnet_config', false); api_register_func('api/statusnet/config', 'api_statusnet_config', false);
function api_statusnet_version($type) { function api_statusnet_version($type)
{
// liar // liar
$fake_statusnet_version = "0.9.7"; $fake_statusnet_version = "0.9.7";
@ -2977,8 +3032,8 @@ $called_api = null;
/** /**
* @todo use api_format_data() to return data * @todo use api_format_data() to return data
*/ */
function api_ff_ids($type,$qtype) { function api_ff_ids($type,$qtype)
{
$a = get_app(); $a = get_app();
if (! api_user()) { if (! api_user()) {
@ -3000,7 +3055,8 @@ $called_api = null;
$stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false); $stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
$r = q("SELECT `pcontact`.`id` FROM `contact` $r = q(
"SELECT `pcontact`.`id` FROM `contact`
INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
WHERE `contact`.`uid` = %s AND NOT `contact`.`self`", WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
intval(api_user()) intval(api_user())
@ -3022,11 +3078,13 @@ $called_api = null;
return api_format_data("ids", $type, array('id' => $ids)); return api_format_data("ids", $type, array('id' => $ids));
} }
function api_friends_ids($type) { function api_friends_ids($type)
{
return api_ff_ids($type, 'friends'); return api_ff_ids($type, 'friends');
} }
function api_followers_ids($type) { function api_followers_ids($type)
{
return api_ff_ids($type, 'followers'); return api_ff_ids($type, 'followers');
} }
@ -3034,7 +3092,8 @@ $called_api = null;
api_register_func('api/friends/ids', 'api_friends_ids', true); api_register_func('api/friends/ids', 'api_friends_ids', true);
api_register_func('api/followers/ids', 'api_followers_ids', true); api_register_func('api/followers/ids', 'api_followers_ids', true);
function api_direct_messages_new($type) { function api_direct_messages_new($type)
{
$a = get_app(); $a = get_app();
@ -3045,9 +3104,11 @@ $called_api = null;
$sender = api_get_user($a); $sender = api_get_user($a);
if ($_POST['screen_name']) { if ($_POST['screen_name']) {
$r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'", $r = q(
"SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
intval(api_user()), intval(api_user()),
dbesc($_POST['screen_name'])); dbesc($_POST['screen_name'])
);
// Selecting the id by priority, friendica first // Selecting the id by priority, friendica first
api_best_nickname($r); api_best_nickname($r);
@ -3060,9 +3121,11 @@ $called_api = null;
$replyto = ''; $replyto = '';
$sub = ''; $sub = '';
if (x($_REQUEST, 'replyto')) { if (x($_REQUEST, 'replyto')) {
$r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d', $r = q(
'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
intval(api_user()), intval(api_user()),
intval($_REQUEST['replyto'])); intval($_REQUEST['replyto'])
);
$replyto = $r[0]['parent-uri']; $replyto = $r[0]['parent-uri'];
$sub = $r[0]['title']; $sub = $r[0]['title'];
} else { } else {
@ -3103,7 +3166,8 @@ $called_api = null;
* @param string $type Known types are 'atom', 'rss', 'xml' and 'json' * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
* @return string * @return string
*/ */
function api_direct_messages_destroy($type) { function api_direct_messages_destroy($type)
{
$a = get_app(); $a = get_app();
if (api_user() === false) { if (api_user() === false) {
@ -3135,9 +3199,11 @@ $called_api = null;
$sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : ""); $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
// get data of the specified message id // get data of the specified message id
$r = q("SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra, $r = q(
"SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
intval($uid), intval($uid),
intval($id)); intval($id)
);
// error message if specified id is not in database // error message if specified id is not in database
if (!DBM::is_result($r)) { if (!DBM::is_result($r)) {
@ -3150,9 +3216,11 @@ $called_api = null;
} }
// delete message // delete message
$result = q("DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra, $result = q(
"DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
intval($uid), intval($uid),
intval($id)); intval($id)
);
if ($verbose == "true") { if ($verbose == "true") {
if ($result) { if ($result) {
@ -3171,8 +3239,8 @@ $called_api = null;
/// @TODO move to top of file or somewhere better /// @TODO move to top of file or somewhere better
api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE); api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
function api_direct_messages_box($type, $box, $verbose) { function api_direct_messages_box($type, $box, $verbose)
{
$a = get_app(); $a = get_app();
if (api_user() === false) { if (api_user() === false) {
@ -3226,10 +3294,12 @@ $called_api = null;
$sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'"; $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
} }
$r = q("SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND $sql_extra AND `mail`.`id` > %d ORDER BY `mail`.`id` DESC LIMIT %d,%d", $r = q(
"SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND $sql_extra AND `mail`.`id` > %d ORDER BY `mail`.`id` DESC LIMIT %d,%d",
intval(api_user()), intval(api_user()),
intval($since_id), intval($since_id),
intval($start), intval($count) intval($start),
intval($count)
); );
if ($verbose == "true" && !DBM::is_result($r)) { if ($verbose == "true" && !DBM::is_result($r)) {
$answer = array('result' => 'error', 'message' => 'no mails available'); $answer = array('result' => 'error', 'message' => 'no mails available');
@ -3258,25 +3328,28 @@ $called_api = null;
} }
return api_format_data("direct-messages", $type, $data); return api_format_data("direct-messages", $type, $data);
} }
function api_direct_messages_sentbox($type) { function api_direct_messages_sentbox($type)
{
$verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false"); $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
return api_direct_messages_box($type, "sentbox", $verbose); return api_direct_messages_box($type, "sentbox", $verbose);
} }
function api_direct_messages_inbox($type) { function api_direct_messages_inbox($type)
{
$verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false"); $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
return api_direct_messages_box($type, "inbox", $verbose); return api_direct_messages_box($type, "inbox", $verbose);
} }
function api_direct_messages_all($type) { function api_direct_messages_all($type)
{
$verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false"); $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
return api_direct_messages_box($type, "all", $verbose); return api_direct_messages_box($type, "all", $verbose);
} }
function api_direct_messages_conversation($type) { function api_direct_messages_conversation($type)
{
$verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false"); $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
return api_direct_messages_box($type, "conversation", $verbose); return api_direct_messages_box($type, "conversation", $verbose);
} }
@ -3287,7 +3360,8 @@ $called_api = null;
api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true); api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
api_register_func('api/direct_messages', 'api_direct_messages_inbox', true); api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
function api_oauth_request_token($type) { function api_oauth_request_token($type)
{
try { try {
$oauth = new FKOAuth1(); $oauth = new FKOAuth1();
$r = $oauth->fetch_request_token(OAuthRequest::from_request()); $r = $oauth->fetch_request_token(OAuthRequest::from_request());
@ -3299,12 +3373,14 @@ $called_api = null;
killme(); killme();
} }
function api_oauth_access_token($type) { function api_oauth_access_token($type)
{
try { try {
$oauth = new FKOAuth1(); $oauth = new FKOAuth1();
$r = $oauth->fetch_access_token(OAuthRequest::from_request()); $r = $oauth->fetch_access_token(OAuthRequest::from_request());
} catch (Exception $e) { } catch (Exception $e) {
echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme(); echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
killme();
} }
echo $r; echo $r;
killme(); killme();
@ -3321,7 +3397,8 @@ $called_api = null;
* @param string $type Known types are 'atom', 'rss', 'xml' and 'json' * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
* @return string * @return string
*/ */
function api_fr_photoalbum_delete($type) { function api_fr_photoalbum_delete($type)
{
if (api_user() === false) { if (api_user() === false) {
throw new ForbiddenException(); throw new ForbiddenException();
} }
@ -3333,16 +3410,19 @@ $called_api = null;
throw new BadRequestException("no albumname specified"); throw new BadRequestException("no albumname specified");
} }
// check if album is existing // check if album is existing
$r = q("SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'", $r = q(
"SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
intval(api_user()), intval(api_user()),
dbesc($album)); dbesc($album)
);
if (!DBM::is_result($r)) if (!DBM::is_result($r))
throw new BadRequestException("album not available"); throw new BadRequestException("album not available");
// function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
// to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
foreach ($r as $rr) { foreach ($r as $rr) {
$photo_item = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'", $photo_item = q(
"SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
intval(local_user()), intval(local_user()),
dbesc($rr['resource-id']) dbesc($rr['resource-id'])
); );
@ -3354,9 +3434,11 @@ $called_api = null;
} }
// now let's delete all photos from the album // now let's delete all photos from the album
$result = q("DELETE FROM `photo` WHERE `uid` = %d AND `album` = '%s'", $result = q(
"DELETE FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
intval(api_user()), intval(api_user()),
dbesc($album)); dbesc($album)
);
// return success of deletion or error message // return success of deletion or error message
if ($result) { if ($result) {
@ -3365,7 +3447,6 @@ $called_api = null;
} else { } else {
throw new InternalServerErrorException("unknown error - deleting from database failed"); throw new InternalServerErrorException("unknown error - deleting from database failed");
} }
} }
/** /**
@ -3374,7 +3455,8 @@ $called_api = null;
* @param string $type Known types are 'atom', 'rss', 'xml' and 'json' * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
* @return string * @return string
*/ */
function api_fr_photoalbum_update($type) { function api_fr_photoalbum_update($type)
{
if (api_user() === false) { if (api_user() === false) {
throw new ForbiddenException(); throw new ForbiddenException();
} }
@ -3390,17 +3472,21 @@ $called_api = null;
throw new BadRequestException("no new albumname specified"); throw new BadRequestException("no new albumname specified");
} }
// check if album is existing // check if album is existing
$r = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'", $r = q(
"SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
intval(api_user()), intval(api_user()),
dbesc($album)); dbesc($album)
);
if (!DBM::is_result($r)) { if (!DBM::is_result($r)) {
throw new BadRequestException("album not available"); throw new BadRequestException("album not available");
} }
// now let's update all photos to the albumname // now let's update all photos to the albumname
$result = q("UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'", $result = q(
"UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
dbesc($album_new), dbesc($album_new),
intval(api_user()), intval(api_user()),
dbesc($album)); dbesc($album)
);
// return success of updating or error message // return success of updating or error message
if ($result) { if ($result) {
@ -3418,11 +3504,13 @@ $called_api = null;
* @param string $type Known types are 'atom', 'rss', 'xml' and 'json' * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
* @return string * @return string
*/ */
function api_fr_photos_list($type) { function api_fr_photos_list($type)
{
if (api_user() === false) { if (api_user() === false) {
throw new ForbiddenException(); throw new ForbiddenException();
} }
$r = q("SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`, $r = q(
"SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo` MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`", WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
intval(local_user()) intval(local_user())
@ -3462,7 +3550,8 @@ $called_api = null;
* @param string $type Known types are 'atom', 'rss', 'xml' and 'json' * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
* @return string * @return string
*/ */
function api_fr_photo_create_update($type) { function api_fr_photo_create_update($type)
{
if (api_user() === false) { if (api_user() === false) {
throw new ForbiddenException(); throw new ForbiddenException();
} }
@ -3498,10 +3587,12 @@ $called_api = null;
$mode = "update"; $mode = "update";
// check if photo is existing in database // check if photo is existing in database
$r = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'", $r = q(
"SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
intval(api_user()), intval(api_user()),
dbesc($photo_id), dbesc($photo_id),
dbesc($album)); dbesc($album)
);
if (!DBM::is_result($r)) { if (!DBM::is_result($r)) {
throw new BadRequestException("photo not available"); throw new BadRequestException("photo not available");
} }
@ -3564,12 +3655,14 @@ $called_api = null;
$result = false; $result = false;
if ($sql_extra != "") { if ($sql_extra != "") {
$nothingtodo = false; $nothingtodo = false;
$result = q("UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'", $result = q(
"UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
$sql_extra, $sql_extra,
datetime_convert(), // update edited timestamp datetime_convert(), // update edited timestamp
intval(api_user()), intval(api_user()),
dbesc($photo_id), dbesc($photo_id),
dbesc($album)); dbesc($album)
);
} else { } else {
$nothingtodo = true; $nothingtodo = true;
} }
@ -3605,7 +3698,8 @@ $called_api = null;
* @param string $type Known types are 'atom', 'rss', 'xml' and 'json' * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
* @return string * @return string
*/ */
function api_fr_photo_delete($type) { function api_fr_photo_delete($type)
{
if (api_user() === false) { if (api_user() === false) {
throw new ForbiddenException(); throw new ForbiddenException();
} }
@ -3618,7 +3712,8 @@ $called_api = null;
throw new BadRequestException("no photo_id specified"); throw new BadRequestException("no photo_id specified");
} }
// check if photo is existing in database // check if photo is existing in database
$r = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'", $r = q(
"SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
intval(api_user()), intval(api_user()),
dbesc($photo_id) dbesc($photo_id)
); );
@ -3626,14 +3721,17 @@ $called_api = null;
throw new BadRequestException("photo not available"); throw new BadRequestException("photo not available");
} }
// now we can perform on the deletion of the photo // now we can perform on the deletion of the photo
$result = q("DELETE FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'", $result = q(
"DELETE FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
intval(api_user()), intval(api_user()),
dbesc($photo_id)); dbesc($photo_id)
);
// return success of deletion or error message // return success of deletion or error message
if ($result) { if ($result) {
// retrieve the id of the parent element (the photo element) // retrieve the id of the parent element (the photo element)
$photo_item = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'", $photo_item = q(
"SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
intval(local_user()), intval(local_user()),
dbesc($photo_id) dbesc($photo_id)
); );
@ -3659,7 +3757,8 @@ $called_api = null;
* @param string $type Known types are 'atom', 'rss', 'xml' and 'json' * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
* @return string * @return string
*/ */
function api_fr_photo_detail($type) { function api_fr_photo_detail($type)
{
if (api_user() === false) { if (api_user() === false) {
throw new ForbiddenException(); throw new ForbiddenException();
} }
@ -3683,7 +3782,8 @@ $called_api = null;
* @param string $type Known types are 'atom', 'rss', 'xml' and 'json' * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
* @return string * @return string
*/ */
function api_account_update_profile_image($type) { function api_account_update_profile_image($type)
{
if (api_user() === false) { if (api_user() === false) {
throw new ForbiddenException(); throw new ForbiddenException();
} }
@ -3697,9 +3797,11 @@ $called_api = null;
// check if specified profile id is valid // check if specified profile id is valid
if ($profileid != 0) { if ($profileid != 0) {
$r = q("SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d", $r = q(
"SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
intval(api_user()), intval(api_user()),
intval($profileid)); intval($profileid)
);
// error message if specified profile id is not in database // error message if specified profile id is not in database
if (!DBM::is_result($r)) { if (!DBM::is_result($r)) {
throw new BadRequestException("profile_id not available"); throw new BadRequestException("profile_id not available");
@ -3732,19 +3834,22 @@ $called_api = null;
} }
// change specified profile or all profiles to the new resource-id // change specified profile or all profiles to the new resource-id
if ($is_default_profile) { if ($is_default_profile) {
$r = q("UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d", $r = q(
"UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
dbesc($data['photo']['id']), dbesc($data['photo']['id']),
intval(local_user()) intval(local_user())
); );
$r = q("UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d", $r = q(
"UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext), dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext), dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext), dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
intval(local_user()) intval(local_user())
); );
} else { } else {
$r = q("UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d", $r = q(
"UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype), dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype), dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
intval($_REQUEST['profile']), intval($_REQUEST['profile']),
@ -3755,7 +3860,8 @@ $called_api = null;
// we'll set the updated profile-photo timestamp even if it isn't the default profile, // we'll set the updated profile-photo timestamp even if it isn't the default profile,
// so that browsers will do a cache update unconditionally // so that browsers will do a cache update unconditionally
$r = q("UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d", $r = q(
"UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
dbesc(datetime_convert()), dbesc(datetime_convert()),
intval(local_user()) intval(local_user())
); );
@ -3789,7 +3895,8 @@ $called_api = null;
api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST); api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
function check_acl_input($acl_string) { function check_acl_input($acl_string)
{
if ($acl_string == null || $acl_string == " ") { if ($acl_string == null || $acl_string == " ") {
return false; return false;
} }
@ -3803,15 +3910,18 @@ $called_api = null;
foreach ($cid_array as $cid) { foreach ($cid_array as $cid) {
$cid = str_replace("<", "", $cid); $cid = str_replace("<", "", $cid);
$cid = str_replace(">", "", $cid); $cid = str_replace(">", "", $cid);
$contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d", $contact = q(
"SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
intval($cid), intval($cid),
intval(api_user())); intval(api_user())
);
$contact_not_found |= !DBM::is_result($contact); $contact_not_found |= !DBM::is_result($contact);
} }
return $contact_not_found; return $contact_not_found;
} }
function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $profile = 0, $visibility = false, $photo_id = null) { function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $profile = 0, $visibility = false, $photo_id = null)
{
$visitor = 0; $visitor = 0;
$src = ""; $src = "";
$filetype = ""; $filetype = "";
@ -3848,8 +3958,10 @@ $called_api = null;
if ($imagedata) { if ($imagedata) {
$filetype = $imagedata['mime']; $filetype = $imagedata['mime'];
} }
logger("File upload src: " . $src . " - filename: " . $filename . logger(
" - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG); "File upload src: " . $src . " - filename: " . $filename .
" - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG
);
// check if there was a php upload error // check if there was a php upload error
if ($filesize == 0 && $media['error'] == 1) { if ($filesize == 0 && $media['error'] == 1) {
@ -3955,7 +4067,8 @@ $called_api = null;
} }
} }
function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false) { function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
{
// get data about the api authenticated user // get data about the api authenticated user
$uri = item_new_uri(get_app()->get_hostname(), intval(api_user())); $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
$owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user())); $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
@ -3999,13 +4112,15 @@ $called_api = null;
item_store($arr); item_store($arr);
} }
function prepare_photo_data($type, $scale, $photo_id) { function prepare_photo_data($type, $scale, $photo_id)
{
$scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale))); $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
$data_sql = ($scale === false ? "" : "data, "); $data_sql = ($scale === false ? "" : "data, ");
// added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
// clients needs to convert this in their way for further processing // clients needs to convert this in their way for further processing
$r = q("SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`, $r = q(
"SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
`type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`, `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale` MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`", FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
@ -4049,20 +4164,21 @@ $called_api = null;
unset($data['photo']['resource-id']); unset($data['photo']['resource-id']);
unset($data['photo']['minscale']); unset($data['photo']['minscale']);
unset($data['photo']['maxscale']); unset($data['photo']['maxscale']);
} else { } else {
throw new NotFoundException(); throw new NotFoundException();
} }
// retrieve item element for getting activities (like, dislike etc.) related to photo // retrieve item element for getting activities (like, dislike etc.) related to photo
$item = q("SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'", $item = q(
"SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
intval(local_user()), intval(local_user()),
dbesc($photo_id) dbesc($photo_id)
); );
$data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type); $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
// retrieve comments on photo // retrieve comments on photo
$r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, $r = q(
"SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`, `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
`contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`, `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
`contact`.`id` AS `cid` `contact`.`id` AS `cid`
@ -4104,17 +4220,18 @@ $called_api = null;
/** /**
* similar as /mod/redir.php * Similar as /mod/redir.php
* redirect to 'url' after dfrn auth * redirect to 'url' after dfrn auth
* *
* why this when there is mod/redir.php already? * Why this when there is mod/redir.php already?
* This use api_user() and api_login() * This use api_user() and api_login()
* *
* params * params
* c_url: url of remote contact to auth to * c_url: url of remote contact to auth to
* url: string, url to redirect after auth * url: string, url to redirect after auth
*/ */
function api_friendica_remoteauth() { function api_friendica_remoteauth()
{
$url = ((x($_GET, 'url')) ? $_GET['url'] : ''); $url = ((x($_GET, 'url')) ? $_GET['url'] : '');
$c_url = ((x($_GET, 'c_url')) ? $_GET['c_url'] : ''); $c_url = ((x($_GET, 'c_url')) ? $_GET['c_url'] : '');
@ -4126,7 +4243,8 @@ $called_api = null;
// traditional DFRN // traditional DFRN
$r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1", $r = q(
"SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
dbesc($c_url), dbesc($c_url),
intval(api_user()) intval(api_user())
); );
@ -4150,7 +4268,8 @@ $called_api = null;
$sec = random_string(); $sec = random_string();
q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`) q(
"INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
VALUES( %d, %s, '%s', '%s', %d )", VALUES( %d, %s, '%s', '%s', %d )",
intval(api_user()), intval(api_user()),
intval($cid), intval($cid),
@ -4161,9 +4280,11 @@ $called_api = null;
logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG); logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
$dest = (($url) ? '&destination_url=' . $url : ''); $dest = (($url) ? '&destination_url=' . $url : '');
goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id goaway(
$r[0]['poll'] . '?dfrn_id=' . $dfrn_id
. '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
. '&type=profile&sec=' . $sec . $dest . $quiet ); . '&type=profile&sec=' . $sec . $dest . $quiet
);
} }
api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true); api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
@ -4173,7 +4294,8 @@ $called_api = null;
* @param array $item Sharer item * @param array $item Sharer item
* @return array Shared item or false if not a reshare * @return array Shared item or false if not a reshare
*/ */
function api_share_as_retweet(&$item) { function api_share_as_retweet(&$item)
{
$body = trim($item["body"]); $body = trim($item["body"]);
if (Diaspora::is_reshare($body, false)===false) { if (Diaspora::is_reshare($body, false)===false) {
@ -4267,7 +4389,8 @@ $called_api = null;
} }
function api_get_nick($profile) { function api_get_nick($profile)
{
/* To-Do: /* To-Do:
- remove trailing junk from profile url - remove trailing junk from profile url
- pump.io check has to check the website - pump.io check has to check the website
@ -4275,16 +4398,20 @@ $called_api = null;
$nick = ""; $nick = "";
$r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'", $r = q(
dbesc(normalise_link($profile))); "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
dbesc(normalise_link($profile))
);
if (DBM::is_result($r)) { if (DBM::is_result($r)) {
$nick = $r[0]["nick"]; $nick = $r[0]["nick"];
} }
if (!$nick == "") { if (!$nick == "") {
$r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'", $r = q(
dbesc(normalise_link($profile))); "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
dbesc(normalise_link($profile))
);
if (DBM::is_result($r)) { if (DBM::is_result($r)) {
$nick = $r[0]["nick"]; $nick = $r[0]["nick"];
@ -4343,14 +4470,15 @@ $called_api = null;
return false; return false;
} }
function api_in_reply_to($item) { function api_in_reply_to($item)
{
$in_reply_to = array(); $in_reply_to = array();
$in_reply_to['status_id'] = NULL; $in_reply_to['status_id'] = null;
$in_reply_to['user_id'] = NULL; $in_reply_to['user_id'] = null;
$in_reply_to['status_id_str'] = NULL; $in_reply_to['status_id_str'] = null;
$in_reply_to['user_id_str'] = NULL; $in_reply_to['user_id_str'] = null;
$in_reply_to['screen_name'] = NULL; $in_reply_to['screen_name'] = null;
if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) { if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
$r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1", $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
@ -4386,18 +4514,19 @@ $called_api = null;
// This is a bugfix for that. // This is a bugfix for that.
if (intval($in_reply_to['status_id']) == intval($item['id'])) { if (intval($in_reply_to['status_id']) == intval($item['id'])) {
logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG); logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
$in_reply_to['status_id'] = NULL; $in_reply_to['status_id'] = null;
$in_reply_to['user_id'] = NULL; $in_reply_to['user_id'] = null;
$in_reply_to['status_id_str'] = NULL; $in_reply_to['status_id_str'] = null;
$in_reply_to['user_id_str'] = NULL; $in_reply_to['user_id_str'] = null;
$in_reply_to['screen_name'] = NULL; $in_reply_to['screen_name'] = null;
} }
} }
return $in_reply_to; return $in_reply_to;
} }
function api_clean_plain_items($Text) { function api_clean_plain_items($Text)
{
$include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false"); $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
$Text = bb_CleanPictureLinks($Text); $Text = bb_CleanPictureLinks($Text);
@ -4422,7 +4551,8 @@ $called_api = null;
* *
* @return string Cleaned body * @return string Cleaned body
*/ */
function api_clean_attachments($body) { function api_clean_attachments($body)
{
$data = get_attachment_data($body); $data = get_attachment_data($body);
if (!$data) if (!$data)
@ -4444,52 +4574,54 @@ $called_api = null;
return $body; return $body;
} }
function api_best_nickname(&$contacts) { function api_best_nickname(&$contacts)
{
$best_contact = array(); $best_contact = array();
if (count($contact) == 0) if (count($contact) == 0)
return; return;
foreach ($contacts AS $contact) foreach ($contacts as $contact)
if ($contact["network"] == "") { if ($contact["network"] == "") {
$contact["network"] = "dfrn"; $contact["network"] = "dfrn";
$best_contact = array($contact); $best_contact = array($contact);
} }
if (sizeof($best_contact) == 0) if (sizeof($best_contact) == 0)
foreach ($contacts AS $contact) foreach ($contacts as $contact)
if ($contact["network"] == "dfrn") if ($contact["network"] == "dfrn")
$best_contact = array($contact); $best_contact = array($contact);
if (sizeof($best_contact) == 0) if (sizeof($best_contact) == 0)
foreach ($contacts AS $contact) foreach ($contacts as $contact)
if ($contact["network"] == "dspr") if ($contact["network"] == "dspr")
$best_contact = array($contact); $best_contact = array($contact);
if (sizeof($best_contact) == 0) if (sizeof($best_contact) == 0)
foreach ($contacts AS $contact) foreach ($contacts as $contact)
if ($contact["network"] == "stat") if ($contact["network"] == "stat")
$best_contact = array($contact); $best_contact = array($contact);
if (sizeof($best_contact) == 0) if (sizeof($best_contact) == 0)
foreach ($contacts AS $contact) foreach ($contacts as $contact)
if ($contact["network"] == "pump") if ($contact["network"] == "pump")
$best_contact = array($contact); $best_contact = array($contact);
if (sizeof($best_contact) == 0) if (sizeof($best_contact) == 0)
foreach ($contacts AS $contact) foreach ($contacts as $contact)
if ($contact["network"] == "twit") if ($contact["network"] == "twit")
$best_contact = array($contact); $best_contact = array($contact);
if (sizeof($best_contact) == 1) if (sizeof($best_contact) == 1) {
$contacts = $best_contact; $contacts = $best_contact;
else } else {
$contacts = array($contacts[0]); $contacts = array($contacts[0]);
} }
}
// return all or a specified group of the user with the containing contacts // return all or a specified group of the user with the containing contacts
function api_friendica_group_show($type) { function api_friendica_group_show($type)
{
$a = get_app(); $a = get_app();
if (api_user() === false) throw new ForbiddenException(); if (api_user() === false) throw new ForbiddenException();
@ -4501,16 +4633,20 @@ $called_api = null;
// get data of the specified group id or all groups if not specified // get data of the specified group id or all groups if not specified
if ($gid != 0) { if ($gid != 0) {
$r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d", $r = q(
"SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
intval($uid), intval($uid),
intval($gid)); intval($gid)
);
// error message if specified gid is not in database // error message if specified gid is not in database
if (!DBM::is_result($r)) if (!DBM::is_result($r))
throw new BadRequestException("gid not available"); throw new BadRequestException("gid not available");
} else {
$r = q(
"SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
intval($uid)
);
} }
else
$r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
intval($uid));
// loop through all groups and retrieve all members for adding data in the user array // loop through all groups and retrieve all members for adding data in the user array
foreach ($r as $rr) { foreach ($r as $rr) {
@ -4539,8 +4675,8 @@ $called_api = null;
// delete the specified group of the user // delete the specified group of the user
function api_friendica_group_delete($type) { function api_friendica_group_delete($type)
{
$a = get_app(); $a = get_app();
if (api_user() === false) throw new ForbiddenException(); if (api_user() === false) throw new ForbiddenException();
@ -4556,18 +4692,22 @@ $called_api = null;
throw new BadRequestException('gid or name not specified'); throw new BadRequestException('gid or name not specified');
// get data of the specified group id // get data of the specified group id
$r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d", $r = q(
"SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
intval($uid), intval($uid),
intval($gid)); intval($gid)
);
// error message if specified gid is not in database // error message if specified gid is not in database
if (!DBM::is_result($r)) if (!DBM::is_result($r))
throw new BadRequestException('gid not available'); throw new BadRequestException('gid not available');
// get data of the specified group id and group name // get data of the specified group id and group name
$rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'", $rname = q(
"SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
intval($uid), intval($uid),
intval($gid), intval($gid),
dbesc($name)); dbesc($name)
);
// error message if specified gid is not in database // error message if specified gid is not in database
if (!DBM::is_result($rname)) if (!DBM::is_result($rname))
throw new BadRequestException('wrong group name'); throw new BadRequestException('wrong group name');
@ -4578,16 +4718,16 @@ $called_api = null;
// return success // return success
$success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array()); $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
return api_format_data("group_delete", $type, array('result' => $success)); return api_format_data("group_delete", $type, array('result' => $success));
} } else {
else
throw new BadRequestException('other API error'); throw new BadRequestException('other API error');
} }
}
api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE); api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
// create the specified group with the posted array of contacts // create the specified group with the posted array of contacts
function api_friendica_group_create($type) { function api_friendica_group_create($type)
{
$a = get_app(); $a = get_app();
if (api_user() === false) throw new ForbiddenException(); if (api_user() === false) throw new ForbiddenException();
@ -4604,27 +4744,32 @@ $called_api = null;
throw new BadRequestException('group name not specified'); throw new BadRequestException('group name not specified');
// get data of the specified group name // get data of the specified group name
$rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0", $rname = q(
"SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
intval($uid), intval($uid),
dbesc($name)); dbesc($name)
);
// error message if specified group name already exists // error message if specified group name already exists
if (DBM::is_result($rname)) if (DBM::is_result($rname))
throw new BadRequestException('group name already exists'); throw new BadRequestException('group name already exists');
// check if specified group name is a deleted group // check if specified group name is a deleted group
$rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1", $rname = q(
"SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
intval($uid), intval($uid),
dbesc($name)); dbesc($name)
);
// error message if specified group name already exists // error message if specified group name already exists
if (DBM::is_result($rname)) if (DBM::is_result($rname))
$reactivate_group = true; $reactivate_group = true;
// create group // create group
$ret = group_add($uid, $name); $ret = group_add($uid, $name);
if ($ret) if ($ret) {
$gid = group_byname($uid, $name); $gid = group_byname($uid, $name);
else } else {
throw new BadRequestException('other API error'); throw new BadRequestException('other API error');
}
// add members // add members
$erroraddinguser = false; $erroraddinguser = false;
@ -4632,9 +4777,11 @@ $called_api = null;
foreach ($users as $user) { foreach ($users as $user) {
$cid = $user['cid']; $cid = $user['cid'];
// check if user really exists as contact // check if user really exists as contact
$contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d", $contact = q(
"SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
intval($cid), intval($cid),
intval($uid)); intval($uid)
);
if (count($contact)) if (count($contact))
$result = group_add_member($uid, $name, $cid, $gid); $result = group_add_member($uid, $name, $cid, $gid);
else { else {
@ -4652,8 +4799,8 @@ $called_api = null;
// update the specified group with the posted array of contacts // update the specified group with the posted array of contacts
function api_friendica_group_update($type) { function api_friendica_group_update($type)
{
$a = get_app(); $a = get_app();
if (api_user() === false) throw new ForbiddenException(); if (api_user() === false) throw new ForbiddenException();
@ -4692,12 +4839,15 @@ $called_api = null;
foreach ($users as $user) { foreach ($users as $user) {
$cid = $user['cid']; $cid = $user['cid'];
// check if user really exists as contact // check if user really exists as contact
$contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d", $contact = q(
"SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
intval($cid), intval($cid),
intval($uid)); intval($uid)
if (count($contact)) );
if (count($contact)) {
$result = group_add_member($uid, $name, $cid, $gid); $result = group_add_member($uid, $name, $cid, $gid);
else { } else {
$erroraddinguser = true; $erroraddinguser = true;
$errorusers[] = $cid; $errorusers[] = $cid;
} }
@ -4711,8 +4861,8 @@ $called_api = null;
api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST); api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
function api_friendica_activity($type) { function api_friendica_activity($type)
{
$a = get_app(); $a = get_app();
if (api_user() === false) throw new ForbiddenException(); if (api_user() === false) throw new ForbiddenException();
@ -4724,15 +4874,15 @@ $called_api = null;
$res = do_like($id, $verb); $res = do_like($id, $verb);
if ($res) { if ($res) {
if ($type == "xml") if ($type == "xml") {
$ok = "true"; $ok = "true";
else } else {
$ok = "ok"; $ok = "ok";
}
return api_format_data('ok', $type, array('ok' => $ok)); return api_format_data('ok', $type, array('ok' => $ok));
} else { } else {
throw new BadRequestException('Error adding activity'); throw new BadRequestException('Error adding activity');
} }
} }
/// @TODO move to top of file or somwhere better /// @TODO move to top of file or somwhere better
@ -4753,8 +4903,8 @@ $called_api = null;
* @param string $type Known types are 'atom', 'rss', 'xml' and 'json' * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
* @return string * @return string
*/ */
function api_friendica_notification($type) { function api_friendica_notification($type)
{
$a = get_app(); $a = get_app();
if (api_user() === false) throw new ForbiddenException(); if (api_user() === false) throw new ForbiddenException();
@ -4765,7 +4915,7 @@ $called_api = null;
if ($type == "xml") { if ($type == "xml") {
$xmlnotes = array(); $xmlnotes = array();
foreach ($notes AS $note) foreach ($notes as $note)
$xmlnotes[] = array("@attributes" => $note); $xmlnotes[] = array("@attributes" => $note);
$notes = $xmlnotes; $notes = $xmlnotes;
@ -4782,8 +4932,8 @@ $called_api = null;
* @param string $type Known types are 'atom', 'rss', 'xml' and 'json' * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
* @return string * @return string
*/ */
function api_friendica_notification_seen($type) { function api_friendica_notification_seen($type)
{
$a = get_app(); $a = get_app();
if (api_user() === false) throw new ForbiddenException(); if (api_user() === false) throw new ForbiddenException();
@ -4798,7 +4948,8 @@ $called_api = null;
$nm->setSeen($note); $nm->setSeen($note);
if ($note['otype']=='item') { if ($note['otype']=='item') {
// would be really better with an ItemsManager and $im->getByID() :-P // would be really better with an ItemsManager and $im->getByID() :-P
$r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d", $r = q(
"SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
intval($note['iid']), intval($note['iid']),
intval(local_user()) intval(local_user())
); );
@ -4824,7 +4975,8 @@ $called_api = null;
* @param string $type Known types are 'atom', 'rss', 'xml' and 'json' * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
* @return string (success result=ok, error result=error with error message) * @return string (success result=ok, error result=error with error message)
*/ */
function api_friendica_direct_messages_setseen($type) { function api_friendica_direct_messages_setseen($type)
{
$a = get_app(); $a = get_app();
if (api_user() === false) { if (api_user() === false) {
throw new ForbiddenException(); throw new ForbiddenException();
@ -4842,9 +4994,11 @@ $called_api = null;
} }
// get data of the specified message id // get data of the specified message id
$r = q("SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d", $r = q(
"SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
intval($id), intval($id),
intval($uid)); intval($uid)
);
// error message if specified id is not in database // error message if specified id is not in database
if (!DBM::is_result($r)) { if (!DBM::is_result($r)) {
@ -4853,9 +5007,11 @@ $called_api = null;
} }
// update seen indicator // update seen indicator
$result = q("UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d", $result = q(
"UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
intval($id), intval($id),
intval($uid)); intval($uid)
);
if ($result) { if ($result) {
// return success // return success
@ -4878,7 +5034,8 @@ $called_api = null;
* success=false if nothing was found, search_result='nothing found', * success=false if nothing was found, search_result='nothing found',
* error: result=error with error message) * error: result=error with error message)
*/ */
function api_friendica_direct_messages_search($type) { function api_friendica_direct_messages_search($type)
{
$a = get_app(); $a = get_app();
if (api_user() === false) { if (api_user() === false) {
@ -4897,7 +5054,8 @@ $called_api = null;
} }
// get data for the specified searchstring // get data for the specified searchstring
$r = q("SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND `body` LIKE '%s' ORDER BY `mail`.`id` DESC", $r = q(
"SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND `body` LIKE '%s' ORDER BY `mail`.`id` DESC",
intval($uid), intval($uid),
dbesc('%'.$searchstring.'%') dbesc('%'.$searchstring.'%')
); );
@ -4937,7 +5095,8 @@ $called_api = null;
* @param string $type Known types are 'atom', 'rss', 'xml' and 'json' * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
* @return string * @return string
*/ */
function api_friendica_profile_show($type) { function api_friendica_profile_show($type)
{
$a = get_app(); $a = get_app();
if (api_user() === false) { if (api_user() === false) {
@ -4953,17 +5112,21 @@ $called_api = null;
// get data of the specified profile id or all profiles of the user if not specified // get data of the specified profile id or all profiles of the user if not specified
if ($profileid != 0) { if ($profileid != 0) {
$r = q("SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d", $r = q(
"SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
intval(api_user()), intval(api_user()),
intval($profileid)); intval($profileid)
);
// error message if specified gid is not in database // error message if specified gid is not in database
if (!DBM::is_result($r)) { if (!DBM::is_result($r)) {
throw new BadRequestException("profile_id not available"); throw new BadRequestException("profile_id not available");
} }
} else { } else {
$r = q("SELECT * FROM `profile` WHERE `uid` = %d", $r = q(
intval(api_user())); "SELECT * FROM `profile` WHERE `uid` = %d",
intval(api_user())
);
} }
// loop through all returned profiles and retrieve data and users // loop through all returned profiles and retrieve data and users
$k = 0; $k = 0;
@ -4972,9 +5135,11 @@ $called_api = null;
// select all users from contact table, loop and prepare standard return for user data // select all users from contact table, loop and prepare standard return for user data
$users = array(); $users = array();
$r = q("SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d", $r = q(
"SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
intval(api_user()), intval(api_user()),
intval($rr['profile_id'])); intval($rr['profile_id'])
);
foreach ($r as $rr) { foreach ($r as $rr) {
$user = api_get_user($a, $rr['nurl']); $user = api_get_user($a, $rr['nurl']);

View file

@ -8,7 +8,8 @@
* https://github.com/annando/Syncom * https://github.com/annando/Syncom
*/ */
require_once("include/xml.php"); use Friendica\Util\Xml;
function node2bbcode(&$doc, $oldnode, $attributes, $startbb, $endbb) function node2bbcode(&$doc, $oldnode, $attributes, $startbb, $endbb)
{ {
@ -86,7 +87,8 @@ function html2bbcode($message, $basepath = '')
// Removing code blocks before the whitespace removal processing below // Removing code blocks before the whitespace removal processing below
$codeblocks = []; $codeblocks = [];
$message = preg_replace_callback('#<pre><code(?: class="([^"]*)")?>(.*)</code></pre>#iUs', $message = preg_replace_callback(
'#<pre><code(?: class="([^"]*)")?>(.*)</code></pre>#iUs',
function ($matches) use (&$codeblocks) { function ($matches) use (&$codeblocks) {
$return = '[codeblock-' . count($codeblocks) . ']'; $return = '[codeblock-' . count($codeblocks) . ']';
@ -96,10 +98,12 @@ function html2bbcode($message, $basepath = '')
} }
$codeblocks[] = $prefix . $matches[2] . '[/code]'; $codeblocks[] = $prefix . $matches[2] . '[/code]';
return $return; return $return;
} },
, $message); $message
);
$message = str_replace(array( $message = str_replace(
array(
"<li><p>", "<li><p>",
"</p></li>", "</p></li>",
), ),
@ -107,7 +111,8 @@ function html2bbcode($message, $basepath = '')
"<li>", "<li>",
"</li>", "</li>",
), ),
$message); $message
);
// remove namespaces // remove namespaces
$message = preg_replace('=<(\w+):(.+?)>=', '<removeme>', $message); $message = preg_replace('=<(\w+):(.+?)>=', '<removeme>', $message);
@ -120,17 +125,18 @@ function html2bbcode($message, $basepath = '')
@$doc->loadHTML($message); @$doc->loadHTML($message);
xml::deleteNode($doc, 'style'); Xml::deleteNode($doc, 'style');
xml::deleteNode($doc, 'head'); Xml::deleteNode($doc, 'head');
xml::deleteNode($doc, 'title'); Xml::deleteNode($doc, 'title');
xml::deleteNode($doc, 'meta'); Xml::deleteNode($doc, 'meta');
xml::deleteNode($doc, 'xml'); Xml::deleteNode($doc, 'xml');
xml::deleteNode($doc, 'removeme'); Xml::deleteNode($doc, 'removeme');
$xpath = new DomXPath($doc); $xpath = new DomXPath($doc);
$list = $xpath->query("//pre"); $list = $xpath->query("//pre");
foreach ($list as $node) foreach ($list as $node) {
$node->nodeValue = str_replace("\n", "\r", $node->nodeValue); $node->nodeValue = str_replace("\n", "\r", $node->nodeValue);
}
$message = $doc->saveHTML(); $message = $doc->saveHTML();
$message = str_replace(array("\n<", ">\n", "\r", "\n", "\xC3\x82\xC2\xA0"), array("<", ">", "<br />", " ", ""), $message); $message = str_replace(array("\n<", ">\n", "\r", "\n", "\xC3\x82\xC2\xA0"), array("<", ">", "<br />", " ", ""), $message);
@ -281,7 +287,8 @@ function html2bbcode($message, $basepath = '')
do { do {
$oldmessage = $message; $oldmessage = $message;
$message = str_replace(array( $message = str_replace(
array(
"[/size]\n\n", "[/size]\n\n",
"\n[hr]", "\n[hr]",
"[hr]\n", "[hr]\n",
@ -301,25 +308,31 @@ function html2bbcode($message, $basepath = '')
"[list]", "[list]",
"[list=1]", "[list=1]",
"[*]"), "[*]"),
$message); $message
);
} while ($message != $oldmessage); } while ($message != $oldmessage);
$message = str_replace(array('[b][b]', '[/b][/b]', '[i][i]', '[/i][/i]'), $message = str_replace(
array('[b]', '[/b]', '[i]', '[/i]'), $message); array('[b][b]', '[/b][/b]', '[i][i]', '[/i][/i]'),
array('[b]', '[/b]', '[i]', '[/i]'),
$message
);
// Handling Yahoo style of mails // Handling Yahoo style of mails
$message = str_replace('[hr][b]From:[/b]', '[quote][b]From:[/b]', $message); $message = str_replace('[hr][b]From:[/b]', '[quote][b]From:[/b]', $message);
// Restore code blocks // Restore code blocks
$message = preg_replace_callback('#\[codeblock-([0-9]+)\]#iU', $message = preg_replace_callback(
'#\[codeblock-([0-9]+)\]#iU',
function ($matches) use ($codeblocks) { function ($matches) use ($codeblocks) {
$return = ''; $return = '';
if (isset($codeblocks[intval($matches[1])])) { if (isset($codeblocks[intval($matches[1])])) {
$return = $codeblocks[$matches[1]]; $return = $codeblocks[$matches[1]];
} }
return $return; return $return;
} },
, $message); $message
);
$message = trim($message); $message = trim($message);
@ -338,7 +351,8 @@ function html2bbcode($message, $basepath = '')
* *
* @return string The expanded URL * @return string The expanded URL
*/ */
function addHostnameSub($matches, $basepath) { function addHostnameSub($matches, $basepath)
{
$base = parse_url($basepath); $base = parse_url($basepath);
unset($base['query']); unset($base['query']);
unset($base['fragment']); unset($base['fragment']);
@ -360,7 +374,8 @@ function addHostnameSub($matches, $basepath) {
* *
* @return string Body with expanded URLs * @return string Body with expanded URLs
*/ */
function addHostname($body, $basepath) { function addHostname($body, $basepath)
{
$URLSearchString = "^\[\]"; $URLSearchString = "^\[\]";
$matches = array("/\[url\=([$URLSearchString]*)\].*?\[\/url\]/ism", $matches = array("/\[url\=([$URLSearchString]*)\].*?\[\/url\]/ism",
@ -373,11 +388,14 @@ function addHostname($body, $basepath) {
"/\[audio\](.*?)\[\/audio\]/ism", "/\[audio\](.*?)\[\/audio\]/ism",
); );
foreach ($matches AS $match) { foreach ($matches as $match) {
$body = preg_replace_callback($match, $body = preg_replace_callback(
$match,
function ($match) use ($basepath) { function ($match) use ($basepath) {
return addHostnameSub($match, $basepath); return addHostnameSub($match, $basepath);
}, $body); },
$body
);
} }
return $body; return $body;
} }

View file

@ -8,8 +8,7 @@ use Friendica\App;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Network\Probe; use Friendica\Network\Probe;
use Friendica\Util\Xml;
require_once("include/xml.php");
/** /**
* @brief Curl wrapper * @brief Curl wrapper
@ -28,8 +27,8 @@ require_once("include/xml.php");
* *
* @return string The fetched content * @return string The fetched content
*/ */
function fetch_url($url,$binary = false, &$redirects = 0, $timeout = 0, $accept_content=Null, $cookiejar = 0) { function fetch_url($url, $binary = false, &$redirects = 0, $timeout = 0, $accept_content = null, $cookiejar = 0)
{
$ret = z_fetch_url( $ret = z_fetch_url(
$url, $url,
$binary, $binary,
@ -37,7 +36,8 @@ function fetch_url($url,$binary = false, &$redirects = 0, $timeout = 0, $accept_
array('timeout'=>$timeout, array('timeout'=>$timeout,
'accept_content'=>$accept_content, 'accept_content'=>$accept_content,
'cookiejar'=>$cookiejar 'cookiejar'=>$cookiejar
)); )
);
return($ret['body']); return($ret['body']);
} }
@ -64,7 +64,8 @@ function fetch_url($url,$binary = false, &$redirects = 0, $timeout = 0, $accept_
* string 'header' => HTTP headers * string 'header' => HTTP headers
* string 'body' => fetched content * string 'body' => fetched content
*/ */
function z_fetch_url($url, $binary = false, &$redirects = 0, $opts = array()) { function z_fetch_url($url, $binary = false, &$redirects = 0, $opts = array())
{
$ret = array('return_code' => 0, 'success' => false, 'header' => '', 'info' => '', 'body' => ''); $ret = array('return_code' => 0, 'success' => false, 'header' => '', 'info' => '', 'body' => '');
$stamp1 = microtime(true); $stamp1 = microtime(true);
@ -94,9 +95,11 @@ function z_fetch_url($url, $binary = false, &$redirects = 0, $opts = array()) {
// @curl_setopt($ch, CURLOPT_MAXREDIRS, 5); // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
if (x($opts, 'accept_content')) { if (x($opts, 'accept_content')) {
curl_setopt($ch, CURLOPT_HTTPHEADER, array( curl_setopt(
'Accept: ' . $opts['accept_content'] $ch,
)); CURLOPT_HTTPHEADER,
array('Accept: ' . $opts['accept_content'])
);
} }
@curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
@ -269,7 +272,8 @@ function z_fetch_url($url, $binary = false, &$redirects = 0, $opts = array()) {
* *
* @return string The content * @return string The content
*/ */
function post_url($url, $params, $headers = null, &$redirects = 0, $timeout = 0) { function post_url($url, $params, $headers = null, &$redirects = 0, $timeout = 0)
{
$stamp1 = microtime(true); $stamp1 = microtime(true);
if (blocked_url($url)) { if (blocked_url($url)) {
@ -394,8 +398,8 @@ function post_url($url, $params, $headers = null, &$redirects = 0, $timeout = 0)
// Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
// of $st and an optional text <message> of $message and terminates the current process. // of $st and an optional text <message> of $message and terminates the current process.
function xml_status($st, $message = '') { function xml_status($st, $message = '')
{
$result = array('status' => $st); $result = array('status' => $st);
if ($message != '') { if ($message != '') {
@ -410,7 +414,7 @@ function xml_status($st, $message = '') {
$xmldata = array("result" => $result); $xmldata = array("result" => $result);
echo xml::from_array($xmldata, $xml); echo Xml::from_array($xmldata, $xml);
killme(); killme();
} }
@ -432,13 +436,15 @@ function xml_status($st, $message = '') {
* 'title' => header title * 'title' => header title
* 'description' => optional message * 'description' => optional message
*/ */
function http_status_exit($val, $description = array()) { function http_status_exit($val, $description = array())
{
$err = ''; $err = '';
if ($val >= 400) { if ($val >= 400) {
$err = 'Error'; $err = 'Error';
if (!isset($description["title"])) if (!isset($description["title"])) {
$description["title"] = $err." ".$val; $description["title"] = $err." ".$val;
} }
}
if ($val >= 200 && $val < 300) if ($val >= 200 && $val < 300)
$err = 'OK'; $err = 'OK';
@ -447,12 +453,15 @@ function http_status_exit($val, $description = array()) {
if (isset($description["title"])) { if (isset($description["title"])) {
$tpl = get_markup_template('http_status.tpl'); $tpl = get_markup_template('http_status.tpl');
echo replace_macros($tpl, array('$title' => $description["title"], echo replace_macros(
'$description' => $description["description"])); $tpl,
array(
'$title' => $description["title"],
'$description' => $description["description"])
);
} }
killme(); killme();
} }
/** /**
@ -464,9 +473,11 @@ function http_status_exit($val, $description = array()) {
* @param string $url The URL to be validated * @param string $url The URL to be validated
* @return boolean True if it's a valid URL, fals if something wrong with it * @return boolean True if it's a valid URL, fals if something wrong with it
*/ */
function validate_url(&$url) { function validate_url(&$url)
if (Config::get('system','disable_url_validation')) {
if (Config::get('system', 'disable_url_validation')) {
return true; return true;
}
// no naked subdomains (allow localhost for tests) // no naked subdomains (allow localhost for tests)
if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) if (strpos($url, '.') === false && strpos($url, '/localhost/') === false)
@ -491,13 +502,16 @@ function validate_url(&$url) {
* @param string $addr The email address * @param string $addr The email address
* @return boolean True if it's a valid email address, false if it's not * @return boolean True if it's a valid email address, false if it's not
*/ */
function validate_email($addr) { function validate_email($addr)
{
if (Config::get('system','disable_email_validation')) if (Config::get('system', 'disable_email_validation')) {
return true; return true;
}
if (! strpos($addr,'@')) if (! strpos($addr, '@')) {
return false; return false;
}
$h = substr($addr, strpos($addr, '@') + 1); $h = substr($addr, strpos($addr, '@') + 1);
if (($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) { if (($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
@ -515,8 +529,8 @@ function validate_email($addr) {
* @param string $url URL which get tested * @param string $url URL which get tested
* @return boolean True if url is allowed otherwise return false * @return boolean True if url is allowed otherwise return false
*/ */
function allowed_url($url) { function allowed_url($url)
{
$h = @parse_url($url); $h = @parse_url($url);
if (! $h) { if (! $h) {
@ -559,7 +573,8 @@ function allowed_url($url) {
* @param string $url The url to check the domain from * @param string $url The url to check the domain from
* @return boolean * @return boolean
*/ */
function blocked_url($url) { function blocked_url($url)
{
$h = @parse_url($url); $h = @parse_url($url);
if (! $h) { if (! $h) {
@ -587,12 +602,12 @@ function blocked_url($url) {
* *
* Compare against our list (wildcards allowed). * Compare against our list (wildcards allowed).
* *
* @param type $email * @param string $email email address
* @return boolean False if not allowed, true if allowed * @return boolean False if not allowed, true if allowed
* or if allowed list is not configured * or if allowed list is not configured
*/ */
function allowed_email($email) { function allowed_email($email)
{
$domain = strtolower(substr($email, strpos($email, '@') + 1)); $domain = strtolower(substr($email, strpos($email, '@') + 1));
if (! $domain) { if (! $domain) {
return false; return false;
@ -620,8 +635,8 @@ function allowed_email($email) {
return $found; return $found;
} }
function avatar_img($email) { function avatar_img($email)
{
$avatar['size'] = 175; $avatar['size'] = 175;
$avatar['email'] = $email; $avatar['email'] = $email;
$avatar['url'] = ''; $avatar['url'] = '';
@ -638,7 +653,8 @@ function avatar_img($email) {
} }
function parse_xml_string($s, $strict = true) { function parse_xml_string($s, $strict = true)
{
// the "strict" parameter is deactivated // the "strict" parameter is deactivated
/// @todo Move this function to the xml class /// @todo Move this function to the xml class
@ -655,8 +671,8 @@ function parse_xml_string($s, $strict = true) {
return $x; return $x;
} }
function scale_external_images($srctext, $include_link = true, $scale_replace = false) { function scale_external_images($srctext, $include_link = true, $scale_replace = false)
{
// Suppress "view full size" // Suppress "view full size"
if (intval(Config::get('system', 'no_view_full_size'))) { if (intval(Config::get('system', 'no_view_full_size'))) {
$include_link = false; $include_link = false;
@ -670,7 +686,7 @@ function scale_external_images($srctext, $include_link = true, $scale_replace =
$matches = null; $matches = null;
$c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism', $s, $matches, PREG_SET_ORDER); $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism', $s, $matches, PREG_SET_ORDER);
if ($c) { if ($c) {
require_once('include/Photo.php'); require_once 'include/Photo.php';
foreach ($matches as $mtch) { foreach ($matches as $mtch) {
logger('scale_external_image: ' . $mtch[1]); logger('scale_external_image: ' . $mtch[1]);
@ -704,15 +720,18 @@ function scale_external_images($srctext, $include_link = true, $scale_replace =
$orig_height = $ph->getHeight(); $orig_height = $ph->getHeight();
if ($orig_width > 640 || $orig_height > 640) { if ($orig_width > 640 || $orig_height > 640) {
$ph->scaleImage(640); $ph->scaleImage(640);
$new_width = $ph->getWidth(); $new_width = $ph->getWidth();
$new_height = $ph->getHeight(); $new_height = $ph->getHeight();
logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG); logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
$s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]' $s = str_replace(
$mtch[0],
'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
. "\n" . (($include_link) . "\n" . (($include_link)
? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n" ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
: ''),$s); : ''),
$s
);
logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG); logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
} }
} }
@ -726,8 +745,8 @@ function scale_external_images($srctext, $include_link = true, $scale_replace =
} }
function fix_contact_ssl_policy(&$contact,$new_policy) { function fix_contact_ssl_policy(&$contact, $new_policy)
{
$ssl_changed = false; $ssl_changed = false;
if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) { if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
$ssl_changed = true; $ssl_changed = true;
@ -771,13 +790,17 @@ function strip_tracking_query_params($url)
parse_str($query, $querydata); parse_str($query, $querydata);
if (is_array($querydata)) { if (is_array($querydata)) {
foreach ($querydata AS $param => $value) { foreach ($querydata as $param => $value) {
if (in_array($param, array("utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign", if (in_array(
$param,
array(
"utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
"wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid", "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
"fb_action_ids", "fb_action_types", "fb_ref", "fb_action_ids", "fb_action_types", "fb_ref",
"awesm", "wtrid", "awesm", "wtrid",
"woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"))) { "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term")
)
) {
$pair = $param . "=" . urlencode($value); $pair = $param . "=" . urlencode($value);
$url = str_replace($pair, "", $url); $url = str_replace($pair, "", $url);
@ -817,13 +840,15 @@ function strip_tracking_query_params($url)
* @param bool $fetchbody Wether to fetch the body or not after the HEAD requests * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
* @return string A canonical URL * @return string A canonical URL
*/ */
function original_url($url, $depth = 1, $fetchbody = false) { function original_url($url, $depth = 1, $fetchbody = false)
{
$a = get_app(); $a = get_app();
$url = strip_tracking_query_params($url); $url = strip_tracking_query_params($url);
if ($depth > 10) if ($depth > 10) {
return($url); return($url);
}
$url = trim($url, "'"); $url = trim($url, "'");
@ -849,24 +874,29 @@ function original_url($url, $depth = 1, $fetchbody = false) {
return($url); return($url);
if ((($curl_info['http_code'] == "301") || ($curl_info['http_code'] == "302")) if ((($curl_info['http_code'] == "301") || ($curl_info['http_code'] == "302"))
&& (($curl_info['redirect_url'] != "") || ($curl_info['location'] != ""))) { && (($curl_info['redirect_url'] != "") || ($curl_info['location'] != ""))
if ($curl_info['redirect_url'] != "") ) {
if ($curl_info['redirect_url'] != "") {
return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody)); return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
else } else {
return(original_url($curl_info['location'], ++$depth, $fetchbody)); return(original_url($curl_info['location'], ++$depth, $fetchbody));
} }
}
// Check for redirects in the meta elements of the body if there are no redirects in the header. // Check for redirects in the meta elements of the body if there are no redirects in the header.
if (!$fetchbody) if (!$fetchbody) {
return(original_url($url, ++$depth, true)); return(original_url($url, ++$depth, true));
}
// if the file is too large then exit // if the file is too large then exit
if ($curl_info["download_content_length"] > 1000000) if ($curl_info["download_content_length"] > 1000000) {
return($url); return($url);
}
// if it isn't a HTML file then exit // if it isn't a HTML file then exit
if (($curl_info["content_type"] != "") && !strstr(strtolower($curl_info["content_type"]),"html")) if (($curl_info["content_type"] != "") && !strstr(strtolower($curl_info["content_type"]), "html")) {
return($url); return($url);
}
$stamp1 = microtime(true); $stamp1 = microtime(true);
@ -883,8 +913,9 @@ function original_url($url, $depth = 1, $fetchbody = false) {
$a->save_timestamp($stamp1, "network"); $a->save_timestamp($stamp1, "network");
if (trim($body) == "") if (trim($body) == "") {
return($url); return($url);
}
// Check for redirect in meta elements // Check for redirect in meta elements
$doc = new DOMDocument(); $doc = new DOMDocument();
@ -895,25 +926,30 @@ function original_url($url, $depth = 1, $fetchbody = false) {
$list = $xpath->query("//meta[@content]"); $list = $xpath->query("//meta[@content]");
foreach ($list as $node) { foreach ($list as $node) {
$attr = array(); $attr = array();
if ($node->attributes->length) if ($node->attributes->length) {
foreach ($node->attributes as $attribute) foreach ($node->attributes as $attribute) {
$attr[$attribute->name] = $attribute->value; $attr[$attribute->name] = $attribute->value;
}
}
if (@$attr["http-equiv"] == 'refresh') { if (@$attr["http-equiv"] == 'refresh') {
$path = $attr["content"]; $path = $attr["content"];
$pathinfo = explode(";", $path); $pathinfo = explode(";", $path);
$content = ""; $content = "";
foreach ($pathinfo AS $value) foreach ($pathinfo as $value) {
if (substr(strtolower($value), 0, 4) == "url=") if (substr(strtolower($value), 0, 4) == "url=") {
return(original_url(substr($value, 4), ++$depth)); return(original_url(substr($value, 4), ++$depth));
} }
} }
}
}
return($url); return($url);
} }
function short_link($url) { function short_link($url)
require_once('library/slinky.php'); {
require_once 'library/slinky.php';
$slinky = new Slinky($url); $slinky = new Slinky($url);
$yourls_url = Config::get('yourls', 'url1'); $yourls_url = Config::get('yourls', 'url1');
if ($yourls_url) { if ($yourls_url) {
@ -944,7 +980,8 @@ function short_link($url) {
* *
* @param array $x The input content * @param array $x The input content
*/ */
function json_return_and_die($x) { function json_return_and_die($x)
{
header("content-type: application/json"); header("content-type: application/json");
echo json_encode($x); echo json_encode($x);
killme(); killme();
@ -957,10 +994,11 @@ function json_return_and_die($x) {
* @param string $url2 * @param string $url2
* @return string The matching part * @return string The matching part
*/ */
function matching_url($url1, $url2) { function matching_url($url1, $url2)
{
if (($url1 == "") || ($url2 == "")) if (($url1 == "") || ($url2 == "")) {
return ""; return "";
}
$url1 = normalise_link($url1); $url1 = normalise_link($url1);
$url2 = normalise_link($url2); $url2 = normalise_link($url2);
@ -968,22 +1006,27 @@ function matching_url($url1, $url2) {
$parts1 = parse_url($url1); $parts1 = parse_url($url1);
$parts2 = parse_url($url2); $parts2 = parse_url($url2);
if (!isset($parts1["host"]) || !isset($parts2["host"])) if (!isset($parts1["host"]) || !isset($parts2["host"])) {
return ""; return "";
}
if ($parts1["scheme"] != $parts2["scheme"]) if ($parts1["scheme"] != $parts2["scheme"]) {
return ""; return "";
}
if ($parts1["host"] != $parts2["host"]) if ($parts1["host"] != $parts2["host"]) {
return ""; return "";
}
if ($parts1["port"] != $parts2["port"]) if ($parts1["port"] != $parts2["port"]) {
return ""; return "";
}
$match = $parts1["scheme"]."://".$parts1["host"]; $match = $parts1["scheme"]."://".$parts1["host"];
if ($parts1["port"]) if ($parts1["port"]) {
$match .= ":".$parts1["port"]; $match .= ":".$parts1["port"];
}
$pathparts1 = explode("/", $parts1["path"]); $pathparts1 = explode("/", $parts1["path"]);
$pathparts2 = explode("/", $parts2["path"]); $pathparts2 = explode("/", $parts2["path"]);
@ -994,9 +1037,9 @@ function matching_url($url1, $url2) {
$path1 = $pathparts1[$i]; $path1 = $pathparts1[$i];
$path2 = $pathparts2[$i]; $path2 = $pathparts2[$i];
if ($path1 == $path2) if ($path1 == $path2) {
$path .= $path1."/"; $path .= $path1."/";
}
} while (($path1 == $path2) && ($i++ <= count($pathparts1))); } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
$match .= $path; $match .= $path;
@ -1011,7 +1054,8 @@ function matching_url($url1, $url2) {
* *
* @return string The glued URL * @return string The glued URL
*/ */
function unParseUrl($parsed) { function unParseUrl($parsed)
{
$get = function ($key) use ($parsed) { $get = function ($key) use ($parsed) {
return isset($parsed[$key]) ? $parsed[$key] : null; return isset($parsed[$key]) ? $parsed[$key] : null;
}; };
@ -1023,8 +1067,7 @@ function unParseUrl($parsed) {
$scheme = $get('scheme'); $scheme = $get('scheme');
$query = $get('query'); $query = $get('query');
$fragment = $get('fragment'); $fragment = $get('fragment');
$authority = $authority = ($userinfo !== null ? $userinfo."@" : '') .
($userinfo !== null ? $userinfo."@" : '') .
$get('host') . $get('host') .
($port ? ":$port" : ''); ($port ? ":$port" : '');

View file

@ -10,6 +10,7 @@ use Friendica\Core\Config;
use Friendica\Database\DBM; use Friendica\Database\DBM;
use Friendica\Network\Probe; use Friendica\Network\Probe;
use Friendica\Util\Lock; use Friendica\Util\Lock;
use Friendica\Util\Xml;
require_once 'include/Contact.php'; require_once 'include/Contact.php';
require_once 'include/threads.php'; require_once 'include/threads.php';
@ -23,7 +24,6 @@ require_once 'include/Photo.php';
require_once 'include/follow.php'; require_once 'include/follow.php';
require_once 'include/api.php'; require_once 'include/api.php';
require_once 'mod/proxy.php'; require_once 'mod/proxy.php';
require_once 'include/xml.php';
/** /**
* @brief This class contain functions for the OStatus protocol * @brief This class contain functions for the OStatus protocol
@ -169,24 +169,29 @@ class ostatus
$contact['nurl'] = normalise_link($contact['url']); $contact['nurl'] = normalise_link($contact['url']);
$value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue; $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
if ($value != "") if ($value != "") {
$contact["alias"] = $value; $contact["alias"] = $value;
}
$value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue; $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
if ($value != "") if ($value != "") {
$contact["name"] = $value; $contact["name"] = $value;
}
$value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue; $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
if ($value != "") if ($value != "") {
$contact["nick"] = $value; $contact["nick"] = $value;
}
$value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue; $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
if ($value != "") if ($value != "") {
$contact["about"] = html2bbcode($value); $contact["about"] = html2bbcode($value);
}
$value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue; $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
if ($value != "") if ($value != "") {
$contact["location"] = $value; $contact["location"] = $value;
}
$contact['name-date'] = datetime_convert(); $contact['name-date'] = datetime_convert();
@ -238,8 +243,9 @@ class ostatus
*/ */
public static function salmon_author($xml, $importer) public static function salmon_author($xml, $importer)
{ {
if ($xml == "") if ($xml == "") {
return; return;
}
$doc = new DOMDocument(); $doc = new DOMDocument();
@$doc->loadXML($xml); @$doc->loadXML($xml);
@ -1113,14 +1119,16 @@ class ostatus
{ {
$elements = explode(":", $href); $elements = explode(":", $href);
if ((count($elements) <= 2) || ($elements[0] != "tag")) if ((count($elements) <= 2) || ($elements[0] != "tag")) {
return $href; return $href;
}
$server = explode(",", $elements[1]); $server = explode(",", $elements[1]);
$conversation = explode("=", $elements[2]); $conversation = explode("=", $elements[2]);
if ((count($elements) == 4) && ($elements[2] == "post")) if ((count($elements) == 4) && ($elements[2] == "post")) {
return "http://".$server[0]."/notice/".$elements[3]; return "http://".$server[0]."/notice/".$elements[3];
}
if ((count($conversation) != 2) || ($conversation[1] =="")) { if ((count($conversation) != 2) || ($conversation[1] =="")) {
return $href; return $href;
@ -1146,26 +1154,31 @@ class ostatus
// Skip if it isn't a pure repeated messages // Skip if it isn't a pure repeated messages
// Does it start with a share? // Does it start with a share?
if (strpos($body, "[share") > 0) if (strpos($body, "[share") > 0) {
return ""; return "";
}
// Does it end with a share? // Does it end with a share?
if (strlen($body) > (strrpos($body, "[/share]") + 8)) if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
return ""; return "";
}
$attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body); $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
// Skip if there is no shared message in there // Skip if there is no shared message in there
if ($body == $attributes) if ($body == $attributes) {
return false; return false;
}
$guid = ""; $guid = "";
preg_match("/guid='(.*?)'/ism", $attributes, $matches); preg_match("/guid='(.*?)'/ism", $attributes, $matches);
if ($matches[1] != "") if ($matches[1] != "") {
$guid = $matches[1]; $guid = $matches[1];
}
preg_match('/guid="(.*?)"/ism', $attributes, $matches); preg_match('/guid="(.*?)"/ism', $attributes, $matches);
if ($matches[1] != "") if ($matches[1] != "") {
$guid = $matches[1]; $guid = $matches[1];
}
return $guid; return $guid;
} }
@ -1232,39 +1245,39 @@ class ostatus
$root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON); $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
$attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION); $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes); Xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
xml::add_element($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]); Xml::add_element($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
xml::add_element($doc, $root, "title", sprintf("%s timeline", $owner["name"])); Xml::add_element($doc, $root, "title", sprintf("%s timeline", $owner["name"]));
xml::add_element($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"])); Xml::add_element($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
xml::add_element($doc, $root, "logo", $owner["photo"]); Xml::add_element($doc, $root, "logo", $owner["photo"]);
xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME)); Xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
$author = self::add_author($doc, $owner); $author = self::add_author($doc, $owner);
$root->appendChild($author); $root->appendChild($author);
$attributes = array("href" => $owner["url"], "rel" => "alternate", "type" => "text/html"); $attributes = array("href" => $owner["url"], "rel" => "alternate", "type" => "text/html");
xml::add_element($doc, $root, "link", "", $attributes); Xml::add_element($doc, $root, "link", "", $attributes);
/// @TODO We have to find out what this is /// @TODO We have to find out what this is
/// $attributes = array("href" => System::baseUrl()."/sup", /// $attributes = array("href" => System::baseUrl()."/sup",
/// "rel" => "http://api.friendfeed.com/2008/03#sup", /// "rel" => "http://api.friendfeed.com/2008/03#sup",
/// "type" => "application/json"); /// "type" => "application/json");
/// xml::add_element($doc, $root, "link", "", $attributes); /// Xml::add_element($doc, $root, "link", "", $attributes);
self::hublinks($doc, $root, $owner["nick"]); self::hublinks($doc, $root, $owner["nick"]);
$attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "salmon"); $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "salmon");
xml::add_element($doc, $root, "link", "", $attributes); Xml::add_element($doc, $root, "link", "", $attributes);
$attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"); $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
xml::add_element($doc, $root, "link", "", $attributes); Xml::add_element($doc, $root, "link", "", $attributes);
$attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"); $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
xml::add_element($doc, $root, "link", "", $attributes); Xml::add_element($doc, $root, "link", "", $attributes);
$attributes = array("href" => System::baseUrl()."/api/statuses/user_timeline/".$owner["nick"].".atom", $attributes = array("href" => System::baseUrl()."/api/statuses/user_timeline/".$owner["nick"].".atom",
"rel" => "self", "type" => "application/atom+xml"); "rel" => "self", "type" => "application/atom+xml");
xml::add_element($doc, $root, "link", "", $attributes); Xml::add_element($doc, $root, "link", "", $attributes);
return $root; return $root;
} }
@ -1279,7 +1292,7 @@ class ostatus
public static function hublinks($doc, $root, $nick) public static function hublinks($doc, $root, $nick)
{ {
$h = System::baseUrl() . '/pubsubhubbub/'.$nick; $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
xml::add_element($doc, $root, "link", "", array("href" => $h, "rel" => "hub")); Xml::add_element($doc, $root, "link", "", array("href" => $h, "rel" => "hub"));
} }
/** /**
@ -1301,7 +1314,7 @@ class ostatus
"href" => $siteinfo["image"], "href" => $siteinfo["image"],
"type" => $imgdata["mime"], "type" => $imgdata["mime"],
"length" => intval($imgdata["size"])); "length" => intval($imgdata["size"]));
xml::add_element($doc, $root, "link", "", $attributes); Xml::add_element($doc, $root, "link", "", $attributes);
break; break;
case 'video': case 'video':
$attributes = array("rel" => "enclosure", $attributes = array("rel" => "enclosure",
@ -1309,7 +1322,7 @@ class ostatus
"type" => "text/html; charset=UTF-8", "type" => "text/html; charset=UTF-8",
"length" => "", "length" => "",
"title" => $siteinfo["title"]); "title" => $siteinfo["title"]);
xml::add_element($doc, $root, "link", "", $attributes); Xml::add_element($doc, $root, "link", "", $attributes);
break; break;
default: default:
break; break;
@ -1322,7 +1335,7 @@ class ostatus
"type" => $imgdata["mime"], "type" => $imgdata["mime"],
"length" => intval($imgdata["size"])); "length" => intval($imgdata["size"]));
xml::add_element($doc, $root, "link", "", $attributes); Xml::add_element($doc, $root, "link", "", $attributes);
} }
$arr = explode('[/attach],', $item['attach']); $arr = explode('[/attach],', $item['attach']);
@ -1341,7 +1354,7 @@ class ostatus
if (trim($matches[4]) != "") { if (trim($matches[4]) != "") {
$attributes["title"] = trim($matches[4]); $attributes["title"] = trim($matches[4]);
} }
xml::add_element($doc, $root, "link", "", $attributes); Xml::add_element($doc, $root, "link", "", $attributes);
} }
} }
} }
@ -1362,15 +1375,15 @@ class ostatus
$profile = $r[0]; $profile = $r[0];
} }
$author = $doc->createElement("author"); $author = $doc->createElement("author");
xml::add_element($doc, $author, "id", $owner["url"]); Xml::add_element($doc, $author, "id", $owner["url"]);
xml::add_element($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON); Xml::add_element($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
xml::add_element($doc, $author, "uri", $owner["url"]); Xml::add_element($doc, $author, "uri", $owner["url"]);
xml::add_element($doc, $author, "name", $owner["nick"]); Xml::add_element($doc, $author, "name", $owner["nick"]);
xml::add_element($doc, $author, "email", $owner["addr"]); Xml::add_element($doc, $author, "email", $owner["addr"]);
xml::add_element($doc, $author, "summary", bbcode($owner["about"], false, false, 7)); Xml::add_element($doc, $author, "summary", bbcode($owner["about"], false, false, 7));
$attributes = array("rel" => "alternate", "type" => "text/html", "href" => $owner["url"]); $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $owner["url"]);
xml::add_element($doc, $author, "link", "", $attributes); Xml::add_element($doc, $author, "link", "", $attributes);
$attributes = array( $attributes = array(
"rel" => "avatar", "rel" => "avatar",
@ -1378,7 +1391,7 @@ class ostatus
"media:width" => 175, "media:width" => 175,
"media:height" => 175, "media:height" => 175,
"href" => $owner["photo"]); "href" => $owner["photo"]);
xml::add_element($doc, $author, "link", "", $attributes); Xml::add_element($doc, $author, "link", "", $attributes);
if (isset($owner["thumb"])) { if (isset($owner["thumb"])) {
$attributes = array( $attributes = array(
@ -1387,34 +1400,34 @@ class ostatus
"media:width" => 80, "media:width" => 80,
"media:height" => 80, "media:height" => 80,
"href" => $owner["thumb"]); "href" => $owner["thumb"]);
xml::add_element($doc, $author, "link", "", $attributes); Xml::add_element($doc, $author, "link", "", $attributes);
} }
xml::add_element($doc, $author, "poco:preferredUsername", $owner["nick"]); Xml::add_element($doc, $author, "poco:preferredUsername", $owner["nick"]);
xml::add_element($doc, $author, "poco:displayName", $owner["name"]); Xml::add_element($doc, $author, "poco:displayName", $owner["name"]);
xml::add_element($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7)); Xml::add_element($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7));
if (trim($owner["location"]) != "") { if (trim($owner["location"]) != "") {
$element = $doc->createElement("poco:address"); $element = $doc->createElement("poco:address");
xml::add_element($doc, $element, "poco:formatted", $owner["location"]); Xml::add_element($doc, $element, "poco:formatted", $owner["location"]);
$author->appendChild($element); $author->appendChild($element);
} }
if (trim($profile["homepage"]) != "") { if (trim($profile["homepage"]) != "") {
$urls = $doc->createElement("poco:urls"); $urls = $doc->createElement("poco:urls");
xml::add_element($doc, $urls, "poco:type", "homepage"); Xml::add_element($doc, $urls, "poco:type", "homepage");
xml::add_element($doc, $urls, "poco:value", $profile["homepage"]); Xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
xml::add_element($doc, $urls, "poco:primary", "true"); Xml::add_element($doc, $urls, "poco:primary", "true");
$author->appendChild($urls); $author->appendChild($urls);
} }
if (count($profile)) { if (count($profile)) {
xml::add_element($doc, $author, "followers", "", array("url" => System::baseUrl()."/viewcontacts/".$owner["nick"])); Xml::add_element($doc, $author, "followers", "", array("url" => System::baseUrl()."/viewcontacts/".$owner["nick"]));
xml::add_element($doc, $author, "statusnet:profile_info", "", array("local_id" => $owner["uid"])); Xml::add_element($doc, $author, "statusnet:profile_info", "", array("local_id" => $owner["uid"]));
} }
if ($profile["publish"]) { if ($profile["publish"]) {
xml::add_element($doc, $author, "mastodon:scope", "public"); Xml::add_element($doc, $author, "mastodon:scope", "public");
} }
return $author; return $author;
} }
@ -1434,8 +1447,10 @@ class ostatus
*/ */
private static function construct_verb($item) private static function construct_verb($item)
{ {
if ($item['verb']) if ($item['verb']) {
return $item['verb']; return $item['verb'];
}
return ACTIVITY_POST; return ACTIVITY_POST;
} }
@ -1466,11 +1481,13 @@ class ostatus
private static function entry($doc, $item, $owner, $toplevel = false) private static function entry($doc, $item, $owner, $toplevel = false)
{ {
$repeated_guid = self::get_reshared_guid($item); $repeated_guid = self::get_reshared_guid($item);
if ($repeated_guid != "") if ($repeated_guid != "") {
$xml = self::reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel); $xml = self::reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel);
}
if ($xml) if ($xml) {
return $xml; return $xml;
}
if ($item["verb"] == ACTIVITY_LIKE) { if ($item["verb"] == ACTIVITY_LIKE) {
return self::like_entry($doc, $item, $owner, $toplevel); return self::like_entry($doc, $item, $owner, $toplevel);
@ -1492,12 +1509,12 @@ class ostatus
private static function source_entry($doc, $contact) private static function source_entry($doc, $contact)
{ {
$source = $doc->createElement("source"); $source = $doc->createElement("source");
xml::add_element($doc, $source, "id", $contact["poll"]); Xml::add_element($doc, $source, "id", $contact["poll"]);
xml::add_element($doc, $source, "title", $contact["name"]); Xml::add_element($doc, $source, "title", $contact["name"]);
xml::add_element($doc, $source, "link", "", array("rel" => "alternate", "type" => "text/html", "href" => $contact["alias"])); Xml::add_element($doc, $source, "link", "", array("rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]));
xml::add_element($doc, $source, "link", "", array("rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"])); Xml::add_element($doc, $source, "link", "", array("rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]));
xml::add_element($doc, $source, "icon", $contact["photo"]); Xml::add_element($doc, $source, "icon", $contact["photo"]);
xml::add_element($doc, $source, "updated", datetime_convert("UTC", "UTC", $contact["success_update"]."+00:00", ATOM_TIME)); Xml::add_element($doc, $source, "updated", datetime_convert("UTC", "UTC", $contact["success_update"]."+00:00", ATOM_TIME));
return $source; return $source;
} }
@ -1510,8 +1527,8 @@ class ostatus
* *
* @return array Contact array * @return array Contact array
*/ */
private static function contact_entry($url, $owner) { private static function contact_entry($url, $owner)
{
$r = q( $r = q(
"SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1", "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
dbesc(normalise_link($url)), dbesc(normalise_link($url)),
@ -1596,7 +1613,7 @@ class ostatus
$as_object = $doc->createElement("activity:object"); $as_object = $doc->createElement("activity:object");
xml::add_element($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity"); Xml::add_element($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
self::entry_content($doc, $as_object, $repeated_item, $owner, "", "", false); self::entry_content($doc, $as_object, $repeated_item, $owner, "", "", false);
@ -1605,7 +1622,7 @@ class ostatus
$as_object2 = $doc->createElement("activity:object"); $as_object2 = $doc->createElement("activity:object");
xml::add_element($doc, $as_object2, "activity:object-type", self::construct_objecttype($repeated_item)); Xml::add_element($doc, $as_object2, "activity:object-type", self::construct_objecttype($repeated_item));
$title = sprintf("New comment by %s", $contact["nick"]); $title = sprintf("New comment by %s", $contact["nick"]);
@ -1656,7 +1673,7 @@ class ostatus
); );
$parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']); $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
xml::add_element($doc, $as_object, "activity:object-type", self::construct_objecttype($parent[0])); Xml::add_element($doc, $as_object, "activity:object-type", self::construct_objecttype($parent[0]));
self::entry_content($doc, $as_object, $parent[0], $owner, "New entry"); self::entry_content($doc, $as_object, $parent[0], $owner, "New entry");
@ -1679,18 +1696,18 @@ class ostatus
private static function add_person_object($doc, $owner, $contact) private static function add_person_object($doc, $owner, $contact)
{ {
$object = $doc->createElement("activity:object"); $object = $doc->createElement("activity:object");
xml::add_element($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON); Xml::add_element($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
if ($contact['network'] == NETWORK_PHANTOM) { if ($contact['network'] == NETWORK_PHANTOM) {
xml::add_element($doc, $object, "id", $contact['url']); Xml::add_element($doc, $object, "id", $contact['url']);
return $object; return $object;
} }
xml::add_element($doc, $object, "id", $contact["alias"]); Xml::add_element($doc, $object, "id", $contact["alias"]);
xml::add_element($doc, $object, "title", $contact["nick"]); Xml::add_element($doc, $object, "title", $contact["nick"]);
$attributes = array("rel" => "alternate", "type" => "text/html", "href" => $contact["url"]); $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $contact["url"]);
xml::add_element($doc, $object, "link", "", $attributes); Xml::add_element($doc, $object, "link", "", $attributes);
$attributes = array( $attributes = array(
"rel" => "avatar", "rel" => "avatar",
@ -1698,14 +1715,14 @@ class ostatus
"media:width" => 175, "media:width" => 175,
"media:height" => 175, "media:height" => 175,
"href" => $contact["photo"]); "href" => $contact["photo"]);
xml::add_element($doc, $object, "link", "", $attributes); Xml::add_element($doc, $object, "link", "", $attributes);
xml::add_element($doc, $object, "poco:preferredUsername", $contact["nick"]); Xml::add_element($doc, $object, "poco:preferredUsername", $contact["nick"]);
xml::add_element($doc, $object, "poco:displayName", $contact["name"]); Xml::add_element($doc, $object, "poco:displayName", $contact["name"]);
if (trim($contact["location"]) != "") { if (trim($contact["location"]) != "") {
$element = $doc->createElement("poco:address"); $element = $doc->createElement("poco:address");
xml::add_element($doc, $element, "poco:formatted", $contact["location"]); Xml::add_element($doc, $element, "poco:formatted", $contact["location"]);
$object->appendChild($element); $object->appendChild($element);
} }
@ -1722,8 +1739,8 @@ class ostatus
* *
* @return object Entry element * @return object Entry element
*/ */
private static function follow_entry($doc, $item, $owner, $toplevel) { private static function follow_entry($doc, $item, $owner, $toplevel)
{
$item["id"] = $item["parent"] = 0; $item["id"] = $item["parent"] = 0;
$item["created"] = $item["edited"] = date("c"); $item["created"] = $item["edited"] = date("c");
$item["private"] = true; $item["private"] = true;
@ -1795,7 +1812,7 @@ class ostatus
$title = self::entry_header($doc, $entry, $owner, $toplevel); $title = self::entry_header($doc, $entry, $owner, $toplevel);
xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE); Xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
self::entry_content($doc, $entry, $item, $owner, $title); self::entry_content($doc, $entry, $item, $owner, $title);
@ -1857,30 +1874,31 @@ class ostatus
$verb = self::construct_verb($item); $verb = self::construct_verb($item);
} }
xml::add_element($doc, $entry, "id", $item["uri"]); Xml::add_element($doc, $entry, "id", $item["uri"]);
xml::add_element($doc, $entry, "title", $title); Xml::add_element($doc, $entry, "title", $title);
$body = self::format_picture_post($item['body']); $body = self::format_picture_post($item['body']);
if ($item['title'] != "") if ($item['title'] != "") {
$body = "[b]".$item['title']."[/b]\n\n".$body; $body = "[b]".$item['title']."[/b]\n\n".$body;
}
$body = bbcode($body, false, false, 7); $body = bbcode($body, false, false, 7);
xml::add_element($doc, $entry, "content", $body, array("type" => "html")); Xml::add_element($doc, $entry, "content", $body, array("type" => "html"));
xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html", Xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
"href" => System::baseUrl()."/display/".$item["guid"]) "href" => System::baseUrl()."/display/".$item["guid"])
); );
if ($complete && ($item["id"] > 0)) { if ($complete && ($item["id"] > 0)) {
xml::add_element($doc, $entry, "status_net", "", array("notice_id" => $item["id"])); Xml::add_element($doc, $entry, "status_net", "", array("notice_id" => $item["id"]));
} }
xml::add_element($doc, $entry, "activity:verb", $verb); Xml::add_element($doc, $entry, "activity:verb", $verb);
xml::add_element($doc, $entry, "published", datetime_convert("UTC", "UTC", $item["created"]."+00:00", ATOM_TIME)); Xml::add_element($doc, $entry, "published", datetime_convert("UTC", "UTC", $item["created"]."+00:00", ATOM_TIME));
xml::add_element($doc, $entry, "updated", datetime_convert("UTC", "UTC", $item["edited"]."+00:00", ATOM_TIME)); Xml::add_element($doc, $entry, "updated", datetime_convert("UTC", "UTC", $item["edited"]."+00:00", ATOM_TIME));
} }
/** /**
@ -1918,12 +1936,12 @@ class ostatus
$attributes = array( $attributes = array(
"ref" => $parent_item, "ref" => $parent_item,
"href" => $parent_plink); "href" => $parent_plink);
xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes); Xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
$attributes = array( $attributes = array(
"rel" => "related", "rel" => "related",
"href" => $parent_plink); "href" => $parent_plink);
xml::add_element($doc, $entry, "link", "", $attributes); Xml::add_element($doc, $entry, "link", "", $attributes);
} }
if (intval($item["parent"]) > 0) { if (intval($item["parent"]) > 0) {
@ -1942,14 +1960,14 @@ class ostatus
} }
} }
xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:conversation", "href" => $conversation_href)); Xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:conversation", "href" => $conversation_href));
$attributes = array( $attributes = array(
"href" => $conversation_href, "href" => $conversation_href,
"local_id" => $item["parent"], "local_id" => $item["parent"],
"ref" => $conversation_uri); "ref" => $conversation_uri);
xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes); Xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
} }
$tags = item_getfeedtags($item); $tags = item_getfeedtags($item);
@ -1977,14 +1995,14 @@ class ostatus
dbesc(normalise_link($mention)) dbesc(normalise_link($mention))
); );
if ($r[0]["forum"] || $r[0]["prv"]) { if ($r[0]["forum"] || $r[0]["prv"]) {
xml::add_element($doc, $entry, "link", "", Xml::add_element($doc, $entry, "link", "",
array( array(
"rel" => "mentioned", "rel" => "mentioned",
"ostatus:object-type" => ACTIVITY_OBJ_GROUP, "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
"href" => $mention) "href" => $mention)
); );
} else { } else {
xml::add_element($doc, $entry, "link", "", Xml::add_element($doc, $entry, "link", "",
array( array(
"rel" => "mentioned", "rel" => "mentioned",
"ostatus:object-type" => ACTIVITY_OBJ_PERSON, "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
@ -1994,18 +2012,18 @@ class ostatus
} }
if (!$item["private"]) { if (!$item["private"]) {
xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:attention", Xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:attention",
"href" => "http://activityschema.org/collection/public")); "href" => "http://activityschema.org/collection/public"));
xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned", Xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
"ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection", "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
"href" => "http://activityschema.org/collection/public")); "href" => "http://activityschema.org/collection/public"));
xml::add_element($doc, $entry, "mastodon:scope", "public"); Xml::add_element($doc, $entry, "mastodon:scope", "public");
} }
if (count($tags)) { if (count($tags)) {
foreach ($tags as $t) { foreach ($tags as $t) {
if ($t[0] != "@") { if ($t[0] != "@") {
xml::add_element($doc, $entry, "category", "", array("term" => $t[2])); Xml::add_element($doc, $entry, "category", "", array("term" => $t[2]));
} }
} }
} }
@ -2014,8 +2032,9 @@ class ostatus
if ($complete && ($item["id"] > 0)) { if ($complete && ($item["id"] > 0)) {
$app = $item["app"]; $app = $item["app"];
if ($app == "") if ($app == "") {
$app = "web"; $app = "web";
}
$attributes = array("local_id" => $item["id"], "source" => $app); $attributes = array("local_id" => $item["id"], "source" => $app);
@ -2024,10 +2043,10 @@ class ostatus
} }
if ($item["coord"] != "") { if ($item["coord"] != "") {
xml::add_element($doc, $entry, "georss:point", $item["coord"]); Xml::add_element($doc, $entry, "georss:point", $item["coord"]);
} }
xml::add_element($doc, $entry, "statusnet:notice_info", "", $attributes); Xml::add_element($doc, $entry, "statusnet:notice_info", "", $attributes);
} }
} }

View file

@ -1,10 +1,14 @@
<?php <?php
/**
* @file include/salmon.php
*/
use Friendica\Network\Probe; use Friendica\Network\Probe;
use Friendica\Util\Xml;
require_once 'include/crypto.php'; require_once 'include/crypto.php';
function get_salmon_key($uri, $keyhash) { function get_salmon_key($uri, $keyhash)
{
$ret = array(); $ret = array();
logger('Fetching salmon key for '.$uri); logger('Fetching salmon key for '.$uri);
@ -42,7 +46,6 @@ function get_salmon_key($uri, $keyhash) {
logger('Key located: ' . print_r($ret, true)); logger('Key located: ' . print_r($ret, true));
if (count($ret) == 1) { if (count($ret) == 1) {
// We only found one one key so we don't care if the hash matches. // We only found one one key so we don't care if the hash matches.
// If it's the wrong key we'll find out soon enough because // If it's the wrong key we'll find out soon enough because
// message verification will fail. This also covers some older // message verification will fail. This also covers some older
@ -64,8 +67,8 @@ function get_salmon_key($uri, $keyhash) {
function slapper($owner, $url, $slap) { function slapper($owner, $url, $slap)
{
// does contact have a salmon endpoint? // does contact have a salmon endpoint?
if (! strlen($url)) { if (! strlen($url)) {
@ -109,7 +112,7 @@ function slapper($owner, $url, $slap) {
$namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env"); $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
$salmon = xml::from_array($xmldata, $xml, false, $namespaces); $salmon = Xml::from_array($xmldata, $xml, false, $namespaces);
// slap them // slap them
post_url($url, $salmon, array( post_url($url, $salmon, array(
@ -123,7 +126,6 @@ function slapper($owner, $url, $slap) {
// check for success, e.g. 2xx // check for success, e.g. 2xx
if ($return_code > 299) { if ($return_code > 299) {
logger('GNU Social salmon failed. Falling back to compliant mode'); logger('GNU Social salmon failed. Falling back to compliant mode');
// Now try the compliant mode that normally isn't used for GNU Social // Now try the compliant mode that normally isn't used for GNU Social
@ -136,7 +138,7 @@ function slapper($owner, $url, $slap) {
$namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env"); $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
$salmon = xml::from_array($xmldata, $xml, false, $namespaces); $salmon = Xml::from_array($xmldata, $xml, false, $namespaces);
// slap them // slap them
post_url($url, $salmon, array( post_url($url, $salmon, array(
@ -159,7 +161,7 @@ function slapper($owner, $url, $slap) {
$namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env"); $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
$salmon = xml::from_array($xmldata, $xml, false, $namespaces); $salmon = Xml::from_array($xmldata, $xml, false, $namespaces);
// slap them // slap them
post_url($url, $salmon, array( post_url($url, $salmon, array(

View file

@ -6,11 +6,12 @@ This file is part of the Diaspora protocol. It is used for fetching single publi
use Friendica\App; use Friendica\App;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Protocol\Diaspora; use Friendica\Protocol\Diaspora;
use Friendica\Util\Xml;
require_once("include/crypto.php"); require_once "include/crypto.php";
require_once("include/xml.php");
function fetch_init(App $a) { function fetch_init(App $a)
{
if (($a->argc != 3) || (!in_array($a->argv[1], array("post", "status_message", "reshare")))) { if (($a->argc != 3) || (!in_array($a->argv[1], array("post", "status_message", "reshare")))) {
header($_SERVER["SERVER_PROTOCOL"].' 404 '.t('Not Found')); header($_SERVER["SERVER_PROTOCOL"].' 404 '.t('Not Found'));
@ -20,13 +21,22 @@ function fetch_init(App $a) {
$guid = $a->argv[2]; $guid = $a->argv[2];
// Fetch the item // Fetch the item
$item = q("SELECT `uid`, `title`, `body`, `guid`, `contact-id`, `private`, `created`, `app`, `location`, `coord` $item = q(
"SELECT `uid`, `title`, `body`, `guid`, `contact-id`, `private`, `created`, `app`, `location`, `coord`
FROM `item` WHERE `wall` AND NOT `private` AND `guid` = '%s' AND `network` IN ('%s', '%s') AND `id` = `parent` LIMIT 1", FROM `item` WHERE `wall` AND NOT `private` AND `guid` = '%s' AND `network` IN ('%s', '%s') AND `id` = `parent` LIMIT 1",
dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA); dbesc($guid),
NETWORK_DFRN,
NETWORK_DIASPORA
);
if (!$item) { if (!$item) {
$r = q("SELECT `author-link` $r = q(
"SELECT `author-link`
FROM `item` WHERE `uid` = 0 AND `guid` = '%s' AND `network` IN ('%s', '%s') AND `id` = `parent` LIMIT 1", FROM `item` WHERE `uid` = 0 AND `guid` = '%s' AND `network` IN ('%s', '%s') AND `id` = `parent` LIMIT 1",
dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA); dbesc($guid),
NETWORK_DFRN,
NETWORK_DIASPORA
);
if ($r) { if ($r) {
$parts = parse_url($r[0]["author-link"]); $parts = parse_url($r[0]["author-link"]);
$host = $parts["scheme"]."://".$parts["host"]; $host = $parts["scheme"]."://".$parts["host"];
@ -45,9 +55,13 @@ function fetch_init(App $a) {
} }
// Fetch some data from the author (We could combine both queries - but I think this is more readable) // Fetch some data from the author (We could combine both queries - but I think this is more readable)
$r = q("SELECT `user`.`prvkey`, `contact`.`addr`, `user`.`nickname`, `contact`.`nick` FROM `user` $r = q(
"SELECT `user`.`prvkey`, `contact`.`addr`, `user`.`nickname`, `contact`.`nick` FROM `user`
INNER JOIN `contact` ON `contact`.`uid` = `user`.`uid` AND `contact`.`self` INNER JOIN `contact` ON `contact`.`uid` = `user`.`uid` AND `contact`.`self`
WHERE `user`.`uid` = %d", intval($item[0]["uid"])); WHERE `user`.`uid` = %d",
intval($item[0]["uid"])
);
if (!$r) { if (!$r) {
header($_SERVER["SERVER_PROTOCOL"].' 404 '.t('Not Found')); header($_SERVER["SERVER_PROTOCOL"].' 404 '.t('Not Found'));
killme(); killme();

View file

@ -7,13 +7,13 @@ use Friendica\Core\Cache;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Core\PConfig; use Friendica\Core\PConfig;
use Friendica\Database\DBM; use Friendica\Database\DBM;
use Friendica\Util\Xml;
require_once 'include/datetime.php'; require_once 'include/datetime.php';
require_once 'include/bbcode.php'; require_once 'include/bbcode.php';
require_once 'include/ForumManager.php'; require_once 'include/ForumManager.php';
require_once 'include/group.php'; require_once 'include/group.php';
require_once 'mod/proxy.php'; require_once 'mod/proxy.php';
require_once 'include/xml.php';
require_once 'include/enotify.php'; require_once 'include/enotify.php';
/** /**
@ -114,7 +114,7 @@ function ping_init(App $a)
} }
} else { } else {
header("Content-type: text/xml"); header("Content-type: text/xml");
echo xml::from_array($data, $xml); echo Xml::from_array($data, $xml);
} }
killme(); killme();
} }
@ -411,7 +411,7 @@ function ping_init(App $a)
$data = ping_format_xml_data($data, $sysnotify_count, $notifications, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen); $data = ping_format_xml_data($data, $sysnotify_count, $notifications, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen);
header("Content-type: text/xml"); header("Content-type: text/xml");
echo xml::from_array(array("result" => $data), $xml); echo Xml::from_array(array("result" => $data), $xml);
} }
killme(); killme();

View file

@ -13,10 +13,9 @@ use Friendica\Core\System;
use Friendica\Core\Cache; use Friendica\Core\Cache;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Database\DBM; use Friendica\Database\DBM;
use Friendica\Util\Xml;
use dba; use dba;
use xml;
use DomXPath; use DomXPath;
use DOMDocument; use DOMDocument;
@ -124,7 +123,7 @@ class Probe {
return array(); return array();
} }
$links = xml::element_to_array($xrd); $links = Xml::element_to_array($xrd);
if (!isset($links["xrd"]["link"])) { if (!isset($links["xrd"]["link"])) {
logger("No xrd data found for ".$host, LOGGER_DEBUG); logger("No xrd data found for ".$host, LOGGER_DEBUG);
return array(); return array();
@ -706,7 +705,7 @@ class Probe {
return false; return false;
} }
$xrd_arr = xml::element_to_array($xrd); $xrd_arr = Xml::element_to_array($xrd);
if (!isset($xrd_arr["xrd"]["link"])) { if (!isset($xrd_arr["xrd"]["link"])) {
logger("No XML webfinger links for ".$url, LOGGER_DEBUG); logger("No XML webfinger links for ".$url, LOGGER_DEBUG);
return false; return false;

View file

@ -6,10 +6,9 @@
namespace Friendica; namespace Friendica;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Util\Xml;
use xml;
use dba; use dba;
use DomXPath; use DomXPath;
use DOMDocument; use DOMDocument;
@ -204,17 +203,17 @@ class ParseUrl
$doc = new DOMDocument(); $doc = new DOMDocument();
@$doc->loadHTML($body); @$doc->loadHTML($body);
xml::deleteNode($doc, "style"); Xml::deleteNode($doc, "style");
xml::deleteNode($doc, "script"); Xml::deleteNode($doc, "script");
xml::deleteNode($doc, "option"); Xml::deleteNode($doc, "option");
xml::deleteNode($doc, "h1"); Xml::deleteNode($doc, "h1");
xml::deleteNode($doc, "h2"); Xml::deleteNode($doc, "h2");
xml::deleteNode($doc, "h3"); Xml::deleteNode($doc, "h3");
xml::deleteNode($doc, "h4"); Xml::deleteNode($doc, "h4");
xml::deleteNode($doc, "h5"); Xml::deleteNode($doc, "h5");
xml::deleteNode($doc, "h6"); Xml::deleteNode($doc, "h6");
xml::deleteNode($doc, "ol"); Xml::deleteNode($doc, "ol");
xml::deleteNode($doc, "ul"); Xml::deleteNode($doc, "ul");
$xpath = new DomXPath($doc); $xpath = new DomXPath($doc);

View file

@ -13,12 +13,12 @@ use Friendica\Core\Config;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Core\Worker; use Friendica\Core\Worker;
use Friendica\Database\DBM; use Friendica\Database\DBM;
use Friendica\Util\Xml;
use dba; use dba;
use DOMDocument; use DOMDocument;
use DomXPath; use DomXPath;
use ostatus; use ostatus;
use xml;
require_once "include/Contact.php"; require_once "include/Contact.php";
require_once "include/enotify.php"; require_once "include/enotify.php";
@ -402,17 +402,17 @@ class DFRN
$mail = $doc->createElement("dfrn:mail"); $mail = $doc->createElement("dfrn:mail");
$sender = $doc->createElement("dfrn:sender"); $sender = $doc->createElement("dfrn:sender");
xml::add_element($doc, $sender, "dfrn:name", $owner['name']); Xml::add_element($doc, $sender, "dfrn:name", $owner['name']);
xml::add_element($doc, $sender, "dfrn:uri", $owner['url']); Xml::add_element($doc, $sender, "dfrn:uri", $owner['url']);
xml::add_element($doc, $sender, "dfrn:avatar", $owner['thumb']); Xml::add_element($doc, $sender, "dfrn:avatar", $owner['thumb']);
$mail->appendChild($sender); $mail->appendChild($sender);
xml::add_element($doc, $mail, "dfrn:id", $item['uri']); Xml::add_element($doc, $mail, "dfrn:id", $item['uri']);
xml::add_element($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']); Xml::add_element($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
xml::add_element($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME)); Xml::add_element($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME));
xml::add_element($doc, $mail, "dfrn:subject", $item['title']); Xml::add_element($doc, $mail, "dfrn:subject", $item['title']);
xml::add_element($doc, $mail, "dfrn:content", $item['body']); Xml::add_element($doc, $mail, "dfrn:content", $item['body']);
$root->appendChild($mail); $root->appendChild($mail);
@ -437,11 +437,11 @@ class DFRN
$suggest = $doc->createElement("dfrn:suggest"); $suggest = $doc->createElement("dfrn:suggest");
xml::add_element($doc, $suggest, "dfrn:url", $item['url']); Xml::add_element($doc, $suggest, "dfrn:url", $item['url']);
xml::add_element($doc, $suggest, "dfrn:name", $item['name']); Xml::add_element($doc, $suggest, "dfrn:name", $item['name']);
xml::add_element($doc, $suggest, "dfrn:photo", $item['photo']); Xml::add_element($doc, $suggest, "dfrn:photo", $item['photo']);
xml::add_element($doc, $suggest, "dfrn:request", $item['request']); Xml::add_element($doc, $suggest, "dfrn:request", $item['request']);
xml::add_element($doc, $suggest, "dfrn:note", $item['note']); Xml::add_element($doc, $suggest, "dfrn:note", $item['note']);
$root->appendChild($suggest); $root->appendChild($suggest);
@ -489,18 +489,18 @@ class DFRN
$relocate = $doc->createElement("dfrn:relocate"); $relocate = $doc->createElement("dfrn:relocate");
xml::add_element($doc, $relocate, "dfrn:url", $owner['url']); Xml::add_element($doc, $relocate, "dfrn:url", $owner['url']);
xml::add_element($doc, $relocate, "dfrn:name", $owner['name']); Xml::add_element($doc, $relocate, "dfrn:name", $owner['name']);
xml::add_element($doc, $relocate, "dfrn:addr", $owner['addr']); Xml::add_element($doc, $relocate, "dfrn:addr", $owner['addr']);
xml::add_element($doc, $relocate, "dfrn:avatar", $owner['avatar']); Xml::add_element($doc, $relocate, "dfrn:avatar", $owner['avatar']);
xml::add_element($doc, $relocate, "dfrn:photo", $photos[4]); Xml::add_element($doc, $relocate, "dfrn:photo", $photos[4]);
xml::add_element($doc, $relocate, "dfrn:thumb", $photos[5]); Xml::add_element($doc, $relocate, "dfrn:thumb", $photos[5]);
xml::add_element($doc, $relocate, "dfrn:micro", $photos[6]); Xml::add_element($doc, $relocate, "dfrn:micro", $photos[6]);
xml::add_element($doc, $relocate, "dfrn:request", $owner['request']); Xml::add_element($doc, $relocate, "dfrn:request", $owner['request']);
xml::add_element($doc, $relocate, "dfrn:confirm", $owner['confirm']); Xml::add_element($doc, $relocate, "dfrn:confirm", $owner['confirm']);
xml::add_element($doc, $relocate, "dfrn:notify", $owner['notify']); Xml::add_element($doc, $relocate, "dfrn:notify", $owner['notify']);
xml::add_element($doc, $relocate, "dfrn:poll", $owner['poll']); Xml::add_element($doc, $relocate, "dfrn:poll", $owner['poll']);
xml::add_element($doc, $relocate, "dfrn:sitepubkey", Config::get('system','site_pubkey')); Xml::add_element($doc, $relocate, "dfrn:sitepubkey", Config::get('system','site_pubkey'));
$root->appendChild($relocate); $root->appendChild($relocate);
@ -539,17 +539,17 @@ class DFRN
$root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS); $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
$root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET); $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
xml::add_element($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]); Xml::add_element($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
xml::add_element($doc, $root, "title", $owner["name"]); Xml::add_element($doc, $root, "title", $owner["name"]);
$attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION); $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes); Xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
$attributes = array("rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"); $attributes = array("rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/");
xml::add_element($doc, $root, "link", "", $attributes); Xml::add_element($doc, $root, "link", "", $attributes);
$attributes = array("rel" => "alternate", "type" => "text/html", "href" => $alternatelink); $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $alternatelink);
xml::add_element($doc, $root, "link", "", $attributes); Xml::add_element($doc, $root, "link", "", $attributes);
if ($public) { if ($public) {
@ -557,26 +557,26 @@ class DFRN
ostatus::hublinks($doc, $root, $owner["nick"]); ostatus::hublinks($doc, $root, $owner["nick"]);
$attributes = array("rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]); $attributes = array("rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
xml::add_element($doc, $root, "link", "", $attributes); Xml::add_element($doc, $root, "link", "", $attributes);
$attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]); $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
xml::add_element($doc, $root, "link", "", $attributes); Xml::add_element($doc, $root, "link", "", $attributes);
$attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]); $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
xml::add_element($doc, $root, "link", "", $attributes); Xml::add_element($doc, $root, "link", "", $attributes);
} }
// For backward compatibility we keep this element // For backward compatibility we keep this element
if ($owner['page-flags'] == PAGE_COMMUNITY) { if ($owner['page-flags'] == PAGE_COMMUNITY) {
xml::add_element($doc, $root, "dfrn:community", 1); Xml::add_element($doc, $root, "dfrn:community", 1);
} }
// The former element is replaced by this one // The former element is replaced by this one
xml::add_element($doc, $root, "dfrn:account_type", $owner["account-type"]); Xml::add_element($doc, $root, "dfrn:account_type", $owner["account-type"]);
/// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP" /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME)); Xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
$author = self::add_author($doc, $owner, $authorelement, $public); $author = self::add_author($doc, $owner, $authorelement, $public);
$root->appendChild($author); $root->appendChild($author);
@ -620,9 +620,9 @@ class DFRN
$attributes = array("dfrn:updated" => $namdate); $attributes = array("dfrn:updated" => $namdate);
} }
xml::add_element($doc, $author, "name", $owner["name"], $attributes); Xml::add_element($doc, $author, "name", $owner["name"], $attributes);
xml::add_element($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes); Xml::add_element($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
xml::add_element($doc, $author, "dfrn:handle", $owner["addr"], $attributes); Xml::add_element($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
$attributes = array("rel" => "photo", "type" => "image/jpeg", $attributes = array("rel" => "photo", "type" => "image/jpeg",
"media:width" => 175, "media:height" => 175, "href" => $owner['photo']); "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
@ -631,13 +631,13 @@ class DFRN
$attributes["dfrn:updated"] = $picdate; $attributes["dfrn:updated"] = $picdate;
} }
xml::add_element($doc, $author, "link", "", $attributes); Xml::add_element($doc, $author, "link", "", $attributes);
$attributes["rel"] = "avatar"; $attributes["rel"] = "avatar";
xml::add_element($doc, $author, "link", "", $attributes); Xml::add_element($doc, $author, "link", "", $attributes);
if ($hidewall) { if ($hidewall) {
xml::add_element($doc, $author, "dfrn:hide", "true"); Xml::add_element($doc, $author, "dfrn:hide", "true");
} }
// The following fields will only be generated if the data isn't meant for a public feed // The following fields will only be generated if the data isn't meant for a public feed
@ -648,7 +648,7 @@ class DFRN
$birthday = feed_birthday($owner['uid'], $owner['timezone']); $birthday = feed_birthday($owner['uid'], $owner['timezone']);
if ($birthday) { if ($birthday) {
xml::add_element($doc, $author, "dfrn:birthday", $birthday); Xml::add_element($doc, $author, "dfrn:birthday", $birthday);
} }
// Only show contact details when we are allowed to // Only show contact details when we are allowed to
@ -664,26 +664,26 @@ class DFRN
if (DBM::is_result($r)) { if (DBM::is_result($r)) {
$profile = $r[0]; $profile = $r[0];
xml::add_element($doc, $author, "poco:displayName", $profile["name"]); Xml::add_element($doc, $author, "poco:displayName", $profile["name"]);
xml::add_element($doc, $author, "poco:updated", $namdate); Xml::add_element($doc, $author, "poco:updated", $namdate);
if (trim($profile["dob"]) > '0001-01-01') { if (trim($profile["dob"]) > '0001-01-01') {
xml::add_element($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"]))); Xml::add_element($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
} }
xml::add_element($doc, $author, "poco:note", $profile["about"]); Xml::add_element($doc, $author, "poco:note", $profile["about"]);
xml::add_element($doc, $author, "poco:preferredUsername", $profile["nickname"]); Xml::add_element($doc, $author, "poco:preferredUsername", $profile["nickname"]);
$savetz = date_default_timezone_get(); $savetz = date_default_timezone_get();
date_default_timezone_set($profile["timezone"]); date_default_timezone_set($profile["timezone"]);
xml::add_element($doc, $author, "poco:utcOffset", date("P")); Xml::add_element($doc, $author, "poco:utcOffset", date("P"));
date_default_timezone_set($savetz); date_default_timezone_set($savetz);
if (trim($profile["homepage"]) != "") { if (trim($profile["homepage"]) != "") {
$urls = $doc->createElement("poco:urls"); $urls = $doc->createElement("poco:urls");
xml::add_element($doc, $urls, "poco:type", "homepage"); Xml::add_element($doc, $urls, "poco:type", "homepage");
xml::add_element($doc, $urls, "poco:value", $profile["homepage"]); Xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
xml::add_element($doc, $urls, "poco:primary", "true"); Xml::add_element($doc, $urls, "poco:primary", "true");
$author->appendChild($urls); $author->appendChild($urls);
} }
@ -691,33 +691,33 @@ class DFRN
$keywords = explode(",", $profile["pub_keywords"]); $keywords = explode(",", $profile["pub_keywords"]);
foreach ($keywords AS $keyword) { foreach ($keywords AS $keyword) {
xml::add_element($doc, $author, "poco:tags", trim($keyword)); Xml::add_element($doc, $author, "poco:tags", trim($keyword));
} }
} }
if (trim($profile["xmpp"]) != "") { if (trim($profile["xmpp"]) != "") {
$ims = $doc->createElement("poco:ims"); $ims = $doc->createElement("poco:ims");
xml::add_element($doc, $ims, "poco:type", "xmpp"); Xml::add_element($doc, $ims, "poco:type", "xmpp");
xml::add_element($doc, $ims, "poco:value", $profile["xmpp"]); Xml::add_element($doc, $ims, "poco:value", $profile["xmpp"]);
xml::add_element($doc, $ims, "poco:primary", "true"); Xml::add_element($doc, $ims, "poco:primary", "true");
$author->appendChild($ims); $author->appendChild($ims);
} }
if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") { if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
$element = $doc->createElement("poco:address"); $element = $doc->createElement("poco:address");
xml::add_element($doc, $element, "poco:formatted", formatted_location($profile)); Xml::add_element($doc, $element, "poco:formatted", formatted_location($profile));
if (trim($profile["locality"]) != "") { if (trim($profile["locality"]) != "") {
xml::add_element($doc, $element, "poco:locality", $profile["locality"]); Xml::add_element($doc, $element, "poco:locality", $profile["locality"]);
} }
if (trim($profile["region"]) != "") { if (trim($profile["region"]) != "") {
xml::add_element($doc, $element, "poco:region", $profile["region"]); Xml::add_element($doc, $element, "poco:region", $profile["region"]);
} }
if (trim($profile["country-name"]) != "") { if (trim($profile["country-name"]) != "") {
xml::add_element($doc, $element, "poco:country", $profile["country-name"]); Xml::add_element($doc, $element, "poco:country", $profile["country-name"]);
} }
$author->appendChild($element); $author->appendChild($element);
@ -744,9 +744,9 @@ class DFRN
$contact = get_contact_details_by_url($contact_url, $item["uid"]); $contact = get_contact_details_by_url($contact_url, $item["uid"]);
$author = $doc->createElement($element); $author = $doc->createElement($element);
xml::add_element($doc, $author, "name", $contact["name"]); Xml::add_element($doc, $author, "name", $contact["name"]);
xml::add_element($doc, $author, "uri", $contact["url"]); Xml::add_element($doc, $author, "uri", $contact["url"]);
xml::add_element($doc, $author, "dfrn:handle", $contact["addr"]); Xml::add_element($doc, $author, "dfrn:handle", $contact["addr"]);
/// @Todo /// @Todo
/// - Check real image type and image size /// - Check real image type and image size
@ -757,7 +757,7 @@ class DFRN
"media:width" => 80, "media:width" => 80,
"media:height" => 80, "media:height" => 80,
"href" => $contact["photo"]); "href" => $contact["photo"]);
xml::add_element($doc, $author, "link", "", $attributes); Xml::add_element($doc, $author, "link", "", $attributes);
$attributes = array( $attributes = array(
"rel" => "avatar", "rel" => "avatar",
@ -765,7 +765,7 @@ class DFRN
"media:width" => 80, "media:width" => 80,
"media:height" => 80, "media:height" => 80,
"href" => $contact["photo"]); "href" => $contact["photo"]);
xml::add_element($doc, $author, "link", "", $attributes); Xml::add_element($doc, $author, "link", "", $attributes);
return $author; return $author;
} }
@ -790,13 +790,13 @@ class DFRN
return false; return false;
} }
if ($r->type) { if ($r->type) {
xml::add_element($doc, $entry, "activity:object-type", $r->type); Xml::add_element($doc, $entry, "activity:object-type", $r->type);
} }
if ($r->id) { if ($r->id) {
xml::add_element($doc, $entry, "id", $r->id); Xml::add_element($doc, $entry, "id", $r->id);
} }
if ($r->title) { if ($r->title) {
xml::add_element($doc, $entry, "title", $r->title); Xml::add_element($doc, $entry, "title", $r->title);
} }
if ($r->link) { if ($r->link) {
@ -815,16 +815,16 @@ class DFRN
foreach ($link->attributes() AS $parameter => $value) { foreach ($link->attributes() AS $parameter => $value) {
$attributes[$parameter] = $value; $attributes[$parameter] = $value;
} }
xml::add_element($doc, $entry, "link", "", $attributes); Xml::add_element($doc, $entry, "link", "", $attributes);
} }
} }
} else { } else {
$attributes = array("rel" => "alternate", "type" => "text/html", "href" => $r->link); $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $r->link);
xml::add_element($doc, $entry, "link", "", $attributes); Xml::add_element($doc, $entry, "link", "", $attributes);
} }
} }
if ($r->content) { if ($r->content) {
xml::add_element($doc, $entry, "content", bbcode($r->content), array("type" => "html")); Xml::add_element($doc, $entry, "content", bbcode($r->content), array("type" => "html"));
} }
return $entry; return $entry;
@ -863,7 +863,7 @@ class DFRN
$attributes["title"] = trim($matches[4]); $attributes["title"] = trim($matches[4]);
} }
xml::add_element($doc, $root, "link", "", $attributes); Xml::add_element($doc, $root, "link", "", $attributes);
} }
} }
} }
@ -893,7 +893,7 @@ class DFRN
if ($item['deleted']) { if ($item['deleted']) {
$attributes = array("ref" => $item['uri'], "when" => datetime_convert('UTC', 'UTC', $item['edited'] . '+00:00', ATOM_TIME)); $attributes = array("ref" => $item['uri'], "when" => datetime_convert('UTC', 'UTC', $item['edited'] . '+00:00', ATOM_TIME));
return xml::create_element($doc, "at:deleted-entry", "", $attributes); return Xml::create_element($doc, "at:deleted-entry", "", $attributes);
} }
if (!$single) { if (!$single) {
@ -944,7 +944,7 @@ class DFRN
$attributes = array("ref" => $parent_item, "type" => "text/html", $attributes = array("ref" => $parent_item, "type" => "text/html",
"href" => $parent[0]['plink'], "href" => $parent[0]['plink'],
"dfrn:diaspora_guid" => $parent[0]['guid']); "dfrn:diaspora_guid" => $parent[0]['guid']);
xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes); Xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
} }
// Add conversation data. This is used for OStatus // Add conversation data. This is used for OStatus
@ -967,23 +967,23 @@ class DFRN
"href" => $conversation_href, "href" => $conversation_href,
"ref" => $conversation_uri); "ref" => $conversation_uri);
xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes); Xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
xml::add_element($doc, $entry, "id", $item["uri"]); Xml::add_element($doc, $entry, "id", $item["uri"]);
xml::add_element($doc, $entry, "title", $item["title"]); Xml::add_element($doc, $entry, "title", $item["title"]);
xml::add_element($doc, $entry, "published", datetime_convert("UTC", "UTC", $item["created"] . "+00:00", ATOM_TIME)); Xml::add_element($doc, $entry, "published", datetime_convert("UTC", "UTC", $item["created"] . "+00:00", ATOM_TIME));
xml::add_element($doc, $entry, "updated", datetime_convert("UTC", "UTC", $item["edited"] . "+00:00", ATOM_TIME)); Xml::add_element($doc, $entry, "updated", datetime_convert("UTC", "UTC", $item["edited"] . "+00:00", ATOM_TIME));
// "dfrn:env" is used to read the content // "dfrn:env" is used to read the content
xml::add_element($doc, $entry, "dfrn:env", base64url_encode($body, true)); Xml::add_element($doc, $entry, "dfrn:env", base64url_encode($body, true));
// The "content" field is not read by the receiver. We could remove it when the type is "text" // The "content" field is not read by the receiver. We could remove it when the type is "text"
// We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env" // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
xml::add_element($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), array("type" => $type)); Xml::add_element($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), array("type" => $type));
// We save this value in "plink". Maybe we should read it from there as well? // We save this value in "plink". Maybe we should read it from there as well?
xml::add_element( Xml::add_element(
$doc, $doc,
$entry, $entry,
"link", "link",
@ -995,50 +995,50 @@ class DFRN
// "comment-allow" is some old fashioned stuff for old Friendica versions. // "comment-allow" is some old fashioned stuff for old Friendica versions.
// It is included in the rewritten code for completeness // It is included in the rewritten code for completeness
if ($comment) { if ($comment) {
xml::add_element($doc, $entry, "dfrn:comment-allow", intval($item['last-child'])); Xml::add_element($doc, $entry, "dfrn:comment-allow", intval($item['last-child']));
} }
if ($item['location']) { if ($item['location']) {
xml::add_element($doc, $entry, "dfrn:location", $item['location']); Xml::add_element($doc, $entry, "dfrn:location", $item['location']);
} }
if ($item['coord']) { if ($item['coord']) {
xml::add_element($doc, $entry, "georss:point", $item['coord']); Xml::add_element($doc, $entry, "georss:point", $item['coord']);
} }
if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) { if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
xml::add_element($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1)); Xml::add_element($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
} }
if ($item['extid']) { if ($item['extid']) {
xml::add_element($doc, $entry, "dfrn:extid", $item['extid']); Xml::add_element($doc, $entry, "dfrn:extid", $item['extid']);
} }
if ($item['bookmark']) { if ($item['bookmark']) {
xml::add_element($doc, $entry, "dfrn:bookmark", "true"); Xml::add_element($doc, $entry, "dfrn:bookmark", "true");
} }
if ($item['app']) { if ($item['app']) {
xml::add_element($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app'])); Xml::add_element($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app']));
} }
xml::add_element($doc, $entry, "dfrn:diaspora_guid", $item["guid"]); Xml::add_element($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
// The signed text contains the content in Markdown, the sender handle and the signatur for the content // The signed text contains the content in Markdown, the sender handle and the signatur for the content
// It is needed for relayed comments to Diaspora. // It is needed for relayed comments to Diaspora.
if ($item['signed_text']) { if ($item['signed_text']) {
$sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']))); $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
xml::add_element($doc, $entry, "dfrn:diaspora_signature", $sign); Xml::add_element($doc, $entry, "dfrn:diaspora_signature", $sign);
} }
xml::add_element($doc, $entry, "activity:verb", construct_verb($item)); Xml::add_element($doc, $entry, "activity:verb", construct_verb($item));
if ($item['object-type'] != "") { if ($item['object-type'] != "") {
xml::add_element($doc, $entry, "activity:object-type", $item['object-type']); Xml::add_element($doc, $entry, "activity:object-type", $item['object-type']);
} elseif ($item['id'] == $item['parent']) { } elseif ($item['id'] == $item['parent']) {
xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE); Xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
} else { } else {
xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT); Xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
} }
$actobj = self::create_activity($doc, "activity:object", $item['object']); $actobj = self::create_activity($doc, "activity:object", $item['object']);
@ -1056,7 +1056,7 @@ class DFRN
if (count($tags)) { if (count($tags)) {
foreach ($tags as $t) { foreach ($tags as $t) {
if (($type != 'html') || ($t[0] != "@")) { if (($type != 'html') || ($t[0] != "@")) {
xml::add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2])); Xml::add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]));
} }
} }
} }
@ -1077,7 +1077,7 @@ class DFRN
); );
if (DBM::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) { if (DBM::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
xml::add_element( Xml::add_element(
$doc, $doc,
$entry, $entry,
"link", "link",
@ -1087,7 +1087,7 @@ class DFRN
"href" => $mention) "href" => $mention)
); );
} else { } else {
xml::add_element( Xml::add_element(
$doc, $doc,
$entry, $entry,
"link", "link",
@ -1705,7 +1705,7 @@ class DFRN
$obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element); $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
$activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue; $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
xml::add_element($obj_doc, $obj_element, "type", $activity_type); Xml::add_element($obj_doc, $obj_element, "type", $activity_type);
$id = $xpath->query("atom:id", $activity)->item(0); $id = $xpath->query("atom:id", $activity)->item(0);
if (is_object($id)) { if (is_object($id)) {
@ -1719,7 +1719,7 @@ class DFRN
$links = $xpath->query("atom:link", $activity); $links = $xpath->query("atom:link", $activity);
if (is_object($links)) { if (is_object($links)) {
foreach ($links AS $link) { foreach ($links as $link) {
$obj_element->appendChild($obj_doc->importNode($link, true)); $obj_element->appendChild($obj_doc->importNode($link, true));
} }
} }

View file

@ -17,10 +17,10 @@ use Friendica\Core\PConfig;
use Friendica\Core\Worker; use Friendica\Core\Worker;
use Friendica\Database\DBM; use Friendica\Database\DBM;
use Friendica\Network\Probe; use Friendica\Network\Probe;
use Friendica\Util\Xml;
use dba; use dba;
use SimpleXMLElement; use SimpleXMLElement;
use xml;
require_once 'include/items.php'; require_once 'include/items.php';
require_once 'include/bb2diaspora.php'; require_once 'include/bb2diaspora.php';
@ -672,7 +672,7 @@ class Diaspora
if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) if (!in_array($fieldname, array("parent_author_signature", "target_author_signature"))
|| ($orig_type == "relayable_retraction") || ($orig_type == "relayable_retraction")
) { ) {
xml::copy($entry, $fields, $fieldname); Xml::copy($entry, $fields, $fieldname);
} }
} }
@ -1912,7 +1912,7 @@ class Diaspora
"title" => "", "title" => "",
"content" => $parent_body)); "content" => $parent_body));
return xml::from_array($xmldata, $xml, true); return Xml::from_array($xmldata, $xml, true);
} }
/** /**
@ -2344,7 +2344,7 @@ class Diaspora
"id" => $contact["url"]."/".$contact["name"], "id" => $contact["url"]."/".$contact["name"],
"link" => $link)); "link" => $link));
return xml::from_array($xmldata, $xml, true); return Xml::from_array($xmldata, $xml, true);
} }
/** /**
@ -3039,7 +3039,7 @@ class Diaspora
$namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env"); $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
return xml::from_array($xmldata, $xml, false, $namespaces); return Xml::from_array($xmldata, $xml, false, $namespaces);
} }
/** /**
@ -3172,7 +3172,7 @@ class Diaspora
{ {
$data = array($type => $message); $data = array($type => $message);
return xml::from_array($data, $xml); return Xml::from_array($data, $xml);
} }
/** /**

View file

@ -1,15 +1,15 @@
<?php <?php
/** /**
* @file include/xml.php * @file xrc/Util/Xml.php
*/ */
namespace Friendica\Util;
/** /**
* @brief This class contain methods to work with XML data * @brief This class contain methods to work with XML data
*
*/ */
class xml { class Xml
{
/** /**
* @brief Creates an XML structure out of a given array * @brief Creates an XML structure out of a given array
* *
@ -17,7 +17,7 @@ class xml {
* @param object $xml The createdXML will be returned by reference * @param object $xml The createdXML will be returned by reference
* @param bool $remove_header Should the XML header be removed or not? * @param bool $remove_header Should the XML header be removed or not?
* @param array $namespaces List of namespaces * @param array $namespaces List of namespaces
* @param bool $root - interally used parameter. Mustn't be used from outside. * @param bool $root interally used parameter. Mustn't be used from outside.
* *
* @return string The created XML * @return string The created XML
*/ */
@ -25,7 +25,7 @@ class xml {
if ($root) { if ($root) {
foreach ($array as $key => $value) { foreach ($array as $key => $value) {
foreach ($namespaces AS $nskey => $nsvalue) { foreach ($namespaces as $nskey => $nsvalue) {
$key .= " xmlns".($nskey == "" ? "":":").$nskey.'="'.$nsvalue.'"'; $key .= " xmlns".($nskey == "" ? "":":").$nskey.'="'.$nsvalue.'"';
} }
@ -72,7 +72,7 @@ class xml {
} elseif (isset($namespaces[""])) { } elseif (isset($namespaces[""])) {
$namespace = $namespaces[""]; $namespace = $namespaces[""];
} else { } else {
$namespace = NULL; $namespace = null;
} }
// Remove undefined namespaces from the key // Remove undefined namespaces from the key
@ -90,7 +90,7 @@ class xml {
if ((count($element_parts) > 1) && isset($namespaces[$element_parts[0]])) { if ((count($element_parts) > 1) && isset($namespaces[$element_parts[0]])) {
$namespace = $namespaces[$element_parts[0]]; $namespace = $namespaces[$element_parts[0]];
} else { } else {
$namespace = NULL; $namespace = null;
} }
$element->addAttribute($attr_key, $attr_value, $namespace); $element->addAttribute($attr_key, $attr_value, $namespace);
@ -102,7 +102,7 @@ class xml {
if (!is_array($value)) { if (!is_array($value)) {
$element = $xml->addChild($key, xmlify($value), $namespace); $element = $xml->addChild($key, xmlify($value), $namespace);
} elseif (is_array($value)) { } elseif (is_array($value)) {
$element = $xml->addChild($key, NULL, $namespace); $element = $xml->addChild($key, null, $namespace);
self::from_array($value, $element, $remove_header, $namespaces, false); self::from_array($value, $element, $remove_header, $namespaces, false);
} }
} }
@ -115,12 +115,13 @@ class xml {
* @param object $target The XML target * @param object $target The XML target
* @param string $elementname Name of the XML element of the target * @param string $elementname Name of the XML element of the target
*/ */
public static function copy(&$source, &$target, $elementname) { public static function copy(&$source, &$target, $elementname)
if (count($source->children()) == 0) {
if (count($source->children()) == 0) {
$target->addChild($elementname, xmlify($source)); $target->addChild($elementname, xmlify($source));
else { } else {
$child = $target->addChild($elementname); $child = $target->addChild($elementname);
foreach ($source->children() AS $childfield => $childentry) { foreach ($source->children() as $childfield => $childentry) {
self::copy($childentry, $child, $childfield); self::copy($childentry, $child, $childfield);
} }
} }
@ -136,10 +137,11 @@ class xml {
* *
* @return object XML element object * @return object XML element object
*/ */
public static function create_element($doc, $element, $value = "", $attributes = array()) { public static function create_element($doc, $element, $value = "", $attributes = array())
{
$element = $doc->createElement($element, xmlify($value)); $element = $doc->createElement($element, xmlify($value));
foreach ($attributes AS $key => $value) { foreach ($attributes as $key => $value) {
$attribute = $doc->createAttribute($key); $attribute = $doc->createAttribute($key);
$attribute->value = xmlify($value); $attribute->value = xmlify($value);
$element->appendChild($attribute); $element->appendChild($attribute);
@ -156,7 +158,8 @@ class xml {
* @param string $value XML value * @param string $value XML value
* @param array $attributes array containing the attributes * @param array $attributes array containing the attributes
*/ */
public static function add_element($doc, $parent, $element, $value = "", $attributes = array()) { public static function add_element($doc, $parent, $element, $value = "", $attributes = array())
{
$element = self::create_element($doc, $element, $value, $attributes); $element = self::create_element($doc, $element, $value, $attributes);
$parent->appendChild($element); $parent->appendChild($element);
} }
@ -171,8 +174,8 @@ class xml {
* *
* @return array | sring The array from the xml element or the string * @return array | sring The array from the xml element or the string
*/ */
public static function element_to_array($xml_element, &$recursion_depth=0) { public static function element_to_array($xml_element, &$recursion_depth=0)
{
// If we're getting too deep, bail out // If we're getting too deep, bail out
if ($recursion_depth > 512) { if ($recursion_depth > 512) {
return(null); return(null);
@ -180,7 +183,8 @@ class xml {
if (!is_string($xml_element) if (!is_string($xml_element)
&& !is_array($xml_element) && !is_array($xml_element)
&& (get_class($xml_element) == 'SimpleXMLElement')) { && (get_class($xml_element) == 'SimpleXMLElement')
) {
$xml_element_copy = $xml_element; $xml_element_copy = $xml_element;
$xml_element = get_object_vars($xml_element); $xml_element = get_object_vars($xml_element);
} }
@ -192,12 +196,11 @@ class xml {
} }
foreach ($xml_element as $key => $value) { foreach ($xml_element as $key => $value) {
$recursion_depth++; $recursion_depth++;
$result_array[strtolower($key)] = $result_array[strtolower($key)] = self::element_to_array($value, $recursion_depth);
self::element_to_array($value, $recursion_depth);
$recursion_depth--; $recursion_depth--;
} }
if ($recursion_depth == 0) { if ($recursion_depth == 0) {
$temp_array = $result_array; $temp_array = $result_array;
$result_array = array( $result_array = array(
@ -206,7 +209,6 @@ class xml {
} }
return ($result_array); return ($result_array);
} else { } else {
return (trim(strval($xml_element))); return (trim(strval($xml_element)));
} }
@ -215,13 +217,13 @@ class xml {
/** /**
* @brief Convert the given XML text to an array in the XML structure. * @brief Convert the given XML text to an array in the XML structure.
* *
* xml::to_array() will convert the given XML text to an array in the XML structure. * Xml::to_array() will convert the given XML text to an array in the XML structure.
* Link: http://www.bin-co.com/php/scripts/xml2array/ * Link: http://www.bin-co.com/php/scripts/xml2array/
* Portions significantly re-written by mike@macgirvin.com for Friendica * Portions significantly re-written by mike@macgirvin.com for Friendica
* (namespaces, lowercase tags, get_attribute default changed, more...) * (namespaces, lowercase tags, get_attribute default changed, more...)
* *
* Examples: $array = xml::to_array(file_get_contents('feed.xml')); * Examples: $array = Xml::to_array(file_get_contents('feed.xml'));
* $array = xml::to_array(file_get_contents('feed.xml', true, 1, 'attribute')); * $array = Xml::to_array(file_get_contents('feed.xml', true, 1, 'attribute'));
* *
* @param object $contents The XML text * @param object $contents The XML text
* @param boolean $namespaces True or false include namespace information * @param boolean $namespaces True or false include namespace information
@ -233,13 +235,14 @@ class xml {
* *
* @return array The parsed XML in an array form. Use print_r() to see the resulting array structure. * @return array The parsed XML in an array form. Use print_r() to see the resulting array structure.
*/ */
public static function to_array($contents, $namespaces = true, $get_attributes = 1, $priority = 'attribute') { public static function to_array($contents, $namespaces = true, $get_attributes = 1, $priority = 'attribute')
{
if (!$contents) { if (!$contents) {
return array(); return array();
} }
if (!function_exists('xml_parser_create')) { if (!function_exists('xml_parser_create')) {
logger('xml::to_array: parser function missing'); logger('Xml::to_array: parser function missing');
return array(); return array();
} }
@ -254,7 +257,7 @@ class xml {
} }
if (! $parser) { if (! $parser) {
logger('xml::to_array: xml_parser_create: no resource'); logger('Xml::to_array: xml_parser_create: no resource');
return array(); return array();
} }
@ -266,7 +269,7 @@ class xml {
@xml_parser_free($parser); @xml_parser_free($parser);
if (! $xml_values) { if (! $xml_values) {
logger('xml::to_array: libxml: parse error: ' . $contents, LOGGER_DATA); logger('Xml::to_array: libxml: parse error: ' . $contents, LOGGER_DATA);
foreach (libxml_get_errors() as $err) { foreach (libxml_get_errors() as $err) {
logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA); logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
} }
@ -331,7 +334,6 @@ class xml {
$repeated_tag_index[$tag.'_'.$level] = 1; $repeated_tag_index[$tag.'_'.$level] = 1;
$current = &$current[$tag]; $current = &$current[$tag];
} else { // There was another element with the same tag name } else { // There was another element with the same tag name
if (isset($current[$tag][0])) { // If there is a 0th element it is already an array if (isset($current[$tag][0])) { // If there is a 0th element it is already an array
@ -345,12 +347,10 @@ class xml {
$current[$tag]['0_attr'] = $current[$tag.'_attr']; $current[$tag]['0_attr'] = $current[$tag.'_attr'];
unset($current[$tag.'_attr']); unset($current[$tag.'_attr']);
} }
} }
$last_item_index = $repeated_tag_index[$tag.'_'.$level]-1; $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
$current = &$current[$tag][$last_item_index]; $current = &$current[$tag][$last_item_index];
} }
} elseif ($type == "complete") { // Tags that ends in 1 line '<tag />' } elseif ($type == "complete") { // Tags that ends in 1 line '<tag />'
//See if the key is already taken. //See if the key is already taken.
if (!isset($current[$tag])) { //New Key if (!isset($current[$tag])) { //New Key
@ -359,7 +359,6 @@ class xml {
if ($priority == 'tag' and $attributes_data) { if ($priority == 'tag' and $attributes_data) {
$current[$tag. '_attr'] = $attributes_data; $current[$tag. '_attr'] = $attributes_data;
} }
} else { // If taken, put all things inside a list(array) } else { // If taken, put all things inside a list(array)
if (isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array... if (isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
@ -370,7 +369,6 @@ class xml {
$current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data; $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
} }
$repeated_tag_index[$tag.'_'.$level]++; $repeated_tag_index[$tag.'_'.$level]++;
} else { // If it is not an array... } else { // If it is not an array...
$current[$tag] = array($current[$tag], $result); //...Make it an array using using the existing value and the new value $current[$tag] = array($current[$tag], $result); //...Make it an array using using the existing value and the new value
$repeated_tag_index[$tag.'_'.$level] = 1; $repeated_tag_index[$tag.'_'.$level] = 1;
@ -388,7 +386,6 @@ class xml {
$repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
} }
} }
} elseif ($type == 'close') { // End of tag '</tag>' } elseif ($type == 'close') { // End of tag '</tag>'
$current = &$parent[$level-1]; $current = &$parent[$level-1];
} }
@ -403,7 +400,8 @@ class xml {
* @param object $doc XML document * @param object $doc XML document
* @param string $node Node name * @param string $node Node name
*/ */
public static function deleteNode(&$doc, $node) { public static function deleteNode(&$doc, $node)
{
$xpath = new DomXPath($doc); $xpath = new DomXPath($doc);
$list = $xpath->query("//".$node); $list = $xpath->query("//".$node);
foreach ($list as $child) { foreach ($list as $child) {