3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
24 use Friendica\Core\ACL;
25 use Friendica\Core\Logger;
26 use Friendica\Core\Session;
27 use Friendica\Core\System;
28 use Friendica\Core\Worker;
29 use Friendica\Database\DBA;
31 use Friendica\Protocol\Activity;
32 use Friendica\Util\DateTimeFormat;
33 use Friendica\Worker\Delivery;
36 * Class to handle private messages
41 * Insert private message
44 * @param bool $notification
45 * @return int|boolean Message ID or false on error
46 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
47 * @throws \ImagickException
49 public static function insert(array $msg, bool $notification = true)
51 if (!isset($msg['reply'])) {
52 $msg['reply'] = DBA::exists('mail', ['parent-uri' => $msg['parent-uri']]);
55 if (empty($msg['convid'])) {
56 $mail = DBA::selectFirst('mail', ['convid'], ["`convid` != 0 AND `parent-uri` = ?", $msg['parent-uri']]);
57 if (DBA::isResult($mail)) {
58 $msg['convid'] = $mail['convid'];
62 if (empty($msg['guid'])) {
63 $host = parse_url($msg['from-url'], PHP_URL_HOST);
64 $msg['guid'] = Item::guidFromUri($msg['uri'], $host);
67 $msg['created'] = (!empty($msg['created']) ? DateTimeFormat::utc($msg['created']) : DateTimeFormat::utcNow());
69 $msg['author-id'] = Contact::getIdForURL($msg['from-url'], 0, false);
70 $msg['uri-id'] = ItemURI::insert(['uri' => $msg['uri'], 'guid' => $msg['guid']]);
71 $msg['parent-uri-id'] = ItemURI::getIdByURI($msg['parent-uri']);
75 if (DBA::exists('mail', ['uri' => $msg['uri'], 'uid' => $msg['uid']])) {
77 Logger::info('duplicate message already delivered.');
81 if ($msg['reply'] && DBA::isResult($reply = DBA::selectFirst('mail', ['uri', 'uri-id'], ['parent-uri' => $msg['parent-uri'], 'reply' => false]))) {
82 $msg['thr-parent'] = $reply['uri'];
83 $msg['thr-parent-id'] = $reply['uri-id'];
85 $msg['thr-parent'] = $msg['uri'];
86 $msg['thr-parent-id'] = $msg['uri-id'];
89 DBA::insert('mail', $msg);
91 $msg['id'] = DBA::lastInsertId();
95 if (!empty($msg['convid'])) {
96 DBA::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $msg['convid']]);
100 $user = User::getById($msg['uid']);
101 // send notifications.
103 'type' => Notification\Type::MAIL,
104 'otype' => Notification\ObjectType::MAIL,
105 'verb' => Activity::POST,
106 'uid' => $user['uid'],
107 'cid' => $msg['contact-id'],
108 'link' => DI::baseUrl() . '/message/' . $msg['id'],
111 DI::notify()->createFromArray($notif_params);
113 Logger::info('Mail is processed, notification was sent.', ['id' => $msg['id'], 'uri' => $msg['uri']]);
120 * Send private message
122 * @param integer $recipient recipient id, default 0
123 * @param string $body message body, default empty
124 * @param string $subject message subject, default empty
125 * @param string $replyto reply to
127 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
129 public static function send(int $recipient = 0, string $body = '', string $subject = '', string $replyto = ''): int
137 if (!strlen($subject)) {
138 $subject = DI::l10n()->t('[no subject]');
141 $me = DBA::selectFirst('contact', [], ['uid' => Session::getLocalUser(), 'self' => true]);
142 if (!DBA::isResult($me)) {
146 $contacts = ACL::getValidMessageRecipientsForUser(Session::getLocalUser());
148 $contactIndex = array_search($recipient, array_column($contacts, 'id'));
149 if ($contactIndex === false) {
153 $contact = $contacts[$contactIndex];
155 Photo::setPermissionFromBody($body, Session::getLocalUser(), $me['id'], '<' . $contact['id'] . '>', '', '', '');
157 $guid = System::createUUID();
158 $uri = Item::newURI($guid);
163 // look for any existing conversation structure
165 if (strlen($replyto)) {
167 $condition = ["`uid` = ? AND (`uri` = ? OR `parent-uri` = ?)",
168 Session::getLocalUser(), $replyto, $replyto];
169 $mail = DBA::selectFirst('mail', ['convid'], $condition);
170 if (DBA::isResult($mail)) {
171 $convid = $mail['convid'];
177 // create a new conversation
178 $conv_guid = System::createUUID();
179 $convuri = $contact['addr'] . ':' . $conv_guid;
181 $fields = ['uid' => Session::getLocalUser(), 'guid' => $conv_guid, 'creator' => $me['addr'],
182 'created' => DateTimeFormat::utcNow(), 'updated' => DateTimeFormat::utcNow(),
183 'subject' => $subject, 'recips' => $contact['addr'] . ';' . $me['addr']];
184 if (DBA::insert('conv', $fields)) {
185 $convid = DBA::lastInsertId();
190 Logger::warning('conversation not found.');
194 if (!strlen($replyto)) {
198 $post_id = self::insert(
200 'uid' => Session::getLocalUser(),
203 'from-name' => $me['name'],
204 'from-photo' => $me['thumb'],
205 'from-url' => $me['url'],
206 'contact-id' => $recipient,
213 'parent-uri' => $replyto,
214 'created' => DateTimeFormat::utcNow()
220 * When a photo was uploaded into the message using the (profile wall) ajax
221 * uploader, The permissions are initially set to disallow anybody but the
222 * owner from seeing it. This is because the permissions may not yet have been
223 * set for the post. If it's private, the photo permissions should be set
224 * appropriately. But we didn't know the final permissions on the post until
225 * now. So now we'll look for links of uploaded messages that are in the
226 * post and set them to the same permissions as the post itself.
230 if (preg_match_all("/\[img\](.*?)\[\/img\]/", $body, $match)) {
232 if (count($images)) {
233 foreach ($images as $image) {
234 $image_rid = Photo::ridFromURI($image);
235 if (!empty($image_rid)) {
236 Photo::update(['allow-cid' => '<' . $recipient . '>'], ['resource-id' => $image_rid, 'album' => 'Wall Photos', 'uid' => Session::getLocalUser()]);
243 Worker::add(Worker::PRIORITY_HIGH, "Notifier", Delivery::MAIL, $post_id);
244 return intval($post_id);
251 * @param array $recipient recipient, default empty
252 * @param string $body message body, default empty
253 * @param string $subject message subject, default empty
254 * @param string $replyto reply to, default empty
256 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
257 * @throws \ImagickException
259 public static function sendWall(array $recipient = [], string $body = '', string $subject = '', string $replyto = ''): int
265 if (!strlen($subject)) {
266 $subject = DI::l10n()->t('[no subject]');
269 $guid = System::createUUID();
270 $uri = Item::newURI($guid);
272 $me = Contact::getByURL($replyto);
277 $conv_guid = System::createUUID();
279 $recip_handle = $recipient['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
281 $sender_handle = $me['addr'];
283 $handles = $recip_handle . ';' . $sender_handle;
286 $fields = ['uid' => $recipient['uid'], 'guid' => $conv_guid, 'creator' => $sender_handle,
287 'created' => DateTimeFormat::utcNow(), 'updated' => DateTimeFormat::utcNow(),
288 'subject' => $subject, 'recips' => $handles];
289 if (DBA::insert('conv', $fields)) {
290 $convid = DBA::lastInsertId();
294 Logger::warning('conversation not found.');
300 'uid' => $recipient['uid'],
303 'from-name' => $me['name'],
304 'from-photo' => $me['photo'],
305 'from-url' => $me['url'],
313 'parent-uri' => $me['url'],
314 'created' => DateTimeFormat::utcNow(),