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