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