X-Git-Url: https://git.mxchange.org/?a=blobdiff_plain;f=include%2Fapi.php;h=22a6ee432133e523108ce5cce4d5899af75b2b7e;hb=8a354dac8269d788f3f8ea90732530eeacf53d98;hp=42b25a6c1be5a3d31e715505eec01d1616d9ec32;hpb=0ecef260644058728988c035cc9a8c66efa7cd17;p=friendica.git diff --git a/include/api.php b/include/api.php index 42b25a6c1b..22a6ee4321 100644 --- a/include/api.php +++ b/include/api.php @@ -24,15 +24,14 @@ */ use Friendica\App; +use Friendica\Collection\Api\Notifications as ApiNotifications; use Friendica\Content\ContactSelector; use Friendica\Content\Text\BBCode; use Friendica\Content\Text\HTML; use Friendica\Core\Hook; use Friendica\Core\Logger; use Friendica\Core\Protocol; -use Friendica\Core\Session; use Friendica\Core\System; -use Friendica\Core\Worker; use Friendica\Database\DBA; use Friendica\DI; use Friendica\Model\Contact; @@ -42,6 +41,7 @@ use Friendica\Model\Mail; use Friendica\Model\Notification; use Friendica\Model\Photo; use Friendica\Model\Post; +use Friendica\Model\Profile; use Friendica\Model\User; use Friendica\Model\Verb; use Friendica\Network\HTTPException; @@ -53,18 +53,14 @@ use Friendica\Network\HTTPException\MethodNotAllowedException; use Friendica\Network\HTTPException\NotFoundException; use Friendica\Network\HTTPException\TooManyRequestsException; use Friendica\Network\HTTPException\UnauthorizedException; +use Friendica\Object\Api\Friendica\Notification as ApiNotification; use Friendica\Object\Image; use Friendica\Protocol\Activity; use Friendica\Protocol\Diaspora; -use Friendica\Security\BasicAuth; -use Friendica\Security\FKOAuth1; use Friendica\Security\OAuth; -use Friendica\Security\OAuth1\OAuthRequest; -use Friendica\Security\OAuth1\OAuthUtil; use Friendica\Util\DateTimeFormat; use Friendica\Util\Images; use Friendica\Util\Network; -use Friendica\Util\Proxy as ProxyUtils; use Friendica\Util\Strings; use Friendica\Util\XML; @@ -95,11 +91,6 @@ function api_user() return $user; } - $user = BasicAuth::getCurrentUserID(false); - if (!empty($user)) { - return $user; - } - if (!empty($_SESSION['allow_api'])) { return local_user(); } @@ -121,11 +112,22 @@ function api_user() */ function api_source() { - $application = OAuth::getCurrentApplicationToken(); - if (empty($application)) { - $application = BasicAuth::getCurrentApplicationToken(); + if (requestdata('source')) { + return requestdata('source'); } - return $application['name'] ?? 'api'; + + // Support for known clients that doesn't send a source name + if (!empty($_SERVER['HTTP_USER_AGENT'])) { + if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) { + return "Twidere"; + } + + Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]); + } else { + Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']); + } + + return "api"; } /** @@ -172,7 +174,7 @@ function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY } /** - * Log in user via OAuth1 or Simple HTTP Auth. + * Log in user via Simple HTTP Auth. * Simple Auth allow username in form of
user@server
, ignoring server part * * @param App $a App @@ -201,24 +203,6 @@ function api_login(App $a) } if (empty($_SERVER['PHP_AUTH_USER'])) { - // Try OAuth when no user is provided - $oauth1 = new FKOAuth1(); - // login with oauth - try { - $request = OAuthRequest::from_request(); - list($consumer, $token) = $oauth1->verify_request($request); - if (!is_null($token)) { - $oauth1->loginUser($token->uid); - Session::set('allow_api', true); - return; - } - echo __FILE__.__LINE__.__FUNCTION__ . "
";
-			var_dump($consumer, $token);
-			die();
-		} catch (Exception $e) {
-			Logger::warning(API_LOG_PREFIX . 'OAuth error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
-		}
-
 		Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
 		header('WWW-Authenticate: Basic realm="Friendica"');
 		throw new UnauthorizedException("This API requires login");
@@ -274,7 +258,7 @@ function api_login(App $a)
 
 	$_SESSION["allow_api"] = true;
 
-	Hook::callAll('logged_in', $a->user);
+	Hook::callAll('logged_in', $record);
 }
 
 /**
@@ -338,7 +322,7 @@ function api_call(App $a, App\Arguments $args = null)
 
 				if (!empty($info['auth']) && api_user() === false) {
 					api_login($a);
-					Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
+					Logger::info(API_LOG_PREFIX . 'nickname {nickname}', ['module' => 'api', 'action' => 'call', 'nickname' => $a->getLoggedInUserNickname()]);
 				}
 
 				Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
@@ -508,9 +492,9 @@ function api_get_user(App $a, $contact_id = null)
 
 	// Searching for contact URL
 	if (!is_null($contact_id) && (intval($contact_id) == 0)) {
-		$user = DBA::escape(Strings::normaliseLink($contact_id));
+		$user = Strings::normaliseLink($contact_id);
 		$url = $user;
-		$extra_query = "AND `contact`.`nurl` = '%s' ";
+		$extra_query = "AND `contact`.`nurl` = ? ";
 		if (api_user() !== false) {
 			$extra_query .= "AND `contact`.`uid`=" . intval(api_user());
 		}
@@ -518,70 +502,69 @@ function api_get_user(App $a, $contact_id = null)
 
 	// Searching for contact id with uid = 0
 	if (!is_null($contact_id) && (intval($contact_id) != 0)) {
-		$user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
+		$user = api_unique_id_to_nurl(intval($contact_id));
 
 		if ($user == "") {
 			throw new BadRequestException("User ID ".$contact_id." not found.");
 		}
 
 		$url = $user;
-		$extra_query = "AND `contact`.`nurl` = '%s' ";
+		$extra_query = "AND `contact`.`nurl` = ? ";
 		if (api_user() !== false) {
 			$extra_query .= "AND `contact`.`uid`=" . intval(api_user());
 		}
 	}
 
 	if (is_null($user) && !empty($_GET['user_id'])) {
-		$user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
+		$user = api_unique_id_to_nurl($_GET['user_id']);
 
 		if ($user == "") {
 			throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
 		}
 
 		$url = $user;
-		$extra_query = "AND `contact`.`nurl` = '%s' ";
+		$extra_query = "AND `contact`.`nurl` = ? ";
 		if (api_user() !== false) {
 			$extra_query .= "AND `contact`.`uid`=" . intval(api_user());
 		}
 	}
 	if (is_null($user) && !empty($_GET['screen_name'])) {
-		$user = DBA::escape($_GET['screen_name']);
-		$extra_query = "AND `contact`.`nick` = '%s' ";
+		$user = $_GET['screen_name'];
+		$extra_query = "AND `contact`.`nick` = ? ";
 		if (api_user() !== false) {
 			$extra_query .= "AND `contact`.`uid`=".intval(api_user());
 		}
 	}
 
 	if (is_null($user) && !empty($_GET['profileurl'])) {
-		$user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
-		$extra_query = "AND `contact`.`nurl` = '%s' ";
+		$user = Strings::normaliseLink($_GET['profileurl']);
+		$extra_query = "AND `contact`.`nurl` = ? ";
 		if (api_user() !== false) {
 			$extra_query .= "AND `contact`.`uid`=".intval(api_user());
 		}
 	}
 
 	// $called_api is the API path exploded on / and is expected to have at least 2 elements
-	if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
+	if (is_null($user) && (DI::args()->getArgc() > (count($called_api) - 1)) && (count($called_api) > 0)) {
 		$argid = count($called_api);
-		if (!empty($a->argv[$argid])) {
-			$data = explode(".", $a->argv[$argid]);
+		if (!empty(DI::args()->getArgv()[$argid])) {
+			$data = explode(".", DI::args()->getArgv()[$argid]);
 			if (count($data) > 1) {
 				list($user, $null) = $data;
 			}
 		}
 		if (is_numeric($user)) {
-			$user = DBA::escape(api_unique_id_to_nurl(intval($user)));
+			$user = api_unique_id_to_nurl(intval($user));
 
 			if ($user != "") {
 				$url = $user;
-				$extra_query = "AND `contact`.`nurl` = '%s' ";
+				$extra_query = "AND `contact`.`nurl` = ? ";
 				if (api_user() !== false) {
 					$extra_query .= "AND `contact`.`uid`=" . intval(api_user());
 				}
 			}
 		} else {
-			$user = DBA::escape($user);
-			$extra_query = "AND `contact`.`nick` = '%s' ";
+			$extra_query = "AND `contact`.`nick` = ? ";
 			if (api_user() !== false) {
 				$extra_query .= "AND `contact`.`uid`=" . intval(api_user());
 			}
@@ -596,19 +579,19 @@ function api_get_user(App $a, $contact_id = null)
 			return false;
 		} else {
 			$user = api_user();
-			$extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
+			$extra_query = "AND `contact`.`uid` = ? AND `contact`.`self` ";
 		}
 	}
 
 	Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
 
 	// user info
-	$uinfo = q(
+	$uinfo = DBA::toArray(DBA::p(
 		"SELECT *, `contact`.`id` AS `cid` FROM `contact`
 			WHERE 1
 		$extra_query",
 		$user
-	);
+	));
 
 	// Selecting the id by priority, friendica first
 	if (is_array($uinfo)) {
@@ -1017,7 +1000,7 @@ function api_statuses_mediap($type)
 	$a = DI::app();
 
 	if (api_user() === false) {
-		Logger::log('api_statuses_update: no user');
+		logger::notice('api_statuses_update: no user');
 		throw new ForbiddenException();
 	}
 	$user_info = api_get_user($a);
@@ -1037,7 +1020,7 @@ function api_statuses_mediap($type)
 	}
 	$txt = HTML::toBBCode($txt);
 
-	$a->argv[1] = $user_info['screen_name']; //should be set to username?
+	DI::args()->getArgv()[1] = $user_info['screen_name']; //should be set to username?
 
 	$picture = wall_upload_post($a, false);
 
@@ -1071,7 +1054,7 @@ function api_statuses_update($type)
 	$a = DI::app();
 
 	if (api_user() === false) {
-		Logger::log('api_statuses_update: no user');
+		logger::notice('api_statuses_update: no user');
 		throw new ForbiddenException();
 	}
 
@@ -1125,7 +1108,7 @@ function api_statuses_update($type)
 			$posts_day = Post::count($condition);
 
 			if ($posts_day > $throttle_day) {
-				Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
+				logger::info('Daily posting limit reached for user '.api_user());
 				// die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
 				throw new TooManyRequestsException(DI::l10n()->tt("Daily posting limit of %d post reached. The post was rejected.", "Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
 			}
@@ -1139,7 +1122,7 @@ function api_statuses_update($type)
 			$posts_week = Post::count($condition);
 
 			if ($posts_week > $throttle_week) {
-				Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
+				logger::info('Weekly posting limit reached for user '.api_user());
 				// die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
 				throw new TooManyRequestsException(DI::l10n()->tt("Weekly posting limit of %d post reached. The post was rejected.", "Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week));
 			}
@@ -1153,7 +1136,7 @@ function api_statuses_update($type)
 			$posts_month = Post::count($condition);
 
 			if ($posts_month > $throttle_month) {
-				Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
+				logger::info('Monthly posting limit reached for user '.api_user());
 				// die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
 				throw new TooManyRequestsException(DI::l10n()->t("Monthly posting limit of %d post reached. The post was rejected.", "Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
 			}
@@ -1204,7 +1187,7 @@ function api_statuses_update($type)
 
 		// We have to avoid that the post is rejected because of an empty body
 		if (empty($_REQUEST['body'])) {
-			$_REQUEST['body'] = '[hr]'; 
+			$_REQUEST['body'] = '[hr]';
 		}
 	}
 
@@ -1254,7 +1237,7 @@ function api_media_upload()
 	$a = DI::app();
 
 	if (api_user() === false) {
-		Logger::log('no user');
+		logger::notice('no user');
 		throw new ForbiddenException();
 	}
 
@@ -1899,7 +1882,7 @@ function api_statuses_show($type)
 	}
 
 	// params
-	$id = intval($a->argv[3] ?? 0);
+	$id = intval(DI::args()->getArgv()[3] ?? 0);
 
 	if ($id == 0) {
 		$id = intval($_REQUEST['id'] ?? 0);
@@ -1907,10 +1890,10 @@ function api_statuses_show($type)
 
 	// Hotot workaround
 	if ($id == 0) {
-		$id = intval($a->argv[4] ?? 0);
+		$id = intval(DI::args()->getArgv()[4] ?? 0);
 	}
 
-	Logger::log('API: api_statuses_show: ' . $id);
+	logger::notice('API: api_statuses_show: ' . $id);
 
 	$conversation = !empty($_REQUEST['conversation']);
 
@@ -1978,7 +1961,7 @@ function api_conversation_show($type)
 	}
 
 	// params
-	$id       = intval($a->argv[3]           ?? 0);
+	$id       = intval(DI::args()->getArgv()[3]           ?? 0);
 	$since_id = intval($_REQUEST['since_id'] ?? 0);
 	$max_id   = intval($_REQUEST['max_id']   ?? 0);
 	$count    = intval($_REQUEST['count']    ?? 20);
@@ -1992,7 +1975,7 @@ function api_conversation_show($type)
 
 	// Hotot workaround
 	if ($id == 0) {
-		$id = intval($a->argv[4] ?? 0);
+		$id = intval(DI::args()->getArgv()[4] ?? 0);
 	}
 
 	Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
@@ -2061,7 +2044,7 @@ function api_statuses_repeat($type)
 	api_get_user($a);
 
 	// params
-	$id = intval($a->argv[3] ?? 0);
+	$id = intval(DI::args()->getArgv()[3] ?? 0);
 
 	if ($id == 0) {
 		$id = intval($_REQUEST['id'] ?? 0);
@@ -2069,10 +2052,10 @@ function api_statuses_repeat($type)
 
 	// Hotot workaround
 	if ($id == 0) {
-		$id = intval($a->argv[4] ?? 0);
+		$id = intval(DI::args()->getArgv()[4] ?? 0);
 	}
 
-	Logger::log('API: api_statuses_repeat: '.$id);
+	logger::notice('API: api_statuses_repeat: ' . $id);
 
 	$fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
 	$item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
@@ -2144,7 +2127,7 @@ function api_statuses_destroy($type)
 	api_get_user($a);
 
 	// params
-	$id = intval($a->argv[3] ?? 0);
+	$id = intval(DI::args()->getArgv()[3] ?? 0);
 
 	if ($id == 0) {
 		$id = intval($_REQUEST['id'] ?? 0);
@@ -2152,10 +2135,10 @@ function api_statuses_destroy($type)
 
 	// Hotot workaround
 	if ($id == 0) {
-		$id = intval($a->argv[4] ?? 0);
+		$id = intval(DI::args()->getArgv()[4] ?? 0);
 	}
 
-	Logger::log('API: api_statuses_destroy: '.$id);
+	logger::notice('API: api_statuses_destroy: ' . $id);
 
 	$ret = api_statuses_show($type);
 
@@ -2209,11 +2192,14 @@ function api_statuses_mentions($type)
 		(SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
 		AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
 
-	$condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(),
-		Post\UserNotification::NOTIF_EXPLICIT_TAGGED | Post\UserNotification::NOTIF_IMPLICIT_TAGGED |
-		Post\UserNotification::NOTIF_THREAD_COMMENT | Post\UserNotification::NOTIF_DIRECT_COMMENT |
-		Post\UserNotification::NOTIF_DIRECT_THREAD_COMMENT,
-		api_user(), $since_id];
+	$condition = [
+		GRAVITY_PARENT, GRAVITY_COMMENT,
+		api_user(),
+		Post\UserNotification::TYPE_EXPLICIT_TAGGED | Post\UserNotification::TYPE_IMPLICIT_TAGGED |
+		Post\UserNotification::TYPE_THREAD_COMMENT | Post\UserNotification::TYPE_DIRECT_COMMENT |
+		Post\UserNotification::TYPE_DIRECT_THREAD_COMMENT,
+		api_user(), $since_id,
+	];
 
 	if ($max_id > 0) {
 		$query .= " AND `id` <= ?";
@@ -2345,16 +2331,16 @@ function api_favorites_create_destroy($type)
 	// for versioned api.
 	/// @TODO We need a better global soluton
 	$action_argv_id = 2;
-	if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
+	if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") {
 		$action_argv_id = 3;
 	}
 
-	if ($a->argc <= $action_argv_id) {
+	if (DI::args()->getArgc() <= $action_argv_id) {
 		throw new BadRequestException("Invalid request.");
 	}
-	$action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
-	if ($a->argc == $action_argv_id + 2) {
-		$itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
+	$action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]);
+	if (DI::args()->getArgc() == $action_argv_id + 2) {
+		$itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0);
 	} else {
 		$itemid = intval($_REQUEST['id'] ?? 0);
 	}
@@ -2520,12 +2506,12 @@ function api_format_messages($item, $recipient, $sender)
 	if (!empty($_GET['getText'])) {
 		$ret['title'] = $item['title'];
 		if ($_GET['getText'] == 'html') {
-			$ret['text'] = BBCode::convert($item['body'], false);
+			$ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
 		} elseif ($_GET['getText'] == 'plain') {
-			$ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0));
+			$ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
 		}
 	} else {
-		$ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0);
+		$ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
 	}
 	if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
 		unset($ret['sender']);
@@ -2546,13 +2532,13 @@ function api_convert_item($item)
 {
 	$body = api_add_attachments_to_body($item);
 
-	$entities = api_get_entitities($statustext, $body);
+	$entities = api_get_entitities($statustext, $body, $item['uri-id']);
 
 	// Add pictures to the attachment array and remove them from the body
-	$attachments = api_get_attachments($body);
+	$attachments = api_get_attachments($body, $item['uri-id']);
 
 	// Workaround for ostatus messages where the title is identically to the body
-	$html = BBCode::convert(api_clean_plain_items($body), false, BBCode::API, true);
+	$html = BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($body), BBCode::API);
 	$statusbody = trim(HTML::toPlaintext($html, 0));
 
 	// handle data: images
@@ -2570,7 +2556,7 @@ function api_convert_item($item)
 		$statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
 	}
 
-	$statushtml = BBCode::convert(BBCode::removeAttachment($body), false, BBCode::API, true);
+	$statushtml = BBCode::convertForUriId($item['uri-id'], BBCode::removeAttachment($body), BBCode::API);
 
 	// Workaround for clients with limited HTML parser functionality
 	$search = ["
", "
", "
", @@ -2584,7 +2570,7 @@ function api_convert_item($item) $statushtml = str_replace($search, $replace, $statushtml); if ($item['title'] != "") { - $statushtml = "

" . BBCode::convert($item['title']) . "


" . $statushtml; + $statushtml = "

" . BBCode::convertForUriId($item['uri-id'], $item['title']) . "


" . $statushtml; } do { @@ -2602,7 +2588,7 @@ function api_convert_item($item) // feeds without body should contain the link if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) { - $statushtml .= BBCode::convert($item['plink']); + $statushtml .= BBCode::convertForUriId($item['uri-id'], $item['plink']); } return [ @@ -2644,11 +2630,12 @@ function api_add_attachments_to_body(array $item) /** * * @param string $body + * @param int $uriid * * @return array * @throws InternalServerErrorException */ -function api_get_attachments(&$body) +function api_get_attachments(&$body, $uriid) { $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body); $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body); @@ -2669,11 +2656,7 @@ function api_get_attachments(&$body) $imagedata = Images::getInfoFromURLCached($image); if ($imagedata) { - if (DI::config()->get("system", "proxy_disabled")) { - $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]]; - } else { - $attachments[] = ["url" => ProxyUtils::proxifyUrl($image, false), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]]; - } + $attachments[] = ["url" => Post\Link::getByLink($uriid, $image), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]]; } } @@ -2689,7 +2672,7 @@ function api_get_attachments(&$body) * @throws InternalServerErrorException * @todo Links at the first character of the post */ -function api_get_entitities(&$text, $bbcode) +function api_get_entitities(&$text, $bbcode, $uriid) { $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false'); @@ -2697,7 +2680,7 @@ function api_get_entitities(&$text, $bbcode) preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images); foreach ($images[1] as $image) { - $replace = ProxyUtils::proxifyUrl($image, false); + $replace = Post\Link::getByLink($uriid, $image); $text = str_replace($image, $replace, $text); } return []; @@ -2809,31 +2792,8 @@ function api_get_entitities(&$text, $bbcode) if (!($start === false)) { $image = Images::getInfoFromURLCached($url); if ($image) { - // If image cache is activated, then use the following sizes: - // thumb (150), small (340), medium (600) and large (1024) - if (!DI::config()->get("system", "proxy_disabled")) { - $media_url = ProxyUtils::proxifyUrl($url, false); - - $sizes = []; - $scale = Images::getScalingDimensions($image[0], $image[1], 150); - $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"]; - - if (($image[0] > 150) || ($image[1] > 150)) { - $scale = Images::getScalingDimensions($image[0], $image[1], 340); - $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"]; - } - - $scale = Images::getScalingDimensions($image[0], $image[1], 600); - $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"]; - - if (($image[0] > 600) || ($image[1] > 600)) { - $scale = Images::getScalingDimensions($image[0], $image[1], 1024); - $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"]; - } - } else { - $media_url = $url; - $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"]; - } + $media_url = Post\Link::getByLink($uriid, $url); + $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"]; $entities["media"][] = [ "id" => $start+1, @@ -3039,7 +2999,7 @@ function api_format_item($item, $type = "json", $status_user = null, $author_use list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item); } - localize_item($item); + DI::contentItem()->localize($item); $in_reply_to = api_in_reply_to($item); @@ -3075,7 +3035,7 @@ function api_format_item($item, $type = "json", $status_user = null, $author_use 'external_url' => DI::baseUrl() . "/display/" . $item['guid'], 'friendica_activities' => api_format_items_activities($item, $type), 'friendica_title' => $item['title'], - 'friendica_html' => BBCode::convert($item['body'], false) + 'friendica_html' => BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::EXTERNAL) ]; if (count($converted["attachments"]) > 0) { @@ -3095,15 +3055,6 @@ function api_format_item($item, $type = "json", $status_user = null, $author_use $retweeted_item = []; $quoted_item = []; - if ($item['gravity'] == GRAVITY_PARENT) { - $body = $item['body']; - $retweeted_item = api_share_as_retweet($item); - if ($body != $item['body']) { - $quoted_item = $retweeted_item; - $retweeted_item = []; - } - } - if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) { $announce = api_get_announce($item); if (!empty($announce)) { @@ -3161,6 +3112,7 @@ function api_format_item($item, $type = "json", $status_user = null, $author_use $retweeted_status['text'] = $rt_converted["text"]; $retweeted_status['statusnet_html'] = $rt_converted["html"]; + $retweeted_status['friendica_html'] = $rt_converted["html"]; $retweeted_status['created_at'] = api_date($retweeted_item['created']); if (!empty($quoted_status)) { @@ -3463,19 +3415,20 @@ function api_statuses_f($qtype) $sql_filter = 'AND (NOT `blocked` OR `pending`)'; } - $r = q( + // @todo This query most likely can be replaced with a Contact::select... + $r = DBA::toArray(DBA::p( "SELECT `nurl` FROM `contact` - WHERE `uid` = %d + WHERE `uid` = ? AND NOT `self` $sql_filter $sql_extra ORDER BY `nick` - LIMIT %d, %d", - intval(api_user()), - intval($start), - intval($count) - ); + LIMIT ?, ?", + api_user(), + $start, + $count + )); $ret = []; foreach ($r as $cid) { @@ -3677,17 +3630,12 @@ function api_direct_messages_new($type) $recipient = null; if (!empty($_POST['screen_name'])) { - $r = q( - "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'", - intval(api_user()), - DBA::escape($_POST['screen_name']) - ); - - if (DBA::isResult($r)) { + $contacts = Contact::selectToArray(['id', 'nurl', 'network'], ['uid' => api_user(), 'nick' => $_POST['screen_name']]); + if (DBA::isResult($contacts)) { // Selecting the id by priority, friendica first - api_best_nickname($r); + api_best_nickname($contacts); - $recipient = api_get_user($a, $r[0]['nurl']); + $recipient = api_get_user($a, $contacts[0]['nurl']); } } else { $recipient = api_get_user($a, $_POST['user_id']); @@ -3699,13 +3647,9 @@ function api_direct_messages_new($type) $replyto = ''; if (!empty($_REQUEST['replyto'])) { - $r = q( - 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d', - intval(api_user()), - intval($_REQUEST['replyto']) - ); - $replyto = $r[0]['parent-uri']; - $sub = $r[0]['title']; + $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => api_user(), 'id' => $_REQUEST['replyto']]); + $replyto = $mail['parent-uri']; + $sub = $mail['title']; } else { if (!empty($_REQUEST['title'])) { $sub = $_REQUEST['title']; @@ -3717,10 +3661,10 @@ function api_direct_messages_new($type) $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto); if ($id > -1) { - $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id)); - $ret = api_format_messages($r[0], $recipient, $sender); + $mail = DBA::selectFirst('mail', [], ['id' => $id]); + $ret = api_format_messages($mail, $recipient, $sender); } else { - $ret = ["error"=>$id]; + $ret = ["error" => $id]; } $data = ['direct_message'=>$ret]; @@ -3783,15 +3727,8 @@ function api_direct_messages_destroy($type) // add parent-uri to sql command if specified by calling app $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : ""); - // get data of the specified message id - $r = q( - "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra, - intval($uid), - intval($id) - ); - // error message if specified id is not in database - if (!DBA::isResult($r)) { + if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) { if ($verbose == "true") { $answer = ['result' => 'error', 'message' => 'message id not in database']; return api_format_data("direct_messages_delete", $type, ['$result' => $answer]); @@ -3801,11 +3738,7 @@ function api_direct_messages_destroy($type) } // delete message - $result = q( - "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra, - intval($uid), - intval($id) - ); + $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]); if ($verbose == "true") { if ($result) { @@ -3828,11 +3761,11 @@ api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', * * @param string $type Known types are 'atom', 'rss', 'xml' and 'json' * @return string|array - * @throws BadRequestException - * @throws ForbiddenException - * @throws ImagickException - * @throws InternalServerErrorException - * @throws NotFoundException + * @throws HTTPException\BadRequestException + * @throws HTTPException\ExpectationFailedException + * @throws HTTPException\ForbiddenException + * @throws HTTPException\InternalServerErrorException + * @throws HTTPException\NotFoundException * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html */ function api_friendships_destroy($type) @@ -3840,25 +3773,31 @@ function api_friendships_destroy($type) $uid = api_user(); if ($uid === false) { - throw new ForbiddenException(); + throw new HTTPException\ForbiddenException(); + } + + $owner = User::getOwnerDataById($uid); + if (!$owner) { + Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]); + throw new HTTPException\NotFoundException('Error Processing Request'); } $contact_id = $_REQUEST['user_id'] ?? 0; if (empty($contact_id)) { Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']); - throw new BadRequestException("no user_id specified"); + throw new HTTPException\BadRequestException('no user_id specified'); } // Get Contact by given id $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]); if(!DBA::isResult($contact)) { - Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]); - throw new NotFoundException("no contact found to given ID"); + Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]); + throw new HTTPException\NotFoundException('no contact found to given ID'); } - $url = $contact["url"]; + $url = $contact['url']; $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)", $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url), @@ -3867,40 +3806,33 @@ function api_friendships_destroy($type) if (!DBA::isResult($contact)) { Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']); - throw new NotFoundException("Not following Contact"); - } - - if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) { - Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]); - throw new ExpectationFailedException("Not supported"); + throw new HTTPException\NotFoundException('Not following Contact'); } - $dissolve = ($contact['rel'] == Contact::SHARING); + try { + $result = Contact::terminateFriendship($owner, $contact); - $owner = User::getOwnerDataById($uid); - if ($owner) { - Contact::terminateFriendship($owner, $contact, $dissolve); - } - else { - Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]); - throw new NotFoundException("Error Processing Request"); - } + if ($result === null) { + Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]); + throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.'); + } - // Sharing-only contacts get deleted as there no relationship any more - if ($dissolve) { - Contact::remove($contact['id']); - } else { - DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]); + if ($result === false) { + throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.'); + } + } catch (Exception $e) { + Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]); + throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator'); } // "uid" and "self" are only needed for some internal stuff, so remove it from here - unset($contact["uid"]); - unset($contact["self"]); + unset($contact['uid']); + unset($contact['self']); // Set screen_name since Twidere requests it - $contact["screen_name"] = $contact["nick"]; + $contact['screen_name'] = $contact['nick']; - return api_format_data("friendships-destroy", $type, ['user' => $contact]); + return api_format_data('friendships-destroy', $type, ['user' => $contact]); } api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST); @@ -3972,13 +3904,13 @@ function api_direct_messages_box($type, $box, $verbose) $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'"; } - $r = q( - "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND $sql_extra AND `mail`.`id` > %d ORDER BY `mail`.`id` DESC LIMIT %d,%d", - intval(api_user()), - intval($since_id), - intval($start), - intval($count) - ); + $r = DBA::toArray(DBA::p( + "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid` = ? AND $sql_extra AND `mail`.`id` > ? ORDER BY `mail`.`id` DESC LIMIT ?,?", + api_user(), + $since_id, + $start, + $count + )); if ($verbose == "true" && !DBA::isResult($r)) { $answer = ['result' => 'error', 'message' => 'no mails available']; return api_format_data("direct_messages_all", $type, ['$result' => $answer]); @@ -4078,48 +4010,6 @@ 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. - * - * @see https://oauth.net/core/1.0/#auth_step1 - */ -function api_oauth_request_token() -{ - $oauth1 = new FKOAuth1(); - try { - $r = $oauth1->fetch_request_token(OAuthRequest::from_request()); - } catch (Exception $e) { - echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage()); - exit(); - } - echo $r; - exit(); -} - -/** - * Returns an OAuth Access Token. - * - * @return array|string - * @see https://oauth.net/core/1.0/#auth_step3 - */ -function api_oauth_access_token() -{ - $oauth1 = new FKOAuth1(); - try { - $r = $oauth1->fetch_access_token(OAuthRequest::from_request()); - } catch (Exception $e) { - echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); - exit(); - } - echo $r; - exit(); -} - -/// @TODO move to top of file or somewhere better -api_register_func('api/oauth/request_token', 'api_oauth_request_token', false); -api_register_func('api/oauth/access_token', 'api_oauth_access_token', false); - - /** * delete a complete photoalbum with all containing photos from database through api * @@ -4222,12 +4112,12 @@ function api_fr_photos_list($type) if (api_user() === false) { throw new ForbiddenException(); } - $r = q( + $r = DBA::toArray(DBA::p( "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`, MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo` - WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`", - intval(local_user()) - ); + WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`", + local_user(), Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER + )); $typetoext = [ 'image/jpeg' => 'jpg', 'image/png' => 'png', @@ -4322,7 +4212,7 @@ function api_fr_photo_create_update($type) // now let's upload the new media in create-mode if ($mode == "create") { $media = $_FILES['media']; - $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility); + $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, Photo::DEFAULT, $visibility); // return success of updating or error message if (!is_null($data)) { @@ -4375,7 +4265,7 @@ function api_fr_photo_create_update($type) if (!empty($_FILES['media'])) { $nothingtodo = false; $media = $_FILES['media']; - $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id); + $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id); if (!is_null($data)) { return api_format_data("photo_update", $type, $data); } @@ -4518,7 +4408,7 @@ function api_account_update_profile_image($type) $media = $_FILES['media']; } // save new profile image - $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t('Profile Photos'), "", "", "", "", "", $is_default_profile); + $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR); // get filetype if (is_array($media['type'])) { @@ -4537,7 +4427,7 @@ function api_account_update_profile_image($type) // change specified profile or all profiles to the new resource-id if ($is_default_profile) { $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()]; - Photo::update(['profile' => false], $condition); + Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition); } else { $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext, 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext]; @@ -4547,12 +4437,7 @@ function api_account_update_profile_image($type) Contact::updateSelfFromUserID(api_user(), true); // Update global directory in background - $url = DI::baseUrl() . '/profile/' . DI::app()->user['nickname']; - if ($url && strlen(DI::config()->get('system', 'directory'))) { - Worker::add(PRIORITY_LOW, "Directory", $url); - } - - Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user()); + Profile::publishUpdate(api_user()); // output for client if ($data) { @@ -4593,21 +4478,17 @@ function api_account_update_profile($type) 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']]); + Contact::update(['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]); + Contact::update(['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']]); + Contact::update(['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]); + Contact::update(['about' => $_POST['description']], ['id' => $api_user['id']]); } - Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user); - // Update global directory in background - if ($api_user['url'] && strlen(DI::config()->get('system', 'directory'))) { - Worker::add(PRIORITY_LOW, "Directory", $api_user['url']); - } + Profile::publishUpdate($local_user); return api_account_verify_credentials($type); } @@ -4653,7 +4534,7 @@ function check_acl_input($acl_string) * @param string $allow_gid * @param string $deny_gid * @param string $desc - * @param integer $profile + * @param integer $phototype * @param boolean $visibility * @param string $photo_id * @return array @@ -4664,7 +4545,7 @@ function check_acl_input($acl_string) * @throws NotFoundException * @throws UnauthorizedException */ -function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $profile = 0, $visibility = false, $photo_id = null) +function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $phototype = 0, $visibility = false, $photo_id = null) { $visitor = 0; $src = ""; @@ -4697,11 +4578,9 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $ $filetype = Images::getMimeTypeBySource($src, $filename, $filetype); - Logger::log( + logger::info( "File upload src: " . $src . " - filename: " . $filename . - " - size: " . $filesize . " - type: " . $filetype, - Logger::DEBUG - ); + " - size: " . $filesize . " - type: " . $filetype); // check if there was a php upload error if ($filesize == 0 && $media['error'] == 1) { @@ -4732,7 +4611,7 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $ } if ($max_length > 0) { $Image->scaleDown($max_length); - Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG); + logger::info("File upload: Scaling picture to new size " . $max_length); } $width = $Image->getWidth(); $height = $Image->getHeight(); @@ -4742,57 +4621,57 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $ if ($mediatype == "photo") { // upload normal image (scales 0, 1, 2) - Logger::log("photo upload: starting new photo upload", Logger::DEBUG); + logger::info("photo upload: starting new photo upload"); - $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc); + $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc); if (!$r) { - Logger::log("photo upload: image upload with scale 0 (original size) failed"); + logger::notice("photo upload: image upload with scale 0 (original size) failed"); } if ($width > 640 || $height > 640) { $Image->scaleDown(640); - $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc); + $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc); if (!$r) { - Logger::log("photo upload: image upload with scale 1 (640x640) failed"); + logger::notice("photo upload: image upload with scale 1 (640x640) failed"); } } if ($width > 320 || $height > 320) { $Image->scaleDown(320); - $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc); + $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc); if (!$r) { - Logger::log("photo upload: image upload with scale 2 (320x320) failed"); + logger::notice("photo upload: image upload with scale 2 (320x320) failed"); } } - Logger::log("photo upload: new photo upload ended", Logger::DEBUG); + logger::info("photo upload: new photo upload ended"); } elseif ($mediatype == "profileimage") { // upload profile image (scales 4, 5, 6) - Logger::log("photo upload: starting new profile image upload", Logger::DEBUG); + logger::info("photo upload: starting new profile image upload"); if ($width > 300 || $height > 300) { $Image->scaleDown(300); - $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc); + $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc); if (!$r) { - Logger::log("photo upload: profile image upload with scale 4 (300x300) failed"); + logger::notice("photo upload: profile image upload with scale 4 (300x300) failed"); } } if ($width > 80 || $height > 80) { $Image->scaleDown(80); - $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc); + $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc); if (!$r) { - Logger::log("photo upload: profile image upload with scale 5 (80x80) failed"); + logger::notice("photo upload: profile image upload with scale 5 (80x80) failed"); } } if ($width > 48 || $height > 48) { $Image->scaleDown(48); - $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc); + $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc); if (!$r) { - Logger::log("photo upload: profile image upload with scale 6 (48x48) failed"); + logger::notice("photo upload: profile image upload with scale 6 (48x48) failed"); } } $Image->__destruct(); - Logger::log("photo upload: new profile image upload ended", Logger::DEBUG); + logger::info("photo upload: new profile image upload ended"); } if (!empty($r)) { @@ -4889,18 +4768,16 @@ function prepare_photo_data($type, $scale, $photo_id) // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database // clients needs to convert this in their way for further processing - $r = q( - "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`, + $r = DBA::toArray(DBA::p( + "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`, `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`, MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale` - FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY + FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`, `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`", - $data_sql, - intval(local_user()), - DBA::escape($photo_id), - $scale_sql - ); + local_user(), + $photo_id + )); $typetoext = [ 'image/jpeg' => 'jpg', @@ -4980,70 +4857,6 @@ function prepare_photo_data($type, $scale, $photo_id) return $data; } - -/** - * Similar as /mod/redir.php - * redirect to 'url' after dfrn auth - * - * Why this when there is mod/redir.php already? - * This use api_user() and api_login() - * - * params - * c_url: url of remote contact to auth to - * url: string, url to redirect after auth - */ -function api_friendica_remoteauth() -{ - $url = $_GET['url'] ?? ''; - $c_url = $_GET['c_url'] ?? ''; - - if ($url === '' || $c_url === '') { - throw new BadRequestException("Wrong parameters."); - } - - $c_url = Strings::normaliseLink($c_url); - - // traditional DFRN - - $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]); - if (!DBA::isResult($contact)) { - throw new BadRequestException("Unknown contact"); - } - - $cid = $contact['id']; - - $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id']; - - if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) { - System::externalRedirect($url ?: $c_url); - } - - if ($contact['duplex'] && $contact['issued-id']) { - $orig_id = $contact['issued-id']; - $dfrn_id = '1:' . $orig_id; - } - if ($contact['duplex'] && $contact['dfrn-id']) { - $orig_id = $contact['dfrn-id']; - $dfrn_id = '0:' . $orig_id; - } - - $sec = Strings::getRandomHex(); - - $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, - 'sec' => $sec, 'expire' => time() + 45]; - DBA::insert('profile_check', $fields); - - Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]); - $dest = ($url ? '&destination_url=' . $url : ''); - - System::externalRedirect( - $contact['poll'] . '?dfrn_id=' . $dfrn_id - . '&dfrn_version=' . DFRN_PROTOCOL_VERSION - . '&type=profile&sec=' . $sec . $dest - ); -} -api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true); - /** * Return an item with announcer data if it had been announced * @@ -5077,76 +4890,6 @@ function api_get_announce($item) return array_merge($item, $announce); } -/** - * Return the item shared, if the item contains only the [share] tag - * - * @param array $item Sharer item - * @return array|false Shared item or false if not a reshare - * @throws ImagickException - * @throws InternalServerErrorException - */ -function api_share_as_retweet(&$item) -{ - $body = trim($item["body"]); - - if (Diaspora::isReshare($body, false) === false) { - if ($item['author-id'] == $item['owner-id']) { - return false; - } else { - // Reshares from OStatus, ActivityPub and Twitter - $reshared_item = $item; - $reshared_item['owner-id'] = $reshared_item['author-id']; - $reshared_item['owner-link'] = $reshared_item['author-link']; - $reshared_item['owner-name'] = $reshared_item['author-name']; - $reshared_item['owner-avatar'] = $reshared_item['author-avatar']; - return $reshared_item; - } - } - - $reshared = Item::getShareArray($item); - if (empty($reshared)) { - return false; - } - - $reshared_item = $item; - - if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) { - return false; - } - - if (!empty($reshared['comment'])) { - $item['body'] = $reshared['comment']; - } - - $reshared_item["share-pre-body"] = $reshared['comment']; - $reshared_item["body"] = $reshared['shared']; - $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, false); - $reshared_item["author-name"] = $reshared['author']; - $reshared_item["author-link"] = $reshared['profile']; - $reshared_item["author-avatar"] = $reshared['avatar']; - $reshared_item["plink"] = $reshared['link'] ?? ''; - $reshared_item["created"] = $reshared['posted']; - $reshared_item["edited"] = $reshared['posted']; - - // Try to fetch the original item - if (!empty($reshared['guid'])) { - $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]]; - } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) { - $condition = ['id' => $original_id]; - } else { - $condition = []; - } - - if (!empty($condition)) { - $original_item = Post::selectFirst([], $condition); - if (DBA::isResult($original_item)) { - $reshared_item = array_merge($reshared_item, $original_item); - } - } - - return $reshared_item; -} - /** * * @param array $item @@ -5320,25 +5063,19 @@ function api_friendica_group_show($type) // get data of the specified group id or all groups if not specified if ($gid != 0) { - $r = q( - "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d", - intval($uid), - intval($gid) - ); + $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]); + // error message if specified gid is not in database - if (!DBA::isResult($r)) { + if (!DBA::isResult($groups)) { throw new BadRequestException("gid not available"); } } else { - $r = q( - "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d", - intval($uid) - ); + $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]); } // loop through all groups and retrieve all members for adding data in the user array $grps = []; - foreach ($r as $rr) { + foreach ($groups as $rr) { $members = Contact\Group::getById($rr['id']); $users = []; @@ -5394,26 +5131,13 @@ function api_friendica_group_delete($type) throw new BadRequestException('gid or name not specified'); } - // get data of the specified group id - $r = q( - "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d", - intval($uid), - intval($gid) - ); // error message if specified gid is not in database - if (!DBA::isResult($r)) { + if (!DBA::exists('group', ['uid' => $uid, 'id' => $gid])) { throw new BadRequestException('gid not available'); } - // get data of the specified group id and group name - $rname = q( - "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'", - intval($uid), - intval($gid), - DBA::escape($name) - ); // error message if specified gid is not in database - if (!DBA::isResult($rname)) { + if (!DBA::exists('group', ['uid' => $uid, 'id' => $gid, 'name' => $name])) { throw new BadRequestException('wrong group name'); } @@ -5497,25 +5221,13 @@ function group_create($name, $uid, $users = []) throw new BadRequestException('group name not specified'); } - // get data of the specified group name - $rname = q( - "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0", - intval($uid), - DBA::escape($name) - ); // error message if specified group name already exists - if (DBA::isResult($rname)) { + if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) { throw new BadRequestException('group name already exists'); } - // check if specified group name is a deleted group - $rname = q( - "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1", - intval($uid), - DBA::escape($name) - ); - // error message if specified group name already exists - if (DBA::isResult($rname)) { + // Check if the group needs to be reactivated + if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) { $reactivate_group = true; } @@ -5532,13 +5244,7 @@ function group_create($name, $uid, $users = []) $errorusers = []; foreach ($users as $user) { $cid = $user['cid']; - // check if user really exists as contact - $contact = q( - "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d", - intval($cid), - intval($uid) - ); - if (count($contact)) { + if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) { Group::addMember($gid, $cid); } else { $erroraddinguser = true; @@ -5680,14 +5386,8 @@ function api_friendica_group_update($type) $errorusers = []; foreach ($users as $user) { $cid = $user['cid']; - // check if user really exists as contact - $contact = q( - "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d", - intval($cid), - intval($uid) - ); - if (count($contact)) { + if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) { Group::addMember($gid, $cid); } else { $erroraddinguser = true; @@ -5773,7 +5473,7 @@ function api_friendica_activity($type) if (api_user() === false) { throw new ForbiddenException(); } - $verb = strtolower($a->argv[3]); + $verb = strtolower(DI::args()->getArgv()[3]); $verb = preg_replace("|\..*$|", "", $verb); $id = $_REQUEST['id'] ?? 0; @@ -5816,23 +5516,24 @@ api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activit */ function api_friendica_notification($type) { - $a = DI::app(); - if (api_user() === false) { throw new ForbiddenException(); } - if ($a->argc!==3) { - throw new BadRequestException("Invalid argument count"); + if (DI::args()->getArgc()!==3) { + throw new BadRequestException('Invalid argument count'); } - $notifications = DI::notification()->getApiList(local_user()); + $Notifies = DI::notify()->selectAllForUser(local_user(), 50); - if ($type == "xml") { - $xmlnotes = false; - if (!empty($notifications)) { - foreach ($notifications as $notification) { - $xmlnotes[] = ["@attributes" => $notification->toArray()]; - } + $notifications = new ApiNotifications(); + foreach ($Notifies as $Notify) { + $notifications[] = new ApiNotification($Notify); + } + + if ($type == 'xml') { + $xmlnotes = []; + foreach ($notifications as $notification) { + $xmlnotes[] = ['@attributes' => $notification->toArray()]; } $result = $xmlnotes; @@ -5842,7 +5543,7 @@ function api_friendica_notification($type) $result = false; } - return api_format_data("notes", $type, ['note' => $result]); + return api_format_data('notes', $type, ['note' => $result]); } /** @@ -5866,27 +5567,37 @@ function api_friendica_notification_seen($type) if (api_user() === false || $user_info === false) { throw new ForbiddenException(); } - if ($a->argc !== 4) { - throw new BadRequestException("Invalid argument count"); + if (DI::args()->getArgc() !== 4) { + throw new BadRequestException('Invalid argument count'); } - $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0); + $id = intval($_REQUEST['id'] ?? 0); try { - $notify = DI::notify()->getByID($id, api_user()); - DI::notify()->setSeen(true, $notify); + $Notify = DI::notify()->selectOneById($id); + if ($Notify->uid !== api_user()) { + throw new NotFoundException(); + } - if ($notify->otype === Notification\ObjectType::ITEM) { - $item = Post::selectFirstForUser(api_user(), [], ['id' => $notify->iid, 'uid' => api_user()]); + if ($Notify->uriId) { + DI::notification()->setAllSeenForUser($Notify->uid, ['target-uri-id' => $Notify->uriId]); + } + + $Notify->setSeen(); + DI::notify()->save($Notify); + + if ($Notify->otype === Notification\ObjectType::ITEM) { + $item = Post::selectFirstForUser(api_user(), [], ['id' => $Notify->iid, 'uid' => api_user()]); if (DBA::isResult($item)) { // we found the item, return it to the user $ret = api_format_items([$item], $user_info, false, $type); $data = ['status' => $ret]; - return api_format_data("status", $type, $data); + return api_format_data('status', $type, $data); } // the item can't be found, but we set the notification as seen, so we count this as a success } - return api_format_data('result', $type, ['result' => "success"]); + + return api_format_data('result', $type, ['result' => 'success']); } catch (NotFoundException $e) { throw new BadRequestException('Invalid argument', $e); } catch (Exception $e) { @@ -5983,11 +5694,11 @@ function api_friendica_direct_messages_search($type, $box = "") } // get data for the specified searchstring - $r = q( - "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND `body` LIKE '%s' ORDER BY `mail`.`id` DESC", - intval($uid), - DBA::escape('%'.$searchstring.'%') - ); + $r = DBA::toArray(DBA::p( + "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid` = ? AND `body` LIKE ? ORDER BY `mail`.`id` DESC", + $uid, + '%'.$searchstring.'%' + )); $profile_url = $user_info["url"];