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