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