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