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