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