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