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