]> git.mxchange.org Git - friendica.git/blob - include/delivery.php
677d893889ce79a6be6ff93815d57d9a52ac09e4
[friendica.git] / include / delivery.php
1 <?php
2 require_once("boot.php");
3 require_once('include/queue_fn.php');
4
5 function delivery_run($argv, $argc){
6         global $a, $db;
7
8         if(is_null($a)){
9                 $a = new App;
10         }
11   
12         if(is_null($db)) {
13                 @include(".htconfig.php");
14                 require_once("dba.php");
15                 $db = new dba($db_host, $db_user, $db_pass, $db_data);
16                         unset($db_host, $db_user, $db_pass, $db_data);
17         }
18
19         require_once("session.php");
20         require_once("datetime.php");
21         require_once('include/items.php');
22         require_once('include/bbcode.php');
23         require_once('include/diaspora.php');
24         require_once('include/email.php');
25
26         load_config('config');
27         load_config('system');
28
29         load_hooks();
30
31         if($argc < 3)
32                 return;
33
34         $a->set_baseurl(get_config('system','url'));
35
36         logger('delivery: invoked: ' . print_r($argv,true), LOGGER_DEBUG);
37
38         $cmd        = $argv[1];
39         $item_id    = intval($argv[2]);
40         $contact_id = intval($argv[3]);
41
42         // Some other process may have delivered this item already.
43
44         $r = q("select * from deliverq where cmd = '%s' and item = %d and contact = %d limit 1",
45                 dbesc($cmd),
46                 dbesc($item_id),
47                 dbesc($contact_id)
48         );
49         if(! count($r)) {
50                 return;
51         }       
52
53         // It's ours to deliver. Remove it from the queue.
54
55         q("delete from deliverq where cmd = '%s' and item = %d and contact = %d limit 1",
56                 dbesc($cmd),
57                 dbesc($item_id),
58                 dbesc($contact_id)
59         );
60
61         if((! $item_id) || (! $contact_id))
62                 return;
63
64         $expire = false;
65         $top_level = false;
66         $recipients = array();
67         $url_recipients = array();
68
69         $normal_mode = true;
70
71         $recipients[] = $contact_id;
72
73         if($cmd === 'expire') {
74                 $normal_mode = false;
75                 $expire = true;
76                 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1 
77                         AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 30 MINUTE",
78                         intval($item_id)
79                 );
80                 $uid = $item_id;
81                 $item_id = 0;
82                 if(! count($items))
83                         return;
84         }
85         else {
86
87                 // find ancestors
88                 $r = q("SELECT * FROM `item` WHERE `id` = %d and visible = 1 and moderated = 0 LIMIT 1",
89                         intval($item_id)
90                 );
91
92                 if((! count($r)) || (! intval($r[0]['parent']))) {
93                         return;
94                 }
95
96                 $target_item = $r[0];
97                 $parent_id = intval($r[0]['parent']);
98                 $uid = $r[0]['uid'];
99                 $updated = $r[0]['edited'];
100
101                 if(! $parent_id)
102                         return;
103
104
105                 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer` 
106                         FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d and visible = 1 and moderated = 0 ORDER BY `id` ASC",
107                         intval($parent_id)
108                 );
109
110                 if(! count($items)) {
111                         return;
112                 }
113
114                 $icontacts = null;
115                 $contacts_arr = array();
116                 foreach($items as $item)
117                         if(! in_array($item['contact-id'],$contacts_arr))
118                                 $contacts_arr[] = intval($item['contact-id']);
119                 if(count($contacts_arr)) {
120                         $str_contacts = implode(',',$contacts_arr); 
121                         $icontacts = q("SELECT * FROM `contact` 
122                                 WHERE `id` IN ( $str_contacts ) "
123                         );
124                 }
125                 if( ! ($icontacts && count($icontacts)))
126                         return;
127
128                 // avoid race condition with deleting entries
129
130                 if($items[0]['deleted']) {
131                         foreach($items as $item)
132                                 $item['deleted'] = 1;
133                 }
134
135                 if((count($items) == 1) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
136                         logger('delivery: top level post');
137                         $top_level = true;
138                 }
139         }
140
141         $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`, 
142                 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`, 
143                 `user`.`page-flags`, `user`.`prvnets`
144                 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid` 
145                 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
146                 intval($uid)
147         );
148
149         if(! count($r))
150                 return;
151
152         $owner = $r[0];
153
154         $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
155
156         $public_message = true;
157
158         // fill this in with a single salmon slap if applicable
159
160         $slap = '';
161
162         require_once('include/group.php');
163
164         $parent = $items[0];
165
166                 // This is IMPORTANT!!!!
167
168                 // We will only send a "notify owner to relay" or followup message if the referenced post
169                 // originated on our system by virtue of having our hostname somewhere
170                 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
171                 // if $parent['wall'] == 1 we will already have the parent message in our array
172                 // and we will relay the whole lot.
173  
174                 // expire sends an entire group of expire messages and cannot be forwarded.
175                 // However the conversation owner will be a part of the conversation and will 
176                 // be notified during this run.
177                 // Other DFRN conversation members will be alerted during polled updates.
178
179                 // Diaspora members currently are not notified of expirations, and other networks have
180                 // either limited or no ability to process deletions. We should at least fix Diaspora 
181                 // by stringing togther an array of retractions and sending them onward.
182                  
183         
184         $localhost = $a->get_hostname();
185         if(strpos($localhost,':'))
186                 $localhost = substr($localhost,0,strpos($localhost,':'));
187
188                 /**
189                  *
190                  * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes 
191                  * have been known to cause runaway conditions which affected several servers, along with 
192                  * permissions issues. 
193                  *
194                  */
195  
196         if((! $top_level) && ($parent['wall'] == 0) && (! $expire) && (stristr($target_item['uri'],$localhost))) {
197                 logger('relay denied for delivery agent.');
198
199                 /* no relay allowed for direct contact delivery */
200                 return;
201         }
202
203         if((strlen($parent['allow_cid'])) 
204                 || (strlen($parent['allow_gid'])) 
205                 || (strlen($parent['deny_cid'])) 
206                 || (strlen($parent['deny_gid']))) {
207                 $public_message = false; // private recipients, not public
208         }
209
210         $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `blocked` = 0 AND `pending` = 0",
211                 intval($contact_id)
212         );
213
214         if(count($r))
215                 $contact = $r[0];
216         
217         $hubxml = feed_hublinks();
218
219         logger('notifier: slaps: ' . print_r($slaps,true), LOGGER_DATA);
220
221         require_once('include/salmon.php');
222
223         if($contact['self'])
224                 return;
225
226         $deliver_status = 0;
227
228         switch($contact['network']) {
229
230                 case NETWORK_DFRN :
231                         logger('notifier: dfrndelivery: ' . $contact['name']);
232
233                         $feed_template = get_markup_template('atom_feed.tpl');
234                         $mail_template = get_markup_template('atom_mail.tpl');
235
236                         $atom = '';
237
238
239                         $birthday = feed_birthday($owner['uid'],$owner['timezone']);
240
241                         if(strlen($birthday))
242                                 $birthday = '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>';
243
244                         $atom .= replace_macros($feed_template, array(
245                                         '$version'      => xmlify(FRIENDICA_VERSION),
246                                         '$feed_id'      => xmlify($a->get_baseurl() . '/profile/' . $owner['nickname'] ),
247                                         '$feed_title'   => xmlify($owner['name']),
248                                         '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00' , ATOM_TIME)) ,
249                                         '$hub'          => $hubxml,
250                                         '$salmon'       => '',  // private feed, we don't use salmon here
251                                         '$name'         => xmlify($owner['name']),
252                                         '$profile_page' => xmlify($owner['url']),
253                                         '$photo'        => xmlify($owner['photo']),
254                                         '$thumb'        => xmlify($owner['thumb']),
255                                         '$picdate'      => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
256                                         '$uridate'      => xmlify(datetime_convert('UTC','UTC',$owner['uri-date']    . '+00:00' , ATOM_TIME)) ,
257                                         '$namdate'      => xmlify(datetime_convert('UTC','UTC',$owner['name-date']   . '+00:00' , ATOM_TIME)) ,
258                                         '$birthday'     => $birthday
259                         ));
260
261                         foreach($items as $item) {
262                                 if(! $item['parent'])
263                                         continue;
264
265                                 // private emails may be in included in public conversations. Filter them.
266                                 if(($public_message) && $item['private'])
267                                         continue;
268
269                                 $item_contact = get_item_contact($item,$icontacts);
270                                 if(! $item_contact)
271                                         continue;
272
273                                 if($normal_mode) {
274                                         if($item_id == $item['id'] || $item['id'] == $item['parent'])
275                                                 $atom .= atom_entry($item,'text',$item_contact,$owner,true);
276                                 }
277                                 else
278                                         $atom .= atom_entry($item,'text',$item_contact,$owner,true);
279
280                         }
281
282                         $atom .= '</feed>' . "\r\n";
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,$a->get_baseurl())) {
290
291                                 $nickname = basename($contact['url']);
292                                 if($contact['issued-id'])
293                                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
294                                 else
295                                         $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
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                                         LEFT 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 LIMIT 1",
310                                         dbesc(NETWORK_DFRN),
311                                         dbesc($nickname)
312                                 );
313
314                                 if(count($x)) {
315                                         if($owner['page-flags'] == PAGE_COMMUNITY && ! $x[0]['writable']) {
316                                                 q("update contact set writable = 1 where id = %d limit 1",
317                                                         intval($x[0]['id'])
318                                                 );
319                                                 $x[0]['writable'] = 1;
320                                         }
321
322                                         require_once('library/simplepie/simplepie.inc');
323                                         logger('mod-delivery: local delivery');
324                                         local_delivery($x[0],$atom);
325                                         break;                                  
326                                 }
327                         }
328
329                         $deliver_status = dfrn_deliver($owner,$contact,$atom);
330
331                         logger('notifier: dfrn_delivery returns ' . $deliver_status);
332         
333                         if($deliver_status == (-1)) {
334                                 logger('notifier: delivery failed: queuing message');
335                                 add_to_queue($contact['id'],NETWORK_DFRN,$atom);
336                         }
337                         break;
338
339                 case NETWORK_OSTATUS :
340
341                         // Do not send to otatus if we are not configured to send to public networks
342                         if($owner['prvnets'])
343                                 break;
344                         if(get_config('system','ostatus_disabled') || get_config('system','dfrn_only'))
345                                 break;
346
347                         // only send salmon if public - e.g. if it's ok to notify
348                         // a public hub, it's ok to send a salmon
349
350                         if(($public_message) && (! $expire)) {
351                                 $slaps = array();
352
353                                 foreach($items as $item) {
354                                         if(! $item['parent'])
355                                                 continue;
356
357                                         // private emails may be in included in public conversations. Filter them.
358                                         if(($public_message) && $item['private'])
359                                                 continue;
360
361                                         $item_contact = get_item_contact($item,$icontacts);
362                                         if(! $item_contact)
363                                                 continue;
364
365                                         if(($top_level) && ($public_message) && ($item['author-link'] === $item['owner-link']) && (! $expire)) 
366                                                 $slaps[] = atom_entry($item,'html',$item_contact,$owner,true);
367                                 }
368
369                                 logger('notifier: slapdelivery: ' . $contact['name']);
370                                 foreach($slaps as $slappy) {
371                                         if($contact['notify']) {
372                                                 $deliver_status = slapper($owner,$contact['notify'],$slappy);
373                                                 if($deliver_status == (-1)) {
374                                                         // queue message for redelivery
375                                                         add_to_queue($contact['id'],NETWORK_OSTATUS,$slappy);
376                                                 }
377                                         }
378                                 }
379                         }
380
381                         break;
382
383                 case NETWORK_MAIL :
384                 case NETWORK_MAIL2:
385                                 
386                         if(get_config('system','dfrn_only'))
387                                 break;
388                         // WARNING: does not currently convert to RFC2047 header encodings, etc.
389
390                         $addr = $contact['addr'];
391                         if(! strlen($addr))
392                                 break;
393
394                         if($cmd === 'wall-new' || $cmd === 'comment-new') {
395
396                                 $it = null;
397                                 if($cmd === 'wall-new') 
398                                         $it = $items[0];
399                                 else {
400                                         $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", 
401                                                 intval($argv[2]),
402                                                 intval($uid)
403                                         );
404                                         if(count($r))
405                                                 $it = $r[0];
406                                 }
407                                 if(! $it)
408                                         break;
409                                         
410
411                                 $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
412                                         intval($uid)
413                                 );
414                                 if(! count($local_user))
415                                         break;
416                                         
417                                 $reply_to = '';
418                                 $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
419                                         intval($uid)
420                                 );
421                                 if($r1 && $r1[0]['reply_to'])
422                                         $reply_to = $r1[0]['reply_to'];
423
424                                 $subject  = (($it['title']) ? email_header_encode($it['title'],'UTF-8') : t("\x28no subject\x29")) ;
425
426                                 // only expose our real email address to true friends
427
428                                 if(($contact['rel'] == CONTACT_IS_FRIEND) && (! $contact['blocked']))
429                                         $headers  = 'From: ' . email_header_encode($local_user[0]['username'],'UTF-8') . ' <' . $local_user[0]['email'] . '>' . "\n";
430                                 else
431                                         $headers  = 'From: ' . email_header_encode($local_user[0]['username'],'UTF-8') . ' <' . t('noreply') . '@' . $a->get_hostname() . '>' . "\n";
432
433                                 if($reply_to)
434                                         $headers .= 'Reply-to: ' . $reply_to . "\n";
435                                 $headers .= 'Message-id: <' . $it['uri'] . '>' . "\n";
436                                 if($it['uri'] !== $it['parent-uri']) {
437                                         $header .= 'References: <' . $it['parent-uri'] . '>' . "\n";
438                                         if(! strlen($it['title'])) {
439                                                 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' LIMIT 1",
440                                                         dbesc($it['parent-uri'])
441                                                 );
442                                                 if(count($r)) {
443                                                         $subtitle = $r[0]['title'];
444                                                         if($subtitle) {
445                                                                 if(strncasecmp($subtitle,'RE:',3))
446                                                                         $subject = $subtitle;
447                                                                 else
448                                                                         $subject = 'Re: ' . $subtitle;
449                                                         }
450                                                 }
451                                         }
452                                 }
453                                 $headers .= 'MIME-Version: 1.0' . "\n";
454                                 $headers .= 'Content-Type: text/html; charset=UTF-8' . "\n";
455                                 $headers .= 'Content-Transfer-Encoding: 8bit' . "\n\n";
456                                 $html    = prepare_body($it);
457                                 $message = '<html><body>' . $html . '</body></html>';
458                                 logger('notifier: email delivery to ' . $addr);
459                                 mail($addr, $subject, $message, $headers);
460                         }
461                         break;
462
463                 case NETWORK_DIASPORA :
464                         if($public_message)
465                                 $loc = 'public batch ' . $contact['batch'];
466                         else 
467                                 $loc = $contact['name'];
468
469                         logger('delivery: diaspora batch deliver: ' . $loc);
470
471                         if(get_config('system','dfrn_only') || (! get_config('system','diaspora_enabled')) || (! $normal_mode))
472                                 break;
473
474                         if((! $contact['pubkey']) && (! $public_message))
475                                 break;
476                                         
477                         if($target_item['verb'] === ACTIVITY_DISLIKE) {
478                                 // unsupported
479                                 break;
480                         }
481                         elseif(($target_item['deleted']) && ($target_item['verb'] !== ACTIVITY_LIKE)) {
482                         logger('delivery: diaspora retract: ' . $loc);
483                                 // diaspora delete, 
484                                 diaspora_send_retraction($target_item,$owner,$contact,$public_message);
485                                 break;
486                         }
487                         elseif($target_item['parent'] != $target_item['id']) {
488
489                         logger('delivery: diaspora relay: ' . $loc);
490
491                                 // we are the relay - send comments, likes and unlikes to our conversants
492                                 diaspora_send_relay($target_item,$owner,$contact,$public_message);
493                                 break;
494                         }               
495                         elseif(($top_level) && (! $walltowall)) {
496                                 // currently no workable solution for sending walltowall
497                                 logger('delivery: diaspora status: ' . $loc);
498                                 diaspora_send_status($target_item,$owner,$contact,$public_message);
499                                 break;
500                         }
501
502                         logger('delivery: diaspora unknown mode: ' . $contact['name']);
503
504                         break;
505
506                 case NETWORK_FEED :
507                 case NETWORK_FACEBOOK :
508                         if(get_config('system','dfrn_only'))
509                                 break;
510                 default:
511                         break;
512         }
513
514         return;
515 }
516
517 if (array_search(__file__,get_included_files())===0){
518   delivery_run($argv,$argc);
519   killme();
520 }