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