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