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