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