]> git.mxchange.org Git - friendica.git/blob - include/poller.php
pull request #91 fabrixxm (manual merge)
[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
291                                 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
292                                 if($mail_disabled)
293                                         continue;
294
295                                 $mbox = null;
296                                 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
297                                         intval($importer_uid)
298                                 );
299                                 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
300                                         intval($importer_uid)
301                                 );
302                                 if(count($x) && count($mailconf)) {
303                                     $mailbox = construct_mailbox_name($mailconf[0]);
304                                         $password = '';
305                                         openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
306                                         $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
307                                         unset($password);
308                                         if($mbox) {
309                                                 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
310                                                         dbesc(datetime_convert()),
311                                                         intval($mailconf[0]['id']),
312                                                         intval($importer_uid)
313                                                 );
314                                         }
315                                 }
316                                 if($mbox) {
317
318                                         $msgs = email_poll($mbox,$contact['addr']);
319
320                                         if(count($msgs)) {
321                                                 foreach($msgs as $msg_uid) {
322                                                         $datarray = array();
323                                                         $meta = email_msg_meta($mbox,$msg_uid);
324                                                         $headers = email_msg_headers($mbox,$msg_uid);
325
326                                                         // look for a 'references' header and try and match with a parent item we have locally.
327
328                                                         $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
329                                                         $datarray['uri'] = trim($meta->message_id,'<>');
330
331                                                         if($raw_refs) {
332                                                                 $refs_arr = explode(' ', $raw_refs);
333                                                                 if(count($refs_arr)) {
334                                                                         for($x = 0; $x < count($refs_arr); $x ++)
335                                                                                 $refs_arr[$x] = "'" . str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x])) . "'";
336                                                                 }
337                                                                 $qstr = implode(',',$refs_arr);
338                                                                 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
339                                                                         intval($importer_uid)
340                                                                 );
341                                                                 if(count($r))
342                                                                         $datarray['parent-uri'] = $r[0]['uri'];
343                                                         }
344
345
346                                                         if(! x($datarray,'parent-uri'))
347                                                                 $datarray['parent-uri'] = $datarray['uri'];
348
349                                                         // Have we seen it before?
350                                                         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
351                                                                 intval($importer_uid),
352                                                                 dbesc($datarray['uri'])
353                                                         );
354
355                                                         if(count($r)) {
356                                                                 if($meta->deleted && ! $r[0]['deleted']) {
357                                                                         q("UPDATE `item` SET `deleted` = `, `changed` = '%s' WHERE `id` = %d LIMIT 1",
358                                                                                 dbesc(datetime_convert()),
359                                                                                 intval($r[0]['id'])
360                                                                         );
361                                                                 }               
362                                                                 continue;
363                                                         }
364                                                         $datarray['title'] = notags(trim($meta->subject));
365                                                         $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
366         
367                                                         $r = email_get_msg($mbox,$msg_uid);
368                                                         if(! $r)
369                                                                 continue;
370                                                         $datarray['body'] = escape_tags($r['body']);
371                                                         $datarray['uid'] = $importer_uid;
372                                                         $datarray['contact-id'] = $contact['id'];
373                                                         if($datarray['parent-uri'] === $datarray['uri'])
374                                                                 $datarray['private'] = 1;
375                                                         $datarray['author-name'] = $contact['name'];
376                                                         $datarray['author-link'] = 'mailbox';
377                                                         $datarray['author-avatar'] = $contact['photo'];
378                                                 
379                                                         $stored_item = item_store($datarray);
380                                                         q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
381                                                                 dbesc($datarray['parent-uri']),
382                                                                 intval($importer_uid)
383                                                         );
384                                                         q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
385                                                                 intval($stored_item)
386                                                         );
387                                                 }
388                                         }
389
390                                         imap_close($mbox);
391                                 }
392                         }
393                         elseif($contact['network'] === NETWORK_FACEBOOK) {
394                                 // TODO: work in progress                       
395                         }
396
397                         if($xml) {
398                                 logger('poller: received xml : ' . $xml, LOGGER_DATA);
399
400                                 if(! strstr($xml,'<?xml')) {
401                                         logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
402                                         $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
403                                                 dbesc(datetime_convert()),
404                                                 intval($contact['id'])
405                                         );
406                                         continue;
407                                 }
408
409
410                                 consume_feed($xml,$importer,$contact,$hub,1, true);
411
412                                 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
413         
414                                 consume_feed($xml,$importer,$contact,$hub,1);
415
416
417                                 if((strlen($hub)) && ($hub_update) && (($contact['rel'] == REL_BUD) || (($contact['network'] === NETWORK_OSTATUS) && (! $contact['readonly'])))) {
418                                         logger('poller: subscribing to hub(s) : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
419                                         $hubs = explode(',', $hub);
420                                         if(count($hubs)) {
421                                                 foreach($hubs as $h) {
422                                                         $h = trim($h);
423                                                         if(! strlen($h))
424                                                                 continue;
425                                                         subscribe_to_hub($h,$importer,$contact);
426                                                 }
427                                         }
428                                 }
429                         }
430
431                         $updated = datetime_convert();
432
433                         $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d LIMIT 1",
434                                 dbesc($updated),
435                                 dbesc($updated),
436                                 intval($contact['id'])
437                         );
438
439                         // loop - next contact
440                 }
441         }
442
443                 
444         return;
445 }
446
447 if (array_search(__file__,get_included_files())===0){
448   poller_run($argv,$argc);
449   killme();
450 }