]> git.mxchange.org Git - friendica.git/blob - include/poller.php
reduce polling load
[friendica.git] / include / poller.php
1 <?php
2
3 require_once("boot.php");
4
5
6 function poller_run($argv, $argc){
7         global $a, $db;
8
9         if(is_null($a)) {
10                 $a = new App;
11         }
12   
13         if(is_null($db)) {
14             @include(".htconfig.php");
15         require_once("dba.php");
16             $db = new dba($db_host, $db_user, $db_pass, $db_data);
17         unset($db_host, $db_user, $db_pass, $db_data);
18         };
19
20
21         require_once('include/session.php');
22         require_once('include/datetime.php');
23         require_once('library/simplepie/simplepie.inc');
24         require_once('include/items.php');
25         require_once('include/Contact.php');
26         require_once('include/email.php');
27         require_once('include/socgraph.php');
28
29         load_config('config');
30         load_config('system');
31
32         $a->set_baseurl(get_config('system','url'));
33
34         load_hooks();
35
36         logger('poller: start');
37         
38         // run queue delivery process in the background
39
40         proc_run('php',"include/queue.php");
41         
42         // expire any expired accounts
43
44         q("UPDATE user SET `account_expired` = 1 where `account_expired` = 0 
45                 AND `account_expires_on` != '0000-00-00 00:00:00' 
46                 AND `account_expires_on` < UTC_TIMESTAMP() ");
47   
48         $abandon_days = intval(get_config('system','account_abandon_days'));
49         if($abandon_days < 1)
50                 $abandon_days = 0;
51
52         
53
54         // once daily run birthday_updates and then expire in background
55
56         $d1 = get_config('system','last_expire_day');
57         $d2 = intval(datetime_convert('UTC','UTC','now','d'));
58
59         if($d2 != intval($d1)) {
60
61                 update_contact_birthdays();
62
63                 set_config('system','last_expire_day',$d2);
64                 proc_run('php','include/expire.php');
65         }
66
67         // clear old cache
68         Cache::clear();
69
70         $manual_id  = 0;
71         $generation = 0;
72         $hub_update = false;
73         $force      = false;
74         $restart    = false;
75
76         if(($argc > 1) && ($argv[1] == 'force'))
77                 $force = true;
78
79         if(($argc > 1) && ($argv[1] == 'restart')) {
80                 $restart = true;
81                 $generation = intval($argv[2]);
82                 if(! $generation)
83                         killme();               
84         }
85
86         if(($argc > 1) && intval($argv[1])) {
87                 $manual_id = intval($argv[1]);
88                 $force     = true;
89         }
90
91         $sql_extra = (($manual_id) ? " AND `id` = $manual_id " : "");
92
93         reload_plugins();
94
95         $d = datetime_convert();
96
97         if(! $restart)
98                 proc_run('php','include/cronhooks.php');
99
100         // Only poll from those with suitable relationships,
101         // and which have a polling address and ignore Diaspora since 
102         // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
103
104         $abandon_sql = (($abandon_days) 
105                 ? sprintf(" AND `user`.`login_date` > UTC_TIMESTAMP() - INTERVAL %d DAY ", intval($abandon_days)) 
106                 : '' 
107         );
108
109         $contacts = q("SELECT `contact`.`id` FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid` 
110                 WHERE ( `rel` = %d OR `rel` = %d ) AND `poll` != ''
111                 AND NOT `network` IN ( '%s', '%s' )
112                 $sql_extra 
113                 AND `self` = 0 AND `contact`.`blocked` = 0 AND `contact`.`readonly` = 0 
114                 AND `user`.`account_expired` = 0 $abandon_sql ORDER BY RAND()",
115                 intval(CONTACT_IS_SHARING),
116                 intval(CONTACT_IS_FRIEND),
117                 dbesc(NETWORK_DIASPORA),
118                 dbesc(NETWORK_FACEBOOK)
119         );
120
121         if(! count($contacts)) {
122                 return;
123         }
124
125         foreach($contacts as $c) {
126
127                 $res = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
128                         intval($c['id'])
129                 );
130
131                 if((! $res) || (! count($res)))
132                         continue;
133
134                 foreach($res as $contact) {
135
136                         $xml = false;
137
138                         if($manual_id)
139                                 $contact['last-update'] = '0000-00-00 00:00:00';
140
141                         if($contact['network'] === NETWORK_DFRN)
142                                 $contact['priority'] = 2;
143
144                         if($contact['priority'] || $contact['subhub']) {
145
146                                 $hub_update = true;
147                                 $update     = false;
148
149                                 $t = $contact['last-update'];
150
151                                 // We should be getting everything via a hub. But just to be sure, let's check once a day.
152                                 // (You can make this more or less frequent if desired by setting 'pushpoll_frequency' appropriately)
153                                 // This also lets us update our subscription to the hub, and add or replace hubs in case it
154                                 // changed. We will only update hubs once a day, regardless of 'pushpoll_frequency'. 
155
156
157                                 if($contact['subhub']) {
158                                         $interval = get_config('system','pushpoll_frequency');
159                                         $contact['priority'] = (($interval !== false) ? intval($interval) : 3);
160                                         $hub_update = false;
161         
162                                         if((datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day")) || $force)
163                                                         $hub_update = true;
164                                 }
165                                 else
166                                         $hub_update = false;
167
168                                 /**
169                                  * Based on $contact['priority'], should we poll this site now? Or later?
170                                  */                     
171
172                                 switch ($contact['priority']) {
173                                         case 5:
174                                                 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 month"))
175                                                         $update = true;
176                                                 break;                                  
177                                         case 4:
178                                                 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 week"))
179                                                         $update = true;
180                                                 break;
181                                         case 3:
182                                                 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
183                                                         $update = true;
184                                                 break;
185                                         case 2:
186                                                 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 12 hour"))
187                                                         $update = true;
188                                                 break;
189                                         case 1:
190                                         default:
191                                                 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 hour"))
192                                                         $update = true;
193                                                 break;
194                                 }
195                                 if((! $update) && (! $force))
196                                         continue;
197                         }
198
199                         // Check to see if we are running out of memory - if so spawn a new process and kill this one
200
201                         $avail_memory = return_bytes(ini_get('memory_limit'));
202                         $memused = memory_get_peak_usage(true);
203                         if(intval($avail_memory)) {
204                                 if(($memused / $avail_memory) > 0.95) {
205                                         if($generation + 1 > 10) {
206                                                 logger('poller: maximum number of spawns exceeded. Terminating.');
207                                                 killme();
208                                         }
209                                         logger('poller: memory exceeded. ' . $memused . ' bytes used. Spawning new poll.');
210                                         proc_run('php', 'include/poller.php', 'restart', (string) $generation + 1);
211                                         killme();
212                                 }
213                         }
214
215                         $importer_uid = $contact['uid'];
216                 
217                         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
218                                 intval($importer_uid)
219                         );
220                         if(! count($r))
221                                 continue;
222
223                         $importer = $r[0];
224
225                         logger("poller: poll: ({$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
226
227                         $last_update = (($contact['last-update'] === '0000-00-00 00:00:00') 
228                                 ? datetime_convert('UTC','UTC','now - 30 days', ATOM_TIME)
229                                 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
230                         );
231
232                         if($contact['network'] === NETWORK_DFRN) {
233
234                                 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
235
236                                 if(intval($contact['duplex']) && $contact['dfrn-id'])
237                                         $idtosend = '0:' . $orig_id;
238                                 if(intval($contact['duplex']) && $contact['issued-id'])
239                                         $idtosend = '1:' . $orig_id;
240
241                                 // they have permission to write to us. We already filtered this in the contact query.
242                                 $perm = 'rw';
243
244                                 $url = $contact['poll'] . '?dfrn_id=' . $idtosend 
245                                         . '&dfrn_version=' . DFRN_PROTOCOL_VERSION 
246                                         . '&type=data&last_update=' . $last_update 
247                                         . '&perm=' . $perm ;
248         
249                                 $handshake_xml = fetch_url($url);
250
251                                 logger('poller: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
252
253
254                                 if(! $handshake_xml) {
255                                         logger("poller: $url appears to be dead - marking for death ");
256                                         // dead connection - might be a transient event, or this might
257                                         // mean the software was uninstalled or the domain expired. 
258                                         // Will keep trying for one month.
259                                         mark_for_death($contact);
260
261                                         // set the last-update so we don't keep polling
262
263                                         $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
264                                                 dbesc(datetime_convert()),
265                                                 intval($contact['id'])
266                                         );
267
268                                         continue;
269                                 }
270
271                                 if(! strstr($handshake_xml,'<?xml')) {
272                                         logger('poller: response from ' . $url . ' did not contain XML.');
273                                         $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
274                                                 dbesc(datetime_convert()),
275                                                 intval($contact['id'])
276                                         );
277                                         continue;
278                                 }
279
280
281                                 $res = parse_xml_string($handshake_xml);
282         
283                                 if(intval($res->status) == 1) {
284                                         logger("poller: $url replied status 1 - marking for death ");
285
286                                         // we may not be friends anymore. Will keep trying for one month.
287                                         // set the last-update so we don't keep polling
288
289                                         $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
290                                                 dbesc(datetime_convert()),
291                                                 intval($contact['id'])
292                                         );
293
294                                         mark_for_death($contact);
295                                 }
296                                 else {
297                                         if($contact['term-date'] != '0000-00-00 00:00:00') {
298                                                 logger("poller: $url back from the dead - removing mark for death");
299                                                 unmark_for_death($contact);
300                                         }
301                                 }
302
303                                 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
304                                         continue;
305
306                                 if(((float) $res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
307                                         q("update contact set poco = '%s' where id = %d limit 1",
308                                                 dbesc(str_replace('/profile/','/poco/', $contact['url'])),
309                                                 intval($contact['id'])
310                                         );
311                                 }
312
313                                 $postvars = array();
314
315                                 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
316                                 $challenge    = hex2bin((string) $res->challenge);
317
318                                 $final_dfrn_id = '';
319
320                                 if(($contact['duplex']) && strlen($contact['prvkey'])) {
321                                         openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
322                                         openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
323                                 }
324                                 else {
325                                         openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
326                                         openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
327                                 }
328
329                                 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
330
331                                 if(strpos($final_dfrn_id,':') == 1)
332                                         $final_dfrn_id = substr($final_dfrn_id,2);
333
334                                 if($final_dfrn_id != $orig_id) {
335                                         logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);    
336                                         // did not decode properly - cannot trust this site 
337                                         continue;
338                                 }
339
340                                 $postvars['dfrn_id'] = $idtosend;
341                                 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
342                                 $postvars['perm'] = 'rw';
343
344                                 $xml = post_url($contact['poll'],$postvars);
345                         }
346                         elseif(($contact['network'] === NETWORK_OSTATUS) 
347                                 || ($contact['network'] === NETWORK_DIASPORA)
348                                 || ($contact['network'] === NETWORK_FEED) ) {
349
350                                 // Upgrading DB fields from an older Friendika version
351                                 // Will only do this once per notify-enabled OStatus contact
352                                 // or if relationship changes
353
354                                 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
355
356                                 if($stat_writeable != $contact['writable']) {
357                                         q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d LIMIT 1",
358                                                 intval($stat_writeable),
359                                                 intval($contact['id'])
360                                         );
361                                 }
362
363                                 // Are we allowed to import from this person?
364
365                                 if($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly'])
366                                         continue;
367
368                                 $xml = fetch_url($contact['poll']);
369                         }
370                         elseif($contact['network'] === NETWORK_MAIL) {
371
372                                 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
373                                 if($mail_disabled)
374                                         continue;
375
376                                 $mbox = null;
377                                 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
378                                         intval($importer_uid)
379                                 );
380                                 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
381                                         intval($importer_uid)
382                                 );
383                                 if(count($x) && count($mailconf)) {
384                                     $mailbox = construct_mailbox_name($mailconf[0]);
385                                         $password = '';
386                                         openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
387                                         $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
388                                         unset($password);
389                                         if($mbox) {
390                                                 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
391                                                         dbesc(datetime_convert()),
392                                                         intval($mailconf[0]['id']),
393                                                         intval($importer_uid)
394                                                 );
395                                         }
396                                 }
397                                 if($mbox) {
398
399                                         $msgs = email_poll($mbox,$contact['addr']);
400
401                                         if(count($msgs)) {
402                                                 foreach($msgs as $msg_uid) {
403                                                         $datarray = array();
404                                                         $meta = email_msg_meta($mbox,$msg_uid);
405                                                         $headers = email_msg_headers($mbox,$msg_uid);
406
407                                                         // look for a 'references' header and try and match with a parent item we have locally.
408
409                                                         $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
410                                                         $datarray['uri'] = trim($meta->message_id,'<>');
411
412                                                         if($raw_refs) {
413                                                                 $refs_arr = explode(' ', $raw_refs);
414                                                                 if(count($refs_arr)) {
415                                                                         for($x = 0; $x < count($refs_arr); $x ++)
416                                                                                 $refs_arr[$x] = "'" . str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x])) . "'";
417                                                                 }
418                                                                 $qstr = implode(',',$refs_arr);
419                                                                 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
420                                                                         intval($importer_uid)
421                                                                 );
422                                                                 if(count($r))
423                                                                         $datarray['parent-uri'] = $r[0]['uri'];
424                                                         }
425
426
427                                                         if(! x($datarray,'parent-uri'))
428                                                                 $datarray['parent-uri'] = $datarray['uri'];
429
430                                                         // Have we seen it before?
431                                                         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
432                                                                 intval($importer_uid),
433                                                                 dbesc($datarray['uri'])
434                                                         );
435
436                                                         if(count($r)) {
437                                                                 if($meta->deleted && ! $r[0]['deleted']) {
438                                                                         q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d LIMIT 1",
439                                                                                 dbesc(datetime_convert()),
440                                                                                 intval($r[0]['id'])
441                                                                         );
442                                                                 }               
443                                                                 continue;
444                                                         }
445                                                         $datarray['title'] = notags(trim($meta->subject));
446                                                         $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
447         
448                                                         $r = email_get_msg($mbox,$msg_uid);
449                                                         if(! $r)
450                                                                 continue;
451                                                         $datarray['body'] = escape_tags($r['body']);
452
453                                                         // some mailing lists have the original author as 'from' - add this sender info to msg body. 
454                                                         // todo: adding a gravatar for the original author would be cool
455
456                                                         if(! stristr($meta->from,$contact['addr']))
457                                                                 $datarray['body'] = t('From: ') . escape_tags($meta->from) . "\n\n" . $datarray['body'];
458
459                                                         $datarray['uid'] = $importer_uid;
460                                                         $datarray['contact-id'] = $contact['id'];
461                                                         if($datarray['parent-uri'] === $datarray['uri'])
462                                                                 $datarray['private'] = 1;
463                                                         if(! get_pconfig($importer_uid,'system','allow_public_email_replies')) {
464                                                                 $datarray['private'] = 1;
465                                                                 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
466                                                         }
467                                                         $datarray['author-name'] = $contact['name'];
468                                                         $datarray['author-link'] = 'mailbox';
469                                                         $datarray['author-avatar'] = $contact['photo'];
470                                                 
471                                                         $stored_item = item_store($datarray);
472                                                         q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
473                                                                 dbesc($datarray['parent-uri']),
474                                                                 intval($importer_uid)
475                                                         );
476                                                         q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
477                                                                 intval($stored_item)
478                                                         );
479                                                 }
480                                         }
481
482                                         imap_close($mbox);
483                                 }
484                         }
485                         elseif($contact['network'] === NETWORK_FACEBOOK) {
486                                 // This is picked up by the Facebook plugin on a cron hook.
487                                 // Ignored here.                        
488                         }
489
490                         if($xml) {
491                                 logger('poller: received xml : ' . $xml, LOGGER_DATA);
492
493                                 if(! strstr($xml,'<?xml')) {
494                                         logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
495                                         $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
496                                                 dbesc(datetime_convert()),
497                                                 intval($contact['id'])
498                                         );
499                                         continue;
500                                 }
501
502
503                                 consume_feed($xml,$importer,$contact,$hub,1,1);
504
505                                 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
506         
507                                 consume_feed($xml,$importer,$contact,$hub,1,2);
508
509                                 $hubmode = 'subscribe';
510                                 if($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly'])
511                                         $hubmode = 'unsubscribe';
512
513                                 if((strlen($hub)) && ($hub_update) && ($contact['rel'] != CONTACT_IS_FOLLOWER)) {
514                                         logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
515                                         $hubs = explode(',', $hub);
516                                         if(count($hubs)) {
517                                                 foreach($hubs as $h) {
518                                                         $h = trim($h);
519                                                         if(! strlen($h))
520                                                                 continue;
521                                                         subscribe_to_hub($h,$importer,$contact,$hubmode);
522                                                 }
523                                         }
524                                 }
525                         }
526
527
528                         $updated = datetime_convert();
529
530                         $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d LIMIT 1",
531                                 dbesc($updated),
532                                 dbesc($updated),
533                                 intval($contact['id'])
534                         );
535
536
537                         // load current friends if possible.
538
539                         if($contact['poco']) {  
540                                 $r = q("SELECT count(*) as total from glink 
541                                         where `cid` = %d and updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
542                                         intval($contact['id'])
543                                 );
544                         }
545                         if(count($r)) {
546                                 if(! $r[0]['total']) {
547                                         poco_load($contact['id'],$importer_uid,$contact['poco']);
548                                 }
549                         }
550
551                         // loop - next contact
552                 }
553         }
554
555                 
556         return;
557 }
558
559 if (array_search(__file__,get_included_files())===0){
560   poller_run($argv,$argc);
561   killme();
562 }