]> git.mxchange.org Git - friendica.git/blob - include/delivery.php
5d81228ee47a9c26ba91beba1c92a101ca780b61
[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));
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
100
101                 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer` 
102                         FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d ORDER BY `id` ASC",
103                         intval($parent_id)
104                 );
105
106                 if(! count($items)) {
107                         return;
108                 }
109
110                 $icontacts = q("SELECT * FROM `contact` WHERE `id` IN ( SELECT distinct(`contact-id`) FROM `item` where `parent` = %d ) ",
111                         intval($parent_id)
112                 );
113                 if(! count($icontacts))
114                         return;
115
116
117                 // avoid race condition with deleting entries
118
119                 if($items[0]['deleted']) {
120                         foreach($items as $item)
121                                 $item['deleted'] = 1;
122                 }
123
124                 if((count($items) == 1) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
125                         logger('delivery: top level post');
126                         $top_level = true;
127                 }
128         }
129
130         $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`, 
131                 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`, 
132                 `user`.`page-flags`, `user`.`prvnets`
133                 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid` 
134                 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
135                 intval($uid)
136         );
137
138         if(! count($r))
139                 return;
140
141         $owner = $r[0];
142
143         $public_message = true;
144
145         // fill this in with a single salmon slap if applicable
146         $slap = '';
147
148         require_once('include/group.php');
149
150         $parent = $items[0];
151
152                 // This is IMPORTANT!!!!
153
154                 // We will only send a "notify owner to relay" or followup message if the referenced post
155                 // originated on our system by virtue of having our hostname somewhere
156                 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
157                 // if $parent['wall'] == 1 we will already have the parent message in our array
158                 // and we will relay the whole lot.
159  
160                 // expire sends an entire group of expire messages and cannot be forwarded.
161                 // However the conversation owner will be a part of the conversation and will 
162                 // be notified during this run.
163                 // Other DFRN conversation members will be alerted during polled updates.
164
165                 // Diaspora members currently are not notified of expirations, and other networks have
166                 // either limited or no ability to process deletions. We should at least fix Diaspora 
167                 // by stringing togther an array of retractions and sending them onward.
168                  
169         
170         $localhost = $a->get_hostname();
171         if(strpos($localhost,':'))
172                 $localhost = substr($localhost,0,strpos($localhost,':'));
173
174                 /**
175                  *
176                  * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes 
177                  * have been known to cause runaway conditions which affected several servers, along with 
178                  * permissions issues. 
179                  *
180                  */
181  
182         if((! $top_level) && ($parent['wall'] == 0) && (! $expire) && (stristr($target_item['uri'],$localhost))) {
183                 logger('relay denied for delivery agent.');
184
185                 /* no relay allowed for direct contact delivery */
186                 return;
187         }
188
189         if((strlen($parent['allow_cid'])) 
190                 || (strlen($parent['allow_gid'])) 
191                 || (strlen($parent['deny_cid'])) 
192                 || (strlen($parent['deny_gid']))) {
193                 $public_message = false; // private recipients, not public
194         }
195
196         $conversant_str = intval($contact_id);
197
198         $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `blocked` = 0 AND `pending` = 0",
199                 intval($contact_id)
200         );
201
202         if(count($r))
203                 $contact = $r[0];
204         
205
206         $feed_template = get_markup_template('atom_feed.tpl');
207         $mail_template = get_markup_template('atom_mail.tpl');
208
209         $atom = '';
210         $slaps = array();
211
212         $hubxml = feed_hublinks();
213
214         $birthday = feed_birthday($owner['uid'],$owner['timezone']);
215
216         if(strlen($birthday))
217                 $birthday = '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>';
218
219         $atom .= replace_macros($feed_template, array(
220                         '$version'      => xmlify(FRIENDIKA_VERSION),
221                         '$feed_id'      => xmlify($a->get_baseurl() . '/profile/' . $owner['nickname'] ),
222                         '$feed_title'   => xmlify($owner['name']),
223                         '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00' , ATOM_TIME)) ,
224                         '$hub'          => $hubxml,
225                         '$salmon'       => '',  // private feed, we don't use salmon here
226                         '$name'         => xmlify($owner['name']),
227                         '$profile_page' => xmlify($owner['url']),
228                         '$photo'        => xmlify($owner['photo']),
229                         '$thumb'        => xmlify($owner['thumb']),
230                         '$picdate'      => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
231                         '$uridate'      => xmlify(datetime_convert('UTC','UTC',$owner['uri-date']    . '+00:00' , ATOM_TIME)) ,
232                         '$namdate'      => xmlify(datetime_convert('UTC','UTC',$owner['name-date']   . '+00:00' , ATOM_TIME)) ,
233                         '$birthday'     => $birthday
234         ));
235
236         foreach($items as $item) {
237                 if(! $item['parent'])
238                         continue;
239
240                 // private emails may be in included in public conversations. Filter them.
241                 if(($public_message) && $item['private'])
242                         continue;
243
244                 $item_contact = get_item_contact($item,$icontacts);
245                 if(! $item_contact)
246                         continue;
247
248                 $atom .= atom_entry($item,'text',$item_contact,$owner,true);
249
250                 if(($top_level) && ($public_message) && ($item['author-link'] === $item['owner-link']) && (! $expire)) 
251                         $slaps[] = atom_entry($item,'html',$item_contact,$owner,true);
252         }
253
254         $atom .= '</feed>' . "\r\n";
255
256         logger('notifier: ' . $atom, LOGGER_DATA);
257
258         logger('notifier: slaps: ' . print_r($slaps,true), LOGGER_DATA);
259
260
261         require_once('include/salmon.php');
262
263         if($contact['self'])
264                 return;
265
266         $deliver_status = 0;
267
268         switch($contact['network']) {
269
270                 case NETWORK_DFRN :
271                         logger('notifier: dfrndelivery: ' . $contact['name']);
272                         $deliver_status = dfrn_deliver($owner,$contact,$atom);
273
274                         logger('notifier: dfrn_delivery returns ' . $deliver_status);
275         
276                         if($deliver_status == (-1)) {
277                                 logger('notifier: delivery failed: queuing message');
278                                 // queue message for redelivery
279                                 q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`)
280                                         VALUES ( %d, '%s', '%s', '%s') ",
281                                         intval($contact['id']),
282                                         dbesc(datetime_convert()),
283                                         dbesc(datetime_convert()),
284                                         dbesc($atom)
285                                 );
286                         }
287                         break;
288
289                 case NETWORK_OSTATUS :
290
291                         // Do not send to otatus if we are not configured to send to public networks
292                         if($owner['prvnets'])
293                                 break;
294                         if(get_config('system','ostatus_disabled') || get_config('system','dfrn_only'))
295                                 break;
296
297                         // only send salmon if public - e.g. if it's ok to notify
298                         // a public hub, it's ok to send a salmon
299
300                         if((count($slaps)) && ($public_message) && (! $expire)) {
301                                 logger('notifier: slapdelivery: ' . $contact['name']);
302                                 foreach($slaps as $slappy) {
303                                         if($contact['notify']) {
304                                                 $deliver_status = slapper($owner,$contact['notify'],$slappy);
305                                                 if($deliver_status == (-1)) {
306                                                         // queue message for redelivery
307                                                         q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`)
308                                                                 VALUES ( %d, '%s', '%s', '%s') ",
309                                                                 intval($contact['id']),
310                                                                 dbesc(datetime_convert()),
311                                                                 dbesc(datetime_convert()),
312                                                                 dbesc($slappy)
313                                                         );                                                              
314                                                 }
315                                         }
316                                 }
317                         }
318
319                         break;
320
321                 case NETWORK_MAIL :
322                                                 
323                         if(get_config('system','dfrn_only'))
324                                 break;
325                         // WARNING: does not currently convert to RFC2047 header encodings, etc.
326
327                         $addr = $contact['addr'];
328                         if(! strlen($addr))
329                                 break;
330
331                         if($cmd === 'wall-new' || $cmd === 'comment-new') {
332
333                                 $it = null;
334                                 if($cmd === 'wall-new') 
335                                         $it = $items[0];
336                                 else {
337                                         $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", 
338                                                 intval($argv[2]),
339                                                 intval($uid)
340                                         );
341                                         if(count($r))
342                                                 $it = $r[0];
343                                 }
344                                 if(! $it)
345                                         break;
346                                         
347
348                                 $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
349                                         intval($uid)
350                                 );
351                                 if(! count($local_user))
352                                         break;
353                                         
354                                 $reply_to = '';
355                                 $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
356                                         intval($uid)
357                                 );
358                                 if($r1 && $r1[0]['reply_to'])
359                                         $reply_to = $r1[0]['reply_to'];
360
361                                 $subject  = (($it['title']) ? $it['title'] : t("\x28no subject\x29")) ;
362                                 $headers  = 'From: ' . $local_user[0]['username'] . ' <' . $local_user[0]['email'] . '>' . "\n";
363                                 if($reply_to)
364                                         $headers .= 'Reply-to: ' . $reply_to . "\n";
365                                 $headers .= 'Message-id: <' . $it['uri'] . '>' . "\n";
366                                 if($it['uri'] !== $it['parent-uri']) {
367                                         $header .= 'References: <' . $it['parent-uri'] . '>' . "\n";
368                                         if(! strlen($it['title'])) {
369                                                 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' LIMIT 1",
370                                                         dbesc($it['parent-uri'])
371                                                 );
372                                                 if(count($r)) {
373                                                         $subtitle = $r[0]['title'];
374                                                         if($subtitle) {
375                                                                 if(strncasecmp($subtitle,'RE:',3))
376                                                                         $subject = $subtitle;
377                                                                 else
378                                                                         $subject = 'Re: ' . $subtitle;
379                                                         }
380                                                 }
381                                         }
382                                 }
383                                 $headers .= 'MIME-Version: 1.0' . "\n";
384                                 $headers .= 'Content-Type: text/html; charset=UTF-8' . "\n";
385                                 $headers .= 'Content-Transfer-Encoding: 8bit' . "\n\n";
386                                 $html    = prepare_body($it);
387                                 $message = '<html><body>' . $html . '</body></html>';
388                                 logger('notifier: email delivery to ' . $addr);
389                                 mail($addr, $subject, $message, $headers);
390                         }
391                         break;
392
393                 case NETWORK_DIASPORA :
394                         logger('delivery: diaspora deliver: ' . $contact['name']);
395
396                         if(get_config('system','dfrn_only') || (! get_config('system','diaspora_enabled')) || (! $normal_mode))
397                                 break;
398
399                         if(! $contact['pubkey'])
400                                 break;
401                                         
402                         if($target_item['verb'] === ACTIVITY_DISLIKE) {
403                                 // unsupported
404                                 break;
405                         }
406                         elseif(($target_item['deleted']) && ($target_item['verb'] !== ACTIVITY_LIKE)) {
407                         logger('delivery: diaspora retract: ' . $contact['name']);
408                                 // diaspora delete, 
409                                 diaspora_send_retraction($target_item,$owner,$contact);
410                                 break;
411                         }
412                         elseif($target_item['parent'] != $target_item['id']) {
413
414                         logger('delivery: diaspora relay: ' . $contact['name']);
415
416                                 // we are the relay - send comments, likes and unlikes to our conversants
417                                 diaspora_send_relay($target_item,$owner,$contact);
418                                 break;
419                         }               
420                         elseif($top_level) {
421                                 logger('delivery: diaspora status: ' . $contact['name']);
422                                 diaspora_send_status($target_item,$owner,$contact);
423                                 break;
424                         }
425
426                         logger('delivery: diaspora unknown mode: ' . $contact['name']);
427
428                         break;
429
430                 case NETWORK_FEED :
431                 case NETWORK_FACEBOOK :
432                         if(get_config('system','dfrn_only'))
433                                 break;
434                 default:
435                         break;
436         }
437
438         return;
439 }
440
441 if (array_search(__file__,get_included_files())===0){
442   delivery_run($argv,$argc);
443   killme();
444 }