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