Merge remote-tracking branch 'upstream/develop' into community

This commit is contained in:
Michael 2018-01-03 01:15:27 +00:00
commit 6925299e5a
65 changed files with 3063 additions and 4000 deletions

View file

@ -1,8 +1,8 @@
<?php
/**
* @file include/api.php
* Friendica implementation of statusnet/twitter API
*
* @file include/api.php
* @todo Automatically detect if incoming data is HTML or BBCode
*/
use Friendica\App;
@ -55,11 +55,11 @@ $API = array();
$called_api = null;
/**
* @brief Auth API user
*
* It is not sufficient to use local_user() to check whether someone is allowed to use the API,
* 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).
*
* @brief Auth API user
*/
function api_user()
{
@ -71,13 +71,13 @@ function api_user()
}
/**
* @brief Get source name from API client
*
* Clients can send 'source' parameter to be show in post metadata
* as "sent via <source>".
* Some clients doesn't send a source param, we support ones we know
* (only Twidere, atm)
*
* @brief Get source name from API client
*
* @return string
* Client source name, default to "api" if unset/unknown
*/
@ -110,9 +110,9 @@ function api_date($str)
}
/**
* @brief Register API endpoint
* Register a function to be the endpoint for defined API path.
*
* Register a function to be the endpont for defined API path.
* @brief Register API endpoint
*
* @param string $path API URL path, relative to System::baseUrl()
* @param string $func Function name to call on path request
@ -142,11 +142,11 @@ function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY
}
/**
* @brief Login API user
*
* Log in user via OAuth1 or Simple HTTP Auth.
* Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
*
* @brief Login API user
*
* @param object $a App
* @hook 'authenticate'
* array $addon_auth
@ -186,7 +186,7 @@ function api_login(App $a)
}
if (!x($_SERVER, 'PHP_AUTH_USER')) {
logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
logger('API_login: ' . print_r($_SERVER, true), LOGGER_DEBUG);
header('WWW-Authenticate: Basic realm="Friendica"');
throw new UnauthorizedException("This API requires login");
}
@ -217,7 +217,7 @@ function api_login(App $a)
*/
call_hooks('authenticate', $addon_auth);
if (($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
$record = $addon_auth['user_record'];
} else {
$user_id = User::authenticate(trim($user), trim($password));
@ -226,7 +226,7 @@ function api_login(App $a)
}
}
if ((! $record) || (! count($record))) {
if (!$record || !count($record)) {
logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
header('WWW-Authenticate: Basic realm="Friendica"');
//header('HTTP/1.0 401 Unauthorized');
@ -242,12 +242,12 @@ function api_login(App $a)
}
/**
* @brief Check HTTP method of called API
*
* API endpoints can define which HTTP method to accept when called.
* This function check the current HTTP method agains endpoint
* registered method.
*
* @brief Check HTTP method of called API
*
* @param string $method Required methods, uppercase, separated by comma
* @return bool
*/
@ -260,10 +260,10 @@ function api_check_method($method)
}
/**
* @brief Main API entry point
*
* Authenticate user, call registered API function, set HTTP headers
*
* @brief Main API entry point
*
* @param object $a App
* @return string API call result
*/
@ -367,12 +367,13 @@ function api_call(App $a)
break;
case "json":
header("Content-Type: application/json");
foreach ($r as $rr)
foreach ($r as $rr) {
$json = json_encode($rr);
if (x($_GET, 'callback')) {
$json = $_GET['callback'] . "(" . $json . ")";
}
return $json;
}
if (x($_GET, 'callback')) {
$json = $_GET['callback'] . "(" . $json . ")";
}
return $json;
break;
case "rss":
header("Content-Type: application/rss+xml");
@ -399,7 +400,7 @@ function api_call(App $a)
*
* @param string $type Return type (xml, json, rss, as)
* @param object $e HTTPException Error object
* @return strin error message formatted as $type
* @return string error message formatted as $type
*/
function api_error($type, $e)
{
@ -742,13 +743,27 @@ function api_get_user(App $a, $contact_id = null)
$pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
if (!empty($profile[0]['about'])) {
$description = $profile[0]['about'];
} else {
$description = $uinfo[0]["about"];
}
if (!empty($usr[0]['default-location'])) {
$location = $usr[0]['default-location'];
} elseif (!empty($uinfo[0]["location"])) {
$location = $uinfo[0]["location"];
} else {
$location = $network_name;
}
$ret = array(
'id' => intval($pcontact_id),
'id_str' => (string) intval($pcontact_id),
'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
'description' => (($profile) ? $profile[0]['pdesc'] : null),
'location' => $location,
'description' => $description,
'profile_image_url' => $uinfo[0]['micro'],
'profile_image_url_https' => $uinfo[0]['micro'],
'url' => $uinfo[0]['url'],
@ -946,12 +961,10 @@ function api_create_xml($data, $root_element)
* @param string $type Return type (atom, rss, xml, json)
* @param array $data JSON style array
*
* @return (string|object) XML data or JSON data
* @return (string|object|array) XML data or JSON data
*/
function api_format_data($root_element, $type, $data)
{
$a = get_app();
switch ($type) {
case "atom":
case "rss":
@ -973,7 +986,9 @@ function api_format_data($root_element, $type, $data)
/**
* Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
* returns a 401 status code and an error message if not.
* http://developer.twitter.com/doc/get/account/verify_credentials
* @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
*
* @param string $type Return type (atom, rss, xml, json)
*/
function api_account_verify_credentials($type)
{
@ -1014,11 +1029,13 @@ function api_account_verify_credentials($type)
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 somewhere better
api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
/**
* Get data from $_POST or $_GET
*
* @param string $k
*/
function requestdata($k)
{
@ -1031,7 +1048,13 @@ function requestdata($k)
return null;
}
/*Waitman Gobble Mod*/
/**
* Waitman Gobble Mod
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
*/
function api_statuses_mediap($type)
{
$a = get_app();
@ -1075,6 +1098,14 @@ function api_statuses_mediap($type)
/// @TODO move this to top of file or somewhere better!
api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
/**
* Updates the users current status.
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
* @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
*/
function api_statuses_update($type)
{
@ -1246,10 +1277,18 @@ function api_statuses_update($type)
return api_status_show($type);
}
/// @TODO move to top of file or somwhere better
/// @TODO move to top of file or somewhere better
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);
/**
* Uploads an image to Friendica.
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array
* @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
*/
function api_media_upload($type)
{
$a = get_app();
@ -1285,9 +1324,15 @@ function api_media_upload($type)
return array("media" => $returndata);
}
/// @TODO move to top of file or somwhere better
/// @TODO move to top of file or somewhere better
api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
/**
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
*/
function api_status_show($type)
{
$a = get_app();
@ -1392,7 +1437,9 @@ function api_status_show($type)
/**
* Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
* The author's most recent status will be returned inline.
* http://developer.twitter.com/doc/get/users/show
*
* @param string $type Return type (atom, rss, xml, json)
* @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
*/
function api_users_show($type)
{
@ -1478,6 +1525,14 @@ function api_users_show($type)
api_register_func('api/users/show', 'api_users_show');
api_register_func('api/externalprofile/show', 'api_users_show');
/**
* Search a public user account.
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
* @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
*/
function api_users_search($type)
{
$a = get_app();
@ -1496,7 +1551,7 @@ function api_users_search($type)
if (DBM::is_result($r)) {
$k = 0;
foreach ($r as $user) {
$user_info = api_get_user($a, $user["id"], "json");
$user_info = api_get_user($a, $user["id"]);
if ($type == "xml") {
$userlist[$k++.":user"] = $user_info;
@ -1608,11 +1663,14 @@ api_register_func('api/search/tweets', 'api_search', true);
api_register_func('api/search', 'api_search', true);
/**
* Returns the most recent statuses posted by the user and the users they follow.
*
* http://developer.twitter.com/doc/get/statuses/home_timeline
* @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
*
* TODO: Optional parameters
* TODO: Add reply info
* @param string $type Return type (atom, rss, xml, json)
*
* @todo Optional parameters
* @todo Add reply info
*/
function api_statuses_home_timeline($type)
{
@ -1709,6 +1767,13 @@ function api_statuses_home_timeline($type)
api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
/**
* Returns the most recent statuses from public users.
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
*/
function api_statuses_public_timeline($type)
{
$a = get_app();
@ -1739,7 +1804,8 @@ function api_statuses_public_timeline($type)
$sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
}
$r = dba::p("SELECT " . item_fieldlists() . "
$r = dba::p(
"SELECT " . item_fieldlists() . "
FROM `thread`
STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
" . item_joins() . "
@ -1768,7 +1834,8 @@ function api_statuses_public_timeline($type)
$sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
}
$r = dba::p("SELECT " . item_fieldlists() . "
$r = dba::p(
"SELECT " . item_fieldlists() . "
FROM `item`
" . item_joins() . "
STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
@ -1807,6 +1874,8 @@ function api_statuses_public_timeline($type)
api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
/**
* Returns the most recent statuses posted by users this node knows about.
*
* @brief Returns the list of public federated posts this node knows about
*
* @param string $type Return format: json, xml, atom, rss
@ -1839,7 +1908,8 @@ function api_statuses_networkpublic_timeline($type)
$sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
}
$r = dba::p("SELECT " . item_fieldlists() . "
$r = dba::p(
"SELECT " . item_fieldlists() . "
FROM `thread`
STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
" . item_joins() . "
@ -1876,7 +1946,11 @@ function api_statuses_networkpublic_timeline($type)
api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
/**
* @TODO nothing to say?
* Returns a single status.
*
* @param string $type Return type (atom, rss, xml, json)
*
* @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
*/
function api_statuses_show($type)
{
@ -1947,7 +2021,10 @@ function api_statuses_show($type)
api_register_func('api/statuses/show', 'api_statuses_show', true);
/**
* @TODO nothing to say?
*
* @param string $type Return type (atom, rss, xml, json)
*
* @todo nothing to say?
*/
function api_conversation_show($type)
{
@ -2011,10 +2088,12 @@ function api_conversation_show($type)
AND `item`.`uid` = %d AND `item`.`verb` = '%s'
AND `item`.`id`>%d $sql_extra
ORDER BY `item`.`id` DESC LIMIT %d ,%d",
intval($id), intval(api_user()),
intval($id),
intval(api_user()),
dbesc(ACTIVITY_POST),
intval($since_id),
intval($start), intval($count)
intval($start),
intval($count)
);
if (!DBM::is_result($r)) {
@ -2032,7 +2111,11 @@ api_register_func('api/conversation/show', 'api_conversation_show', true);
api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
/**
* @TODO nothing to say?
* Repeats a status.
*
* @param string $type Return type (atom, rss, xml, json)
*
* @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
*/
function api_statuses_repeat($type)
{
@ -2110,7 +2193,11 @@ function api_statuses_repeat($type)
api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
/**
* @TODO nothing to say?
* Destroys a specific status.
*
* @param string $type Return type (atom, rss, xml, json)
*
* @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
*/
function api_statuses_destroy($type)
{
@ -2147,8 +2234,11 @@ function api_statuses_destroy($type)
api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
/**
* @TODO Nothing more than an URL to say?
* http://developer.twitter.com/doc/get/statuses/mentions
* Returns the most recent mentions.
*
* @param string $type Return type (atom, rss, xml, json)
*
* @see http://developer.twitter.com/doc/get/statuses/mentions
*/
function api_statuses_mentions($type)
{
@ -2234,11 +2324,14 @@ api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
/**
* Returns the most recent statuses posted by the user.
*
* @brief Returns a user's public timeline
*
* @param string $type Either "json" or "xml"
* @return string|array
* @throws ForbiddenException
* @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
*/
function api_statuses_user_timeline($type)
{
@ -2322,14 +2415,16 @@ function api_statuses_user_timeline($type)
return api_format_data("statuses", $type, $data);
}
/// @TODO move to top of file or somwhere better
api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
/// @TODO move to top of file or somewhere better
api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
/**
* Star/unstar an item
* Star/unstar an item.
* param: id : id of the item
*
* api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
* @param string $type Return type (atom, rss, xml, json)
*
* @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
*/
function api_favorites_create_destroy($type)
{
@ -2374,7 +2469,7 @@ function api_favorites_create_destroy($type)
throw new BadRequestException("Invalid action ".$action);
}
$r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
$r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
@ -2397,10 +2492,17 @@ function api_favorites_create_destroy($type)
return api_format_data("status", $type, $data);
}
/// @TODO move to top of file or somwhere better
/// @TODO move to top of file or somewhere better
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);
/**
* Returns the most recent favorite statuses.
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return string|array
*/
function api_favorites($type)
{
global $called_api;
@ -2472,9 +2574,17 @@ function api_favorites($type)
return api_format_data("statuses", $type, $data);
}
/// @TODO move to top of file or somwhere better
/// @TODO move to top of file or somewhere better
api_register_func('api/favorites', 'api_favorites', true);
/**
*
* @param array $item
* @param array $recipient
* @param array $sender
*
* @return array
*/
function api_format_messages($item, $recipient, $sender)
{
// standard meta information
@ -2519,6 +2629,12 @@ function api_format_messages($item, $recipient, $sender)
return $ret;
}
/**
*
* @param array $item
*
* @return array
*/
function api_convert_item($item)
{
$body = $item['body'];
@ -2588,6 +2704,12 @@ function api_convert_item($item)
);
}
/**
*
* @param string $body
*
* @return array|false
*/
function api_get_attachments(&$body)
{
$text = $body;
@ -2619,13 +2741,16 @@ function api_get_attachments(&$body)
return $attachments;
}
/**
*
* @param string $text
* @param string $bbcode
*
* @return array
* @todo Links at the first character of the post
*/
function api_get_entitities(&$text, $bbcode)
{
/*
To-Do:
* Links at the first character of the post
*/
$a = get_app();
$include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
@ -2694,14 +2819,15 @@ function api_get_entitities(&$text, $bbcode)
foreach ($ordered_urls as $url) {
if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
&& !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
)
) {
$display_url = $url["title"];
else {
} else {
$display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
$display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
if (strlen($display_url) > 26)
if (strlen($display_url) > 26) {
$display_url = substr($display_url, 0, 25)."";
}
}
//$start = strpos($text, $url, $offset);
@ -2720,8 +2846,9 @@ function api_get_entitities(&$text, $bbcode)
foreach ($images[1] as $image) {
//$start = strpos($text, $url, $offset);
$start = iconv_strpos($text, $image, 0, "UTF-8");
if (!($start === false))
if (!($start === false)) {
$ordered_images[$start] = $image;
}
}
//$entities["media"] = array();
$offset = 0;
@ -2730,8 +2857,9 @@ function api_get_entitities(&$text, $bbcode)
$display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
$display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
if (strlen($display_url) > 26)
if (strlen($display_url) > 26) {
$display_url = substr($display_url, 0, 25)."";
}
$start = iconv_strpos($text, $url, $offset, "UTF-8");
if (!($start === false)) {
@ -2781,6 +2909,14 @@ function api_get_entitities(&$text, $bbcode)
return $entities;
}
/**
*
* @param array $item
* @param string $text
*
* @return string
*/
function api_format_items_embeded_images(&$item, $text)
{
$text = preg_replace_callback(
@ -2799,7 +2935,7 @@ function api_format_items_embeded_images(&$item, $text)
*
* @param string $txt text
* @return array
* name => 'name'
* 'name' => 'name',
* 'url => 'url'
*/
function api_contactlink_to_array($txt)
@ -2825,8 +2961,10 @@ function api_contactlink_to_array($txt)
* @brief return likes, dislikes and attend status for item
*
* @param array $item array
* @param string $type Return type (atom, rss, xml, json)
*
* @return array
* likes => int count
* likes => int count,
* dislikes => int count
*/
function api_format_items_activities(&$item, $type = "json")
@ -2882,8 +3020,9 @@ function api_format_items_activities(&$item, $type = "json")
$xml_activities["friendica:".$k] = $v;
// add user data into xml output
$k_user = 0;
foreach ($v as $user)
foreach ($v as $user) {
$xml_activities["friendica:".$k][$k_user++.":user"] = $user;
}
}
$activities = $xml_activities;
}
@ -2948,9 +3087,10 @@ function api_format_items_profiles(&$profile = null, $type = "json")
/**
* @brief format items to be returned by api
*
* @param array $r array of items
* @param array $user_info
* @param bool $filter_user filter items by $user_info
* @param array $r array of items
* @param array $user_info
* @param bool $filter_user filter items by $user_info
* @param string $type Return type (atom, rss, xml, json)
*/
function api_format_items($r, $user_info, $filter_user = false, $type = "json")
{
@ -3051,12 +3191,13 @@ function api_format_items($r, $user_info, $filter_user = false, $type = "json")
if ($item["coord"] != "") {
$coords = explode(' ', $item["coord"]);
if (count($coords) == 2) {
if ($type == "json")
if ($type == "json") {
$status["geo"] = array('type' => 'Point',
'coordinates' => array((float) $coords[0],
(float) $coords[1]));
else // Not sure if this is the official format - if someone founds a documentation we can check
} else {// Not sure if this is the official format - if someone founds a documentation we can check
$status["georss:point"] = $item["coord"];
}
}
}
$ret[] = $status;
@ -3064,6 +3205,13 @@ function api_format_items($r, $user_info, $filter_user = false, $type = "json")
return $ret;
}
/**
* Returns the remaining number of API requests available to the user before the API limit is reached.
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
*/
function api_account_rate_limit_status($type)
{
if ($type == "xml") {
@ -3089,9 +3237,16 @@ function api_account_rate_limit_status($type)
return api_format_data('hash', $type, array('hash' => $hash));
}
/// @TODO move to top of file or somwhere better
/// @TODO move to top of file or somewhere better
api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
/**
* Returns the string "ok" in the requested format with a 200 OK HTTP status code.
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
*/
function api_help_test($type)
{
if ($type == 'xml') {
@ -3103,9 +3258,15 @@ function api_help_test($type)
return api_format_data('ok', $type, array("ok" => $ok));
}
/// @TODO move to top of file or somwhere better
/// @TODO move to top of file or somewhere better
api_register_func('api/help/test', 'api_help_test', false);
/**
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
*/
function api_lists($type)
{
$ret = array();
@ -3113,9 +3274,17 @@ function api_lists($type)
return api_format_data('lists', $type, array("lists_list" => $ret));
}
/// @TODO move to top of file or somwhere better
/// @TODO move to top of file or somewhere better
api_register_func('api/lists', 'api_lists', true);
/**
* Returns all lists the user subscribes to.
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
* @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
*/
function api_lists_list($type)
{
$ret = array();
@ -3123,15 +3292,15 @@ function api_lists_list($type)
return api_format_data('lists', $type, array("lists_list" => $ret));
}
/// @TODO move to top of file or somwhere better
/// @TODO move to top of file or somewhere better
api_register_func('api/lists/list', 'api_lists_list', true);
/**
* @brief Returns either the friends of the follower list
*
* Note: Considers friends and followers lists to be private and won't return
* Considers friends and followers lists to be private and won't return
* anything if any user_id parameter is passed.
*
* @brief Returns either the friends of the follower list
*
* @param string $qtype Either "friends" or "followers"
* @return boolean|array
* @throws ForbiddenException
@ -3165,10 +3334,10 @@ function api_statuses_f($qtype)
return false;
}
$sql_extra = '';
if ($qtype == 'friends') {
$sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
}
if ($qtype == 'followers') {
} elseif ($qtype == 'followers') {
$sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
}
@ -3216,6 +3385,8 @@ function api_statuses_f($qtype)
/**
* Returns the user's friends.
*
* @brief Returns the list of friends of the provided user
*
* @deprecated By Twitter API in favor of friends/list
@ -3233,7 +3404,9 @@ function api_statuses_friends($type)
}
/**
* @brief Returns the list of friends of the provided user
* Returns the user's followers.
*
* @brief Returns the list of followers of the provided user
*
* @deprecated By Twitter API in favor of friends/list
*
@ -3301,6 +3474,13 @@ function api_friendships_incoming($type)
/// @TODO move to top of file or somewhere better
api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
/**
* Returns the instance's configuration information.
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
*/
function api_statusnet_config($type)
{
$a = get_app();
@ -3313,7 +3493,7 @@ function api_statusnet_config($type)
$private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
$textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
if ($a->config['api_import_size']) {
$texlimit = string($a->config['api_import_size']);
$textlimit = (string) $a->config['api_import_size'];
}
$ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
$sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
@ -3340,6 +3520,12 @@ function api_statusnet_config($type)
api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
api_register_func('api/statusnet/config', 'api_statusnet_config', false);
/**
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
*/
function api_statusnet_version($type)
{
// liar
@ -3353,9 +3539,13 @@ api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
api_register_func('api/statusnet/version', 'api_statusnet_version', false);
/**
*
* @param string $type Return type (atom, rss, xml, json)
* @param string $qtype
*
* @todo use api_format_data() to return data
*/
function api_ff_ids($type,$qtype)
function api_ff_ids($type, $qtype)
{
$a = get_app();
@ -3365,17 +3555,6 @@ function api_ff_ids($type,$qtype)
$user_info = api_get_user($a);
if ($qtype == 'friends') {
$sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
}
if ($qtype == 'followers') {
$sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
}
if (!$user_info["self"]) {
$sql_extra = " AND false ";
}
$stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
$r = q(
@ -3401,11 +3580,27 @@ function api_ff_ids($type,$qtype)
return api_format_data("ids", $type, array('id' => $ids));
}
/**
* Returns the ID of every user the user is following.
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
* @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
*/
function api_friends_ids($type)
{
return api_ff_ids($type, 'friends');
}
/**
* Returns the ID of every user following the user.
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
* @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
*/
function api_followers_ids($type)
{
return api_ff_ids($type, 'followers');
@ -3415,14 +3610,26 @@ function api_followers_ids($type)
api_register_func('api/friends/ids', 'api_friends_ids', true);
api_register_func('api/followers/ids', 'api_followers_ids', true);
/**
* Sends a new direct message.
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
* @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
*/
function api_direct_messages_new($type)
{
$a = get_app();
if (api_user() === false) throw new ForbiddenException();
if (api_user() === false) {
throw new ForbiddenException();
}
if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) return;
if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) {
return;
}
$sender = api_get_user($a);
@ -3477,17 +3684,19 @@ function api_direct_messages_new($type)
}
return api_format_data("direct-messages", $type, $data);
}
/// @TODO move to top of file or somewhere better
api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
/**
* Destroys a direct message.
*
* @brief delete a direct_message from mail table through api
*
* @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
* @return string
* @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
*/
function api_direct_messages_destroy($type)
{
@ -3556,12 +3765,19 @@ function api_direct_messages_destroy($type)
}
}
/// @todo return JSON data like Twitter API not yet implemented
}
/// @TODO move to top of file or somewhere better
api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
/**
*
* @param string $type Return type (atom, rss, xml, json)
* @param string $box
* @param string $verbose
*
* @return array|string
*/
function api_direct_messages_box($type, $box, $verbose)
{
$a = get_app();
@ -3653,24 +3869,52 @@ function api_direct_messages_box($type, $box, $verbose)
return api_format_data("direct-messages", $type, $data);
}
/**
* Returns the most recent direct messages sent by the user.
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
* @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
*/
function api_direct_messages_sentbox($type)
{
$verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
return api_direct_messages_box($type, "sentbox", $verbose);
}
/**
* Returns the most recent direct messages sent to the user.
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
* @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
*/
function api_direct_messages_inbox($type)
{
$verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
return api_direct_messages_box($type, "inbox", $verbose);
}
/**
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
*/
function api_direct_messages_all($type)
{
$verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
return api_direct_messages_box($type, "all", $verbose);
}
/**
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
*/
function api_direct_messages_conversation($type)
{
$verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
@ -3683,6 +3927,12 @@ api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
/**
* Returns an OAuth Request Token.
*
* @param string $type Return type (atom, rss, xml, json)
* @see https://oauth.net/core/1.0/#auth_step1
*/
function api_oauth_request_token($type)
{
$oauth1 = new FKOAuth1();
@ -3696,6 +3946,14 @@ function api_oauth_request_token($type)
killme();
}
/**
* Returns an OAuth Access Token.
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
* @see https://oauth.net/core/1.0/#auth_step3
*/
function api_oauth_access_token($type)
{
$oauth1 = new FKOAuth1();
@ -3738,8 +3996,9 @@ function api_fr_photoalbum_delete($type)
intval(api_user()),
dbesc($album)
);
if (!DBM::is_result($r))
if (!DBM::is_result($r)) {
throw new BadRequestException("album not available");
}
// 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
@ -4070,7 +4329,7 @@ function api_fr_photo_delete($type)
* @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
*
* @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
* @return string
* @return string|array
*/
function api_fr_photo_detail($type)
{
@ -4092,10 +4351,14 @@ function api_fr_photo_detail($type)
/**
* Updates the users profile image.
*
* @brief updates the profile image for the user (either a specified profile or the default profile)
*
* @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
*
* @return string
* @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
*/
function api_account_update_profile_image($type)
{
@ -4209,7 +4472,47 @@ api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API
api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
/**
* Update user profile
*
* @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
*
* @return array|string
*/
function api_account_update_profile($type)
{
$local_user = api_user();
$api_user = api_get_user(get_app());
if (!empty($_POST['name'])) {
dba::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
dba::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
dba::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
dba::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
}
if (isset($_POST['description'])) {
dba::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
dba::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
dba::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
}
Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
// Update global directory in background
if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
}
return api_account_verify_credentials($type);
}
/// @TODO move to top of file or somewhere better
api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
/**
*
* @param string $acl_string
*/
function check_acl_input($acl_string)
{
if ($acl_string == null || $acl_string == " ") {
@ -4235,6 +4538,21 @@ function check_acl_input($acl_string)
return $contact_not_found;
}
/**
*
* @param string $mediatype
* @param array $media
* @param string $type
* @param string $album
* @param string $allow_cid
* @param string $deny_cid
* @param string $allow_gid
* @param string $deny_gid
* @param string $desc
* @param integer $profile
* @param boolean $visibility
* @param string $photo_id
*/
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;
@ -4275,7 +4593,8 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $
}
logger(
"File upload src: " . $src . " - filename: " . $filename .
" - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG
" - size: " . $filesize . " - type: " . $filetype,
LOGGER_DEBUG
);
// check if there was a php upload error
@ -4284,7 +4603,7 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $
}
// check against max upload size within Friendica instance
$maximagesize = Config::get('system', 'maximagesize');
if (($maximagesize) && ($filesize > $maximagesize)) {
if ($maximagesize && ($filesize > $maximagesize)) {
$formattedBytes = formatBytes($maximagesize);
throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
}
@ -4382,6 +4701,16 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $
}
}
/**
*
* @param string $hash
* @param string $allow_cid
* @param string $deny_cid
* @param string $allow_gid
* @param string $deny_gid
* @param string $filetype
* @param boolean $visibility
*/
function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
{
// get data about the api authenticated user
@ -4427,6 +4756,14 @@ function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $f
item_store($arr);
}
/**
*
* @param string $type
* @param int $scale
* @param string $photo_id
*
* @return array
*/
function prepare_photo_data($type, $scale, $photo_id)
{
$scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
@ -4547,8 +4884,8 @@ function prepare_photo_data($type, $scale, $photo_id)
*/
function api_friendica_remoteauth()
{
$url = ((x($_GET, 'url')) ? $_GET['url'] : '');
$c_url = ((x($_GET, 'c_url')) ? $_GET['c_url'] : '');
$url = (x($_GET, 'url') ? $_GET['url'] : '');
$c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
if ($url === '' || $c_url === '') {
throw new BadRequestException("Wrong parameters.");
@ -4558,26 +4895,22 @@ function api_friendica_remoteauth()
// traditional DFRN
$r = q(
"SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
dbesc($c_url),
intval(api_user())
);
$r = dba::select('contact', [], ['uid' => api_user(), 'nurl' => $c_url], ['limit' => 1]);
if ((! DBM::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN)) {
if (!DBM::is_result($r) || ($r['network'] !== NETWORK_DFRN)) {
throw new BadRequestException("Unknown contact");
}
$cid = $r[0]['id'];
$cid = $r['id'];
$dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
$dfrn_id = $orig_id = (($r['issued-id']) ? $r['issued-id'] : $r['dfrn-id']);
if ($r[0]['duplex'] && $r[0]['issued-id']) {
$orig_id = $r[0]['issued-id'];
if ($r['duplex'] && $r['issued-id']) {
$orig_id = $r['issued-id'];
$dfrn_id = '1:' . $orig_id;
}
if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
$orig_id = $r[0]['dfrn-id'];
if ($r['duplex'] && $r['dfrn-id']) {
$orig_id = $r['dfrn-id'];
$dfrn_id = '0:' . $orig_id;
}
@ -4593,10 +4926,10 @@ function api_friendica_remoteauth()
intval(time() + 45)
);
logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
$dest = (($url) ? '&destination_url=' . $url : '');
logger($r['name'] . ' ' . $sec, LOGGER_DEBUG);
$dest = ($url ? '&destination_url=' . $url : '');
goaway(
$r[0]['poll'] . '?dfrn_id=' . $dfrn_id
$r['poll'] . '?dfrn_id=' . $dfrn_id
. '&dfrn_version=' . DFRN_PROTOCOL_VERSION
. '&type=profile&sec=' . $sec . $dest . $quiet
);
@ -4607,7 +4940,7 @@ api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
* @brief Return the item shared, if the item contains only the [share] tag
*
* @param array $item Sharer item
* @return array Shared item or false if not a reshare
* @return array|false Shared item or false if not a reshare
*/
function api_share_as_retweet(&$item)
{
@ -4678,8 +5011,9 @@ function api_share_as_retweet(&$item)
$posted = "";
preg_match("/posted='(.*?)'/ism", $attributes, $matches);
if ($matches[1] != "")
if ($matches[1] != "") {
$posted = $matches[1];
}
preg_match('/posted="(.*?)"/ism', $attributes, $matches);
if ($matches[1] != "") {
@ -4701,16 +5035,18 @@ function api_share_as_retweet(&$item)
$reshared_item["edited"] = $posted;
return $reshared_item;
}
/**
*
* @param string $profile
*
* @return string|false
* @todo remove trailing junk from profile url
* @todo pump.io check has to check the website
*/
function api_get_nick($profile)
{
/* To-Do:
- remove trailing junk from profile url
- pump.io check has to check the website
*/
$nick = "";
$r = q(
@ -4785,6 +5121,12 @@ function api_get_nick($profile)
return false;
}
/**
*
* @param array $item
*
* @return array
*/
function api_in_reply_to($item)
{
$in_reply_to = array();
@ -4796,9 +5138,11 @@ function api_in_reply_to($item)
$in_reply_to['screen_name'] = null;
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",
intval($item['uid']),
dbesc($item['thr-parent']));
dbesc($item['thr-parent'])
);
if (DBM::is_result($r)) {
$in_reply_to['status_id'] = intval($r[0]['id']);
@ -4808,7 +5152,8 @@ function api_in_reply_to($item)
$in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
$r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
$r = q(
"SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
WHERE `item`.`id` = %d LIMIT 1",
intval($in_reply_to['status_id'])
@ -4840,6 +5185,12 @@ function api_in_reply_to($item)
return $in_reply_to;
}
/**
*
* @param string $Text
*
* @return string
*/
function api_clean_plain_items($Text)
{
$include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
@ -4870,62 +5221,85 @@ function api_clean_attachments($body)
{
$data = get_attachment_data($body);
if (!$data)
if (!$data) {
return $body;
}
$body = "";
if (isset($data["text"]))
if (isset($data["text"])) {
$body = $data["text"];
if (($body == "") && (isset($data["title"])))
}
if (($body == "") && isset($data["title"])) {
$body = $data["title"];
if (isset($data["url"]))
}
if (isset($data["url"])) {
$body .= "\n".$data["url"];
}
$body .= $data["after"];
return $body;
}
/**
*
* @param array $contacts
*
* @return array
*/
function api_best_nickname(&$contacts)
{
$best_contact = array();
if (count($contact) == 0)
if (count($contact) == 0) {
return;
}
foreach ($contacts as $contact)
foreach ($contacts as $contact) {
if ($contact["network"] == "") {
$contact["network"] = "dfrn";
$best_contact = array($contact);
}
}
if (sizeof($best_contact) == 0)
foreach ($contacts as $contact)
if ($contact["network"] == "dfrn")
if (sizeof($best_contact) == 0) {
foreach ($contacts as $contact) {
if ($contact["network"] == "dfrn") {
$best_contact = array($contact);
}
}
}
if (sizeof($best_contact) == 0)
foreach ($contacts as $contact)
if ($contact["network"] == "dspr")
if (sizeof($best_contact) == 0) {
foreach ($contacts as $contact) {
if ($contact["network"] == "dspr") {
$best_contact = array($contact);
}
}
}
if (sizeof($best_contact) == 0)
foreach ($contacts as $contact)
if ($contact["network"] == "stat")
if (sizeof($best_contact) == 0) {
foreach ($contacts as $contact) {
if ($contact["network"] == "stat") {
$best_contact = array($contact);
}
}
}
if (sizeof($best_contact) == 0)
foreach ($contacts as $contact)
if ($contact["network"] == "pump")
if (sizeof($best_contact) == 0) {
foreach ($contacts as $contact) {
if ($contact["network"] == "pump") {
$best_contact = array($contact);
}
}
}
if (sizeof($best_contact) == 0)
foreach ($contacts as $contact)
if ($contact["network"] == "twit")
if (sizeof($best_contact) == 0) {
foreach ($contacts as $contact) {
if ($contact["network"] == "twit") {
$best_contact = array($contact);
}
}
}
if (sizeof($best_contact) == 1) {
$contacts = $best_contact;
@ -4934,12 +5308,20 @@ function api_best_nickname(&$contacts)
}
}
// 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.
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
*/
function api_friendica_group_show($type)
{
$a = get_app();
if (api_user() === false) throw new ForbiddenException();
if (api_user() === false) {
throw new ForbiddenException();
}
// params
$user_info = api_get_user($a);
@ -4954,8 +5336,9 @@ function api_friendica_group_show($type)
intval($gid)
);
// 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");
}
} else {
$r = q(
"SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
@ -4989,7 +5372,13 @@ function api_friendica_group_show($type)
api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
// delete the specified group of the user
/**
* Delete the specified group of the user.
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
*/
function api_friendica_group_delete($type)
{
$a = get_app();
@ -5045,12 +5434,20 @@ function api_friendica_group_delete($type)
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.
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
*/
function api_friendica_group_create($type)
{
$a = get_app();
if (api_user() === false) throw new ForbiddenException();
if (api_user() === false) {
throw new ForbiddenException();
}
// params
$user_info = api_get_user($a);
@ -5060,8 +5457,9 @@ function api_friendica_group_create($type)
$users = $json['user'];
// error if no name specified
if ($name == "")
if ($name == "") {
throw new BadRequestException('group name not specified');
}
// get data of the specified group name
$rname = q(
@ -5070,8 +5468,9 @@ function api_friendica_group_create($type)
dbesc($name)
);
// 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');
}
// check if specified group name is a deleted group
$rname = q(
@ -5080,8 +5479,9 @@ function api_friendica_group_create($type)
dbesc($name)
);
// error message if specified group name already exists
if (DBM::is_result($rname))
if (DBM::is_result($rname)) {
$reactivate_group = true;
}
// create group
$ret = Group::create($uid, $name);
@ -5102,9 +5502,9 @@ function api_friendica_group_create($type)
intval($cid),
intval($uid)
);
if (count($contact))
if (count($contact)) {
$result = Group::addMember($gid, $cid);
else {
} else {
$erroraddinguser = true;
$errorusers[] = $cid;
}
@ -5118,12 +5518,20 @@ function api_friendica_group_create($type)
api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
// update the specified group with the posted array of contacts
/**
* Update the specified group with the posted array of contacts.
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
*/
function api_friendica_group_update($type)
{
$a = get_app();
if (api_user() === false) throw new ForbiddenException();
if (api_user() === false) {
throw new ForbiddenException();
}
// params
$user_info = api_get_user($a);
@ -5134,12 +5542,14 @@ function api_friendica_group_update($type)
$users = $json['user'];
// error if no name specified
if ($name == "")
if ($name == "") {
throw new BadRequestException('group name not specified');
}
// error if no gid specified
if ($gid == "")
if ($gid == "") {
throw new BadRequestException('gid not specified');
}
// remove members
$members = Contact::getByGroupId($gid);
@ -5181,11 +5591,19 @@ function api_friendica_group_update($type)
api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
/**
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
*/
function api_friendica_activity($type)
{
$a = get_app();
if (api_user() === false) throw new ForbiddenException();
if (api_user() === false) {
throw new ForbiddenException();
}
$verb = strtolower($a->argv[3]);
$verb = preg_replace("|\..*$|", "", $verb);
@ -5205,7 +5623,7 @@ function api_friendica_activity($type)
}
}
/// @TODO move to top of file or somwhere better
/// @TODO move to top of file or somewhere better
api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
@ -5227,16 +5645,21 @@ function api_friendica_notification($type)
{
$a = get_app();
if (api_user() === false) throw new ForbiddenException();
if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
if (api_user() === false) {
throw new ForbiddenException();
}
if ($a->argc!==3) {
throw new BadRequestException("Invalid argument count");
}
$nm = new NotificationsManager();
$notes = $nm->getAll(array(), "+seen -date", 50);
if ($type == "xml") {
$xmlnotes = array();
foreach ($notes as $note)
foreach ($notes as $note) {
$xmlnotes[] = array("@attributes" => $note);
}
$notes = $xmlnotes;
}
@ -5245,10 +5668,10 @@ function api_friendica_notification($type)
}
/**
* @brief Set notification as seen and returns associated item (if possible)
*
* POST request with 'id' param as notification id
*
* @brief Set notification as seen and returns associated item (if possible)
*
* @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
* @return string
*/
@ -5256,14 +5679,20 @@ function api_friendica_notification_seen($type)
{
$a = get_app();
if (api_user() === false) throw new ForbiddenException();
if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
if (api_user() === false) {
throw new ForbiddenException();
}
if ($a->argc!==4) {
throw new BadRequestException("Invalid argument count");
}
$id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
$nm = new NotificationsManager();
$note = $nm->getByID($id);
if (is_null($note)) throw new BadRequestException("Invalid argument");
if (is_null($note)) {
throw new BadRequestException("Invalid argument");
}
$nm->setSeen($note);
if ($note['otype']=='item') {
@ -5285,7 +5714,7 @@ function api_friendica_notification_seen($type)
return api_format_data('result', $type, array('result' => "success"));
}
/// @TODO move to top of file or somwhere better
/// @TODO move to top of file or somewhere better
api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
@ -5343,14 +5772,14 @@ function api_friendica_direct_messages_setseen($type)
}
}
/// @TODO move to top of file or somwhere better
/// @TODO move to top of file or somewhere better
api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
/**
* @brief search for direct_messages containing a searchstring through api
*
* @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
* @return string (success: success=true if found and search_result contains found messages
* @return string (success: success=true if found and search_result contains found messages,
* success=false if nothing was found, search_result='nothing found',
* error: result=error with error message)
*/
@ -5406,7 +5835,7 @@ function api_friendica_direct_messages_search($type)
return api_format_data("direct_message_search", $type, array('$result' => $success));
}
/// @TODO move to top of file or somwhere better
/// @TODO move to top of file or somewhere better
api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
/**
@ -5514,21 +5943,21 @@ function api_saved_searches_list($type)
return api_format_data("terms", $type, array('terms' => $result));
}
/// @TODO move to top of file or somwhere better
/// @TODO move to top of file or somewhere better
api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
/*
@TODO Maybe open to implement?
To.Do:
[pagename] => api/1.1/statuses/lookup.json
[id] => 605138389168451584
[include_cards] => true
[cards_platform] => Android-12
[include_entities] => true
[include_my_retweet] => 1
[include_rts] => 1
[include_reply_count] => true
[include_descendent_reply_count] => true
[pagename] => api/1.1/statuses/lookup.json
[id] => 605138389168451584
[include_cards] => true
[cards_platform] => Android-12
[include_entities] => true
[include_my_retweet] => 1
[include_rts] => 1
[include_reply_count] => true
[include_descendent_reply_count] => true
(?)

View file

@ -7,7 +7,6 @@ use Friendica\Network\Probe;
use League\HTMLToMarkdown\HtmlConverter;
require_once 'include/oembed.php';
require_once 'include/event.php';
require_once 'library/markdown.php';
require_once 'include/html2bbcode.php';

View file

@ -2,13 +2,13 @@
use Friendica\App;
use Friendica\Content\Smilies;
use Friendica\Content\OEmbed;
use Friendica\Core\Cache;
use Friendica\Core\System;
use Friendica\Core\Config;
use Friendica\Model\Contact;
use Friendica\Util\Map;
require_once 'include/oembed.php';
require_once 'include/event.php';
require_once 'mod/proxy.php';
require_once 'include/plaintext.php';
@ -232,7 +232,7 @@ function tryoembed($match) {
$url = str_replace(array("http://www.youtube.com/", "http://player.vimeo.com/"),
array("https://www.youtube.com/", "https://player.vimeo.com/"), $url);
$o = oembed_fetch_url($url);
$o = OEmbed::fetchURL($url);
if (!is_object($o)) {
return $match[0];
@ -246,7 +246,7 @@ function tryoembed($match) {
return $match[0];
}
$html = oembed_format_object($o);
$html = OEmbed::formatObject($o);
return $html;
}
@ -435,60 +435,65 @@ function bb_replace_images($body, $images) {
return $newbody;
}
function bb_ShareAttributes($share, $simplehtml) {
function bb_ShareAttributes($share, $simplehtml)
{
$attributes = $share[2];
$author = "";
preg_match("/author='(.*?)'/ism", $attributes, $matches);
if ($matches[1] != "")
$author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
if (x($matches, 1)) {
$author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
}
preg_match('/author="(.*?)"/ism', $attributes, $matches);
if ($matches[1] != "")
if (x($matches, 1)) {
$author = $matches[1];
}
$profile = "";
preg_match("/profile='(.*?)'/ism", $attributes, $matches);
if ($matches[1] != "")
if (x($matches, 1)) {
$profile = $matches[1];
}
preg_match('/profile="(.*?)"/ism', $attributes, $matches);
if ($matches[1] != "")
if (x($matches, 1)) {
$profile = $matches[1];
}
$avatar = "";
preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
if ($matches[1] != "")
if (x($matches, 1)) {
$avatar = $matches[1];
}
preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
if ($matches[1] != "")
if (x($matches, 1)) {
$avatar = $matches[1];
}
$link = "";
preg_match("/link='(.*?)'/ism", $attributes, $matches);
if ($matches[1] != "")
if (x($matches, 1)) {
$link = $matches[1];
}
preg_match('/link="(.*?)"/ism', $attributes, $matches);
if ($matches[1] != "")
if (x($matches, 1)) {
$link = $matches[1];
}
$posted = "";
$itemcache = get_itemcachepath();
preg_match("/posted='(.*?)'/ism", $attributes, $matches);
if ($matches[1] != "")
if (x($matches, 1)) {
$posted = $matches[1];
}
preg_match('/posted="(.*?)"/ism', $attributes, $matches);
if ($matches[1] != "")
if (x($matches, 1)) {
$posted = $matches[1];
// relative dates only make sense when they aren't cached
if ($itemcache == "")
$reldate = (($posted) ? " " . relative_date($posted) : '');
}
// We only call this so that a previously unknown contact can be added.
// This is important for the function "get_contact_details_by_url".
@ -497,99 +502,107 @@ function bb_ShareAttributes($share, $simplehtml) {
$data = Contact::getDetailsByURL($profile);
if (isset($data["name"]) && ($data["name"] != "") && isset($data["addr"]) && ($data["addr"] != ""))
$userid_compact = $data["name"]." (".$data["addr"].")";
else
$userid_compact = GetProfileUsername($profile,$author, true);
if (x($data, "name") && x($data, "addr")) {
$userid_compact = $data["name"] . " (" . $data["addr"] . ")";
} else {
$userid_compact = GetProfileUsername($profile, $author, true);
}
if (isset($data["addr"]) && ($data["addr"] != ""))
if (x($data, "addr")) {
$userid = $data["addr"];
else
$userid = GetProfileUsername($profile,$author, false);
} else {
$userid = GetProfileUsername($profile, $author, false);
}
if (isset($data["name"]) && ($data["name"] != ""))
if (x($data, "name")) {
$author = $data["name"];
}
if (isset($data["micro"]) && ($data["micro"] != ""))
if (x($data, "micro")) {
$avatar = $data["micro"];
}
$preshare = trim($share[1]);
if ($preshare != "")
if ($preshare != "") {
$preshare .= "<br /><br />";
}
switch ($simplehtml) {
case 1:
$text = $preshare.html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8').' <a href="'.$profile.'">'.$userid."</a>: <br />»".$share[3]."«";
$text = $preshare . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8') . ' <a href="' . $profile . '">' . $userid . "</a>: <br />»" . $share[3] . "«";
break;
case 2:
$text = $preshare.html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8').' '.$userid_compact.": <br />".$share[3];
$text = $preshare . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8') . ' ' . $userid_compact . ": <br />" . $share[3];
break;
case 3: // Diaspora
$headline .= '<b>'.html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8').$userid.':</b><br />';
$headline .= '<b>' . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8') . $userid . ':</b><br />';
$text = trim($share[1]);
if ($text != "")
if ($text != "") {
$text .= "<hr />";
}
if (substr(normalise_link($link), 0, 19) != "http://twitter.com/") {
$text .= $headline.'<blockquote>'.trim($share[3])."</blockquote><br />";
$text .= $headline . '<blockquote>' . trim($share[3]) . "</blockquote><br />";
if ($link != "")
$text .= '<br /><a href="'.$link.'">[l]</a>';
} else
$text .= '<br /><a href="'.$link.'">'.$link.'</a>';
if ($link != "") {
$text .= '<br /><a href="' . $link . '">[l]</a>';
}
} else {
$text .= '<br /><a href="' . $link . '">' . $link . '</a>';
}
break;
case 4:
$headline .= '<br /><b>'.html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8');
$headline .= sprintf(t('<a href="%1$s" target="_blank">%2$s</a> %3$s'), $link, $userid, $posted);
$headline .= '<br /><b>' . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8');
$headline .= t('<a href="%1$s" target="_blank">%2$s</a> %3$s', $link, $userid, $posted);
$headline .= ":</b><br />";
$text = trim($share[1]);
if ($text != "")
if ($text != "") {
$text .= "<hr />";
}
$text .= $headline.'<blockquote class="shared_content">'.trim($share[3])."</blockquote><br />";
$text .= $headline . '<blockquote class="shared_content">' . trim($share[3]) . "</blockquote><br />";
break;
case 5:
$text = $preshare.html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8').' '.$userid_compact.": <br />".$share[3];
$text = $preshare . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8') . ' ' . $userid_compact . ": <br />" . $share[3];
break;
case 6: // app.net
$text = $preshare."&gt;&gt; @".$userid_compact.": <br />".$share[3];
$text = $preshare . "&gt;&gt; @" . $userid_compact . ": <br />" . $share[3];
break;
case 7: // statusnet/GNU Social
$text = $preshare.html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8')." @".$userid_compact.": ".$share[3];
$text = $preshare . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8') . " @" . $userid_compact . ": " . $share[3];
break;
case 8: // twitter
$text = $preshare."RT @".$userid_compact.": ".$share[3];
$text = $preshare . "RT @" . $userid_compact . ": " . $share[3];
break;
case 9: // Google+/Facebook
$text = $preshare.html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8').' '.$userid_compact.": <br />".$share[3];
$text = $preshare . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8') . ' ' . $userid_compact . ": <br />" . $share[3];
if ($link != "")
$text .= "<br /><br />".$link;
if ($link != "") {
$text .= "<br /><br />" . $link;
}
break;
default:
$text = trim($share[1])."\n";
$text = trim($share[1]) . "\n";
$avatar = proxy_url($avatar, false, PROXY_SIZE_THUMB);
$tpl = get_markup_template('shared_content.tpl');
$text .= replace_macros($tpl,
array(
'$profile' => $profile,
'$avatar' => $avatar,
'$author' => $author,
'$link' => $link,
'$posted' => $posted,
'$reldate' => $reldate,
'$content' => trim($share[3])
)
);
$text .= replace_macros($tpl, array(
'$profile' => $profile,
'$avatar' => $avatar,
'$author' => $author,
'$link' => $link,
'$posted' => $posted,
'$content' => trim($share[3])
)
);
break;
}
@ -1263,7 +1276,7 @@ function bbcode($Text, $preserve_nl = false, $tryoembed = true, $simplehtml = fa
// $Text = preg_replace("/\[youtube\](.*?)\[\/youtube\]/", '<object width="425" height="350" type="application/x-shockwave-flash" data="http://www.youtube.com/v/$1" ><param name="movie" value="http://www.youtube.com/v/$1"></param><!--[if IE]><embed src="http://www.youtube.com/v/$1" type="application/x-shockwave-flash" width="425" height="350" /><![endif]--></object>', $Text);
// oembed tag
$Text = oembed_bbcode2html($Text);
$Text = OEmbed::BBCode2HTML($Text);
// Avoid triple linefeeds through oembed
$Text = str_replace("<br style='clear:left'></span><br /><br />", "<br style='clear:left'></span><br />", $Text);

View file

@ -545,8 +545,10 @@ function conversation(App $a, $items, $mode, $update, $preview = false) {
$profile_owner = $a->profile['profile_uid'];
if (!$update) {
$tab = notags(trim($_GET['tab']));
$tab = ( $tab ? $tab : 'posts' );
$tab = 'posts';
if (x($_GET, 'tab')) {
$tab = notags(trim($_GET['tab']));
}
if ($tab === 'posts') {
/*
* This is ugly, but we can't pass the profile_uid through the session to the ajax updater,
@ -649,20 +651,10 @@ function conversation(App $a, $items, $mode, $update, $preview = false) {
$threadsid++;
$comment = '';
$owner_url = '';
$owner_name = '';
$sparkle = '';
if ($mode === 'search' || $mode === 'community') {
if (((activity_match($item['verb'], ACTIVITY_LIKE)) || (activity_match($item['verb'], ACTIVITY_DISLIKE)))
&& ($item['id'] != $item['parent']))
continue;
$nickname = $item['nickname'];
} else {
$nickname = $a->user['nickname'];
}
// prevent private email from leaking.
if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
continue;
@ -815,7 +807,6 @@ function conversation(App $a, $items, $mode, $update, $preview = false) {
'like' => '',
'dislike' => '',
'comment' => '',
//'conv' => (($preview) ? '' : array('href'=> 'display/' . $nickname . '/' . $item['id'], 'title'=> t('View in context'))),
'conv' => (($preview) ? '' : array('href'=> 'display/'.$item['guid'], 'title'=> t('View in context'))),
'previewing' => $previewing,
'wait' => t('Please wait'),
@ -1199,39 +1190,40 @@ function format_like($cnt, array $arr, $type, $id) {
return $o;
}
function status_editor(App $a, $x, $notes_cid = 0, $popup = false) {
function status_editor(App $a, $x, $notes_cid = 0, $popup = false)
{
$o = '';
$geotag = (x($x, 'allow_location') ? replace_macros(get_markup_template('jot_geotag.tpl'), array()) : '');
$geotag = x($x, 'allow_location') ? replace_macros(get_markup_template('jot_geotag.tpl'), array()) : '';
$tpl = get_markup_template('jot-header.tpl');
$a->page['htmlhead'] .= replace_macros($tpl, array(
'$newpost' => 'true',
'$baseurl' => System::baseUrl(true),
'$geotag' => $geotag,
'$nickname' => $x['nickname'],
'$ispublic' => t('Visible to <strong>everybody</strong>'),
'$linkurl' => t('Please enter a link URL:'),
'$vidurl' => t("Please enter a video link/URL:"),
'$audurl' => t("Please enter an audio link/URL:"),
'$term' => t('Tag term:'),
'$fileas' => t('Save to Folder:'),
'$newpost' => 'true',
'$baseurl' => System::baseUrl(true),
'$geotag' => $geotag,
'$nickname' => $x['nickname'],
'$ispublic' => t('Visible to <strong>everybody</strong>'),
'$linkurl' => t('Please enter a link URL:'),
'$vidurl' => t("Please enter a video link/URL:"),
'$audurl' => t("Please enter an audio link/URL:"),
'$term' => t('Tag term:'),
'$fileas' => t('Save to Folder:'),
'$whereareu' => t('Where are you right now?'),
'$delitems' => t('Delete item(s)?')
'$delitems' => t('Delete item(s)?')
));
$tpl = get_markup_template('jot-end.tpl');
$a->page['end'] .= replace_macros($tpl, array(
'$newpost' => 'true',
'$baseurl' => System::baseUrl(true),
'$geotag' => $geotag,
'$nickname' => $x['nickname'],
'$ispublic' => t('Visible to <strong>everybody</strong>'),
'$linkurl' => t('Please enter a link URL:'),
'$vidurl' => t("Please enter a video link/URL:"),
'$audurl' => t("Please enter an audio link/URL:"),
'$term' => t('Tag term:'),
'$fileas' => t('Save to Folder:'),
'$newpost' => 'true',
'$baseurl' => System::baseUrl(true),
'$geotag' => $geotag,
'$nickname' => $x['nickname'],
'$ispublic' => t('Visible to <strong>everybody</strong>'),
'$linkurl' => t('Please enter a link URL:'),
'$vidurl' => t("Please enter a video link/URL:"),
'$audurl' => t("Please enter an audio link/URL:"),
'$term' => t('Tag term:'),
'$fileas' => t('Save to Folder:'),
'$whereareu' => t('Where are you right now?')
));
@ -1264,57 +1256,56 @@ function status_editor(App $a, $x, $notes_cid = 0, $popup = false) {
$tpl = get_markup_template("jot.tpl");
$o .= replace_macros($tpl,array(
'$return_path' => $query_str,
'$action' => 'item',
'$share' => (x($x,'button') ? $x['button'] : t('Share')),
'$upload' => t('Upload photo'),
'$shortupload' => t('upload photo'),
'$attach' => t('Attach file'),
'$shortattach' => t('attach file'),
'$weblink' => t('Insert web link'),
'$return_path' => $query_str,
'$action' => 'item',
'$share' => defaults($x, 'button', t('Share')),
'$upload' => t('Upload photo'),
'$shortupload' => t('upload photo'),
'$attach' => t('Attach file'),
'$shortattach' => t('attach file'),
'$weblink' => t('Insert web link'),
'$shortweblink' => t('web link'),
'$video' => t('Insert video link'),
'$shortvideo' => t('video link'),
'$audio' => t('Insert audio link'),
'$shortaudio' => t('audio link'),
'$setloc' => t('Set your location'),
'$shortsetloc' => t('set location'),
'$noloc' => t('Clear browser location'),
'$shortnoloc' => t('clear location'),
'$title' => $x['title'],
'$video' => t('Insert video link'),
'$shortvideo' => t('video link'),
'$audio' => t('Insert audio link'),
'$shortaudio' => t('audio link'),
'$setloc' => t('Set your location'),
'$shortsetloc' => t('set location'),
'$noloc' => t('Clear browser location'),
'$shortnoloc' => t('clear location'),
'$title' => defaults($x, 'title', ''),
'$placeholdertitle' => t('Set title'),
'$category' => $x['category'],
'$placeholdercategory' => (Feature::isEnabled(local_user(), 'categories') ? t('Categories (comma-separated list)') : ''),
'$wait' => t('Please wait'),
'$permset' => t('Permission settings'),
'$category' => defaults($x, 'category', ''),
'$placeholdercategory' => Feature::isEnabled(local_user(), 'categories') ? t('Categories (comma-separated list)') : '',
'$wait' => t('Please wait'),
'$permset' => t('Permission settings'),
'$shortpermset' => t('permissions'),
'$ptyp' => (($notes_cid) ? 'note' : 'wall'),
'$content' => $x['content'],
'$post_id' => $x['post_id'],
'$baseurl' => System::baseUrl(true),
'$defloc' => $x['default_location'],
'$visitor' => $x['visitor'],
'$pvisit' => (($notes_cid) ? 'none' : $x['visitor']),
'$public' => t('Public post'),
'$jotnets' => $jotnets,
'$lockstate' => $x['lockstate'],
'$bang' => $x['bang'],
'$profile_uid' => $x['profile_uid'],
'$preview' => ((Feature::isEnabled($x['profile_uid'],'preview')) ? t('Preview') : ''),
'$jotplugins' => $jotplugins,
'$notes_cid' => $notes_cid,
'$sourceapp' => t($a->sourcename),
'$cancel' => t('Cancel'),
'$rand_num' => random_digits(12),
'$ptyp' => $notes_cid ? 'note' : 'wall',
'$content' => defaults($x, 'content', ''),
'$post_id' => defaults($x, 'post_id', ''),
'$baseurl' => System::baseUrl(true),
'$defloc' => $x['default_location'],
'$visitor' => $x['visitor'],
'$pvisit' => $notes_cid ? 'none' : $x['visitor'],
'$public' => t('Public post'),
'$lockstate' => $x['lockstate'],
'$bang' => $x['bang'],
'$profile_uid' => $x['profile_uid'],
'$preview' => Feature::isEnabled($x['profile_uid'], 'preview') ? t('Preview') : '',
'$jotplugins' => $jotplugins,
'$notes_cid' => $notes_cid,
'$sourceapp' => t($a->sourcename),
'$cancel' => t('Cancel'),
'$rand_num' => random_digits(12),
// ACL permissions box
'$acl' => $x['acl'],
'$acl_data' => $x['acl_data'],
'$group_perms' => t('Post to Groups'),
'$acl' => $x['acl'],
'$acl_data' => $x['acl_data'],
'$group_perms' => t('Post to Groups'),
'$contact_perms' => t('Post to Contacts'),
'$private' => t('Private post'),
'$is_private' => $private_post,
'$public_link' => $public_post_link,
'$private' => t('Private post'),
'$is_private' => $private_post,
'$public_link' => $public_post_link,
//jot nav tab (used in some themes)
'$message' => t('Message'),
@ -1323,7 +1314,7 @@ function status_editor(App $a, $x, $notes_cid = 0, $popup = false) {
if ($popup == true) {
$o = '<div id="jot-popup" style="display: none;">'.$o.'</div>';
$o = '<div id="jot-popup" style="display: none;">' . $o . '</div>';
}
return $o;
@ -1579,9 +1570,9 @@ function get_responses($conv_responses, $response_verbs, $ob, $item) {
$ret = array();
foreach ($response_verbs as $v) {
$ret[$v] = array();
$ret[$v]['count'] = ((x($conv_responses[$v], $item['uri'])) ? $conv_responses[$v][$item['uri']] : '');
$ret[$v]['list'] = ((x($conv_responses[$v], $item['uri'])) ? $conv_responses[$v][$item['uri'] . '-l'] : '');
$ret[$v]['self'] = ((x($conv_responses[$v], $item['uri'])) ? $conv_responses[$v][$item['uri'] . '-self'] : '0');
$ret[$v]['count'] = defaults($conv_responses[$v], $item['uri'], '');
$ret[$v]['list'] = defaults($conv_responses[$v], $item['uri'] . '-l', '');
$ret[$v]['self'] = defaults($conv_responses[$v], $item['uri'] . '-self', '0');
if (count($ret[$v]['list']) > MAX_LIKERS) {
$ret[$v]['list_part'] = array_slice($ret[$v]['list'], 0, MAX_LIKERS);
array_push($ret[$v]['list_part'], '<a href="#" data-toggle="modal" data-target="#' . $v . 'Modal-'

View file

@ -1,172 +0,0 @@
<?php
use Friendica\Core\Config;
require_once 'library/ASNValue.class.php';
require_once 'library/asn1.php';
// supported algorithms are 'sha256', 'sha1'
function rsa_sign($data, $key, $alg = 'sha256') {
openssl_sign($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
return $sig;
}
function rsa_verify($data, $sig, $key, $alg = 'sha256') {
return openssl_verify($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
}
function DerToPem($Der, $Private = false) {
//Encode:
$Der = base64_encode($Der);
//Split lines:
$lines = str_split($Der, 65);
$body = implode("\n", $lines);
//Get title:
$title = $Private ? 'RSA PRIVATE KEY' : 'PUBLIC KEY';
//Add wrapping:
$result = "-----BEGIN {$title}-----\n";
$result .= $body . "\n";
$result .= "-----END {$title}-----\n";
return $result;
}
function DerToRsa($Der) {
//Encode:
$Der = base64_encode($Der);
//Split lines:
$lines = str_split($Der, 64);
$body = implode("\n", $lines);
//Get title:
$title = 'RSA PUBLIC KEY';
//Add wrapping:
$result = "-----BEGIN {$title}-----\n";
$result .= $body . "\n";
$result .= "-----END {$title}-----\n";
return $result;
}
function pkcs8_encode($Modulus, $PublicExponent) {
//Encode key sequence
$modulus = new ASNValue(ASNValue::TAG_INTEGER);
$modulus->SetIntBuffer($Modulus);
$publicExponent = new ASNValue(ASNValue::TAG_INTEGER);
$publicExponent->SetIntBuffer($PublicExponent);
$keySequenceItems = array($modulus, $publicExponent);
$keySequence = new ASNValue(ASNValue::TAG_SEQUENCE);
$keySequence->SetSequence($keySequenceItems);
//Encode bit string
$bitStringValue = $keySequence->Encode();
$bitStringValue = chr(0x00) . $bitStringValue; //Add unused bits byte
$bitString = new ASNValue(ASNValue::TAG_BITSTRING);
$bitString->Value = $bitStringValue;
//Encode body
$bodyValue = "\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01\x05\x00" . $bitString->Encode();
$body = new ASNValue(ASNValue::TAG_SEQUENCE);
$body->Value = $bodyValue;
//Get DER encoded public key:
$PublicDER = $body->Encode();
return $PublicDER;
}
function pkcs1_encode($Modulus, $PublicExponent) {
//Encode key sequence
$modulus = new ASNValue(ASNValue::TAG_INTEGER);
$modulus->SetIntBuffer($Modulus);
$publicExponent = new ASNValue(ASNValue::TAG_INTEGER);
$publicExponent->SetIntBuffer($PublicExponent);
$keySequenceItems = array($modulus, $publicExponent);
$keySequence = new ASNValue(ASNValue::TAG_SEQUENCE);
$keySequence->SetSequence($keySequenceItems);
//Encode bit string
$bitStringValue = $keySequence->Encode();
return $bitStringValue;
}
function metopem($m, $e) {
$der = pkcs8_encode($m, $e);
$key = DerToPem($der, false);
return $key;
}
function pubrsatome($key, &$m, &$e)
{
require_once 'library/asn1.php';
$lines = explode("\n", $key);
unset($lines[0]);
unset($lines[count($lines)]);
$x = base64_decode(implode('', $lines));
$r = ASN_BASE::parseASNString($x);
$m = base64url_decode($r[0]->asnData[0]->asnData);
$e = base64url_decode($r[0]->asnData[1]->asnData);
}
function rsatopem($key) {
pubrsatome($key, $m, $e);
return metopem($m, $e);
}
function pemtorsa($key) {
pemtome($key, $m, $e);
return metorsa($m, $e);
}
function pemtome($key, &$m, &$e)
{
$lines = explode("\n", $key);
unset($lines[0]);
unset($lines[count($lines)]);
$x = base64_decode(implode('', $lines));
$r = ASN_BASE::parseASNString($x);
$m = base64url_decode($r[0]->asnData[1]->asnData[0]->asnData[0]->asnData);
$e = base64url_decode($r[0]->asnData[1]->asnData[0]->asnData[1]->asnData);
}
function metorsa($m, $e) {
$der = pkcs1_encode($m, $e);
$key = DerToRsa($der);
return $key;
}
function salmon_key($pubkey) {
pemtome($pubkey, $m, $e);
return 'RSA' . '.' . base64url_encode($m, true) . '.' . base64url_encode($e, true) ;
}
function new_keypair($bits) {
$openssl_options = array(
'digest_alg' => 'sha1',
'private_key_bits' => $bits,
'encrypt_key' => false
);
$conf = Config::get('system', 'openssl_conf_file');
if ($conf) {
$openssl_options['config'] = $conf;
}
$result = openssl_pkey_new($openssl_options);
if (empty($result)) {
logger('new_keypair: failed');
return false;
}
// Get private key
$response = array('prvkey' => '', 'pubkey' => '');
openssl_pkey_export($result, $response['prvkey']);
// Get public key
$pkey = openssl_pkey_get_details($result);
$response['pubkey'] = $pkey["key"];
return $response;
}

View file

@ -13,7 +13,7 @@ use Friendica\Util\Map;
require_once 'include/bbcode.php';
require_once 'include/datetime.php';
require_once "include/conversation.php";
require_once 'include/conversation.php';
function format_event_html($ev, $simple = false) {
if (! ((is_array($ev)) && count($ev))) {
@ -88,7 +88,7 @@ function format_event_html($ev, $simple = false) {
/**
* @brief Convert an array with event data to bbcode.
*
*
* @param array $ev Array which conains the event data.
* @return string The event as a bbcode formatted string.
*/
@ -126,7 +126,7 @@ function format_event_bbcode($ev) {
/**
* @brief Extract bbcode formatted event data from a string
* and convert it to html.
*
*
* @params: string $s The string which should be parsed for event data.
* @return string The html output.
*/
@ -143,7 +143,7 @@ function bbtovcal($s) {
/**
* @brief Extract bbcode formatted event data from a string.
*
*
* @params: string $s The string which should be parsed for event data.
* @return array The array with the event information.
*/
@ -206,10 +206,10 @@ function ev_compare($a,$b) {
/**
* @brief Delete an event from the event table.
*
*
* Note: This function does only delete the event from the event table not its
* related entry in the item table.
*
*
* @param int $event_id Event ID.
* @return void
*/
@ -224,9 +224,9 @@ function event_delete($event_id) {
/**
* @brief Store the event.
*
*
* Store the event in the event table and create an event item in the item table.
*
*
* @param array $arr Array with event data.
* @return int The event id.
*/
@ -433,7 +433,7 @@ function event_store($arr) {
/**
* @brief Create an array with translation strings used for events.
*
*
* @return array Array with translations strings.
*/
function get_event_strings() {
@ -564,7 +564,7 @@ function event_by_id($owner_uid = 0, $event_params, $sql_extra = '') {
* string 'adjust_start' =>
*
* @param string $sql_extra Additional sql conditions (e.g. permission request).
*
*
* @return array Query results.
*/
function events_by_date($owner_uid = 0, $event_params, $sql_extra = '') {
@ -626,6 +626,9 @@ function process_events($arr) {
// Show edit and drop actions only if the user is the owner of the event and the event
// is a real event (no bithdays).
$edit = null;
$copy = null;
$drop = null;
if (local_user() && local_user() == $rr['uid'] && $rr['type'] == 'event') {
$edit = ((! $rr['cid']) ? array(System::baseUrl() . '/events/event/' . $rr['id'], t('Edit event'), '', '') : null);
$copy = ((! $rr['cid']) ? array(System::baseUrl() . '/events/copy/' . $rr['id'], t('Duplicate event'), '', '') : null);
@ -768,7 +771,7 @@ function event_format_export ($events, $format = 'ical', $timezone) {
/**
* @brief Get all events for a user ID.
*
*
* The query for events is done permission sensitive.
* If the user is the owner of the calendar he/she
* will get all of his/her available events.
@ -922,7 +925,7 @@ function widget_events() {
/**
* @brief Format an item array with event data to HTML.
*
*
* @param arr $item Array with item and event data.
* @return string HTML output.
*/
@ -1013,12 +1016,12 @@ function format_event_item($item) {
/**
* @brief Format a string with map bbcode to an array with location data.
*
*
* Note: The string must only contain location data. A string with no bbcode will be
* handled as location name.
*
*
* @param string $s The string with the bbcode formatted location data.
*
*
* @return array The array with the location data.
* 'name' => The name of the location,<br>
* 'address' => The address of the location,<br>

View file

@ -1,8 +1,8 @@
<?php
/**
* @file include/identity.php
*/
use Friendica\App;
use Friendica\Content\Feature;
use Friendica\Content\ForumManager;
@ -41,21 +41,34 @@ require_once 'mod/proxy.php';
* @param string $nickname string
* @param int $profile int
* @param array $profiledata array
* @param boolean $show_connect Show connect link
*/
function profile_load(App $a, $nickname, $profile = 0, $profiledata = array())
function profile_load(App $a, $nickname, $profile = 0, $profiledata = array(), $show_connect = true)
{
$user = q(
"SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1",
dbesc($nickname)
);
if (!$user && count($user) && !count($profiledata)) {
if (!$user && !count($user) && !count($profiledata)) {
logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
notice(t('Requested account is not available.') . EOL);
$a->error = 404;
return;
}
if (!x($a->page, 'aside')) {
$a->page['aside'] = '';
}
if ($profiledata) {
$a->page['aside'] .= profile_sidebar($profiledata, true, $show_connect);
if (!DBM::is_result($user)) {
return;
}
}
$pdata = get_profiledata_by_nick($nickname, $user[0]['uid'], $profile);
if (empty($pdata) && empty($profiledata)) {
@ -72,8 +85,9 @@ function profile_load(App $a, $nickname, $profile = 0, $profiledata = array())
"SELECT `pub_keywords` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
intval($pdata['profile_uid'])
);
if ($x && count($x))
if ($x && count($x)) {
$pdata['pub_keywords'] = $x[0]['pub_keywords'];
}
}
$a->profile = $pdata;
@ -82,9 +96,9 @@ function profile_load(App $a, $nickname, $profile = 0, $profiledata = array())
$a->profile['mobile-theme'] = PConfig::get($a->profile['profile_uid'], 'system', 'mobile_theme');
$a->profile['network'] = NETWORK_DFRN;
$a->page['title'] = $a->profile['name'] . " @ " . $a->config['sitename'];
$a->page['title'] = $a->profile['name'] . ' @ ' . $a->config['sitename'];
if (!$profiledata && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
if (!$profiledata && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
$_SESSION['theme'] = $a->profile['theme'];
}
@ -96,45 +110,38 @@ function profile_load(App $a, $nickname, $profile = 0, $profiledata = array())
$a->set_template_engine(); // reset the template engine to the default in case the user's theme doesn't specify one
$theme_info_file = "view/theme/" . current_theme() . "/theme.php";
$theme_info_file = 'view/theme/' . current_theme() . '/theme.php';
if (file_exists($theme_info_file)) {
require_once $theme_info_file;
}
if (! (x($a->page, 'aside'))) {
if (!x($a->page, 'aside')) {
$a->page['aside'] = '';
}
if (local_user() && local_user() == $a->profile['uid'] && $profiledata) {
$a->page['aside'] .= replace_macros(
get_markup_template('profile_edlink.tpl'),
array(
get_markup_template('profile_edlink.tpl'), array(
'$editprofile' => t('Edit profile'),
'$profid' => $a->profile['id']
)
);
}
$block = (((Config::get('system', 'block_public')) && (! local_user()) && (! remote_user())) ? true : false);
$block = ((Config::get('system', 'block_public') && !local_user() && !remote_user()) ? true : false);
/**
* @todo
* By now, the contact block isn't shown, when a different profile is given
* But: When this profile was on the same server, then we could display the contacts
*/
if ($profiledata) {
$a->page['aside'] .= profile_sidebar($profiledata, true);
} else {
$a->page['aside'] .= profile_sidebar($a->profile, $block);
if (!$profiledata) {
$a->page['aside'] .= profile_sidebar($a->profile, $block, $show_connect);
}
/*if (! $block)
$a->page['aside'] .= contact_block();*/
return;
}
/**
* @brief Get all profil data of a local user
*
@ -143,11 +150,12 @@ function profile_load(App $a, $nickname, $profile = 0, $profiledata = array())
* Passing a non-zero profile ID can also allow a preview of a selected profile
* by the owner
*
* Includes all available profile data
*
* @param string $nickname nick
* @param int $uid uid
* @param int $profile ID of the profile
* @returns array
* Includes all available profile data
*/
function get_profiledata_by_nick($nickname, $uid = 0, $profile = 0)
{
@ -197,7 +205,6 @@ function get_profiledata_by_nick($nickname, $uid = 0, $profile = 0)
return $r;
}
/**
* @brief Formats a profile for display in the sidebar.
*
@ -206,6 +213,7 @@ function get_profiledata_by_nick($nickname, $uid = 0, $profile = 0)
*
* @param array $profile
* @param int $block
* @param boolean $show_connect Show connect link
*
* @return HTML string stuitable for sidebar inclusion
*
@ -216,35 +224,34 @@ function get_profiledata_by_nick($nickname, $uid = 0, $profile = 0)
* @hooks 'profile_sidebar'
* array $arr
*/
function profile_sidebar($profile, $block = 0)
function profile_sidebar($profile, $block = 0, $show_connect = true)
{
$a = get_app();
$o = '';
$location = false;
$address = false;
// $pdesc = true;
// This function can also use contact information in $profile
$is_contact = x($profile, 'cid');
if ((! is_array($profile)) && (! count($profile))) {
if (!is_array($profile) && !count($profile)) {
return $o;
}
$profile['picdate'] = urlencode($profile['picdate']);
$profile['picdate'] = urlencode(defaults($profile, 'picdate', ''));
if (($profile['network'] != "") && ($profile['network'] != NETWORK_DFRN)) {
if (($profile['network'] != '') && ($profile['network'] != NETWORK_DFRN)) {
$profile['network_name'] = format_network_name($profile['network'], $profile['url']);
} else {
$profile['network_name'] = "";
$profile['network_name'] = '';
}
call_hooks('profile_sidebar_enter', $profile);
// don't show connect link to yourself
$connect = (($profile['uid'] != local_user()) ? t('Connect') : false);
$connect = $profile['uid'] != local_user() ? t('Connect') : false;
// don't show connect link to authenticated visitors either
if (remote_user() && count($_SESSION['remote'])) {
@ -256,12 +263,16 @@ function profile_sidebar($profile, $block = 0)
}
}
if (!$show_connect) {
$connect = false;
}
// Is the local user already connected to that user?
if ($connect && local_user()) {
if (isset($profile["url"])) {
$profile_url = normalise_link($profile["url"]);
if (isset($profile['url'])) {
$profile_url = normalise_link($profile['url']);
} else {
$profile_url = normalise_link(System::baseUrl()."/profile/".$profile["nickname"]);
$profile_url = normalise_link(System::baseUrl() . '/profile/' . $profile['nickname']);
}
if (dba::exists('contact', array('pending' => false, 'uid' => local_user(), 'nurl' => $profile_url))) {
@ -269,21 +280,24 @@ function profile_sidebar($profile, $block = 0)
}
}
if ($connect && ($profile['network'] != NETWORK_DFRN) && !isset($profile['remoteconnect']))
if ($connect && ($profile['network'] != NETWORK_DFRN) && !isset($profile['remoteconnect'])) {
$connect = false;
}
$remoteconnect = null;
if (isset($profile['remoteconnect']))
if (isset($profile['remoteconnect'])) {
$remoteconnect = $profile['remoteconnect'];
}
if ($connect && ($profile['network'] == NETWORK_DFRN) && !isset($remoteconnect))
$subscribe_feed = t("Atom feed");
else
if ($connect && ($profile['network'] == NETWORK_DFRN) && !isset($remoteconnect)) {
$subscribe_feed = t('Atom feed');
} else {
$subscribe_feed = false;
}
if (remote_user() || (get_my_url() && $profile['unkmail'] && ($profile['uid'] != local_user()))) {
if (remote_user() || (get_my_url() && x($profile, 'unkmail') && ($profile['uid'] != local_user()))) {
$wallmessage = t('Message');
$wallmessage_link = "wallmessage/".$profile["nickname"];
$wallmessage_link = 'wallmessage/' . $profile['nickname'];
if (remote_user()) {
$r = q(
@ -301,9 +315,9 @@ function profile_sidebar($profile, $block = 0)
);
}
if ($r) {
$remote_url = $r[0]["url"];
$message_path = preg_replace("=(.*)/profile/(.*)=ism", "$1/message/new/", $remote_url);
$wallmessage_link = $message_path.base64_encode($profile["addr"]);
$remote_url = $r[0]['url'];
$message_path = preg_replace('=(.*)/profile/(.*)=ism', '$1/message/new/', $remote_url);
$wallmessage_link = $message_path . base64_encode($profile['addr']);
}
} else {
$wallmessage = false;
@ -312,7 +326,7 @@ function profile_sidebar($profile, $block = 0)
// show edit profile to yourself
if (!$is_contact && $profile['uid'] == local_user() && Feature::isEnabled(local_user(), 'multi_profiles')) {
$profile['edit'] = array(System::baseUrl(). '/profiles', t('Profiles'),"", t('Manage/edit profiles'));
$profile['edit'] = array(System::baseUrl() . '/profiles', t('Profiles'), '', t('Manage/edit profiles'));
$r = q(
"SELECT * FROM `profile` WHERE `uid` = %d",
local_user()
@ -332,14 +346,14 @@ function profile_sidebar($profile, $block = 0)
'alt' => t('Profile Image'),
'profile_name' => $rr['profile-name'],
'isdefault' => $rr['is-default'],
'visibile_to_everybody' => t('visible to everybody'),
'visibile_to_everybody' => t('visible to everybody'),
'edit_visibility' => t('Edit visibility'),
);
}
}
}
if (!$is_contact && $profile['uid'] == local_user() && !Feature::isEnabled(local_user(), 'multi_profiles')) {
$profile['edit'] = array(System::baseUrl(). '/profiles/'.$profile['id'], t('Edit profile'),"", t('Edit profile'));
$profile['edit'] = array(System::baseUrl() . '/profiles/' . $profile['id'], t('Edit profile'), '', t('Edit profile'));
$profile['menu'] = array(
'chg_photo' => t('Change profile photo'),
'cr_new' => null,
@ -350,28 +364,23 @@ function profile_sidebar($profile, $block = 0)
// Fetch the account type
$account_type = Contact::getAccountType($profile);
if ((x($profile, 'address') == 1)
|| (x($profile, 'location') == 1)
|| (x($profile, 'locality') == 1)
|| (x($profile, 'region') == 1)
|| (x($profile, 'postal-code') == 1)
|| (x($profile, 'country-name') == 1)
if (x($profile, 'address')
|| x($profile, 'location')
|| x($profile, 'locality')
|| x($profile, 'region')
|| x($profile, 'postal-code')
|| x($profile, 'country-name')
) {
$location = t('Location:');
}
$gender = ((x($profile, 'gender') == 1) ? t('Gender:') : false);
$gender = x($profile, 'gender') ? t('Gender:') : false;
$marital = x($profile, 'marital') ? t('Status:') : false;
$homepage = x($profile, 'homepage') ? t('Homepage:') : false;
$about = x($profile, 'about') ? t('About:') : false;
$xmpp = x($profile, 'xmpp') ? t('XMPP:') : false;
$marital = ((x($profile, 'marital') == 1) ? t('Status:') : false);
$homepage = ((x($profile, 'homepage') == 1) ? t('Homepage:') : false);
$about = ((x($profile, 'about') == 1) ? t('About:') : false);
$xmpp = ((x($profile, 'xmpp') == 1) ? t('XMPP:') : false);
if (($profile['hidewall'] || $block) && (! local_user()) && (! remote_user())) {
if ((x($profile, 'hidewall') || $block) && !local_user() && !remote_user()) {
$location = $pdesc = $gender = $marital = $homepage = $about = false;
}
@ -379,7 +388,7 @@ function profile_sidebar($profile, $block = 0)
$firstname = $split_name['first'];
$lastname = $split_name['last'];
if ($profile['guid'] != "") {
if (x($profile, 'guid')) {
$diaspora = array(
'guid' => $profile['guid'],
'podloc' => System::baseUrl(),
@ -396,6 +405,9 @@ function profile_sidebar($profile, $block = 0)
$diaspora = false;
}
$contact_block = '';
$updated = '';
$contacts = 0;
if (!$block) {
$contact_block = contact_block();
@ -405,7 +417,7 @@ function profile_sidebar($profile, $block = 0)
intval($a->profile['uid'])
);
if (DBM::is_result($r)) {
$updated = date("c", strtotime($r[0]['updated']));
$updated = date('c', strtotime($r[0]['updated']));
}
$r = q(
@ -431,45 +443,41 @@ function profile_sidebar($profile, $block = 0)
$p[$k] = $v;
}
if (isset($p["about"])) {
$p["about"] = bbcode($p["about"]);
if (isset($p['about'])) {
$p['about'] = bbcode($p['about']);
}
if (isset($p["address"])) {
$p["address"] = bbcode($p["address"]);
if (isset($p['address'])) {
$p['address'] = bbcode($p['address']);
} else {
$p["address"] = bbcode($p["location"]);
$p['address'] = bbcode($p['location']);
}
if (isset($p["photo"])) {
$p["photo"] = proxy_url($p["photo"], false, PROXY_SIZE_SMALL);
if (isset($p['photo'])) {
$p['photo'] = proxy_url($p['photo'], false, PROXY_SIZE_SMALL);
}
$tpl = get_markup_template('profile_vcard.tpl');
$o .= replace_macros(
$tpl,
array(
$o .= replace_macros($tpl, array(
'$profile' => $p,
'$xmpp' => $xmpp,
'$connect' => $connect,
'$remoteconnect' => $remoteconnect,
'$connect' => $connect,
'$remoteconnect' => $remoteconnect,
'$subscribe_feed' => $subscribe_feed,
'$wallmessage' => $wallmessage,
'$wallmessage_link' => $wallmessage_link,
'$account_type' => $account_type,
'$location' => $location,
'$gender' => $gender,
// '$pdesc' => $pdesc,
'$marital' => $marital,
'$gender' => $gender,
'$marital' => $marital,
'$homepage' => $homepage,
'$about' => $about,
'$network' => t('Network:'),
'$network' => t('Network:'),
'$contacts' => $contacts,
'$updated' => $updated,
'$diaspora' => $diaspora,
'$contact_block' => $contact_block,
)
);
));
$arr = array('profile' => &$profile, 'entry' => &$o);
@ -478,27 +486,26 @@ function profile_sidebar($profile, $block = 0)
return $o;
}
function get_birthdays()
{
$a = get_app();
$o = '';
if (! local_user() || $a->is_mobile || $a->is_tablet) {
if (!local_user() || $a->is_mobile || $a->is_tablet) {
return $o;
}
/*
* $mobile_detect = new Mobile_Detect();
* $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
* if ($is_mobile)
* return $o;
* if ($is_mobile)
* return $o;
*/
$bd_format = t('g A l F d'); // 8 AM Friday January 18
$bd_short = t('F d');
$cachekey = "get_birthdays:".local_user();
$cachekey = 'get_birthdays:' . local_user();
$r = Cache::get($cachekey);
if (is_null($r)) {
$s = dba::p(
@ -532,7 +539,7 @@ function get_birthdays()
$classtoday = $istoday ? ' birthday-today ' : '';
if ($total) {
foreach ($r as &$rr) {
if (! strlen($rr['name'])) {
if (!strlen($rr['name'])) {
continue;
}
@ -547,54 +554,50 @@ function get_birthdays()
$sparkle = '';
$url = $rr['url'];
if ($rr['network'] === NETWORK_DFRN) {
$sparkle = " sparkle";
$url = System::baseUrl() . '/redir/' . $rr['cid'];
$sparkle = ' sparkle';
$url = System::baseUrl() . '/redir/' . $rr['cid'];
}
$rr['link'] = $url;
$rr['title'] = $rr['name'];
$rr['date'] = day_translate(datetime_convert('UTC', $a->timezone, $rr['start'], $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . t('[today]') : '');
$rr['date'] = day_translate(datetime_convert('UTC', $a->timezone, $rr['start'], $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . t('[today]') : '');
$rr['startime'] = null;
$rr['today'] = $today;
}
}
}
$tpl = get_markup_template("birthdays_reminder.tpl");
return replace_macros(
$tpl,
array(
$tpl = get_markup_template('birthdays_reminder.tpl');
return replace_macros($tpl, array(
'$baseurl' => System::baseUrl(),
'$classtoday' => $classtoday,
'$count' => $total,
'$event_reminders' => t('Birthday Reminders'),
'$event_title' => t('Birthdays this week:'),
'$events' => $r,
'$lbr' => '{', // raw brackets mess up if/endif macro processing
'$lbr' => '{', // raw brackets mess up if/endif macro processing
'$rbr' => '}'
)
);
));
}
function get_events()
{
require_once 'include/bbcode.php';
$a = get_app();
if (! local_user() || $a->is_mobile || $a->is_tablet) {
if (!local_user() || $a->is_mobile || $a->is_tablet) {
return $o;
}
/*
* $mobile_detect = new Mobile_Detect();
* $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
* if ($is_mobile)
* return $o;
* $mobile_detect = new Mobile_Detect();
* $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
* if ($is_mobile)
* return $o;
*/
$bd_format = t('g A l F d'); // 8 AM Friday January 18
$bd_short = t('F d');
$classtoday = '';
$s = dba::p(
"SELECT `event`.* FROM `event`
@ -608,7 +611,6 @@ function get_events()
$r = array();
if (DBM::is_result($s)) {
$now = strtotime('now');
$istoday = false;
while ($rr = dba::fetch($s)) {
@ -628,7 +630,7 @@ function get_events()
}
$description = substr(strip_tags(bbcode($rr['desc'])), 0, 32) . '... ';
if (! $description) {
if (!$description) {
$description = t('[No description]');
}
@ -641,8 +643,8 @@ function get_events()
$today = ((substr($strt, 0, 10) === datetime_convert('UTC', $a->timezone, 'now', 'Y-m-d')) ? true : false);
$rr['title'] = $title;
$rr['description'] = $desciption;
$rr['date'] = day_translate(datetime_convert('UTC', $rr['adjust'] ? $a->timezone : 'UTC', $rr['start'], $bd_format)) . (($today) ? ' ' . t('[today]') : '');
$rr['description'] = $description;
$rr['date'] = day_translate(datetime_convert('UTC', $rr['adjust'] ? $a->timezone : 'UTC', $rr['start'], $bd_format)) . (($today) ? ' ' . t('[today]') : '');
$rr['startime'] = $strt;
$rr['today'] = $today;
@ -651,18 +653,15 @@ function get_events()
dba::close($s);
$classtoday = (($istoday) ? 'event-today' : '');
}
$tpl = get_markup_template("events_reminder.tpl");
return replace_macros(
$tpl,
array(
$tpl = get_markup_template('events_reminder.tpl');
return replace_macros($tpl, array(
'$baseurl' => System::baseUrl(),
'$classtoday' => $classtoday,
'$count' => count($r),
'$event_reminders' => t('Event Reminders'),
'$event_title' => t('Events this week:'),
'$events' => $r,
)
);
));
}
function advanced_profile(App $a)
@ -671,9 +670,8 @@ function advanced_profile(App $a)
$uid = $a->profile['uid'];
$o .= replace_macros(
get_markup_template('section_title.tpl'),
array(
'$title' => t('Profile')
get_markup_template('section_title.tpl'), array(
'$title' => t('Profile')
)
);
@ -682,32 +680,32 @@ function advanced_profile(App $a)
$profile = array();
$profile['fullname'] = array( t('Full Name:'), $a->profile['name'] ) ;
$profile['fullname'] = array(t('Full Name:'), $a->profile['name']);
if ($a->profile['gender']) {
$profile['gender'] = array( t('Gender:'), $a->profile['gender'] );
$profile['gender'] = array(t('Gender:'), $a->profile['gender']);
}
if (($a->profile['dob']) && ($a->profile['dob'] > '0001-01-01')) {
$year_bd_format = t('j F, Y');
$short_bd_format = t('j F');
$val = intval($a->profile['dob']) ?
day_translate(datetime_convert('UTC', 'UTC', $a->profile['dob'] . ' 00:00 +00:00', $year_bd_format))
: day_translate(datetime_convert('UTC', 'UTC', '2001-' . substr($a->profile['dob'], 5) . ' 00:00 +00:00', $short_bd_format));
$val = ((intval($a->profile['dob']))
? day_translate(datetime_convert('UTC', 'UTC', $a->profile['dob'] . ' 00:00 +00:00', $year_bd_format))
: day_translate(datetime_convert('UTC', 'UTC', '2001-' . substr($a->profile['dob'], 5) . ' 00:00 +00:00', $short_bd_format)));
$profile['birthday'] = array( t('Birthday:'), $val);
$profile['birthday'] = array(t('Birthday:'), $val);
}
if (!empty($a->profile['dob'])
&& $a->profile['dob'] > '0001-01-01'
&& $age = age($a->profile['dob'], $a->profile['timezone'], '')
) {
$profile['age'] = array( t('Age:'), $age );
$profile['age'] = array(t('Age:'), $age);
}
if ($a->profile['marital']) {
$profile['marital'] = array( t('Status:'), $a->profile['marital']);
$profile['marital'] = array(t('Status:'), $a->profile['marital']);
}
/// @TODO Maybe use x() here, plus below?
@ -720,95 +718,92 @@ function advanced_profile(App $a)
}
if ($a->profile['sexual']) {
$profile['sexual'] = array( t('Sexual Preference:'), $a->profile['sexual'] );
$profile['sexual'] = array(t('Sexual Preference:'), $a->profile['sexual']);
}
if ($a->profile['homepage']) {
$profile['homepage'] = array( t('Homepage:'), linkify($a->profile['homepage']) );
$profile['homepage'] = array(t('Homepage:'), linkify($a->profile['homepage']));
}
if ($a->profile['hometown']) {
$profile['hometown'] = array( t('Hometown:'), linkify($a->profile['hometown']) );
$profile['hometown'] = array(t('Hometown:'), linkify($a->profile['hometown']));
}
if ($a->profile['pub_keywords']) {
$profile['pub_keywords'] = array( t('Tags:'), $a->profile['pub_keywords']);
$profile['pub_keywords'] = array(t('Tags:'), $a->profile['pub_keywords']);
}
if ($a->profile['politic']) {
$profile['politic'] = array( t('Political Views:'), $a->profile['politic']);
$profile['politic'] = array(t('Political Views:'), $a->profile['politic']);
}
if ($a->profile['religion']) {
$profile['religion'] = array( t('Religion:'), $a->profile['religion']);
$profile['religion'] = array(t('Religion:'), $a->profile['religion']);
}
if ($txt = prepare_text($a->profile['about'])) {
$profile['about'] = array( t('About:'), $txt );
$profile['about'] = array(t('About:'), $txt);
}
if ($txt = prepare_text($a->profile['interest'])) {
$profile['interest'] = array( t('Hobbies/Interests:'), $txt);
$profile['interest'] = array(t('Hobbies/Interests:'), $txt);
}
if ($txt = prepare_text($a->profile['likes'])) {
$profile['likes'] = array( t('Likes:'), $txt);
$profile['likes'] = array(t('Likes:'), $txt);
}
if ($txt = prepare_text($a->profile['dislikes'])) {
$profile['dislikes'] = array( t('Dislikes:'), $txt);
$profile['dislikes'] = array(t('Dislikes:'), $txt);
}
if ($txt = prepare_text($a->profile['contact'])) {
$profile['contact'] = array( t('Contact information and Social Networks:'), $txt);
$profile['contact'] = array(t('Contact information and Social Networks:'), $txt);
}
if ($txt = prepare_text($a->profile['music'])) {
$profile['music'] = array( t('Musical interests:'), $txt);
$profile['music'] = array(t('Musical interests:'), $txt);
}
if ($txt = prepare_text($a->profile['book'])) {
$profile['book'] = array( t('Books, literature:'), $txt);
$profile['book'] = array(t('Books, literature:'), $txt);
}
if ($txt = prepare_text($a->profile['tv'])) {
$profile['tv'] = array( t('Television:'), $txt);
$profile['tv'] = array(t('Television:'), $txt);
}
if ($txt = prepare_text($a->profile['film'])) {
$profile['film'] = array( t('Film/dance/culture/entertainment:'), $txt);
$profile['film'] = array(t('Film/dance/culture/entertainment:'), $txt);
}
if ($txt = prepare_text($a->profile['romance'])) {
$profile['romance'] = array( t('Love/Romance:'), $txt);
$profile['romance'] = array(t('Love/Romance:'), $txt);
}
if ($txt = prepare_text($a->profile['work'])) {
$profile['work'] = array( t('Work/employment:'), $txt);
$profile['work'] = array(t('Work/employment:'), $txt);
}
if ($txt = prepare_text($a->profile['education'])) {
$profile['education'] = array( t('School/education:'), $txt );
$profile['education'] = array(t('School/education:'), $txt);
}
//show subcribed forum if it is enabled in the usersettings
if (Feature::isEnabled($uid, 'forumlist_profile')) {
$profile['forumlist'] = array( t('Forums:'), ForumManager::profileAdvanced($uid));
$profile['forumlist'] = array(t('Forums:'), ForumManager::profileAdvanced($uid));
}
if ($a->profile['uid'] == local_user()) {
$profile['edit'] = array(System::baseUrl(). '/profiles/'.$a->profile['id'], t('Edit profile'),"", t('Edit profile'));
$profile['edit'] = array(System::baseUrl() . '/profiles/' . $a->profile['id'], t('Edit profile'), '', t('Edit profile'));
}
return replace_macros(
$tpl,
array(
return replace_macros($tpl, array(
'$title' => t('Profile'),
'$basic' => t('Basic'),
'$advanced' => t('Advanced'),
'$profile' => $profile
)
);
));
}
return '';
@ -816,12 +811,11 @@ function advanced_profile(App $a)
function profile_tabs($a, $is_owner = false, $nickname = null)
{
//echo "<pre>"; var_dump($a->user); killme();
if (is_null($nickname)) {
$nickname = $a->user['nickname'];
$nickname = $a->user['nickname'];
}
$tab = false;
if (x($_GET, 'tab')) {
$tab = notags(trim($_GET['tab']));
}
@ -830,85 +824,85 @@ function profile_tabs($a, $is_owner = false, $nickname = null)
$tabs = array(
array(
'label'=>t('Status'),
'url' => $url,
'sel' => ((!isset($tab) && $a->argv[0]=='profile') ? 'active' : ''),
'label' => t('Status'),
'url' => $url,
'sel' => !$tab && $a->argv[0] == 'profile' ? 'active' : '',
'title' => t('Status Messages and Posts'),
'id' => 'status-tab',
'id' => 'status-tab',
'accesskey' => 'm',
),
array(
'label' => t('Profile'),
'url' => $url.'/?tab=profile',
'sel' => ((isset($tab) && $tab=='profile') ? 'active' : ''),
'url' => $url . '/?tab=profile',
'sel' => $tab == 'profile' ? 'active' : '',
'title' => t('Profile Details'),
'id' => 'profile-tab',
'id' => 'profile-tab',
'accesskey' => 'r',
),
array(
'label' => t('Photos'),
'url' => System::baseUrl() . '/photos/' . $nickname,
'sel' => ((!isset($tab) && $a->argv[0]=='photos') ? 'active' : ''),
'url' => System::baseUrl() . '/photos/' . $nickname,
'sel' => !$tab && $a->argv[0] == 'photos' ? 'active' : '',
'title' => t('Photo Albums'),
'id' => 'photo-tab',
'id' => 'photo-tab',
'accesskey' => 'h',
),
array(
'label' => t('Videos'),
'url' => System::baseUrl() . '/videos/' . $nickname,
'sel' => ((!isset($tab) && $a->argv[0]=='videos') ? 'active' : ''),
'url' => System::baseUrl() . '/videos/' . $nickname,
'sel' => !$tab && $a->argv[0] == 'videos' ? 'active' : '',
'title' => t('Videos'),
'id' => 'video-tab',
'id' => 'video-tab',
'accesskey' => 'v',
),
);
// the calendar link for the full featured events calendar
if ($is_owner && $a->theme_events_in_profile) {
$tabs[] = array(
'label' => t('Events'),
'url' => System::baseUrl() . '/events',
'sel' =>((!isset($tab) && $a->argv[0]=='events') ? 'active' : ''),
'title' => t('Events and Calendar'),
'id' => 'events-tab',
'accesskey' => 'e',
);
$tabs[] = array(
'label' => t('Events'),
'url' => System::baseUrl() . '/events',
'sel' => !$tab && $a->argv[0] == 'events' ? 'active' : '',
'title' => t('Events and Calendar'),
'id' => 'events-tab',
'accesskey' => 'e',
);
// if the user is not the owner of the calendar we only show a calendar
// with the public events of the calendar owner
} elseif (! $is_owner) {
} elseif (!$is_owner) {
$tabs[] = array(
'label' => t('Events'),
'url' => System::baseUrl() . '/cal/' . $nickname,
'sel' =>((!isset($tab) && $a->argv[0]=='cal') ? 'active' : ''),
'title' => t('Events and Calendar'),
'id' => 'events-tab',
'accesskey' => 'e',
);
'label' => t('Events'),
'url' => System::baseUrl() . '/cal/' . $nickname,
'sel' => !$tab && $a->argv[0] == 'cal' ? 'active' : '',
'title' => t('Events and Calendar'),
'id' => 'events-tab',
'accesskey' => 'e',
);
}
if ($is_owner) {
$tabs[] = array(
'label' => t('Personal Notes'),
'url' => System::baseUrl() . '/notes',
'sel' =>((!isset($tab) && $a->argv[0]=='notes') ? 'active' : ''),
'url' => System::baseUrl() . '/notes',
'sel' => !$tab && $a->argv[0] == 'notes' ? 'active' : '',
'title' => t('Only You Can See This'),
'id' => 'notes-tab',
'id' => 'notes-tab',
'accesskey' => 't',
);
}
if ((! $is_owner) && ((count($a->profile)) || (! $a->profile['hide-friends']))) {
if ((!$is_owner) && ((count($a->profile)) || (!$a->profile['hide-friends']))) {
$tabs[] = array(
'label' => t('Contacts'),
'url' => System::baseUrl() . '/viewcontacts/' . $nickname,
'sel' => ((!isset($tab) && $a->argv[0]=='viewcontacts') ? 'active' : ''),
'url' => System::baseUrl() . '/viewcontacts/' . $nickname,
'sel' => !$tab && $a->argv[0] == 'viewcontacts' ? 'active' : '',
'title' => t('Contacts'),
'id' => 'viewcontacts-tab',
'id' => 'viewcontacts-tab',
'accesskey' => 'k',
);
}
$arr = array('is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => (($tab) ? $tab : false), 'tabs' => $tabs);
$arr = array('is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => $tab, 'tabs' => $tabs);
call_hooks('profile_tabs', $arr);
$tpl = get_markup_template('common_tabs.tpl');
@ -932,9 +926,9 @@ function zrl_init(App $a)
// The check fetches the cached value from gprobe to reduce the load for this system
$urlparts = parse_url($tmp_str);
$result = Cache::get("gprobe:" . $urlparts["host"]);
if ((!is_null($result)) && (in_array($result["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
logger("DDoS attempt detected for " . $urlparts["host"] . " by " . $_SERVER["REMOTE_ADDR"] . ". server data: " . print_r($_SERVER, true), LOGGER_DEBUG);
$result = Cache::get('gprobe:' . $urlparts['host']);
if ((!is_null($result)) && (in_array($result['network'], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
logger('DDoS attempt detected for ' . $urlparts['host'] . ' by ' . $_SERVER['REMOTE_ADDR'] . '. server data: ' . print_r($_SERVER, true), LOGGER_DEBUG);
return;
}
@ -946,10 +940,10 @@ function zrl_init(App $a)
function zrl($s, $force = false)
{
if (! strlen($s)) {
if (!strlen($s)) {
return $s;
}
if ((! strpos($s, '/profile/')) && (! $force)) {
if ((!strpos($s, '/profile/')) && (!$force)) {
return $s;
}
if ($force && substr($s, -1, 1) !== '/') {
@ -957,7 +951,7 @@ function zrl($s, $force = false)
}
$achar = strpos($s, '?') ? '&' : '?';
$mine = get_my_url();
if ($mine && ! link_compare($mine, $s)) {
if ($mine && !link_compare($mine, $s)) {
return $s . $achar . 'zrl=' . urlencode($mine);
}
return $s;
@ -980,7 +974,7 @@ function zrl($s, $force = false)
function get_theme_uid()
{
$uid = ((!empty($_REQUEST['puid'])) ? intval($_REQUEST['puid']) : 0);
if ((local_user()) && ((PConfig::get(local_user(), 'system', 'always_my_theme')) || (! $uid))) {
if ((local_user()) && ((PConfig::get(local_user(), 'system', 'always_my_theme')) || (!$uid))) {
return local_user();
}

View file

@ -20,8 +20,6 @@ use Friendica\Protocol\OStatus;
use Friendica\Protocol\Feed;
require_once 'include/bbcode.php';
require_once 'include/oembed.php';
require_once 'include/crypto.php';
require_once 'include/tags.php';
require_once 'include/files.php';
require_once 'include/text.php';
@ -423,7 +421,7 @@ function uri_to_guid($uri, $host = "") {
* @return array Item array with removed conversation data
*/
function store_conversation($arr) {
if (in_array($arr['network'], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS)) && !empty($arr['uri'])) {
if (in_array(defaults($arr, 'network', NETWORK_PHANTOM), array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS)) && !empty($arr['uri'])) {
$conversation = array('item-uri' => $arr['uri'], 'received' => DBM::date());
if (isset($arr['parent-uri']) && ($arr['parent-uri'] != $arr['uri'])) {
@ -481,8 +479,8 @@ function store_conversation($arr) {
}
/// @TODO add type-hint array
function item_store($arr, $force_parent = false, $notify = false, $dontcache = false) {
function item_store($arr, $force_parent = false, $notify = false, $dontcache = false)
{
$a = get_app();
// If it is a posting where users should get notifications, then define it as wall posting
@ -504,6 +502,8 @@ function item_store($arr, $force_parent = false, $notify = false, $dontcache = f
$arr['guid'] = uri_to_guid($arr['uri'], $a->get_hostname());
}
}
} else {
$arr['network'] = trim(defaults($arr, 'network', NETWORK_PHANTOM));
}
if ($notify) {
@ -583,7 +583,7 @@ function item_store($arr, $force_parent = false, $notify = false, $dontcache = f
* We have to check several networks since Friendica posts could be repeated
* via OStatus (maybe Diasporsa as well)
*/
if (in_array(trim($arr['network']), array(NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""))) {
if (in_array($arr['network'], array(NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""))) {
$r = q("SELECT `id`, `network` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` IN ('%s', '%s', '%s') LIMIT 1",
dbesc(trim($arr['uri'])),
intval($uid),
@ -646,7 +646,6 @@ function item_store($arr, $force_parent = false, $notify = false, $dontcache = f
$arr['attach'] = ((x($arr, 'attach')) ? notags(trim($arr['attach'])) : '');
$arr['app'] = ((x($arr, 'app')) ? notags(trim($arr['app'])) : '');
$arr['origin'] = ((x($arr, 'origin')) ? intval($arr['origin']) : 0 );
$arr['network'] = ((x($arr, 'network')) ? trim($arr['network']) : '');
$arr['postopts'] = ((x($arr, 'postopts')) ? trim($arr['postopts']) : '');
$arr['resource-id'] = ((x($arr, 'resource-id')) ? trim($arr['resource-id']) : '');
$arr['event-id'] = ((x($arr, 'event-id')) ? intval($arr['event-id']) : 0 );
@ -676,18 +675,19 @@ function item_store($arr, $force_parent = false, $notify = false, $dontcache = f
$arr['plink'] = System::baseUrl() . '/display/' . urlencode($arr['guid']);
}
if ($arr['network'] == "") {
if ($arr['network'] == NETWORK_PHANTOM) {
$r = q("SELECT `network` FROM `contact` WHERE `network` IN ('%s', '%s', '%s') AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS),
dbesc(normalise_link($arr['author-link'])),
intval($arr['uid'])
);
if (!DBM::is_result($r))
if (!DBM::is_result($r)) {
$r = q("SELECT `network` FROM `gcontact` WHERE `network` IN ('%s', '%s', '%s') AND `nurl` = '%s' LIMIT 1",
dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS),
dbesc(normalise_link($arr['author-link']))
);
}
if (!DBM::is_result($r)) {
$r = q("SELECT `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
@ -735,7 +735,7 @@ function item_store($arr, $force_parent = false, $notify = false, $dontcache = f
logger("Contact-id was missing for post ".$arr["guid"]." from user id ".$uid." - now set to ".$arr["contact-id"], LOGGER_DEBUG);
}
if ($arr["gcontact-id"] == 0) {
if (!x($arr, "gcontact-id")) {
/*
* The gcontact should mostly behave like the contact. But is is supposed to be global for the system.
* This means that wall posts, repeated posts, etc. should have the gcontact id of the owner.

View file

@ -24,7 +24,7 @@ use Friendica\Protocol\Diaspora;
function do_like($item_id, $verb) {
$a = get_app();
if (! local_user() && ! remote_user()) {
if (!local_user() && !remote_user()) {
return false;
}
@ -73,28 +73,33 @@ function do_like($item_id, $verb) {
dbesc($item_id)
);
if (! $item_id || ! DBM::is_result($items)) {
if (!$item_id || !DBM::is_result($items)) {
logger('like: unknown item ' . $item_id);
return false;
}
$item = $items[0];
$uid = $item['uid'];
if (! can_write_wall($a, $item['uid'])) {
logger('like: unable to write on wall ' . $item['uid']);
if (($uid == 0) && local_user()) {
$uid = local_user();
}
if (!can_write_wall($a, $uid)) {
logger('like: unable to write on wall ' . $uid);
return false;
}
// Retrieves the local post owner
$owners = q("SELECT `contact`.* FROM `contact`
WHERE `contact`.`self` = 1
WHERE `contact`.`self`
AND `contact`.`uid` = %d",
intval($item['uid'])
intval($uid)
);
if (DBM::is_result($owners)) {
$owner_self_contact = $owners[0];
} else {
logger('like: unknown owner ' . $item['uid']);
logger('like: unknown owner ' . $uid);
return false;
}
@ -112,11 +117,11 @@ function do_like($item_id, $verb) {
}
// Contact-id is the uid-dependant author contact
if (local_user() == $item['uid']) {
if (local_user() == $uid) {
$item_contact_id = $owner_self_contact['id'];
$item_contact = $owner_self_contact;
} else {
$item_contact_id = Contact::getIdForURL($author_contact['url'], $item['uid']);
$item_contact_id = Contact::getIdForURL($author_contact['url'], $uid);
$contacts = q("SELECT * FROM `contact` WHERE `id` = %d",
intval($item_contact_id)
@ -240,9 +245,8 @@ EOT;
// @todo: Explain this block
if (! $item['visible']) {
q("UPDATE `item` SET `visible` = 1 WHERE `id` = %d AND `uid` = %d",
intval($item['id']),
intval($item['uid'])
q("UPDATE `item` SET `visible` = 1 WHERE `id` = %d",
intval($item['id'])
);
}

View file

@ -1,317 +0,0 @@
<?php
/**
* @file include/oembed.php
*/
use Friendica\App;
use Friendica\Core\Cache;
use Friendica\Core\System;
use Friendica\ParseUrl;
use Friendica\Core\Config;
use Friendica\Database\DBM;
function oembed_replacecb($matches){
$embedurl=$matches[1];
$j = oembed_fetch_url($embedurl);
$s = oembed_format_object($j);
return $s;
}
/**
* @brief Get data from an URL to embed its content.
*
* @param string $embedurl The URL from which the data should be fetched.
* @param bool $no_rich_type If set to true rich type content won't be fetched.
*
* @return bool|object Returns object with embed content or false if no embedable
* content exists
*/
function oembed_fetch_url($embedurl, $no_rich_type = false) {
$embedurl = trim($embedurl, "'");
$embedurl = trim($embedurl, '"');
$a = get_app();
$condition = array('url' => normalise_link($embedurl));
$r = dba::select('oembed', array('content'), $condition, array('limit' => 1));
if (DBM::is_result($r)) {
$txt = $r["content"];
} else {
$txt = Cache::get($a->videowidth . $embedurl);
}
// These media files should now be caught in bbcode.php
// left here as a fallback in case this is called from another source
$noexts = array("mp3", "mp4", "ogg", "ogv", "oga", "ogm", "webm");
$ext = pathinfo(strtolower($embedurl), PATHINFO_EXTENSION);
if (is_null($txt)) {
$txt = "";
if (!in_array($ext, $noexts)){
// try oembed autodiscovery
$redirects = 0;
$html_text = fetch_url($embedurl, false, $redirects, 15, "text/*");
if ($html_text) {
$dom = @DOMDocument::loadHTML($html_text);
if ($dom) {
$xpath = new DOMXPath($dom);
$attr = "oembed";
$xattr = oe_build_xpath("class","oembed");
$entries = $xpath->query("//link[@type='application/json+oembed']");
foreach ($entries as $e) {
$href = $e->getAttributeNode("href")->nodeValue;
$txt = fetch_url($href . '&maxwidth=' . $a->videowidth);
break;
}
$entries = $xpath->query("//link[@type='text/json+oembed']");
foreach ($entries as $e) {
$href = $e->getAttributeNode("href")->nodeValue;
$txt = fetch_url($href . '&maxwidth=' . $a->videowidth);
break;
}
}
}
}
$txt = trim($txt);
if ($txt[0] != "{") {
$txt = '{"type":"error"}';
} else { //save in cache
$j = json_decode($txt);
if ($j->type != "error") {
dba::insert('oembed', array('url' => normalise_link($embedurl),
'content' => $txt, 'created' => datetime_convert()), true);
}
Cache::set($a->videowidth.$embedurl, $txt, CACHE_DAY);
}
}
$j = json_decode($txt);
if (!is_object($j)) {
return false;
}
// Always embed the SSL version
if (isset($j->html)) {
$j->html = str_replace(array("http://www.youtube.com/", "http://player.vimeo.com/"),
array("https://www.youtube.com/", "https://player.vimeo.com/"), $j->html);
}
$j->embedurl = $embedurl;
// If fetching information doesn't work, then improve via internal functions
if (($j->type == "error") || ($no_rich_type && ($j->type == "rich"))) {
$data = ParseUrl::getSiteinfoCached($embedurl, true, false);
$j->type = $data["type"];
if ($j->type == "photo") {
$j->url = $data["url"];
//$j->width = $data["images"][0]["width"];
//$j->height = $data["images"][0]["height"];
}
if (isset($data["title"])) {
$j->title = $data["title"];
}
if (isset($data["text"])) {
$j->description = $data["text"];
}
if (is_array($data["images"])) {
$j->thumbnail_url = $data["images"][0]["src"];
$j->thumbnail_width = $data["images"][0]["width"];
$j->thumbnail_height = $data["images"][0]["height"];
}
}
call_hooks('oembed_fetch_url', $embedurl, $j);
return $j;
}
function oembed_format_object($j){
require_once("mod/proxy.php");
$embedurl = $j->embedurl;
$jhtml = oembed_iframe($j->embedurl,(isset($j->width) ? $j->width : null), (isset($j->height) ? $j->height : null) );
$ret="<span class='oembed ".$j->type."'>";
switch ($j->type) {
case "video":
if (isset($j->thumbnail_url)) {
$tw = (isset($j->thumbnail_width) && intval($j->thumbnail_width)) ? $j->thumbnail_width:200;
$th = (isset($j->thumbnail_height) && intval($j->thumbnail_height)) ? $j->thumbnail_height:180;
// make sure we don't attempt divide by zero, fallback is a 1:1 ratio
$tr = (($th) ? $tw/$th : 1);
$th=120; $tw = $th*$tr;
$tpl=get_markup_template('oembed_video.tpl');
$ret.=replace_macros($tpl, array(
'$baseurl' => System::baseUrl(),
'$embedurl' => $embedurl,
'$escapedhtml' => base64_encode($jhtml),
'$tw' => $tw,
'$th' => $th,
'$turl' => $j->thumbnail_url,
));
} else {
$ret=$jhtml;
}
//$ret.="<br>";
break;
case "photo":
$ret.= "<img width='".$j->width."' src='".proxy_url($j->url)."'>";
break;
case "link":
break;
case "rich":
// not so safe..
if (!Config::get("system","no_oembed_rich_content")) {
$ret.= proxy_parse_html($jhtml);
}
break;
}
// add link to source if not present in "rich" type
if ($j->type!='rich' || !strpos($j->html,$embedurl) ){
$ret .= "<h4>";
if (isset($j->title)) {
if (isset($j->provider_name)) {
$ret .= $j->provider_name.": ";
}
$embedlink = (isset($j->title))?$j->title:$embedurl;
$ret .= "<a href='$embedurl' rel='oembed'>$embedlink</a>";
if (isset($j->author_name)) {
$ret.=" (".$j->author_name.")";
}
} elseif (isset($j->provider_name) || isset($j->author_name)) {
$embedlink = "";
if (isset($j->provider_name)) {
$embedlink .= $j->provider_name;
}
if (isset($j->author_name)) {
if ($embedlink != "") {
$embedlink .= ": ";
}
$embedlink .= $j->author_name;
}
if (trim($embedlink) == "") {
$embedlink = $embedurl;
}
$ret .= "<a href='$embedurl' rel='oembed'>$embedlink</a>";
}
//if (isset($j->author_name)) $ret.=" by ".$j->author_name;
//if (isset($j->provider_name)) $ret.=" on ".$j->provider_name;
$ret .= "</h4>";
} else {
// add <a> for html2bbcode conversion
$ret .= "<a href='$embedurl' rel='oembed'>$embedurl</a>";
}
$ret.="</span>";
$ret = str_replace("\n","",$ret);
return mb_convert_encoding($ret, 'HTML-ENTITIES', mb_detect_encoding($ret));
}
/**
* @brief Generates the iframe HTML for an oembed attachment.
*
* Width and height are given by the remote, and are regularly too small for
* the generated iframe.
*
* The width is entirely discarded for the actual width of the post, while fixed
* height is used as a starting point before the inevitable resizing.
*
* Since the iframe is automatically resized on load, there are no need for ugly
* and impractical scrollbars.
*
* @param string $src Original remote URL to embed
* @param string $width
* @param string $height
* @return string formatted HTML
*
* @see oembed_format_object()
*/
function oembed_iframe($src, $width, $height) {
$a = get_app();
if (!$height || strstr($height,'%')) {
$height = '200';
}
$width = '100%';
$s = System::baseUrl() . '/oembed/' . base64url_encode($src);
return '<iframe onload="resizeIframe(this);" class="embed_rich" height="' . $height . '" width="' . $width . '" src="' . $s . '" allowfullscreen scrolling="no" frameborder="no">' . t('Embedded content') . '</iframe>';
}
function oembed_bbcode2html($text){
$stopoembed = Config::get("system","no_oembed");
if ($stopoembed == true){
return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "<!-- oembed $1 --><i>". t('Embedding disabled') ." : $1</i><!-- /oembed $1 -->" ,$text);
}
return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", 'oembed_replacecb' ,$text);
}
function oe_build_xpath($attr, $value){
// http://westhoffswelt.de/blog/0036_xpath_to_select_html_by_class.html
return "contains( normalize-space( @$attr ), ' $value ' ) or substring( normalize-space( @$attr ), 1, string-length( '$value' ) + 1 ) = '$value ' or substring( normalize-space( @$attr ), string-length( @$attr ) - string-length( '$value' ) ) = ' $value' or @$attr = '$value'";
}
function oe_get_inner_html($node) {
$innerHTML= '';
$children = $node->childNodes;
foreach ($children as $child) {
$innerHTML .= $child->ownerDocument->saveXML($child);
}
return $innerHTML;
}
/**
* Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span>
* and replace it with [embed]url[/embed]
*/
function oembed_html2bbcode($text) {
// start parser only if 'oembed' is in text
if (strpos($text, "oembed")) {
// convert non ascii chars to html entities
$html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));
// If it doesn't parse at all, just return the text.
$dom = @DOMDocument::loadHTML($html_text);
if (! $dom) {
return $text;
}
$xpath = new DOMXPath($dom);
$attr = "oembed";
$xattr = oe_build_xpath("class","oembed");
$entries = $xpath->query("//span[$xattr]");
$xattr = "@rel='oembed'";//oe_build_xpath("rel","oembed");
foreach ($entries as $e) {
$href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
if (!is_null($href)) {
$e->parentNode->replaceChild(new DOMText("[embed]".$href."[/embed]"), $e);
}
}
return oe_get_inner_html( $dom->getElementsByTagName("body")->item(0) );
} else {
return $text;
}
}

View file

@ -1,4 +1,5 @@
<?php
/**
* @file include/tags.php
*/
@ -8,11 +9,13 @@ use Friendica\Core\System;
use Friendica\Database\DBM;
use Friendica\Model\Contact;
function create_tags_from_item($itemid) {
function create_tags_from_item($itemid)
{
$profile_base = System::baseUrl();
$profile_data = parse_url($profile_base);
$profile_base_friendica = $profile_data['host'].$profile_data['path']."/profile/";
$profile_base_diaspora = $profile_data['host'].$profile_data['path']."/u/";
$profile_path = defaults($profile_data, 'path', '');
$profile_base_friendica = $profile_data['host'] . $profile_path . '/profile/';
$profile_base_diaspora = $profile_data['host'] . $profile_path . '/u/';
$messages = q("SELECT `guid`, `uid`, `id`, `edited`, `deleted`, `created`, `received`, `title`, `body`, `tag`, `parent` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
@ -28,48 +31,53 @@ function create_tags_from_item($itemid) {
intval(TERM_HASHTAG),
intval(TERM_MENTION));
if ($message["deleted"])
if ($message['deleted']) {
return;
}
$taglist = explode(",", $message["tag"]);
$taglist = explode(',', $message['tag']);
$tags = "";
foreach ($taglist as $tag)
if ((substr(trim($tag), 0, 1) == "#") || (substr(trim($tag), 0, 1) == "@"))
$tags .= " ".trim($tag);
else
$tags .= " #".trim($tag);
$tags = '';
foreach ($taglist as $tag) {
if ((substr(trim($tag), 0, 1) == '#') || (substr(trim($tag), 0, 1) == '@')) {
$tags .= ' ' . trim($tag);
} else {
$tags .= ' #' . trim($tag);
}
}
$data = " ".$message["title"]." ".$message["body"]." ".$tags." ";
$data = ' ' . $message['title'] . ' ' . $message['body'] . ' ' . $tags . ' ';
// ignore anything in a code block
$data = preg_replace('/\[code\](.*?)\[\/code\]/sm','',$data);
$data = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $data);
$tags = array();
$pattern = "/\W\#([^\[].*?)[\s'\".,:;\?!\[\]\/]/ism";
if (preg_match_all($pattern, $data, $matches))
foreach ($matches[1] as $match)
$tags["#".strtolower($match)] = "";
$pattern = "/\W([\#@])\[url\=(.*?)\](.*?)\[\/url\]/ism";
if (preg_match_all($pattern, $data, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match)
$tags[$match[1].strtolower(trim($match[3], ',.:;[]/\"?!'))] = $match[2];
$pattern = '/\W\#([^\[].*?)[\s\'".,:;\?!\[\]\/]/ism';
if (preg_match_all($pattern, $data, $matches)) {
foreach ($matches[1] as $match) {
$tags['#' . strtolower($match)] = '';
}
}
foreach ($tags as $tag=>$link) {
$pattern = '/\W([\#@])\[url\=(.*?)\](.*?)\[\/url\]/ism';
if (preg_match_all($pattern, $data, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
$tags[$match[1] . strtolower(trim($match[3], ',.:;[]/\"?!'))] = $match[2];
}
}
if (substr(trim($tag), 0, 1) == "#") {
foreach ($tags as $tag => $link) {
if (substr(trim($tag), 0, 1) == '#') {
// try to ignore #039 or #1 or anything like that
if (ctype_digit(substr(trim($tag),1)))
if (ctype_digit(substr(trim($tag), 1)))
continue;
// try to ignore html hex escapes, e.g. #x2317
if ((substr(trim($tag),1,1) == 'x' || substr(trim($tag),1,1) == 'X') && ctype_digit(substr(trim($tag),2)))
if ((substr(trim($tag), 1, 1) == 'x' || substr(trim($tag), 1, 1) == 'X') && ctype_digit(substr(trim($tag), 2)))
continue;
$type = TERM_HASHTAG;
$term = substr($tag, 1);
} elseif (substr(trim($tag), 0, 1) == "@") {
} elseif (substr(trim($tag), 0, 1) == '@') {
$type = TERM_MENTION;
$term = substr($tag, 1);
} else { // This shouldn't happen
@ -77,78 +85,78 @@ function create_tags_from_item($itemid) {
$term = $tag;
}
if ($message["uid"] == 0) {
if ($message['uid'] == 0) {
$global = true;
q("UPDATE `term` SET `global` = 1 WHERE `otype` = %d AND `guid` = '%s'",
intval(TERM_OBJ_POST), dbesc($message["guid"]));
intval(TERM_OBJ_POST), dbesc($message['guid']));
} else {
$isglobal = q("SELECT `global` FROM `term` WHERE `uid` = 0 AND `otype` = %d AND `guid` = '%s'",
intval(TERM_OBJ_POST), dbesc($message["guid"]));
intval(TERM_OBJ_POST), dbesc($message['guid']));
$global = (count($isglobal) > 0);
}
$r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `guid`, `created`, `received`, `global`)
VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s', %d)",
intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval($type), dbesc($term),
dbesc($link), dbesc($message["guid"]), dbesc($message["created"]), dbesc($message["received"]), intval($global));
intval($message['uid']), intval($itemid), intval(TERM_OBJ_POST), intval($type), dbesc($term),
dbesc($link), dbesc($message['guid']), dbesc($message['created']), dbesc($message['received']), intval($global));
// Search for mentions
if ((substr($tag, 0, 1) == '@') && (strpos($link, $profile_base_friendica) || strpos($link, $profile_base_diaspora))) {
$users = q("SELECT `uid` FROM `contact` WHERE self AND (`url` = '%s' OR `nurl` = '%s')", $link, $link);
foreach ($users AS $user) {
if ($user["uid"] == $message["uid"]) {
if ($user['uid'] == $message['uid']) {
q("UPDATE `item` SET `mention` = 1 WHERE `id` = %d", intval($itemid));
q("UPDATE `thread` SET `mention` = 1 WHERE `iid` = %d", intval($message["parent"]));
q("UPDATE `thread` SET `mention` = 1 WHERE `iid` = %d", intval($message['parent']));
}
}
}
}
}
function create_tags_from_itemuri($itemuri, $uid) {
function create_tags_from_itemuri($itemuri, $uid)
{
$messages = q("SELECT `id` FROM `item` WHERE uri ='%s' AND uid=%d", dbesc($itemuri), intval($uid));
if (count($messages)) {
foreach ($messages as $message) {
create_tags_from_item($message["id"]);
create_tags_from_item($message['id']);
}
}
}
function update_items() {
function update_items()
{
$messages = dba::p("SELECT `oid`,`item`.`guid`, `item`.`created`, `item`.`received` FROM `term` INNER JOIN `item` ON `item`.`id`=`term`.`oid` WHERE `term`.`otype` = 1 AND `term`.`guid` = ''");
logger("fetched messages: ".dba::num_rows($messages));
logger('fetched messages: ' . dba::num_rows($messages));
while ($message = dba::fetch($messages)) {
if ($message["uid"] == 0) {
if ($message['uid'] == 0) {
$global = true;
q("UPDATE `term` SET `global` = 1 WHERE `otype` = %d AND `guid` = '%s'",
intval(TERM_OBJ_POST), dbesc($message["guid"]));
intval(TERM_OBJ_POST), dbesc($message['guid']));
} else {
$isglobal = q("SELECT `global` FROM `term` WHERE `uid` = 0 AND `otype` = %d AND `guid` = '%s'",
intval(TERM_OBJ_POST), dbesc($message["guid"]));
intval(TERM_OBJ_POST), dbesc($message['guid']));
$global = (count($isglobal) > 0);
}
q("UPDATE `term` SET `guid` = '%s', `created` = '%s', `received` = '%s', `global` = %d WHERE `otype` = %d AND `oid` = %d",
dbesc($message["guid"]), dbesc($message["created"]), dbesc($message["received"]),
intval($global), intval(TERM_OBJ_POST), intval($message["oid"]));
dbesc($message['guid']), dbesc($message['created']), dbesc($message['received']),
intval($global), intval(TERM_OBJ_POST), intval($message['oid']));
}
dba::close($messages);
$messages = dba::p("SELECT `guid` FROM `item` WHERE `uid` = 0");
logger("fetched messages: ".dba::num_rows($messages));
logger('fetched messages: ' . dba::num_rows($messages));
while ($message = dba::fetch(messages)) {
q("UPDATE `item` SET `global` = 1 WHERE `guid` = '%s'", dbesc($message["guid"]));
q("UPDATE `item` SET `global` = 1 WHERE `guid` = '%s'", dbesc($message['guid']));
}
dba::close($messages);
@ -166,21 +174,22 @@ function update_items() {
*
* @return arr Alphabetical sorted array of used tags of an user.
*/
function tagadelic($uid, $count = 0, $owner_id = 0, $flags = '', $type = TERM_HASHTAG) {
require_once('include/security.php');
function tagadelic($uid, $count = 0, $owner_id = 0, $flags = '', $type = TERM_HASHTAG)
{
require_once 'include/security.php';
$item_condition = item_condition();
$sql_options = item_permissions_sql($uid);
$limit = $count ? sprintf("LIMIT %d", intval($count)) : "";
$limit = $count ? sprintf('LIMIT %d', intval($count)) : '';
if ($flags) {
if ($flags === 'wall') {
$sql_options .= " AND `item`.`wall` ";
$sql_options .= ' AND `item`.`wall` ';
}
}
if ($owner_id) {
$sql_options .= " AND `item`.`owner-id` = ".intval($owner_id)." ";
$sql_options .= ' AND `item`.`owner-id` = ' . intval($owner_id) . ' ';
}
// Fetch tags
@ -194,7 +203,7 @@ function tagadelic($uid, $count = 0, $owner_id = 0, $flags = '', $type = TERM_HA
$type,
TERM_OBJ_POST
);
if(!DBM::is_result($r)) {
if (!DBM::is_result($r)) {
return array();
}
@ -212,32 +221,32 @@ function tagadelic($uid, $count = 0, $owner_id = 0, $flags = '', $type = TERM_HA
*
* @return string HTML formatted output.
*/
function wtagblock($uid, $count = 0,$owner_id = 0, $flags = '', $type = TERM_HASHTAG) {
function wtagblock($uid, $count = 0, $owner_id = 0, $flags = '', $type = TERM_HASHTAG)
{
$o = '';
$r = tagadelic($uid, $count, $owner_id, $flags, $type);
if (count($r)) {
$contact = dba::select(
"contact",
array("url"),
array("id" => $uid),
array("limit" => 1)
'contact',
array('url'),
array('id' => $uid),
array('limit' => 1)
);
$url = System::removedBaseUrl($contact['url']);
foreach ($r as $rr) {
$tag['level'] = $rr[2];
$tag['url'] = $url."?tag=".urlencode($rr[0]);
$tag['url'] = $url . '?tag=' . urlencode($rr[0]);
$tag['name'] = $rr[0];
$tags[] = $tag;
}
$tpl = get_markup_template("tagblock_widget.tpl");
$tpl = get_markup_template('tagblock_widget.tpl');
$o = replace_macros($tpl, array(
'$title' => t('Tags'),
'$tags' => $tags
'$tags' => $tags
));
}
return $o;
}
@ -248,7 +257,8 @@ function wtagblock($uid, $count = 0,$owner_id = 0, $flags = '', $type = TERM_HAS
* @param array $arr Array of tags/terms with tag/term name and total count of use.
* @return array Alphabetical sorted array of used tags/terms of an user.
*/
function tag_calc($arr) {
function tag_calc($arr)
{
$tags = array();
$min = 1e9;
$max = -1e9;
@ -285,7 +295,8 @@ function tag_calc($arr) {
*
* @return int
*/
function tags_sort($a, $b) {
function tags_sort($a, $b)
{
if (strtolower($a[0]) == strtolower($b[0])) {
return 0;
}
@ -298,21 +309,22 @@ function tags_sort($a, $b) {
* @param int $limit Max number of displayed tags.
* @return string HTML formattat output.
*/
function tagcloud_wall_widget($limit = 50) {
function tagcloud_wall_widget($limit = 50)
{
$a = get_app();
if(!$a->profile['profile_uid'] || !$a->profile['url']) {
return "";
if (!$a->profile['profile_uid'] || !$a->profile['url']) {
return '';
}
if(Feature::isEnabled($a->profile['profile_uid'], 'tagadelic')) {
if (Feature::isEnabled($a->profile['profile_uid'], 'tagadelic')) {
$owner_id = Contact::getIdForURL($a->profile['url']);
if(!$owner_id) {
return "";
if (!$owner_id) {
return '';
}
return wtagblock($a->profile['profile_uid'], $limit, $owner_id, 'wall');
}
return "";
return '';
}

View file

@ -994,7 +994,7 @@ function contact_block() {
function micropro($contact, $redirect = false, $class = '', $textmode = false) {
// Use the contact URL if no address is available
if ($contact["addr"] == "") {
if (!x($contact, "addr")) {
$contact["addr"] = $contact["url"];
}
@ -1020,7 +1020,7 @@ function micropro($contact, $redirect = false, $class = '', $textmode = false) {
}
return replace_macros(get_markup_template(($textmode)?'micropro_txt.tpl':'micropro_img.tpl'),array(
'$click' => (($contact['click']) ? $contact['click'] : ''),
'$click' => defaults($contact, 'click', ''),
'$class' => $class,
'$url' => $url,
'$photo' => proxy_url($contact['thumb'], false, PROXY_SIZE_THUMB),
@ -1202,11 +1202,15 @@ function redir_private_images($a, &$item)
}
}
function put_item_in_cache(&$item, $update = false) {
if (($item["rendered-hash"] != hash("md5", $item["body"])) || ($item["rendered-hash"] == "") ||
($item["rendered-html"] == "") || Config::get("system", "ignore_cache")) {
function put_item_in_cache(&$item, $update = false)
{
$rendered_hash = defaults($item, 'rendered-hash', '');
if ($rendered_hash == ''
|| $item["rendered-html"] == ""
|| $rendered_hash != hash("md5", $item["body"])
|| Config::get("system", "ignore_cache")
) {
// The function "redir_private_images" changes the body.
// I'm not sure if we should store it permanently, so we save the old value.
$body = $item["body"];
@ -2026,7 +2030,7 @@ function deindent($text, $chr = "[\t ]", $count = NULL) {
}
function formatBytes($bytes, $precision = 2) {
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));