]> git.mxchange.org Git - friendica.git/blob - include/poller.php
email follow seems to be stabilising
[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                                         $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
296                                                 intval($importer_uid)
297                                         );
298                                         if(count($x) && count($r)) {
299                                             $mailbox = construct_mailbox_name($r[0]);
300                                                 $password = '';
301                                                 openssl_private_decrypt(hex2bin($r[0]['pass']),$password,$x[0]['prvkey']);
302                                                 $mbox = email_connect($mailbox,$r[0]['user'],$password);
303                                                 unset($password);
304                                         }
305                                 }
306                                 if($mbox) {
307                                         $msgs = email_poll($mbox,$contact['addr']);
308                                         if(count($msgs)) {
309                                                 foreach($msgs as $msg_uid) {
310                                                         $datarray = array();
311                                                         $meta = email_msg_meta($mbox,$msg_uid);
312                                                         $datarray['uri'] = trim($meta->message_id,'<>');
313 //FIXME
314                                                         $datarray['parent-uri'] = $datarray['uri'];
315                                                         // Have we seen it before?
316                                                         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
317                                                                 intval($importer_uid),
318                                                                 dbesc($datarray['uri'])
319                                                         );
320                                                         if(count($r)) {
321                                                                 if($meta->deleted && ! $r[0]['deleted']) {
322                                                                         q("UPDATE `item` SET `deleted` = `, `changed` = '%s' WHERE `id` = %d LIMIT 1",
323                                                                                 dbesc(datetime_convert()),
324                                                                                 intval($r[0]['id'])
325                                                                         );
326                                                                 }               
327                                                                 continue;
328                                                         }
329                                                         $datarray['title'] = notags(trim($meta->subject));
330                                                         $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
331         
332                                                         $r = email_get_msg($mbox,$msg_uid);
333                                                         if(! $r)
334                                                                 continue;
335                                                         $datarray['body'] = escape_tags($r['body']);
336                                                         $datarray['uid'] = $importer_uid;
337                                                         $datarray['contact-id'] = $contact['id'];
338                                                         $datarray['private'] = 1;
339                                                         $datarray['author-name'] = $contact['name'];
340                                                         $datarray['author-link'] = 'mailbox';
341                                                         $datarray['author-avatar'] = $contact['photo'];
342                                                 
343                                                         item_store($datarray);
344                                                 }
345                                         }
346                                 }
347                         }
348                         elseif($contact['network'] === NETWORK_FACEBOOK) {
349                                 // TODO: work in progress                       
350                         }
351
352                         if($xml) {
353                                 logger('poller: received xml : ' . $xml, LOGGER_DATA);
354
355                                 if(! strstr($xml,'<?xml')) {
356                                         logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
357                                         $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
358                                                 dbesc(datetime_convert()),
359                                                 intval($contact['id'])
360                                         );
361                                         continue;
362                                 }
363
364
365                                 consume_feed($xml,$importer,$contact,$hub,1, true);
366
367                                 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
368         
369                                 consume_feed($xml,$importer,$contact,$hub,1);
370
371
372                                 if((strlen($hub)) && ($hub_update) && (($contact['rel'] == REL_BUD) || (($contact['network'] === NETWORK_OSTATUS) && (! $contact['readonly'])))) {
373                                         logger('poller: subscribing to hub(s) : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
374                                         $hubs = explode(',', $hub);
375                                         if(count($hubs)) {
376                                                 foreach($hubs as $h) {
377                                                         $h = trim($h);
378                                                         if(! strlen($h))
379                                                                 continue;
380                                                         subscribe_to_hub($h,$importer,$contact);
381                                                 }
382                                         }
383                                 }
384                         }
385
386                         $updated = datetime_convert();
387
388                         $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d LIMIT 1",
389                                 dbesc($updated),
390                                 dbesc($updated),
391                                 intval($contact['id'])
392                         );
393
394                         // loop - next contact
395                 }
396         }
397
398         if($mbox && function_exists('imap_close'))
399                 imap_close($mbox);
400                 
401         return;
402 }
403
404 if (array_search(__file__,get_included_files())===0){
405   poller_run($argv,$argc);
406   killme();
407 }