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