]> git.mxchange.org Git - friendica.git/blob - include/poller.php
sql error diaspora re-queue
[friendica.git] / include / poller.php
1 <?php
2
3 require_once("boot.php");
4
5
6 function poller_run($argv, $argc){
7         global $a, $db;
8
9         if(is_null($a)) {
10                 $a = new App;
11         }
12   
13         if(is_null($db)) {
14             @include(".htconfig.php");
15         require_once("dba.php");
16             $db = new dba($db_host, $db_user, $db_pass, $db_data);
17         unset($db_host, $db_user, $db_pass, $db_data);
18         };
19
20
21         require_once('include/session.php');
22         require_once('include/datetime.php');
23         require_once('library/simplepie/simplepie.inc');
24         require_once('include/items.php');
25         require_once('include/Contact.php');
26         require_once('include/email.php');
27
28         load_config('config');
29         load_config('system');
30
31         $a->set_baseurl(get_config('system','url'));
32
33         load_hooks();
34
35         logger('poller: start');
36         
37         // run queue delivery process in the background
38
39         proc_run('php',"include/queue.php");
40         
41         // expire any expired accounts
42
43         q("UPDATE user SET `account_expired` = 1 where `account_expired` = 0 
44                 AND `account_expires_on` != '0000-00-00 00:00:00' 
45                 AND `account_expires_on` < UTC_TIMESTAMP() ");
46   
47         // once daily run expire in background
48
49         $d1 = get_config('system','last_expire_day');
50         $d2 = intval(datetime_convert('UTC','UTC','now','d'));
51
52         if($d2 != intval($d1)) {
53                 set_config('system','last_expire_day',$d2);
54                 proc_run('php','include/expire.php');
55         }
56
57         // clear old cache
58         q("DELETE FROM `cache` WHERE `updated` < '%s'",
59                 dbesc(datetime_convert('UTC','UTC',"now - 30 days")));
60
61         $manual_id  = 0;
62         $generation = 0;
63         $hub_update = false;
64         $force      = false;
65         $restart    = false;
66
67         if(($argc > 1) && ($argv[1] == 'force'))
68                 $force = true;
69
70         if(($argc > 1) && ($argv[1] == 'restart')) {
71                 $restart = true;
72                 $generation = intval($argv[2]);
73                 if(! $generation)
74                         killme();               
75         }
76
77         if(($argc > 1) && intval($argv[1])) {
78                 $manual_id = intval($argv[1]);
79                 $force     = true;
80         }
81
82         $sql_extra = (($manual_id) ? " AND `id` = $manual_id " : "");
83
84         reload_plugins();
85
86         $d = datetime_convert();
87
88         if(! $restart)
89                 proc_run('php','include/cronhooks.php');
90
91         // Only poll from those with suitable relationships,
92         // and which have a polling address and ignore Diaspora since 
93         // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
94
95         $contacts = q("SELECT `contact`.`id` FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid` 
96                 WHERE ( `rel` = %d OR `rel` = %d ) AND `poll` != ''
97                 AND `network` != '%s'
98                 $sql_extra 
99                 AND `self` = 0 AND `contact`.`blocked` = 0 AND `contact`.`readonly` = 0 
100                 AND `user`.`account_expired` = 0 ORDER BY RAND()",
101                 intval(CONTACT_IS_SHARING),
102                 intval(CONTACT_IS_FRIEND),
103                 dbesc(NETWORK_DIASPORA)
104         );
105
106         if(! count($contacts)) {
107                 return;
108         }
109
110         foreach($contacts as $c) {
111
112                 $res = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
113                         intval($c['id'])
114                 );
115
116                 if((! $res) || (! count($res)))
117                         continue;
118
119                 foreach($res as $contact) {
120
121                         $xml = false;
122
123                         if($manual_id)
124                                 $contact['last-update'] = '0000-00-00 00:00:00';
125
126                         if($contact['priority'] || $contact['subhub']) {
127
128                                 $hub_update = true;
129                                 $update     = false;
130
131                                 $t = $contact['last-update'];
132
133                                 // We should be getting everything via a hub. But just to be sure, let's check once a day.
134                                 // (You can make this more or less frequent if desired by setting 'pushpoll_frequency' appropriately)
135                                 // This also lets us update our subscription to the hub, and add or replace hubs in case it
136                                 // changed. We will only update hubs once a day, regardless of 'pushpoll_frequency'. 
137
138
139                                 if($contact['subhub']) {
140                                         $interval = get_config('system','pushpoll_frequency');
141                                         $contact['priority'] = (($interval !== false) ? intval($interval) : 3);
142                                         $hub_update = false;
143         
144                                         if((datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day")) || $force)
145                                                         $hub_update = true;
146                                 }
147                                 else
148                                         $hub_update = false;
149
150                                 /**
151                                  * Based on $contact['priority'], should we poll this site now? Or later?
152                                  */                     
153
154                                 switch ($contact['priority']) {
155                                         case 5:
156                                                 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 month"))
157                                                         $update = true;
158                                                 break;                                  
159                                         case 4:
160                                                 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 week"))
161                                                         $update = true;
162                                                 break;
163                                         case 3:
164                                                 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
165                                                         $update = true;
166                                                 break;
167                                         case 2:
168                                                 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 12 hour"))
169                                                         $update = true;
170                                                 break;
171                                         case 1:
172                                         default:
173                                                 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 hour"))
174                                                         $update = true;
175                                                 break;
176                                 }
177                                 if((! $update) && (! $force))
178                                         continue;
179                         }
180
181                         // Check to see if we are running out of memory - if so spawn a new process and kill this one
182
183                         $avail_memory = return_bytes(ini_get('memory_limit'));
184                         $memused = memory_get_peak_usage(true);
185                         if(intval($avail_memory)) {
186                                 if(($memused / $avail_memory) > 0.95) {
187                                         if($generation + 1 > 10) {
188                                                 logger('poller: maximum number of spawns exceeded. Terminating.');
189                                                 killme();
190                                         }
191                                         logger('poller: memory exceeded. ' . $memused . ' bytes used. Spawning new poll.');
192                                         proc_run('php', 'include/poller.php', 'restart', (string) $generation + 1);
193                                         killme();
194                                 }
195                         }
196
197                         $importer_uid = $contact['uid'];
198                 
199                         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
200                                 intval($importer_uid)
201                         );
202                         if(! count($r))
203                                 continue;
204
205                         $importer = $r[0];
206
207                         logger("poller: poll: IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
208
209                         $last_update = (($contact['last-update'] === '0000-00-00 00:00:00') 
210                                 ? datetime_convert('UTC','UTC','now - 30 days', ATOM_TIME)
211                                 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
212                         );
213
214                         if($contact['network'] === NETWORK_DFRN) {
215
216                                 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
217
218                                 if(intval($contact['duplex']) && $contact['dfrn-id'])
219                                         $idtosend = '0:' . $orig_id;
220                                 if(intval($contact['duplex']) && $contact['issued-id'])
221                                         $idtosend = '1:' . $orig_id;
222
223                                 // they have permission to write to us. We already filtered this in the contact query.
224                                 $perm = 'rw';
225
226                                 $url = $contact['poll'] . '?dfrn_id=' . $idtosend 
227                                         . '&dfrn_version=' . DFRN_PROTOCOL_VERSION 
228                                         . '&type=data&last_update=' . $last_update 
229                                         . '&perm=' . $perm ;
230         
231                                 $handshake_xml = fetch_url($url);
232
233                                 logger('poller: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
234
235
236                                 if(! $handshake_xml) {
237                                         logger("poller: $url appears to be dead - marking for death ");
238                                         // dead connection - might be a transient event, or this might
239                                         // mean the software was uninstalled or the domain expired. 
240                                         // Will keep trying for one month.
241                                         mark_for_death($contact);
242
243                                         // set the last-update so we don't keep polling
244
245                                         $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
246                                                 dbesc(datetime_convert()),
247                                                 intval($contact['id'])
248                                         );
249
250                                         continue;
251                                 }
252
253                                 if(! strstr($handshake_xml,'<?xml')) {
254                                         logger('poller: response from ' . $url . ' did not contain XML.');
255                                         $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
256                                                 dbesc(datetime_convert()),
257                                                 intval($contact['id'])
258                                         );
259                                         continue;
260                                 }
261
262
263                                 $res = parse_xml_string($handshake_xml);
264         
265                                 if(intval($res->status) == 1) {
266                                         logger("poller: $url replied status 1 - marking for death ");
267
268                                         // we may not be friends anymore. Will keep trying for one month.
269                                         // set the last-update so we don't keep polling
270
271                                         $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
272                                                 dbesc(datetime_convert()),
273                                                 intval($contact['id'])
274                                         );
275
276                                         mark_for_death($contact);
277                                 }
278                                 else {
279                                         if($contact['term-date'] != '0000-00-00 00:00:00') {
280                                                 logger("poller: $url back from the dead - removing mark for death");
281                                                 unmark_for_death($contact);
282                                         }
283                                 }
284
285                                 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
286                                         continue;
287
288                                 $postvars = array();
289
290                                 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
291                                 $challenge    = hex2bin((string) $res->challenge);
292
293                                 $final_dfrn_id = '';
294
295                                 if(($contact['duplex']) && strlen($contact['prvkey'])) {
296                                         openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
297                                         openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
298                                 }
299                                 else {
300                                         openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
301                                         openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
302                                 }
303
304                                 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
305
306                                 if(strpos($final_dfrn_id,':') == 1)
307                                         $final_dfrn_id = substr($final_dfrn_id,2);
308
309                                 if($final_dfrn_id != $orig_id) {
310                                         logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);    
311                                         // did not decode properly - cannot trust this site 
312                                         continue;
313                                 }
314
315                                 $postvars['dfrn_id'] = $idtosend;
316                                 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
317                                 $postvars['perm'] = 'rw';
318
319                                 $xml = post_url($contact['poll'],$postvars);
320                         }
321                         elseif(($contact['network'] === NETWORK_OSTATUS) 
322                                 || ($contact['network'] === NETWORK_DIASPORA)
323                                 || ($contact['network'] === NETWORK_FEED) ) {
324
325                                 // Upgrading DB fields from an older Friendika version
326                                 // Will only do this once per notify-enabled OStatus contact
327                                 // or if relationship changes
328
329                                 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
330
331                                 if($stat_writeable != $contact['writable']) {
332                                         q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d LIMIT 1",
333                                                 intval($stat_writeable),
334                                                 intval($contact['id'])
335                                         );
336                                 }
337
338                                 // Are we allowed to import from this person?
339
340                                 if($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly'])
341                                         continue;
342
343                                 $xml = fetch_url($contact['poll']);
344                         }
345                         elseif($contact['network'] === NETWORK_MAIL) {
346
347                                 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
348                                 if($mail_disabled)
349                                         continue;
350
351                                 $mbox = null;
352                                 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
353                                         intval($importer_uid)
354                                 );
355                                 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
356                                         intval($importer_uid)
357                                 );
358                                 if(count($x) && count($mailconf)) {
359                                     $mailbox = construct_mailbox_name($mailconf[0]);
360                                         $password = '';
361                                         openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
362                                         $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
363                                         unset($password);
364                                         if($mbox) {
365                                                 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
366                                                         dbesc(datetime_convert()),
367                                                         intval($mailconf[0]['id']),
368                                                         intval($importer_uid)
369                                                 );
370                                         }
371                                 }
372                                 if($mbox) {
373
374                                         $msgs = email_poll($mbox,$contact['addr']);
375
376                                         if(count($msgs)) {
377                                                 foreach($msgs as $msg_uid) {
378                                                         $datarray = array();
379                                                         $meta = email_msg_meta($mbox,$msg_uid);
380                                                         $headers = email_msg_headers($mbox,$msg_uid);
381
382                                                         // look for a 'references' header and try and match with a parent item we have locally.
383
384                                                         $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
385                                                         $datarray['uri'] = trim($meta->message_id,'<>');
386
387                                                         if($raw_refs) {
388                                                                 $refs_arr = explode(' ', $raw_refs);
389                                                                 if(count($refs_arr)) {
390                                                                         for($x = 0; $x < count($refs_arr); $x ++)
391                                                                                 $refs_arr[$x] = "'" . str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x])) . "'";
392                                                                 }
393                                                                 $qstr = implode(',',$refs_arr);
394                                                                 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
395                                                                         intval($importer_uid)
396                                                                 );
397                                                                 if(count($r))
398                                                                         $datarray['parent-uri'] = $r[0]['uri'];
399                                                         }
400
401
402                                                         if(! x($datarray,'parent-uri'))
403                                                                 $datarray['parent-uri'] = $datarray['uri'];
404
405                                                         // Have we seen it before?
406                                                         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
407                                                                 intval($importer_uid),
408                                                                 dbesc($datarray['uri'])
409                                                         );
410
411                                                         if(count($r)) {
412                                                                 if($meta->deleted && ! $r[0]['deleted']) {
413                                                                         q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d LIMIT 1",
414                                                                                 dbesc(datetime_convert()),
415                                                                                 intval($r[0]['id'])
416                                                                         );
417                                                                 }               
418                                                                 continue;
419                                                         }
420                                                         $datarray['title'] = notags(trim($meta->subject));
421                                                         $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
422         
423                                                         $r = email_get_msg($mbox,$msg_uid);
424                                                         if(! $r)
425                                                                 continue;
426                                                         $datarray['body'] = escape_tags($r['body']);
427
428                                                         // some mailing lists have the original author as 'from' - add this sender info to msg body. 
429                                                         // todo: adding a gravatar for the original author would be cool
430
431                                                         if(! stristr($meta->from,$contact['addr']))
432                                                                 $datarray['body'] = t('From: ') . escape_tags($meta->from) . "\n\n" . $datarray['body'];
433
434                                                         $datarray['uid'] = $importer_uid;
435                                                         $datarray['contact-id'] = $contact['id'];
436                                                         if($datarray['parent-uri'] === $datarray['uri'])
437                                                                 $datarray['private'] = 1;
438                                                         if(! get_pconfig($importer_uid,'system','allow_public_email_replies')) {
439                                                                 $datarray['private'] = 1;
440                                                                 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
441                                                         }
442                                                         $datarray['author-name'] = $contact['name'];
443                                                         $datarray['author-link'] = 'mailbox';
444                                                         $datarray['author-avatar'] = $contact['photo'];
445                                                 
446                                                         $stored_item = item_store($datarray);
447                                                         q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
448                                                                 dbesc($datarray['parent-uri']),
449                                                                 intval($importer_uid)
450                                                         );
451                                                         q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
452                                                                 intval($stored_item)
453                                                         );
454                                                 }
455                                         }
456
457                                         imap_close($mbox);
458                                 }
459                         }
460                         elseif($contact['network'] === NETWORK_FACEBOOK) {
461                                 // This is picked up by the Facebook plugin on a cron hook.
462                                 // Ignored here.                        
463                         }
464
465                         if($xml) {
466                                 logger('poller: received xml : ' . $xml, LOGGER_DATA);
467
468                                 if(! strstr($xml,'<?xml')) {
469                                         logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
470                                         $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
471                                                 dbesc(datetime_convert()),
472                                                 intval($contact['id'])
473                                         );
474                                         continue;
475                                 }
476
477
478                                 consume_feed($xml,$importer,$contact,$hub,1, true);
479
480                                 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
481         
482                                 consume_feed($xml,$importer,$contact,$hub,1);
483
484                                 $hubmode = 'subscribe';
485                                 if($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly'])
486                                         $hubmode = 'unsubscribe';
487
488                                 if((strlen($hub)) && ($hub_update) && ($contact['rel'] != CONTACT_IS_FOLLOWER)) {
489                                         logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
490                                         $hubs = explode(',', $hub);
491                                         if(count($hubs)) {
492                                                 foreach($hubs as $h) {
493                                                         $h = trim($h);
494                                                         if(! strlen($h))
495                                                                 continue;
496                                                         subscribe_to_hub($h,$importer,$contact,$hubmode);
497                                                 }
498                                         }
499                                 }
500                         }
501
502
503                         $updated = datetime_convert();
504
505                         $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d LIMIT 1",
506                                 dbesc($updated),
507                                 dbesc($updated),
508                                 intval($contact['id'])
509                         );
510
511                         // loop - next contact
512                 }
513         }
514
515                 
516         return;
517 }
518
519 if (array_search(__file__,get_included_files())===0){
520   poller_run($argv,$argc);
521   killme();
522 }