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