]> git.mxchange.org Git - friendica.git/blob - src/Worker/Delivery.php
API: fix sender/recipient of PMs: check api_user before get user info.
[friendica.git] / src / Worker / Delivery.php
1 <?php
2 /**
3  * @file src/Worker/Delivery.php
4  */
5 namespace Friendica\Worker;
6
7 use Friendica\BaseObject;
8 use Friendica\Core\Config;
9 use Friendica\Core\L10n;
10 use Friendica\Core\System;
11 use Friendica\Database\DBM;
12 use Friendica\Model\Contact;
13 use Friendica\Model\Item;
14 use Friendica\Model\Queue;
15 use Friendica\Model\User;
16 use Friendica\Protocol\DFRN;
17 use Friendica\Protocol\Diaspora;
18 use Friendica\Protocol\Email;
19 use dba;
20
21 require_once 'include/items.php';
22
23 class Delivery extends BaseObject
24 {
25         const MAIL =       'mail';
26         const SUGGESTION = 'suggest';
27         const RELOCATION = 'relocate';
28         const DELETION =   'drop';
29         const POST =       'wall-new';
30         const COMMENT =    'comment-new';
31         const REMOVAL =    'removeme';
32
33         public static function execute($cmd, $item_id, $contact_id)
34         {
35                 logger('Invoked: ' . $cmd . ': ' . $item_id . ' to ' . $contact_id, LOGGER_DEBUG);
36
37                 $top_level = false;
38                 $followup = false;
39                 $public_message = false;
40
41                 if ($cmd == self::MAIL) {
42                         $target_item = dba::selectFirst('mail', [], ['id' => $item_id]);
43                         if (!DBM::is_result($target_item)) {
44                                 return;
45                         }
46                         $uid = $target_item['uid'];
47                 } elseif ($cmd == self::SUGGESTION) {
48                         $target_item = dba::selectFirst('fsuggest', [], ['id' => $item_id]);
49                         if (!DBM::is_result($target_item)) {
50                                 return;
51                         }
52                         $uid = $target_item['uid'];
53                 } elseif ($cmd == self::RELOCATION) {
54                         $uid = $item_id;
55                 } else {
56                         $item = dba::selectFirst('item', ['parent'], ['id' => $item_id]);
57                         if (!DBM::is_result($item) || empty($item['parent'])) {
58                                 return;
59                         }
60                         $parent_id = intval($item['parent']);
61
62                         $itemdata = dba::p("SELECT `item`.*, `contact`.`uid` AS `cuid`,
63                                                         `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
64                                                 FROM `item`
65                                                 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
66                                                 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
67                                                 WHERE `item`.`id` IN (?, ?) AND `visible` AND NOT `moderated`
68                                                 ORDER BY `item`.`id`",
69                                         $item_id, $parent_id);
70                         $items = [];
71                         while ($item = dba::fetch($itemdata)) {
72                                 if ($item['id'] == $parent_id) {
73                                         $parent = $item;
74                                 }
75                                 if ($item['id'] == $item_id) {
76                                         $target_item = $item;
77                                 }
78                                 $items[] = $item;
79                         }
80                         dba::close($itemdata);
81
82                         $uid = $target_item['cuid'];
83
84                         // avoid race condition with deleting entries
85                         if ($items[0]['deleted']) {
86                                 foreach ($items as $item) {
87                                         $item['deleted'] = 1;
88                                 }
89                         }
90
91                         // When commenting too fast after delivery, a post wasn't recognized as top level post.
92                         // The count then showed more than one entry. The additional check should help.
93                         // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
94                         if ((($parent['id'] == $item_id) || (count($items) == 1)) && ($parent['uri'] === $parent['parent-uri'])) {
95                                 logger('Top level post');
96                                 $top_level = true;
97                         }
98
99                         // This is IMPORTANT!!!!
100
101                         // We will only send a "notify owner to relay" or followup message if the referenced post
102                         // originated on our system by virtue of having our hostname somewhere
103                         // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
104                         // if $parent['wall'] == 1 we will already have the parent message in our array
105                         // and we will relay the whole lot.
106
107                         $localhost = self::getApp()->get_hostname();
108                         if (strpos($localhost, ':')) {
109                                 $localhost = substr($localhost, 0, strpos($localhost, ':'));
110                         }
111                         /**
112                          *
113                          * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
114                          * have been known to cause runaway conditions which affected several servers, along with
115                          * permissions issues.
116                          *
117                          */
118
119                         if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
120                                 logger('Followup ' . $target_item["guid"], LOGGER_DEBUG);
121                                 // local followup to remote post
122                                 $followup = true;
123                         }
124
125                         if (empty($parent['allow_cid'])
126                                 && empty($parent['allow_gid'])
127                                 && empty($parent['deny_cid'])
128                                 && empty($parent['deny_gid'])
129                                 && !$parent["private"]) {
130                                 $public_message = true;
131                         }
132                 }
133
134                 $owner = User::getOwnerDataById($uid);
135                 if (!DBM::is_result($owner)) {
136                         return;
137                 }
138
139                 // We don't deliver our items to blocked or pending contacts, and not to ourselves either
140                 $contact = dba::selectFirst('contact', [],
141                         ['id' => $contact_id, 'blocked' => false, 'pending' => false, 'self' => false]
142                 );
143                 if (!DBM::is_result($contact)) {
144                         return;
145                 }
146
147                 // Transmit via Diaspora if the thread had started as Diaspora post
148                 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
149                 if (isset($parent) && ($parent['network'] == NETWORK_DIASPORA) && ($contact['network'] == NETWORK_DFRN)) {
150                         $contact['network'] = NETWORK_DIASPORA;
151                 }
152
153                 logger("Delivering " . $cmd . " followup=$followup - via network " . $contact['network']);
154
155                 switch ($contact['network']) {
156
157                         case NETWORK_DFRN:
158                                 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
159                                 break;
160
161                         case NETWORK_DIASPORA:
162                                 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
163                                 break;
164
165                         case NETWORK_OSTATUS:
166                                 // Do not send to otatus if we are not configured to send to public networks
167                                 if ($owner['prvnets']) {
168                                         break;
169                                 }
170                                 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
171                                         break;
172                                 }
173
174                                 // There is currently no code here to distribute anything to OStatus.
175                                 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
176                                 break;
177
178                         case NETWORK_MAIL:
179                                 self::deliverMail($cmd, $contact, $owner, $target_item);
180                                 break;
181
182                         default:
183                                 break;
184                 }
185
186                 return;
187         }
188
189         /**
190          * @brief Deliver content via DFRN
191          *
192          * @param string  $cmd            Command
193          * @param array   $contact        Contact record of the receiver
194          * @param array   $owner          Owner record of the sender
195          * @param array   $items          Item record of the content and the parent
196          * @param array   $target_item    Item record of the content
197          * @param boolean $public_message Is the content public?
198          * @param boolean $top_level      Is it a thread starter?
199          * @param boolean $followup       Is it an answer to a remote post?
200          */
201         private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
202         {
203                 logger('Deliver ' . $target_item["guid"] . ' via DFRN to ' . (empty($contact['addr']) ? $contact['url'] : $contact['addr']));
204
205                 if ($cmd == self::MAIL) {
206                         $item = $target_item;
207                         $item['body'] = Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
208                         $atom = DFRN::mail($item, $owner);
209                 } elseif ($cmd == self::SUGGESTION) {
210                         $item = $target_item;
211                         $atom = DFRN::fsuggest($item, $owner);
212                         dba::delete('fsuggest', ['id' => $item['id']]);
213                 } elseif ($cmd == self::RELOCATION) {
214                         $atom = DFRN::relocate($owner, $owner['uid']);
215                 } elseif ($followup) {
216                         $msgitems = [$target_item];
217                         $atom = DFRN::entries($msgitems, $owner);
218                 } else {
219                         $msgitems = [];
220                         foreach ($items as $item) {
221                                 // Only add the parent when we don't delete other items.
222                                 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
223                                         $item["entry:comment-allow"] = true;
224                                         $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
225                                         $msgitems[] = $item;
226                                 }
227                         }
228                         $atom = DFRN::entries($msgitems, $owner);
229                 }
230
231                 logger('Notifier entry: ' . $contact["url"] . ' ' . $target_item["guid"] . ' entry: ' . $atom, LOGGER_DATA);
232
233                 $basepath =  implode('/', array_slice(explode('/', $contact['url']), 0, 3));
234
235                 // perform local delivery if we are on the same site
236
237                 if (link_compare($basepath, System::baseUrl())) {
238                         $condition = ['nurl' => normalise_link($contact['url']), 'self' => true];
239                         $target_self = dba::selectFirst('contact', ['uid'], $condition);
240                         if (!DBM::is_result($target_self)) {
241                                 return;
242                         }
243                         $target_uid = $target_self['uid'];
244
245                         // Check if the user has got this contact
246                         $cid = Contact::getIdForURL($owner['url'], $target_uid);
247                         if (!$cid) {
248                                 // Otherwise there should be a public contact
249                                 $cid = Contact::getIdForURL($owner['url']);
250                                 if (!$cid) {
251                                         return;
252                                 }
253                         }
254
255                         // We now have some contact, so we fetch it
256                         $target_importer = dba::fetch_first("SELECT *, `name` as `senderName`
257                                                         FROM `contact`
258                                                         WHERE NOT `blocked` AND `id` = ? LIMIT 1",
259                                                         $cid);
260
261                         // This should never fail
262                         if (!DBM::is_result($target_importer)) {
263                                 return;
264                         }
265
266                         // Set the user id. This is important if this is a public contact
267                         $target_importer['importer_uid']  = $target_uid;
268                         DFRN::import($atom, $target_importer);
269                         return;
270                 }
271
272                 // We don't have a relationship with contacts on a public post.
273                 // Se we transmit with the new method and via Diaspora as a fallback
274                 if (($items[0]['uid'] == 0) || ($contact['uid'] == 0)) {
275                         // Transmit in public if it's a relay post
276                         $public_dfrn = ($contact['contact-type'] == ACCOUNT_TYPE_RELAY);
277
278                         $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
279
280                         // We never spool failed relay deliveries
281                         if ($public_dfrn) {
282                                 logger('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
283                                 return;
284                         }
285
286                         if (($deliver_status < 200) || ($deliver_status > 299)) {
287                                 // Transmit via Diaspora if not possible via Friendica
288                                 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
289                                 return;
290                         }
291                 } else {
292                         $deliver_status = DFRN::deliver($owner, $contact, $atom);
293                 }
294
295                 logger('Delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
296
297                 if ($deliver_status < 0) {
298                         logger('Delivery failed: queuing message ' . $target_item["guid"] );
299                         Queue::add($contact['id'], NETWORK_DFRN, $atom, false, $target_item['guid']);
300                 }
301
302                 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
303                         // We successfully delivered a message, the contact is alive
304                         Contact::unmarkForArchival($contact);
305                 } else {
306                         // The message could not be delivered. We mark the contact as "dead"
307                         Contact::markForArchival($contact);
308                 }
309         }
310
311         /**
312          * @brief Deliver content via Diaspora
313          *
314          * @param string  $cmd            Command
315          * @param array   $contact        Contact record of the receiver
316          * @param array   $owner          Owner record of the sender
317          * @param array   $items          Item record of the content and the parent
318          * @param array   $target_item    Item record of the content
319          * @param boolean $public_message Is the content public?
320          * @param boolean $top_level      Is it a thread starter?
321          * @param boolean $followup       Is it an answer to a remote post?
322          */
323         private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
324         {
325                 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
326                 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != ACCOUNT_TYPE_COMMUNITY);
327
328                 if ($public_message) {
329                         $loc = 'public batch ' . $contact['batch'];
330                 } else {
331                         $loc = $contact['addr'];
332                 }
333
334                 logger('Deliver ' . $target_item["guid"] . ' via Diaspora to ' . $loc);
335
336                 if (Config::get('system', 'dfrn_only') || !Config::get('system', 'diaspora_enabled')) {
337                         return;
338                 }
339                 if ($cmd == self::MAIL) {
340                         Diaspora::sendMail($target_item, $owner, $contact);
341                         return;
342                 }
343
344                 if ($cmd == self::SUGGESTION) {
345                         return;
346                 }
347                 if (!$contact['pubkey'] && !$public_message) {
348                         return;
349                 }
350                 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
351                         // top-level retraction
352                         logger('diaspora retract: ' . $loc);
353                         Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
354                         return;
355                 } elseif ($cmd == self::RELOCATION) {
356                         Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
357                         return;
358                 } elseif ($followup) {
359                         // send comments and likes to owner to relay
360                         logger('diaspora followup: ' . $loc);
361                         Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
362                         return;
363                 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
364                         // we are the relay - send comments, likes and relayable_retractions to our conversants
365                         logger('diaspora relay: ' . $loc);
366                         Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
367                         return;
368                 } elseif ($top_level && !$walltowall) {
369                         // currently no workable solution for sending walltowall
370                         logger('diaspora status: ' . $loc);
371                         Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
372                         return;
373                 }
374
375                 logger('Unknown mode ' . $cmd . ' for ' . $loc);
376         }
377
378         /**
379          * @brief Deliver content via mail
380          *
381          * @param string $cmd         Command
382          * @param array  $contact     Contact record of the receiver
383          * @param array  $owner       Owner record of the sender
384          * @param array  $target_item Item record of the content
385          */
386         private static function deliverMail($cmd, $contact, $owner, $target_item)
387         {
388                 if (Config::get('system','dfrn_only')) {
389                         return;
390                 }
391                 // WARNING: does not currently convert to RFC2047 header encodings, etc.
392
393                 $addr = $contact['addr'];
394                 if (!strlen($addr)) {
395                         return;
396                 }
397
398                 if (!in_array($cmd, [self::POST, self::COMMENT])) {
399                         return;
400                 }
401
402                 $local_user = dba::selectFirst('user', [], ['uid' => $owner['uid']]);
403                 if (!DBM::is_result($local_user)) {
404                         return;
405                 }
406
407                 logger('Deliver ' . $target_item["guid"] . ' via mail to ' . $contact['addr']);
408
409                 $reply_to = '';
410                 $mailacct = dba::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
411                 if (DBM::is_result($mailacct) && !empty($mailacct['reply_to'])) {
412                         $reply_to = $mailacct['reply_to'];
413                 }
414
415                 $subject  = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : L10n::t("\x28no subject\x29"));
416
417                 // only expose our real email address to true friends
418
419                 if (($contact['rel'] == CONTACT_IS_FRIEND) && !$contact['blocked']) {
420                         if ($reply_to) {
421                                 $headers  = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to.'>' . "\n";
422                                 $headers .= 'Sender: ' . $local_user['email'] . "\n";
423                         } else {
424                                 $headers  = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8').' <' . $local_user['email'] . '>' . "\n";
425                         }
426                 } else {
427                         $headers  = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <noreply@' . self::getApp()->get_hostname() . '>' . "\n";
428                 }
429
430                 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
431
432                 if ($target_item['uri'] !== $target_item['parent-uri']) {
433                         $headers .= "References: <" . Email::iri2msgid($target_item["parent-uri"]) . ">";
434
435                         // If Threading is enabled, write down the correct parent
436                         if (($target_item["thr-parent"] != "") && ($target_item["thr-parent"] != $target_item["parent-uri"])) {
437                                 $headers .= " <".Email::iri2msgid($target_item["thr-parent"]).">";
438                         }
439                         $headers .= "\n";
440
441                         if (empty($target_item['title'])) {
442                                 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
443                                 $title = dba::selectFirst('item', ['title'], $condition);
444                                 if (DBM::is_result($title) && ($title['title'] != '')) {
445                                         $subject = $title['title'];
446                                 } else {
447                                         $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
448                                         $title = dba::selectFirst('item', ['title'], $condition);
449                                         if (DBM::is_result($title) && ($title['title'] != '')) {
450                                                 $subject = $title['title'];
451                                         }
452                                 }
453                         }
454                         if (strncasecmp($subject, 'RE:', 3)) {
455                                 $subject = 'Re: ' . $subject;
456                         }
457                 }
458                 Email::send($addr, $subject, $headers, $target_item);
459         }
460 }