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