]> git.mxchange.org Git - friendica.git/blob - include/notifier.php
NL update to the strings, thx Ralph
[friendica.git] / include / notifier.php
1 <?php
2 require_once("boot.php");
3 require_once('include/queue_fn.php');
4 require_once('include/html2plain.php');
5 require_once("include/Scrape.php");
6 require_once('include/diaspora.php');
7
8 /*
9  * This file was at one time responsible for doing all deliveries, but this caused
10  * big problems on shared hosting systems, where the process might get killed by the
11  * hosting provider and nothing would get delivered.
12  * It now only delivers one message under certain cases, and invokes a queued
13  * delivery mechanism (include/deliver.php) to deliver individual contacts at
14  * controlled intervals.
15  * This has a much better chance of surviving random processes getting killed
16  * by the hosting provider.
17  * A lot of this code is duplicated in include/deliver.php until we have time to go back
18  * and re-structure the delivery procedure based on the obstacles that have been thrown at
19  * us by hosting providers.
20  */
21
22 /*
23  * The notifier is typically called with:
24  *
25  *              proc_run('php', "include/notifier.php", COMMAND, ITEM_ID);
26  *
27  * where COMMAND is one of the following:
28  *
29  *              activity                                (in diaspora.php, dfrn_confirm.php, profiles.php)
30  *              comment-import                  (in diaspora.php, items.php)
31  *              comment-new                             (in item.php)
32  *              drop                                    (in diaspora.php, items.php, photos.php)
33  *              edit_post                               (in item.php)
34  *              event                                   (in events.php)
35  *              expire                                  (in items.php)
36  *              like                                    (in like.php, poke.php)
37  *              mail                                    (in message.php)
38  *              suggest                                 (in fsuggest.php)
39  *              tag                                             (in photos.php, poke.php, tagger.php)
40  *              tgroup                                  (in items.php)
41  *              wall-new                                (in photos.php, item.php)
42  *              removeme                                (in Contact.php)
43  *              relocate                                (in uimport.php)
44  *
45  * and ITEM_ID is the id of the item in the database that needs to be sent to others.
46  */
47
48
49 function notifier_run(&$argv, &$argc){
50         global $a, $db;
51
52         if(is_null($a)){
53                 $a = new App;
54         }
55
56         if(is_null($db)) {
57                 @include(".htconfig.php");
58                 require_once("include/dba.php");
59                 $db = new dba($db_host, $db_user, $db_pass, $db_data);
60                         unset($db_host, $db_user, $db_pass, $db_data);
61         }
62
63         require_once("include/session.php");
64         require_once("include/datetime.php");
65         require_once('include/items.php');
66         require_once('include/bbcode.php');
67         require_once('include/email.php');
68         load_config('config');
69         load_config('system');
70
71         load_hooks();
72
73         if($argc < 3)
74                 return;
75
76         $a->set_baseurl(get_config('system','url'));
77
78         logger('notifier: invoked: ' . print_r($argv,true), LOGGER_DEBUG);
79
80         $cmd = $argv[1];
81
82         switch($cmd) {
83                 case 'mail':
84                 default:
85                         $item_id = intval($argv[2]);
86                         if(! $item_id){
87                                 return;
88                         }
89                         break;
90         }
91
92         $expire = false;
93         $mail = false;
94         $fsuggest = false;
95         $relocate = false;
96         $top_level = false;
97         $recipients = array();
98         $url_recipients = array();
99
100         $normal_mode = true;
101
102         if($cmd === 'mail') {
103                 $normal_mode = false;
104                 $mail = true;
105                 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
106                                 intval($item_id)
107                 );
108                 if(! count($message)){
109                         return;
110                 }
111                 $uid = $message[0]['uid'];
112                 $recipients[] = $message[0]['contact-id'];
113                 $item = $message[0];
114
115         }
116         elseif($cmd === 'expire') {
117                 $normal_mode = false;
118                 $expire = true;
119                 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
120                         AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 10 MINUTE",
121                         intval($item_id)
122                 );
123                 $uid = $item_id;
124                 $item_id = 0;
125                 if(! count($items))
126                         return;
127         }
128         elseif($cmd === 'suggest') {
129                 $normal_mode = false;
130                 $fsuggest = true;
131
132                 $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
133                         intval($item_id)
134                 );
135                 if(! count($suggest))
136                         return;
137                 $uid = $suggest[0]['uid'];
138                 $recipients[] = $suggest[0]['cid'];
139                 $item = $suggest[0];
140         } elseif($cmd === 'removeme') {
141                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($item_id));
142                 if (! $r)
143                         return;
144
145                 $user = $r[0];
146                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1", intval($item_id));
147                 if (! $r)
148                         return;
149
150                 $self = $r[0];
151                 $r = q("SELECT * FROM `contact` WHERE `self` = 0 AND `uid` = %d", intval($item_id));
152                 if(! $r)
153                         return;
154
155                 require_once('include/Contact.php');
156                 foreach($r as $contact) {
157                         terminate_friendship($user, $self, $contact);
158                 }
159                 return;
160         } elseif($cmd === 'relocate') {
161                 $normal_mode = false;
162                 $relocate = true;
163                 $uid = $item_id;
164         } else {
165                 // find ancestors
166                 $r = q("SELECT * FROM `item` WHERE `id` = %d and visible = 1 and moderated = 0 LIMIT 1",
167                         intval($item_id)
168                 );
169
170                 if((! count($r)) || (! intval($r[0]['parent']))) {
171                         return;
172                 }
173
174                 $target_item = $r[0];
175                 $parent_id = intval($r[0]['parent']);
176                 $uid = $r[0]['uid'];
177                 $updated = $r[0]['edited'];
178
179                 // POSSIBLE CLEANUP --> The following seems superfluous. We've already checked for "if (! intval($r[0]['parent']))" a few lines up
180                 if(! $parent_id)
181                         return;
182
183                 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
184                         FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d and visible = 1 and moderated = 0 ORDER BY `id` ASC",
185                         intval($parent_id)
186                 );
187
188                 if(! count($items)) {
189                         return;
190                 }
191
192                 // avoid race condition with deleting entries
193
194                 if($items[0]['deleted']) {
195                         foreach($items as $item)
196                                 $item['deleted'] = 1;
197                 }
198
199                 if((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
200                         logger('notifier: top level post');
201                         $top_level = true;
202                 }
203
204         }
205
206         $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
207                 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
208                 `user`.`page-flags`, `user`.`prvnets`
209                 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
210                 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
211                 intval($uid)
212         );
213
214         if(! count($r))
215                 return;
216
217         $owner = $r[0];
218
219         $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
220
221         $hub = get_config('system','huburl');
222
223         // If this is a public conversation, notify the feed hub
224         $public_message = true;
225
226         // Do a PuSH
227         $push_notify = false;
228
229         // fill this in with a single salmon slap if applicable
230         $slap = '';
231
232         if(! ($mail || $fsuggest || $relocate)) {
233
234                 require_once('include/group.php');
235
236                 $parent = $items[0];
237
238                 $thr_parent = q("SELECT `network` FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
239                         dbesc($target_item["thr-parent"]), intval($target_item["uid"]));
240
241                 logger('Parent is '.$parent['network'].'. Thread parent is '.$thr_parent[0]['network'], LOGGER_DEBUG);
242
243                 // This is IMPORTANT!!!!
244
245                 // We will only send a "notify owner to relay" or followup message if the referenced post
246                 // originated on our system by virtue of having our hostname somewhere
247                 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
248
249                 // if $parent['wall'] == 1 we will already have the parent message in our array
250                 // and we will relay the whole lot.
251
252                 // expire sends an entire group of expire messages and cannot be forwarded.
253                 // However the conversation owner will be a part of the conversation and will
254                 // be notified during this run.
255                 // Other DFRN conversation members will be alerted during polled updates.
256
257
258
259                 // Diaspora members currently are not notified of expirations, and other networks have
260                 // either limited or no ability to process deletions. We should at least fix Diaspora
261                 // by stringing togther an array of retractions and sending them onward.
262
263
264                 $localhost = str_replace('www.','',$a->get_hostname());
265                 if(strpos($localhost,':'))
266                         $localhost = substr($localhost,0,strpos($localhost,':'));
267
268                 /**
269                  *
270                  * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
271                  * have been known to cause runaway conditions which affected several servers, along with
272                  * permissions issues.
273                  *
274                  */
275
276                 $relay_to_owner = false;
277
278                 if((! $top_level) && ($parent['wall'] == 0) && (! $expire) && (stristr($target_item['uri'],$localhost))) {
279                         $relay_to_owner = true;
280                 }
281
282
283                 if(($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && (! $top_level)) {
284                         $relay_to_owner = true;
285                 }
286
287                 // until the 'origin' flag has been in use for several months
288                 // we will just use it as a fallback test
289                 // later we will be able to use it as the primary test of whether or not to relay.
290
291                 if(! $target_item['origin'])
292                         $relay_to_owner = false;
293
294                 if($parent['origin'])
295                         $relay_to_owner = false;
296
297                 if($relay_to_owner) {
298                         logger('notifier: followup '.$target_item["guid"], LOGGER_DEBUG);
299                         // local followup to remote post
300                         $followup = true;
301                         $public_message = false; // not public
302                         $conversant_str = dbesc($parent['contact-id']);
303                         $recipients = array($parent['contact-id']);
304
305                         if (!$target_item['private'] AND $target_item['wall'] AND
306                                 (strlen($target_item['allow_cid'].$target_item['allow_gid'].
307                                         $target_item['deny_cid'].$target_item['deny_gid']) == 0))
308                                 $push_notify = true;
309
310                         // We notify Friendica users in the thread when it is an OStatus thread.
311                         // Hopefully this transfers the messages to the other Friendica servers. (Untested)
312                         if (($thr_parent AND ($thr_parent[0]['network'] == NETWORK_OSTATUS)) OR ($parent['network'] == NETWORK_OSTATUS)) {
313
314                                 $push_notify = true;
315
316                                 if ($parent["network"] == NETWORK_OSTATUS) {
317                                         $r = q("SELECT `author-link` FROM `item` WHERE `parent` = %d AND `author-link` != '%s'",
318                                                 intval($target_item["parent"]), dbesc($owner['url']));
319                                         foreach($r as $parent_item) {
320                                                 $probed_contact = probe_url($parent_item["author-link"]);
321                                                 if (($probed_contact["notify"] != "") AND ($probed_contact["network"] == NETWORK_DFRN)) {
322                                                         logger('Notify Friendica user '.$probed_contact["url"].': '.$probed_contact["notify"]);
323                                                         $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
324                                                 }
325                                         }
326                                 }
327
328                                 if (count($url_recipients))
329                                         logger("url_recipients ".print_r($url_recipients,true));
330                         }
331                 } else {
332                         $followup = false;
333
334                         logger('Distributing directly '.$target_item["guid"], LOGGER_DEBUG);
335
336                         // don't send deletions onward for other people's stuff
337
338                         if($target_item['deleted'] && (! intval($target_item['wall']))) {
339                                 logger('notifier: ignoring delete notification for non-wall item');
340                                 return;
341                         }
342
343                         if((strlen($parent['allow_cid']))
344                                 || (strlen($parent['allow_gid']))
345                                 || (strlen($parent['deny_cid']))
346                                 || (strlen($parent['deny_gid']))) {
347                                 $public_message = false; // private recipients, not public
348                         }
349
350                         $allow_people = expand_acl($parent['allow_cid']);
351                         $allow_groups = expand_groups(expand_acl($parent['allow_gid']),true);
352                         $deny_people  = expand_acl($parent['deny_cid']);
353                         $deny_groups  = expand_groups(expand_acl($parent['deny_gid']));
354
355                         // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
356                         // a delivery fork. private groups (forum_mode == 2) do not uplink
357
358                         if((intval($parent['forum_mode']) == 1) && (! $top_level) && ($cmd !== 'uplink')) {
359                                 proc_run('php','include/notifier.php','uplink',$item_id);
360                         }
361
362                         $conversants = array();
363
364                         foreach($items as $item) {
365                                 $recipients[] = $item['contact-id'];
366                                 $conversants[] = $item['contact-id'];
367                                 // pull out additional tagged people to notify (if public message)
368                                 if($public_message && strlen($item['inform'])) {
369                                         $people = explode(',',$item['inform']);
370                                         foreach($people as $person) {
371                                                 if(substr($person,0,4) === 'cid:') {
372                                                         $recipients[] = intval(substr($person,4));
373                                                         $conversants[] = intval(substr($person,4));
374                                                 }
375                                                 else {
376                                                         $url_recipients[] = substr($person,4);
377                                                 }
378                                         }
379                                 }
380                         }
381
382                         if (count($url_recipients))
383                                 logger('notifier: '.$target_item["guid"].' url_recipients ' . print_r($url_recipients,true));
384
385                         $conversants = array_unique($conversants);
386
387
388                         $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
389                         $deny = array_unique(array_merge($deny_people,$deny_groups));
390                         $recipients = array_diff($recipients,$deny);
391
392                         $conversant_str = dbesc(implode(', ',$conversants));
393                 }
394
395                 // If the thread parent is OStatus then do some magic to distribute the messages.
396                 // We have not only to look at the parent, since it could be a Friendica thread.
397                 if (($thr_parent AND ($thr_parent[0]['network'] == NETWORK_OSTATUS)) OR ($parent['network'] == NETWORK_OSTATUS)) {
398
399                         logger('Some parent is OStatus for '.$target_item["guid"], LOGGER_DEBUG);
400
401                         // Send a salmon notification to every person we mentioned in the post
402                         $arr = explode(',',$target_item['tag']);
403                         foreach($arr as $x) {
404                                 //logger('Checking tag '.$x, LOGGER_DEBUG);
405                                 $matches = null;
406                                 if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
407                                                 $probed_contact = probe_url($matches[1]);
408                                         if ($probed_contact["notify"] != "") {
409                                                 logger('Notify mentioned user '.$probed_contact["url"].': '.$probed_contact["notify"]);
410                                                 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
411                                         }
412                                 }
413                         }
414
415                         // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
416                         $sql_extra = " AND `network` IN ('".NETWORK_OSTATUS."', '".NETWORK_DFRN."')";
417                 } else
418                         $sql_extra = "";
419
420                 $r = q("SELECT * FROM `contact` WHERE `id` IN ($conversant_str) AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0".$sql_extra);
421
422                 if(count($r))
423                         $contacts = $r;
424         }
425
426         $feed_template = get_markup_template('atom_feed.tpl');
427         $mail_template = get_markup_template('atom_mail.tpl');
428
429         $atom = '';
430         $slaps = array();
431
432         $hubxml = feed_hublinks();
433
434         $birthday = feed_birthday($owner['uid'],$owner['timezone']);
435
436         if(strlen($birthday))
437                 $birthday = '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>';
438
439         $atom .= replace_macros($feed_template, array(
440                         '$version'      => xmlify(FRIENDICA_VERSION),
441                         '$feed_id'      => xmlify($a->get_baseurl() . '/profile/' . $owner['nickname'] ),
442                         '$feed_title'   => xmlify($owner['name']),
443                         '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00' , ATOM_TIME)) ,
444                         '$hub'          => $hubxml,
445                         '$salmon'       => '',  // private feed, we don't use salmon here
446                         '$name'         => xmlify($owner['name']),
447                         '$profile_page' => xmlify($owner['url']),
448                         '$photo'        => xmlify($owner['photo']),
449                         '$thumb'        => xmlify($owner['thumb']),
450                         '$picdate'      => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
451                         '$uridate'      => xmlify(datetime_convert('UTC','UTC',$owner['uri-date']    . '+00:00' , ATOM_TIME)) ,
452                         '$namdate'      => xmlify(datetime_convert('UTC','UTC',$owner['name-date']   . '+00:00' , ATOM_TIME)) ,
453                         '$birthday'     => $birthday,
454                         '$community'    => (($owner['page-flags'] == PAGE_COMMUNITY) ? '<dfrn:community>1</dfrn:community>' : '')
455
456         ));
457
458         if($mail) {
459                 $public_message = false;  // mail is  not public
460
461                 $body = fix_private_photos($item['body'],$owner['uid'],null,$message[0]['contact-id']);
462
463                 $atom .= replace_macros($mail_template, array(
464                         '$name'         => xmlify($owner['name']),
465                         '$profile_page' => xmlify($owner['url']),
466                         '$thumb'        => xmlify($owner['thumb']),
467                         '$item_id'      => xmlify($item['uri']),
468                         '$subject'      => xmlify($item['title']),
469                         '$created'      => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME)),
470                         '$content'      => xmlify($body),
471                         '$parent_id'    => xmlify($item['parent-uri'])
472                 ));
473         } elseif($fsuggest) {
474                 $public_message = false;  // suggestions are not public
475
476                 $sugg_template = get_markup_template('atom_suggest.tpl');
477
478                 $atom .= replace_macros($sugg_template, array(
479                         '$name'         => xmlify($item['name']),
480                         '$url'          => xmlify($item['url']),
481                         '$photo'        => xmlify($item['photo']),
482                         '$request'      => xmlify($item['request']),
483                         '$note'         => xmlify($item['note'])
484                 ));
485
486                 // We don't need this any more
487
488                 q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1",
489                         intval($item['id'])
490                 );
491
492         } elseif($relocate) {
493                 $public_message = false;  // suggestions are not public
494
495                 $sugg_template = get_markup_template('atom_relocate.tpl');
496
497                 /* get site pubkey. this could be a new installation with no site keys*/
498                 $pubkey = get_config('system','site_pubkey');
499                 if(! $pubkey) {
500                         $res = new_keypair(1024);
501                         set_config('system','site_prvkey', $res['prvkey']);
502                         set_config('system','site_pubkey', $res['pubkey']);
503                 }
504
505                 $rp = q("SELECT `resource-id` , `scale`, type FROM `photo` 
506                                                 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
507                 $photos = array();
508                 $ext = Photo::supportedTypes();
509                 foreach($rp as $p){
510                         $photos[$p['scale']] = $a->get_baseurl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
511                 }
512                 unset($rp, $ext);
513
514                 $atom .= replace_macros($sugg_template, array(
515                                         '$name' => xmlify($owner['name']),
516                                         '$photo' => xmlify($photos[4]),
517                                         '$thumb' => xmlify($photos[5]),
518                                         '$micro' => xmlify($photos[6]),
519                                         '$url' => xmlify($owner['url']),
520                                         '$request' => xmlify($owner['request']),
521                                         '$confirm' => xmlify($owner['confirm']),
522                                         '$notify' => xmlify($owner['notify']),
523                                         '$poll' => xmlify($owner['poll']),
524                                         '$sitepubkey' => xmlify(get_config('system','site_pubkey')),
525                                         //'$pubkey' => xmlify($owner['pubkey']),
526                                         //'$prvkey' => xmlify($owner['prvkey']),
527                         ));
528                 $recipients_relocate = q("SELECT * FROM contact WHERE uid = %d  AND self = 0 AND network = '%s'" , intval($uid), NETWORK_DFRN);
529                 unset($photos);
530         } else {
531
532                 $slap = atom_entry($target_item,'html',null,$owner,false);
533
534                 if($followup) {
535                         foreach($items as $item) {  // there is only one item
536                                 if(! $item['parent'])
537                                         continue;
538                                 if($item['id'] == $item_id) {
539                                         logger('notifier: followup: item: ' . print_r($item,true), LOGGER_DATA);
540                                         //$slap  = atom_entry($item,'html',null,$owner,false);
541                                         $atom .= atom_entry($item,'text',null,$owner,false);
542                                 }
543                         }
544                 } else {
545                         foreach($items as $item) {
546
547                                 if(! $item['parent'])
548                                         continue;
549
550                                 // private emails may be in included in public conversations. Filter them.
551
552                                 if(($public_message) && $item['private'] == 1)
553                                         continue;
554
555
556                                 $contact = get_item_contact($item,$contacts);
557
558                                 if(! $contact)
559                                         continue;
560
561                                 if($normal_mode) {
562
563                                         // we only need the current item, but include the parent because without it
564                                         // older sites without a corresponding dfrn_notify change may do the wrong thing.
565
566                                     if($item_id == $item['id'] || $item['id'] == $item['parent'])
567                                                 $atom .= atom_entry($item,'text',null,$owner,true);
568                                 } else
569                                         $atom .= atom_entry($item,'text',null,$owner,true);
570
571                                 if(($top_level) && ($public_message) && ($item['author-link'] === $item['owner-link']) && (! $expire))
572                                         $slaps[] = atom_entry($item,'html',null,$owner,true);
573                         }
574                 }
575         }
576         $atom .= '</feed>' . "\r\n";
577
578         logger('notifier: ' . $atom, LOGGER_DATA);
579
580         logger('notifier: slaps: ' . print_r($slaps,true), LOGGER_DATA);
581
582         // If this is a public message and pubmail is set on the parent, include all your email contacts
583
584         $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
585
586         if(! $mail_disabled) {
587                 if((! strlen($target_item['allow_cid'])) && (! strlen($target_item['allow_gid']))
588                         && (! strlen($target_item['deny_cid'])) && (! strlen($target_item['deny_gid']))
589                         && (intval($target_item['pubmail']))) {
590                         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
591                                 intval($uid),
592                                 dbesc(NETWORK_MAIL)
593                         );
594                         if(count($r)) {
595                                 foreach($r as $rr)
596                                         $recipients[] = $rr['id'];
597                         }
598                 }
599         }
600
601         if($followup)
602                 $recip_str = $parent['contact-id'];
603         else
604                 $recip_str = implode(', ', $recipients);
605
606         if ($relocate)
607                 $r = $recipients_relocate;
608         else
609                 $r = q("SELECT * FROM `contact` WHERE `id` IN ( %s ) AND `blocked` = 0 AND `pending` = 0 ",
610                         dbesc($recip_str)
611                 );
612
613
614         require_once('include/salmon.php');
615
616         $interval = ((get_config('system','delivery_interval') === false) ? 2 : intval(get_config('system','delivery_interval')));
617
618         // If we are using the worker we don't need a delivery interval
619         if (get_config("system", "worker"))
620                 $interval = false;
621
622         // delivery loop
623
624         if(count($r)) {
625
626                 foreach($r as $contact) {
627                         if((! $mail) && (! $fsuggest) && (! $followup) && (!$relocate) && (! $contact['self'])) {
628                                 if(($contact['network'] === NETWORK_DIASPORA) && ($public_message))
629                                         continue;
630                                 q("insert into deliverq ( `cmd`,`item`,`contact` ) values ('%s', %d, %d )",
631                                         dbesc($cmd),
632                                         intval($item_id),
633                                         intval($contact['id'])
634                                 );
635                         }
636                 }
637
638
639                 // This controls the number of deliveries to execute with each separate delivery process.
640                 // By default we'll perform one delivery per process. Assuming a hostile shared hosting
641                 // provider, this provides the greatest chance of deliveries if processes start getting
642                 // killed. We can also space them out with the delivery_interval to also help avoid them
643                 // getting whacked.
644
645                 // If $deliveries_per_process > 1, we will chain this number of multiple deliveries
646                 // together into a single process. This will reduce the overall number of processes
647                 // spawned for each delivery, but they will run longer.
648
649                 // When using the workerqueue, we don't need this functionality.
650
651                 $deliveries_per_process = intval(get_config('system','delivery_batch_count'));
652                 if (($deliveries_per_process <= 0) OR get_config("system", "worker"))
653                         $deliveries_per_process = 1;
654
655                 $this_batch = array();
656
657                 for($x = 0; $x < count($r); $x ++) {
658                         $contact = $r[$x];
659
660                         if($contact['self'])
661                                 continue;
662
663                         logger("Deliver ".$target_item["guid"]." to ".$contact['url'], LOGGER_DEBUG);
664
665                         // potentially more than one recipient. Start a new process and space them out a bit.
666                         // we will deliver single recipient types of message and email recipients here.
667
668                         if((! $mail) && (! $fsuggest) && (!$relocate) && (! $followup)) {
669
670                                 $this_batch[] = $contact['id'];
671
672                                 if(count($this_batch) == $deliveries_per_process) {
673                                         proc_run('php','include/delivery.php',$cmd,$item_id,$this_batch);
674                                         $this_batch = array();
675                                         if($interval)
676                                                 @time_sleep_until(microtime(true) + (float) $interval);
677                                 }
678                                 continue;
679                         }
680                         // be sure to pick up any stragglers
681                         if(count($this_batch))
682                                 proc_run('php','include/delivery.php',$cmd,$item_id,$this_batch);
683
684
685                         $deliver_status = 0;
686
687                         logger("main delivery by notifier: followup=$followup mail=$mail fsuggest=$fsuggest relocate=$relocate");
688
689                         switch($contact['network']) {
690                                 case NETWORK_DFRN:
691
692                                         // perform local delivery if we are on the same site
693
694                                         $basepath =  implode('/', array_slice(explode('/',$contact['url']),0,3));
695
696                                         if(link_compare($basepath,$a->get_baseurl())) {
697
698                                                 $nickname = basename($contact['url']);
699                                                 if($contact['issued-id'])
700                                                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
701                                                 else
702                                                         $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
703
704                                                 $x = q("SELECT  `contact`.*, `contact`.`uid` AS `importer_uid`,
705                                                         `contact`.`pubkey` AS `cpubkey`,
706                                                         `contact`.`prvkey` AS `cprvkey`,
707                                                         `contact`.`thumb` AS `thumb`,
708                                                         `contact`.`url` as `url`,
709                                                         `contact`.`name` as `senderName`,
710                                                         `user`.*
711                                                         FROM `contact`
712                                                         INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
713                                                         WHERE `contact`.`blocked` = 0 AND `contact`.`archive` = 0
714                                                         AND `contact`.`pending` = 0
715                                                         AND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'
716                                                         $sql_extra
717                                                         AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 LIMIT 1",
718                                                         dbesc(NETWORK_DFRN),
719                                                         dbesc($nickname)
720                                                 );
721
722                                                 if($x && count($x)) {
723                                                         $write_flag = ((($x[0]['rel']) && ($x[0]['rel'] != CONTACT_IS_SHARING)) ? true : false);
724                                                         if((($owner['page-flags'] == PAGE_COMMUNITY) || ($write_flag)) && (! $x[0]['writable'])) {
725                                                                 q("update contact set writable = 1 where id = %d",
726                                                                         intval($x[0]['id'])
727                                                                 );
728                                                                 $x[0]['writable'] = 1;
729                                                         }
730
731                                                         // if contact's ssl policy changed, which we just determined
732                                                         // is on our own server, update our contact links
733
734                                                         $ssl_policy = get_config('system','ssl_policy');
735                                                         fix_contact_ssl_policy($x[0],$ssl_policy);
736
737                                                         // If we are setup as a soapbox we aren't accepting top level posts from this person
738
739                                                         if (($x[0]['page-flags'] == PAGE_SOAPBOX) AND $top_level)
740                                                                 break;
741
742                                                         require_once('library/simplepie/simplepie.inc');
743                                                         logger('mod-delivery: local delivery');
744                                                         local_delivery($x[0],$atom);
745                                                         break;
746                                                 }
747                                         }
748
749                                         logger('notifier: dfrndelivery: ' . $contact['name']);
750                                         $deliver_status = dfrn_deliver($owner,$contact,$atom);
751
752                                         logger('notifier: dfrn_delivery returns ' . $deliver_status);
753
754                                         if($deliver_status == (-1)) {
755                                                 logger('notifier: delivery failed: queuing message');
756                                                 // queue message for redelivery
757                                                 add_to_queue($contact['id'],NETWORK_DFRN,$atom);
758                                         }
759                                         break;
760                                 case NETWORK_OSTATUS:
761
762                                         // Do not send to ostatus if we are not configured to send to public networks
763                                         if($owner['prvnets'])
764                                                 break;
765
766                                         if(get_config('system','ostatus_disabled') || get_config('system','dfrn_only'))
767                                                 break;
768
769                                         if($followup && $contact['notify']) {
770                                                 logger('slapdelivery followup item '.$item_id.' to ' . $contact['name']);
771                                                 $deliver_status = slapper($owner,$contact['notify'],$slap);
772
773                                                 if($deliver_status == (-1)) {
774                                                         // queue message for redelivery
775                                                         add_to_queue($contact['id'],NETWORK_OSTATUS,$slap);
776                                                 }
777                                         } else {
778
779                                                 // only send salmon if public - e.g. if it's ok to notify
780                                                 // a public hub, it's ok to send a salmon
781
782                                                 if((count($slaps)) && ($public_message) && (! $expire)) {
783                                                         logger('slapdelivery item '.$item_id.' to ' . $contact['name']);
784                                                         foreach($slaps as $slappy) {
785                                                                 if($contact['notify']) {
786                                                                         $deliver_status = slapper($owner,$contact['notify'],$slappy);
787                                                                         if($deliver_status == (-1)) {
788                                                                                 // queue message for redelivery
789                                                                                 add_to_queue($contact['id'],NETWORK_OSTATUS,$slappy);
790                                                                         }
791                                                                 }
792                                                         }
793                                                 }
794                                         }
795                                         break;
796
797                                 case NETWORK_MAIL:
798                                 case NETWORK_MAIL2:
799
800                                         if(get_config('system','dfrn_only'))
801                                                 break;
802
803                                         // WARNING: does not currently convert to RFC2047 header encodings, etc.
804
805                                         $addr = $contact['addr'];
806                                         if(! strlen($addr))
807                                                 break;
808
809                                         if($cmd === 'wall-new' || $cmd === 'comment-new') {
810
811                                                 $it = null;
812                                                 if($cmd === 'wall-new') 
813                                                         $it = $items[0];
814                                                 else {
815                                                         $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", 
816                                                                 intval($argv[2]),
817                                                                 intval($uid)
818                                                         );
819                                                         if(count($r))
820                                                                 $it = $r[0];
821                                                 }
822                                                 if(! $it)
823                                                         break;
824
825
826
827                                                 $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
828                                                         intval($uid)
829                                                 );
830                                                 if(! count($local_user))
831                                                         break;
832
833                                                 $reply_to = '';
834                                                 $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
835                                                         intval($uid)
836                                                 );
837                                                 if($r1 && $r1[0]['reply_to'])
838                                                         $reply_to = $r1[0]['reply_to'];
839
840                                                 $subject  = (($it['title']) ? email_header_encode($it['title'],'UTF-8') : t("\x28no subject\x29")) ;
841
842                                                 // only expose our real email address to true friends
843                                                 if(($contact['rel'] == CONTACT_IS_FRIEND) && (! $contact['blocked']))
844                                                         if($reply_to) {
845                                                                 $headers  = 'From: ' . email_header_encode($local_user[0]['username'],'UTF-8') . ' <' . $reply_to . '>' . "\n";
846                                                                 $headers .= 'Sender: '.$local_user[0]['email']."\n";
847                                                         } else
848                                                                 $headers  = 'From: ' . email_header_encode($local_user[0]['username'],'UTF-8') . ' <' . $local_user[0]['email'] . '>' . "\n";
849                                                 else
850                                                         $headers  = 'From: ' . email_header_encode($local_user[0]['username'],'UTF-8') . ' <' . t('noreply') . '@' . $a->get_hostname() . '>' . "\n";
851
852                                                 //if($reply_to)
853                                                 //      $headers .= 'Reply-to: ' . $reply_to . "\n";
854
855                                                 $headers .= 'Message-Id: <' . iri2msgid($it['uri']) . '>' . "\n";
856
857                                                 if($it['uri'] !== $it['parent-uri']) {
858                                                         $headers .= "References: <".iri2msgid($it["parent-uri"]).">";
859
860                                                         // If Threading is enabled, write down the correct parent
861                                                         if (($it["thr-parent"] != "") and ($it["thr-parent"] != $it["parent-uri"]))
862                                                                 $headers .= " <".iri2msgid($it["thr-parent"]).">";
863                                                         $headers .= "\n";
864
865                                                         if(!$it['title']) {
866                                                                 $r = q("SELECT `title` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
867                                                                         dbesc($it['parent-uri']),
868                                                                         intval($uid));
869
870                                                                 if(count($r) AND ($r[0]['title'] != ''))
871                                                                         $subject = $r[0]['title'];
872                                                                 else {
873                                                                         $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d LIMIT 1",
874                                                                                 dbesc($it['parent-uri']),
875                                                                                 intval($uid));
876
877                                                                         if(count($r) AND ($r[0]['title'] != ''))
878                                                                                 $subject = $r[0]['title'];
879                                                                 }
880                                                         }
881                                                         if(strncasecmp($subject,'RE:',3))
882                                                                 $subject = 'Re: '.$subject;
883                                                 }
884                                                 email_send($addr, $subject, $headers, $it);
885                                         }
886                                         break;
887                                 case NETWORK_DIASPORA:
888                                         if(get_config('system','dfrn_only') || (! get_config('system','diaspora_enabled')))
889                                                 break;
890
891                                         if($mail) {
892                                                 diaspora_send_mail($item,$owner,$contact);
893                                                 break;
894                                         }
895
896                                         if(! $normal_mode)
897                                                 break;
898
899                                         // special handling for followup to public post
900                                         // all other public posts processed as public batches further below
901
902                                         if($public_message) {
903                                                 if($followup)
904                                                         diaspora_send_followup($target_item,$owner,$contact, true);
905                                                 break;
906                                         }
907
908                                         if(! $contact['pubkey'])
909                                                 break;
910
911                                         $unsupported_activities = array(ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE);
912
913                                         //don't transmit activities which are not supported by diaspora
914                                         foreach($unsupported_activities as $act) {
915                                                 if(activity_match($target_item['verb'],$act)) {
916                                                         break 2;
917                                                 }
918                                         }
919
920                                         if(($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
921                                                 // send both top-level retractions and relayable retractions for owner to relay
922                                                 diaspora_send_retraction($target_item,$owner,$contact);
923                                                 break;
924                                         }
925                                         elseif($followup) {
926                                                 // send comments and likes to owner to relay
927                                                 diaspora_send_followup($target_item,$owner,$contact);
928                                                 break;
929                                         }
930                                         elseif($target_item['uri'] !== $target_item['parent-uri']) {
931                                                 // we are the relay - send comments, likes and relayable_retractions
932                                                 // (of comments and likes) to our conversants
933                                                 diaspora_send_relay($target_item,$owner,$contact);
934                                                 break;
935                                         }
936                                         elseif(($top_level) && (! $walltowall)) {
937                                                 // currently no workable solution for sending walltowall
938                                                 diaspora_send_status($target_item,$owner,$contact);
939                                                 break;
940                                         }
941
942                                         break;
943
944                                 case NETWORK_FEED:
945                                 case NETWORK_FACEBOOK:
946                                         if(get_config('system','dfrn_only'))
947                                                 break;
948                                 case NETWORK_PUMPIO:
949                                         if(get_config('system','dfrn_only'))
950                                                 break;
951                                 default:
952                                         break;
953                         }
954                 }
955         }
956
957         // send additional slaps to mentioned remote tags (@foo@example.com)
958
959         //if($slap && count($url_recipients) && ($followup || $top_level) && ($public_message || $push_notify) && (! $expire)) {
960         if($slap && count($url_recipients) && ($public_message || $push_notify) && (!$expire)) {
961                 if(! get_config('system','dfrn_only')) {
962                         foreach($url_recipients as $url) {
963                                 if($url) {
964                                         logger('notifier: urldelivery: ' . $url);
965                                         $deliver_status = slapper($owner,$url,$slap);
966                                         // TODO: redeliver/queue these items on failure, though there is no contact record
967                                 }
968                         }
969                 }
970         }
971
972
973         if($public_message) {
974
975                 if (!$followup)
976                         $r0 = diaspora_fetch_relay();
977                 else
978                         $r0 = array();
979
980                 $r1 = q("SELECT DISTINCT(`batch`), `id`, `name`,`network` FROM `contact` WHERE `network` = '%s'
981                         AND `uid` = %d AND `rel` != %d group by `batch` ORDER BY rand() ",
982                         dbesc(NETWORK_DIASPORA),
983                         intval($owner['uid']),
984                         intval(CONTACT_IS_SHARING)
985                 );
986
987                 $r2 = q("SELECT `id`, `name`,`network` FROM `contact`
988                         WHERE `network` in ( '%s', '%s')  AND `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0
989                         AND `rel` != %d order by rand() ",
990                         dbesc(NETWORK_DFRN),
991                         dbesc(NETWORK_MAIL2),
992                         intval($owner['uid']),
993                         intval(CONTACT_IS_SHARING)
994                 );
995
996                 $r = array_merge($r2,$r1,$r0);
997
998                 if(count($r)) {
999                         logger('pubdeliver: ' . print_r($r,true), LOGGER_DEBUG);
1000
1001                         // throw everything into the queue in case we get killed
1002
1003                         foreach($r as $rr) {
1004                                 if((! $mail) && (! $fsuggest) && (! $followup)) {
1005                                         q("insert into deliverq ( `cmd`,`item`,`contact` ) values ('%s', %d, %d )",
1006                                                 dbesc($cmd),
1007                                                 intval($item_id),
1008                                                 intval($rr['id'])
1009                                         );
1010                                 }
1011                         }
1012
1013                         foreach($r as $rr) {
1014
1015                                 // except for Diaspora batch jobs
1016                                 // Don't deliver to folks who have already been delivered to
1017
1018                                 if(($rr['network'] !== NETWORK_DIASPORA) && (in_array($rr['id'],$conversants))) {
1019                                         logger('notifier: already delivered id=' . $rr['id']);
1020                                         continue;
1021                                 }
1022
1023                                 if((! $mail) && (! $fsuggest) && (! $followup)) {
1024                                         logger('notifier: delivery agent: ' . $rr['name'] . ' ' . $rr['id']);
1025                                         proc_run('php','include/delivery.php',$cmd,$item_id,$rr['id']);
1026                                         if($interval)
1027                                                 @time_sleep_until(microtime(true) + (float) $interval);
1028                                 }
1029                         }
1030                 }
1031
1032                 $push_notify = true;
1033
1034         }
1035
1036
1037         if($push_notify AND strlen($hub)) {
1038                 $hubs = explode(',', $hub);
1039                 if(count($hubs)) {
1040                         foreach($hubs as $h) {
1041                                 $h = trim($h);
1042                                 if(! strlen($h))
1043                                         continue;
1044
1045                                 if ($h === '[internal]') {
1046                                         // Set push flag for PuSH subscribers to this topic,
1047                                         // they will be notified in queue.php
1048                                         q("UPDATE `push_subscriber` SET `push` = 1 " .
1049                                           "WHERE `nickname` = '%s'", dbesc($owner['nickname']));
1050
1051                                         logger('Activating internal PuSH for item '.$item_id, LOGGER_DEBUG);
1052
1053                                 } else {
1054
1055                                         $params = 'hub.mode=publish&hub.url=' . urlencode( $a->get_baseurl() . '/dfrn_poll/' . $owner['nickname'] );
1056                                         post_url($h,$params);
1057                                         logger('publish for item '.$item_id.' ' . $h . ' ' . $params . ' returned ' . $a->get_curl_code());
1058                                 }
1059                                 if(count($hubs) > 1)
1060                                         sleep(7);                               // try and avoid multiple hubs responding at precisely the same time
1061                         }
1062                 }
1063
1064                 // Handling the pubsubhubbub requests
1065                 proc_run('php','include/pubsubpublish.php');
1066         }
1067
1068         // If the item was deleted, clean up the `sign` table
1069         if($target_item['deleted']) {
1070                 $r = q("DELETE FROM sign where `retract_iid` = %d",
1071                         intval($target_item['id'])
1072                 );
1073         }
1074
1075         logger('notifier: calling hooks', LOGGER_DEBUG);
1076
1077         if($normal_mode)
1078                 call_hooks('notifier_normal',$target_item);
1079
1080         call_hooks('notifier_end',$target_item);
1081
1082         return;
1083 }
1084
1085
1086 if (array_search(__file__,get_included_files())===0){
1087         notifier_run($_SERVER["argv"],$_SERVER["argc"]);
1088         killme();
1089 }