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