]> git.mxchange.org Git - friendica.git/blob - src/Worker/Delivery.php
Update functions and calls
[friendica.git] / src / Worker / Delivery.php
1 <?php
2 /**
3  * @file src/Worker/Delivery.php
4  */
5 namespace Friendica\Worker;
6
7 use Friendica\App;
8 use Friendica\Core\System;
9 use Friendica\Core\Config;
10 use Friendica\Database\DBM;
11 use Friendica\Model\Contact;
12 use Friendica\Model\Queue;
13 use Friendica\Model\User;
14 use Friendica\Protocol\Diaspora;
15 use Friendica\Protocol\DFRN;
16 use Friendica\Protocol\Email;
17 use dba;
18
19 require_once 'include/html2plain.php';
20 require_once 'include/datetime.php';
21 require_once 'include/items.php';
22 require_once 'include/bbcode.php';
23
24 /// @todo This is some ugly code that needs to be split into several methods
25
26 class Delivery {
27         public static function execute($cmd, $item_id, $contact_id) {
28                 global $a;
29
30                 logger('delivery: invoked: '.$cmd.': '.$item_id.' to '.$contact_id, LOGGER_DEBUG);
31
32                 $expire = false;
33                 $mail = false;
34                 $fsuggest = false;
35                 $relocate = false;
36                 $top_level = false;
37                 $recipients = [];
38                 $url_recipients = [];
39                 $followup = false;
40
41                 $normal_mode = true;
42
43                 $recipients[] = $contact_id;
44
45                 if ($cmd === 'mail') {
46                         $normal_mode = false;
47                         $mail = true;
48                         $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
49                                         intval($item_id)
50                         );
51                         if (!count($message)) {
52                                 return;
53                         }
54                         $uid = $message[0]['uid'];
55                         $recipients[] = $message[0]['contact-id'];
56                         $item = $message[0];
57                 } elseif ($cmd === 'expire') {
58                         $normal_mode = false;
59                         $expire = true;
60                         $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
61                                 AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 30 MINUTE",
62                                 intval($item_id)
63                         );
64                         $uid = $item_id;
65                         $item_id = 0;
66                         if (!count($items)) {
67                                 return;
68                         }
69                 } elseif ($cmd === 'suggest') {
70                         $normal_mode = false;
71                         $fsuggest = true;
72
73                         $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
74                                 intval($item_id)
75                         );
76                         if (!count($suggest)) {
77                                 return;
78                         }
79                         $uid = $suggest[0]['uid'];
80                         $recipients[] = $suggest[0]['cid'];
81                         $item = $suggest[0];
82                 } elseif ($cmd === 'relocate') {
83                         $normal_mode = false;
84                         $relocate = true;
85                         $uid = $item_id;
86                 } else {
87                         // find ancestors
88                         $target_item = dba::fetch_first("SELECT `item`.*, `contact`.`uid` AS `cuid` FROM `item`
89                                                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
90                                                         WHERE `item`.`id` = ? AND `visible` AND NOT `moderated`", $item_id);
91
92                         if (!DBM::is_result($target_item) || !intval($target_item['parent'])) {
93                                 return;
94                         }
95
96                         $parent_id = intval($target_item['parent']);
97                         $uid = $target_item['cuid'];
98                         $updated = $target_item['edited'];
99
100                         $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
101                                 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d AND visible = 1 AND moderated = 0 ORDER BY `id` ASC",
102                                 intval($parent_id)
103                         );
104
105                         if (!count($items)) {
106                                 return;
107                         }
108
109                         $icontacts = null;
110                         $contacts_arr = [];
111                         foreach ($items as $item) {
112                                 if (!in_array($item['contact-id'],$contacts_arr)) {
113                                         $contacts_arr[] = intval($item['contact-id']);
114                                 }
115                         }
116                         if (count($contacts_arr)) {
117                                 $str_contacts = implode(',',$contacts_arr);
118                                 $icontacts = q("SELECT * FROM `contact`
119                                         WHERE `id` IN ( $str_contacts ) "
120                                 );
121                         }
122                         if ( !($icontacts && count($icontacts))) {
123                                 return;
124                         }
125
126                         // avoid race condition with deleting entries
127
128                         if ($items[0]['deleted']) {
129                                 foreach ($items as $item) {
130                                         $item['deleted'] = 1;
131                                 }
132                         }
133
134                         // When commenting too fast after delivery, a post wasn't recognized as top level post.
135                         // The count then showed more than one entry. The additional check should help.
136                         // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
137                         if ((($items[0]['id'] == $item_id) || (count($items) == 1)) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
138                                 logger('delivery: top level post');
139                                 $top_level = true;
140                         }
141                 }
142
143                 $owner = User::getOwnerDataById($uid);
144                 if (!$owner) {
145                         return;
146                 }
147
148                 $walltowall = (($top_level && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
149
150                 $public_message = true;
151
152                 if (!$mail && !$fsuggest && !$relocate) {
153                         $parent = $items[0];
154
155                         // This is IMPORTANT!!!!
156
157                         // We will only send a "notify owner to relay" or followup message if the referenced post
158                         // originated on our system by virtue of having our hostname somewhere
159                         // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
160                         // if $parent['wall'] == 1 we will already have the parent message in our array
161                         // and we will relay the whole lot.
162
163                         // expire sends an entire group of expire messages and cannot be forwarded.
164                         // However the conversation owner will be a part of the conversation and will
165                         // be notified during this run.
166                         // Other DFRN conversation members will be alerted during polled updates.
167
168                         // Diaspora members currently are not notified of expirations, and other networks have
169                         // either limited or no ability to process deletions. We should at least fix Diaspora
170                         // by stringing togther an array of retractions and sending them onward.
171
172
173                         $localhost = $a->get_hostname();
174                         if (strpos($localhost,':')) {
175                                 $localhost = substr($localhost,0,strpos($localhost,':'));
176                         }
177                         /**
178                          *
179                          * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
180                          * have been known to cause runaway conditions which affected several servers, along with
181                          * permissions issues.
182                          *
183                          */
184
185                         $relay_to_owner = false;
186
187                         if (!$top_level && ($parent['wall'] == 0) && !$expire && stristr($target_item['uri'],$localhost)) {
188                                 $relay_to_owner = true;
189                         }
190
191                         if ($relay_to_owner) {
192                                 logger('followup '.$target_item["guid"], LOGGER_DEBUG);
193                                 // local followup to remote post
194                                 $followup = true;
195                         }
196
197                         if (strlen($parent['allow_cid'])
198                                 || strlen($parent['allow_gid'])
199                                 || strlen($parent['deny_cid'])
200                                 || strlen($parent['deny_gid'])
201                                 || $parent["private"]) {
202                                 $public_message = false; // private recipients, not public
203                         }
204
205                 }
206
207                 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `blocked` = 0 AND `pending` = 0",
208                         intval($contact_id)
209                 );
210
211                 if (DBM::is_result($r)) {
212                         $contact = $r[0];
213                 }
214                 if ($contact['self']) {
215                         return;
216                 }
217                 $deliver_status = 0;
218
219                 // Transmit via Diaspora if not possible via Friendica
220                 if (($item['uid'] == 0) && ($contact['network'] == NETWORK_DFRN)) {
221                         $contact['network'] = NETWORK_DIASPORA;
222                 }
223
224                 logger("main delivery by delivery: followup=$followup mail=$mail fsuggest=$fsuggest relocate=$relocate - network ".$contact['network']);
225
226                 switch ($contact['network']) {
227
228                         case NETWORK_DFRN:
229                                 logger('notifier: '.$target_item["guid"].' dfrndelivery: '.$contact['name']);
230
231                                 if ($mail) {
232                                         $item['body'] = fix_private_photos($item['body'],$owner['uid'],null,$message[0]['contact-id']);
233                                         $atom = DFRN::mail($item, $owner);
234                                 } elseif ($fsuggest) {
235                                         $atom = DFRN::fsuggest($item, $owner);
236                                         q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1", intval($item['id']));
237                                 } elseif ($relocate) {
238                                         $atom = DFRN::relocate($owner, $uid);
239                                 } elseif ($followup) {
240                                         $msgitems = [];
241                                         foreach ($items as $item) {  // there is only one item
242                                                 if (!$item['parent']) {
243                                                         return;
244                                                 }
245                                                 if ($item['id'] == $item_id) {
246                                                         logger('followup: item: '. print_r($item,true), LOGGER_DATA);
247                                                         $msgitems[] = $item;
248                                                 }
249                                         }
250                                         $atom = DFRN::entries($msgitems,$owner);
251                                 } else {
252                                         $msgitems = [];
253                                         foreach ($items as $item) {
254                                                 if (!$item['parent']) {
255                                                         return;
256                                                 }
257
258                                                 // private emails may be in included in public conversations. Filter them.
259                                                 if ($public_message && $item['private']) {
260                                                         return;
261                                                 }
262
263                                                 $item_contact = get_item_contact($item,$icontacts);
264                                                 if (!$item_contact) {
265                                                         return;
266                                                 }
267
268                                                 if ($normal_mode) {
269                                                         if ($item_id == $item['id'] || $item['id'] == $item['parent']) {
270                                                                 $item["entry:comment-allow"] = true;
271                                                                 $item["entry:cid"] = (($top_level) ? $contact['id'] : 0);
272                                                                 $msgitems[] = $item;
273                                                         }
274                                                 } else {
275                                                         $item["entry:comment-allow"] = true;
276                                                         $msgitems[] = $item;
277                                                 }
278                                         }
279                                         $atom = DFRN::entries($msgitems,$owner);
280                                 }
281
282                                 logger('notifier entry: '.$contact["url"].' '.$target_item["guid"].' entry: '.$atom, LOGGER_DEBUG);
283
284                                 logger('notifier: '.$atom, LOGGER_DATA);
285                                 $basepath =  implode('/', array_slice(explode('/',$contact['url']),0,3));
286
287                                 // perform local delivery if we are on the same site
288
289                                 if (link_compare($basepath,System::baseUrl())) {
290                                         $nickname = basename($contact['url']);
291                                         if ($contact['issued-id']) {
292                                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
293                                         } else {
294                                                 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
295                                         }
296
297                                         $x = q("SELECT  `contact`.*, `contact`.`uid` AS `importer_uid`,
298                                                 `contact`.`pubkey` AS `cpubkey`,
299                                                 `contact`.`prvkey` AS `cprvkey`,
300                                                 `contact`.`thumb` AS `thumb`,
301                                                 `contact`.`url` as `url`,
302                                                 `contact`.`name` as `senderName`,
303                                                 `user`.*
304                                                 FROM `contact`
305                                                 INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
306                                                 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
307                                                 AND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'
308                                                 $sql_extra
309                                                 AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 LIMIT 1",
310                                                 dbesc(NETWORK_DFRN),
311                                                 dbesc($nickname)
312                                         );
313
314                                         if ($x && count($x)) {
315                                                 $write_flag = ((($x[0]['rel']) && ($x[0]['rel'] != CONTACT_IS_SHARING)) ? true : false);
316                                                 if ((($owner['page-flags'] == PAGE_COMMUNITY) || $write_flag) && !$x[0]['writable']) {
317                                                         q("UPDATE `contact` SET `writable` = 1 WHERE `id` = %d",
318                                                                 intval($x[0]['id'])
319                                                         );
320                                                         $x[0]['writable'] = 1;
321                                                 }
322
323                                                 $ssl_policy = Config::get('system','ssl_policy');
324                                                 fix_contact_ssl_policy($x[0],$ssl_policy);
325
326                                                 // If we are setup as a soapbox we aren't accepting top level posts from this person
327
328                                                 if (($x[0]['page-flags'] == PAGE_SOAPBOX) && $top_level) {
329                                                         break;
330                                                 }
331                                                 logger('mod-delivery: local delivery');
332                                                 DFRN::import($atom, $x[0]);
333                                                 break;
334                                         }
335                                 }
336
337                                 if (!Queue::wasDelayed($contact['id'])) {
338                                         $deliver_status = DFRN::deliver($owner, $contact, $atom);
339                                 } else {
340                                         $deliver_status = (-1);
341                                 }
342
343                                 logger('notifier: dfrn_delivery to '.$contact["url"].' with guid '.$target_item["guid"].' returns '.$deliver_status);
344
345                                 if ($deliver_status < 0) {
346                                         logger('notifier: delivery failed: queuing message');
347                                         Queue::add($contact['id'], NETWORK_DFRN, $atom);
348
349                                         // The message could not be delivered. We mark the contact as "dead"
350                                         Contact::markForArchival($contact);
351                                 } else {
352                                         // We successfully delivered a message, the contact is alive
353                                         Contact::unmarkForArchival($contact);
354                                 }
355
356                                 break;
357
358                         case NETWORK_OSTATUS:
359                                 // Do not send to otatus if we are not configured to send to public networks
360                                 if ($owner['prvnets']) {
361                                         break;
362                                 }
363                                 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
364                                         break;
365                                 }
366
367                                 // There is currently no code here to distribute anything to OStatus.
368                                 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
369                                 break;
370
371                         case NETWORK_MAIL:
372
373                                 if (Config::get('system','dfrn_only')) {
374                                         break;
375                                 }
376                                 // WARNING: does not currently convert to RFC2047 header encodings, etc.
377
378                                 $addr = $contact['addr'];
379                                 if (!strlen($addr)) {
380                                         break;
381                                 }
382
383                                 if ($cmd === 'wall-new' || $cmd === 'comment-new') {
384                                         $it = null;
385                                         if ($cmd === 'wall-new') {
386                                                 $it = $items[0];
387                                         } else {
388                                                 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
389                                                         intval($item_id)
390                                                 );
391                                                 if (DBM::is_result($r)) {
392                                                         $it = $r[0];
393                                                 }
394                                         }
395                                         if (!$it) {
396                                                 break;
397                                         }
398
399                                         $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
400                                                 intval($uid)
401                                         );
402                                         if (!count($local_user)) {
403                                                 break;
404                                         }
405
406                                         $reply_to = '';
407                                         $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
408                                                 intval($uid)
409                                         );
410                                         if ($r1 && $r1[0]['reply_to']) {
411                                                 $reply_to = $r1[0]['reply_to'];
412                                         }
413
414                                         $subject  = (($it['title']) ? Email::encodeHeader($it['title'],'UTF-8') : t("\x28no subject\x29")) ;
415
416                                         // only expose our real email address to true friends
417
418                                         if (($contact['rel'] == CONTACT_IS_FRIEND) && !$contact['blocked']) {
419                                                 if ($reply_to) {
420                                                         $headers  = 'From: '.Email::encodeHeader($local_user[0]['username'],'UTF-8').' <'.$reply_to.'>'."\n";
421                                                         $headers .= 'Sender: '.$local_user[0]['email']."\n";
422                                                 } else {
423                                                         $headers  = 'From: '.Email::encodeHeader($local_user[0]['username'],'UTF-8').' <'.$local_user[0]['email'].'>'."\n";
424                                                 }
425                                         } else {
426                                                 $headers  = 'From: '. Email::encodeHeader($local_user[0]['username'],'UTF-8') .' <'. t('noreply') .'@'.$a->get_hostname() .'>'. "\n";
427                                         }
428
429                                         //if ($reply_to)
430                                         //      $headers .= 'Reply-to: '.$reply_to . "\n";
431
432                                         $headers .= 'Message-Id: <'. Email::iri2msgid($it['uri']).'>'. "\n";
433
434                                         //logger("Mail: uri: ".$it['uri']." parent-uri ".$it['parent-uri'], LOGGER_DEBUG);
435                                         //logger("Mail: Data: ".print_r($it, true), LOGGER_DEBUG);
436                                         //logger("Mail: Data: ".print_r($it, true), LOGGER_DATA);
437
438                                         if ($it['uri'] !== $it['parent-uri']) {
439                                                 $headers .= "References: <".Email::iri2msgid($it["parent-uri"]).">";
440
441                                                 // If Threading is enabled, write down the correct parent
442                                                 if (($it["thr-parent"] != "") && ($it["thr-parent"] != $it["parent-uri"])) {
443                                                         $headers .= " <".Email::iri2msgid($it["thr-parent"]).">";
444                                                 }
445                                                 $headers .= "\n";
446
447                                                 if (!$it['title']) {
448                                                         $r = q("SELECT `title` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
449                                                                 dbesc($it['parent-uri']),
450                                                                 intval($uid));
451
452                                                         if (DBM::is_result($r) && ($r[0]['title'] != '')) {
453                                                                 $subject = $r[0]['title'];
454                                                         } else {
455                                                                 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d LIMIT 1",
456                                                                         dbesc($it['parent-uri']),
457                                                                         intval($uid));
458
459                                                                 if (DBM::is_result($r) && ($r[0]['title'] != '')) {
460                                                                         $subject = $r[0]['title'];
461                                                                 }
462                                                         }
463                                                 }
464                                                 if (strncasecmp($subject,'RE:',3)) {
465                                                         $subject = 'Re: '.$subject;
466                                                 }
467                                         }
468                                         Email::send($addr, $subject, $headers, $it);
469                                 }
470                                 break;
471
472                         case NETWORK_DIASPORA:
473                                 if ($public_message) {
474                                         $loc = 'public batch '.$contact['batch'];
475                                 } else {
476                                         $loc = $contact['name'];
477                                 }
478
479                                 logger('delivery: diaspora batch deliver: '.$loc);
480
481                                 if (Config::get('system','dfrn_only') || !Config::get('system','diaspora_enabled')) {
482                                         break;
483                                 }
484                                 if ($mail) {
485                                         Diaspora::sendMail($item,$owner,$contact);
486                                         break;
487                                 }
488
489                                 if (!$normal_mode) {
490                                         break;
491                                 }
492                                 if (!$contact['pubkey'] && !$public_message) {
493                                         break;
494                                 }
495                                 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
496                                         // top-level retraction
497                                         logger('diaspora retract: '.$loc);
498                                         Diaspora::sendRetraction($target_item,$owner,$contact,$public_message);
499                                         break;
500                                 } elseif ($relocate) {
501                                         Diaspora::sendAccountMigration($owner, $contact, $uid);
502                                         break;
503                                 } elseif ($followup) {
504                                         // send comments and likes to owner to relay
505                                         logger('diaspora followup: '.$loc);
506                                         Diaspora::sendFollowup($target_item,$owner,$contact,$public_message);
507                                         break;
508                                 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
509                                         // we are the relay - send comments, likes and relayable_retractions to our conversants
510                                         logger('diaspora relay: '.$loc);
511                                         Diaspora::sendRelay($target_item,$owner,$contact,$public_message);
512                                         break;
513                                 } elseif ($top_level && !$walltowall) {
514                                         // currently no workable solution for sending walltowall
515                                         logger('diaspora status: '.$loc);
516                                         Diaspora::sendStatus($target_item,$owner,$contact,$public_message);
517                                         break;
518                                 }
519
520                                 logger('delivery: diaspora unknown mode: '.$contact['name']);
521
522                                 break;
523
524                         default:
525                                 break;
526                 }
527
528                 return;
529         }
530 }