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