]> git.mxchange.org Git - friendica.git/blob - include/poller.php
load db configs (config,system) for all "executables"
[friendica.git] / include / poller.php
1 <?php
2
3 require_once("boot.php");
4
5 function poller_run($argv, $argc){
6         global $a, $db;
7
8         if(is_null($a)) {
9                 $a = new App;
10         }
11   
12         if(is_null($db)) {
13             @include(".htconfig.php");
14         require_once("dba.php");
15             $db = new dba($db_host, $db_user, $db_pass, $db_data);
16         unset($db_host, $db_user, $db_pass, $db_data);
17         };
18
19
20         require_once('include/session.php');
21         require_once('include/datetime.php');
22         require_once('library/simplepie/simplepie.inc');
23         require_once('include/items.php');
24         require_once('include/Contact.php');
25         require_once('include/email.php');
26
27         load_config('config');
28         load_config('system');
29
30         $a->set_baseurl(get_config('system','url'));
31
32         load_hooks();
33
34         logger('poller: start');
35         
36         // run queue delivery process in the background
37
38         proc_run('php',"include/queue.php");
39         
40         // once daily run expire in background
41
42         $d1 = get_config('system','last_expire_day');
43         $d2 = intval(datetime_convert('UTC','UTC','now','d'));
44
45         if($d2 != intval($d1)) {
46                 set_config('system','last_expire_day',$d2);
47                 proc_run('php','include/expire.php');
48         }
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         $hub_update = false;
57         $force      = false;
58
59         if(($argc > 1) && ($argv[1] == 'force'))
60                 $force = true;
61
62         if(($argc > 1) && intval($argv[1])) {
63                 $manual_id = intval($argv[1]);
64                 $force     = true;
65         }
66
67         $sql_extra = (($manual_id) ? " AND `id` = $manual_id " : "");
68
69         reload_plugins();
70
71         $d = datetime_convert();
72
73         call_hooks('cron', $d);
74
75
76         $contacts = q("SELECT `id` FROM `contact` 
77                 WHERE ( `rel` = %d OR `rel` = %d ) AND `poll` != ''
78                 $sql_extra 
79                 AND `self` = 0 AND `blocked` = 0 AND `readonly` = 0 ORDER BY RAND()",
80                 intval(REL_FAN),
81                 intval(REL_BUD)
82         );
83
84         if(! count($contacts)) {
85                 return;
86         }
87
88         foreach($contacts as $c) {
89
90                 $res = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
91                         intval($c['id'])
92                 );
93
94                 if(! count($res))
95                         continue;
96
97                 foreach($res as $contact) {
98
99                         $xml = false;
100
101                         if($manual_id)
102                                 $contact['last-update'] = '0000-00-00 00:00:00';
103
104                         if($contact['priority'] || $contact['subhub']) {
105
106                                 $hub_update = true;
107                                 $update     = false;
108
109                                 $t = $contact['last-update'];
110
111                                 // We should be getting everything via a hub. But just to be sure, let's check once a day.
112                                 // (You can make this more or less frequent if desired by setting 'pushpoll_frequency' appropriately)
113                                 // This also lets us update our subscription to the hub, and add or replace hubs in case it
114                                 // changed. We will only update hubs once a day, regardless of 'pushpoll_frequency'. 
115
116
117                                 if($contact['subhub']) {
118                                         $interval = get_config('system','pushpoll_frequency');
119                                         $contact['priority'] = (($interval !== false) ? intval($interval) : 3);
120                                         $hub_update = false;
121         
122                                         if((datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day")) || $force)
123                                                         $hub_update = true;
124                                 }
125
126                                 /**
127                                  * Based on $contact['priority'], should we poll this site now? Or later?
128                                  */                     
129
130                                 switch ($contact['priority']) {
131                                         case 5:
132                                                 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 month"))
133                                                         $update = true;
134                                                 break;                                  
135                                         case 4:
136                                                 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 week"))
137                                                         $update = true;
138                                                 break;
139                                         case 3:
140                                                 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
141                                                         $update = true;
142                                                 break;
143                                         case 2:
144                                                 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 12 hour"))
145                                                         $update = true;
146                                                 break;
147                                         case 1:
148                                         default:
149                                                 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 hour"))
150                                                         $update = true;
151                                                 break;
152                                 }
153                                 if((! $update) && (! $force))
154                                         continue;
155                         }
156
157                         $importer_uid = $contact['uid'];
158                 
159                         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
160                                 intval($importer_uid)
161                         );
162                         if(! count($r))
163                                 continue;
164
165                         $importer = $r[0];
166
167                         logger("poller: poll: IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
168
169                         $last_update = (($contact['last-update'] === '0000-00-00 00:00:00') 
170                                 ? datetime_convert('UTC','UTC','now - 30 days', ATOM_TIME)
171                                 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
172                         );
173
174                         if($contact['network'] === NETWORK_DFRN) {
175
176                                 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
177
178                                 if(intval($contact['duplex']) && $contact['dfrn-id'])
179                                         $idtosend = '0:' . $orig_id;
180                                 if(intval($contact['duplex']) && $contact['issued-id'])
181                                         $idtosend = '1:' . $orig_id;
182
183                                 // they have permission to write to us. We already filtered this in the contact query.
184                                 $perm = 'rw';
185
186                                 $url = $contact['poll'] . '?dfrn_id=' . $idtosend 
187                                         . '&dfrn_version=' . DFRN_PROTOCOL_VERSION 
188                                         . '&type=data&last_update=' . $last_update 
189                                         . '&perm=' . $perm ;
190         
191                                 $handshake_xml = fetch_url($url);
192
193                                 logger('poller: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
194
195
196                                 if(! $handshake_xml) {
197                                         logger("poller: $url appears to be dead - marking for death ");
198                                         // dead connection - might be a transient event, or this might
199                                         // mean the software was uninstalled or the domain expired. 
200                                         // Will keep trying for one month.
201                                         mark_for_death($contact);
202
203                                         // set the last-update so we don't keep polling
204
205                                         $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
206                                                 dbesc(datetime_convert()),
207                                                 intval($contact['id'])
208                                         );
209
210                                         continue;
211                                 }
212
213                                 if(! strstr($handshake_xml,'<?xml')) {
214                                         logger('poller: response from ' . $url . ' did not contain XML.');
215                                         $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
216                                                 dbesc(datetime_convert()),
217                                                 intval($contact['id'])
218                                         );
219                                         continue;
220                                 }
221
222
223                                 $res = parse_xml_string($handshake_xml);
224         
225                                 if(intval($res->status) == 1) {
226                                         logger("poller: $url replied status 1 - marking for death ");
227
228                                         // we may not be friends anymore. Will keep trying for one month.
229                                         // set the last-update so we don't keep polling
230
231                                         $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
232                                                 dbesc(datetime_convert()),
233                                                 intval($contact['id'])
234                                         );
235
236                                         mark_for_death($contact);
237                                 }
238                                 else {
239                                         if($contact['term-date'] != '0000-00-00 00:00:00') {
240                                                 logger("poller: $url back from the dead - removing mark for death");
241                                                 unmark_for_death($contact);
242                                         }
243                                 }
244
245                                 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
246                                         continue;
247
248                                 $postvars = array();
249
250                                 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
251                                 $challenge    = hex2bin((string) $res->challenge);
252
253                                 $final_dfrn_id = '';
254
255                                 if(($contact['duplex']) && strlen($contact['prvkey'])) {
256                                         openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
257                                         openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
258                                 }
259                                 else {
260                                         openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
261                                         openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
262                                 }
263
264                                 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
265
266                                 if(strpos($final_dfrn_id,':') == 1)
267                                         $final_dfrn_id = substr($final_dfrn_id,2);
268
269                                 if($final_dfrn_id != $orig_id) {
270                                         logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);    
271                                         // did not decode properly - cannot trust this site 
272                                         continue;
273                                 }
274
275                                 $postvars['dfrn_id'] = $idtosend;
276                                 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
277                                 $postvars['perm'] = 'rw';
278
279                                 $xml = post_url($contact['poll'],$postvars);
280                         }
281                         elseif(($contact['network'] === NETWORK_OSTATUS) 
282                                 || ($contact['network'] === NETWORK_DIASPORA)
283                                 || ($contact['network'] === NETWORK_FEED) ) {
284
285                                 // Upgrading DB fields from an older Friendika version
286                                 // Will only do this once per notify-enabled OStatus contact
287
288                                 if(($contact['notify']) && (! $contact['writable'])) {
289                                         q("UPDATE `contact` SET `writable` = 1 WHERE `id` = %d LIMIT 1",
290                                                 intval($contact['id'])
291                                         );
292                                 }
293
294                                 $xml = fetch_url($contact['poll']);
295                         }
296                         elseif($contact['network'] === NETWORK_MAIL) {
297
298                                 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
299                                 if($mail_disabled)
300                                         continue;
301
302                                 $mbox = null;
303                                 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
304                                         intval($importer_uid)
305                                 );
306                                 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
307                                         intval($importer_uid)
308                                 );
309                                 if(count($x) && count($mailconf)) {
310                                     $mailbox = construct_mailbox_name($mailconf[0]);
311                                         $password = '';
312                                         openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
313                                         $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
314                                         unset($password);
315                                         if($mbox) {
316                                                 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
317                                                         dbesc(datetime_convert()),
318                                                         intval($mailconf[0]['id']),
319                                                         intval($importer_uid)
320                                                 );
321                                         }
322                                 }
323                                 if($mbox) {
324
325                                         $msgs = email_poll($mbox,$contact['addr']);
326
327                                         if(count($msgs)) {
328                                                 foreach($msgs as $msg_uid) {
329                                                         $datarray = array();
330                                                         $meta = email_msg_meta($mbox,$msg_uid);
331                                                         $headers = email_msg_headers($mbox,$msg_uid);
332
333                                                         // look for a 'references' header and try and match with a parent item we have locally.
334
335                                                         $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
336                                                         $datarray['uri'] = trim($meta->message_id,'<>');
337
338                                                         if($raw_refs) {
339                                                                 $refs_arr = explode(' ', $raw_refs);
340                                                                 if(count($refs_arr)) {
341                                                                         for($x = 0; $x < count($refs_arr); $x ++)
342                                                                                 $refs_arr[$x] = "'" . str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x])) . "'";
343                                                                 }
344                                                                 $qstr = implode(',',$refs_arr);
345                                                                 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
346                                                                         intval($importer_uid)
347                                                                 );
348                                                                 if(count($r))
349                                                                         $datarray['parent-uri'] = $r[0]['uri'];
350                                                         }
351
352
353                                                         if(! x($datarray,'parent-uri'))
354                                                                 $datarray['parent-uri'] = $datarray['uri'];
355
356                                                         // Have we seen it before?
357                                                         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
358                                                                 intval($importer_uid),
359                                                                 dbesc($datarray['uri'])
360                                                         );
361
362                                                         if(count($r)) {
363                                                                 if($meta->deleted && ! $r[0]['deleted']) {
364                                                                         q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d LIMIT 1",
365                                                                                 dbesc(datetime_convert()),
366                                                                                 intval($r[0]['id'])
367                                                                         );
368                                                                 }               
369                                                                 continue;
370                                                         }
371                                                         $datarray['title'] = notags(trim($meta->subject));
372                                                         $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
373         
374                                                         $r = email_get_msg($mbox,$msg_uid);
375                                                         if(! $r)
376                                                                 continue;
377                                                         $datarray['body'] = escape_tags($r['body']);
378
379                                                         // some mailing lists have the original author as 'from' - add this sender info to msg body. 
380                                                         // todo: adding a gravatar for the original author would be cool
381
382                                                         if(! stristr($meta->from,$contact['addr']))
383                                                                 $datarray['body'] = t('From: ') . escape_tags($meta->from) . "\n\n" . $datarray['body'];
384
385                                                         $datarray['uid'] = $importer_uid;
386                                                         $datarray['contact-id'] = $contact['id'];
387                                                         if($datarray['parent-uri'] === $datarray['uri'])
388                                                                 $datarray['private'] = 1;
389                                                         $datarray['author-name'] = $contact['name'];
390                                                         $datarray['author-link'] = 'mailbox';
391                                                         $datarray['author-avatar'] = $contact['photo'];
392                                                 
393                                                         $stored_item = item_store($datarray);
394                                                         q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
395                                                                 dbesc($datarray['parent-uri']),
396                                                                 intval($importer_uid)
397                                                         );
398                                                         q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
399                                                                 intval($stored_item)
400                                                         );
401                                                 }
402                                         }
403
404                                         imap_close($mbox);
405                                 }
406                         }
407                         elseif($contact['network'] === NETWORK_FACEBOOK) {
408                                 // TODO: work in progress                       
409                         }
410
411                         if($xml) {
412                                 logger('poller: received xml : ' . $xml, LOGGER_DATA);
413
414                                 if(! strstr($xml,'<?xml')) {
415                                         logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
416                                         $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
417                                                 dbesc(datetime_convert()),
418                                                 intval($contact['id'])
419                                         );
420                                         continue;
421                                 }
422
423
424                                 consume_feed($xml,$importer,$contact,$hub,1, true);
425
426                                 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
427         
428                                 consume_feed($xml,$importer,$contact,$hub,1);
429
430
431                                 if((strlen($hub)) && ($hub_update) && (($contact['rel'] == REL_BUD) || (($contact['network'] === NETWORK_OSTATUS) && (! $contact['readonly'])))) {
432                                         logger('poller: subscribing to hub(s) : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
433                                         $hubs = explode(',', $hub);
434                                         if(count($hubs)) {
435                                                 foreach($hubs as $h) {
436                                                         $h = trim($h);
437                                                         if(! strlen($h))
438                                                                 continue;
439                                                         subscribe_to_hub($h,$importer,$contact);
440                                                 }
441                                         }
442                                 }
443                         }
444
445                         $updated = datetime_convert();
446
447                         $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d LIMIT 1",
448                                 dbesc($updated),
449                                 dbesc($updated),
450                                 intval($contact['id'])
451                         );
452
453                         // loop - next contact
454                 }
455         }
456
457                 
458         return;
459 }
460
461 if (array_search(__file__,get_included_files())===0){
462   poller_run($argv,$argc);
463   killme();
464 }