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