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