3 require_once("boot.php");
6 function poller_run($argv, $argc){
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);
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');
28 load_config('config');
29 load_config('system');
31 $a->set_baseurl(get_config('system','url'));
35 logger('poller: start');
37 // run queue delivery process in the background
39 proc_run('php',"include/queue.php");
41 // once daily run expire in background
43 $d1 = get_config('system','last_expire_day');
44 $d2 = intval(datetime_convert('UTC','UTC','now','d'));
46 if($d2 != intval($d1)) {
47 set_config('system','last_expire_day',$d2);
48 proc_run('php','include/expire.php');
52 q("DELETE FROM `cache` WHERE `updated` < '%s'",
53 dbesc(datetime_convert('UTC','UTC',"now - 30 days")));
61 if(($argc > 1) && ($argv[1] == 'force'))
64 if(($argc > 1) && ($argv[1] == 'restart')) {
66 $generation = intval($argv[2]);
71 if(($argc > 1) && intval($argv[1])) {
72 $manual_id = intval($argv[1]);
76 $sql_extra = (($manual_id) ? " AND `id` = $manual_id " : "");
80 $d = datetime_convert();
83 call_hooks('cron', $d);
86 $contacts = q("SELECT `id` FROM `contact`
87 WHERE ( `rel` = %d OR `rel` = %d ) AND `poll` != ''
89 AND `self` = 0 AND `blocked` = 0 AND `readonly` = 0 ORDER BY RAND()",
90 intval(CONTACT_IS_SHARING),
91 intval(CONTACT_IS_FRIEND)
94 if(! count($contacts)) {
98 foreach($contacts as $c) {
100 $res = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
107 foreach($res as $contact) {
112 $contact['last-update'] = '0000-00-00 00:00:00';
114 if($contact['priority'] || $contact['subhub']) {
119 $t = $contact['last-update'];
121 // We should be getting everything via a hub. But just to be sure, let's check once a day.
122 // (You can make this more or less frequent if desired by setting 'pushpoll_frequency' appropriately)
123 // This also lets us update our subscription to the hub, and add or replace hubs in case it
124 // changed. We will only update hubs once a day, regardless of 'pushpoll_frequency'.
127 if($contact['subhub']) {
128 $interval = get_config('system','pushpoll_frequency');
129 $contact['priority'] = (($interval !== false) ? intval($interval) : 3);
132 if((datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day")) || $force)
137 * Based on $contact['priority'], should we poll this site now? Or later?
140 switch ($contact['priority']) {
142 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 month"))
146 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 week"))
150 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
154 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 12 hour"))
159 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 hour"))
163 if((! $update) && (! $force))
167 // Check to see if we are running out of memory - if so spawn a new process and kill this one
169 $avail_memory = return_bytes(ini_get('memory_limit'));
170 $memused = memory_get_peak_usage(true);
171 if(intval($avail_memory)) {
172 if(($memused / $avail_memory) > 0.95) {
173 if($generation + 1 > 10) {
174 logger('poller: maximum number of spawns exceeded. Terminating.');
177 logger('poller: memory exceeded. ' . $memused . ' bytes used. Spawning new poll.');
178 proc_run('php', 'include/poller.php', 'restart', (string) $generation + 1);
183 $importer_uid = $contact['uid'];
185 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
186 intval($importer_uid)
193 logger("poller: poll: IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
195 $last_update = (($contact['last-update'] === '0000-00-00 00:00:00')
196 ? datetime_convert('UTC','UTC','now - 30 days', ATOM_TIME)
197 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
200 if($contact['network'] === NETWORK_DFRN) {
202 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
204 if(intval($contact['duplex']) && $contact['dfrn-id'])
205 $idtosend = '0:' . $orig_id;
206 if(intval($contact['duplex']) && $contact['issued-id'])
207 $idtosend = '1:' . $orig_id;
209 // they have permission to write to us. We already filtered this in the contact query.
212 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
213 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
214 . '&type=data&last_update=' . $last_update
217 $handshake_xml = fetch_url($url);
219 logger('poller: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
222 if(! $handshake_xml) {
223 logger("poller: $url appears to be dead - marking for death ");
224 // dead connection - might be a transient event, or this might
225 // mean the software was uninstalled or the domain expired.
226 // Will keep trying for one month.
227 mark_for_death($contact);
229 // set the last-update so we don't keep polling
231 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
232 dbesc(datetime_convert()),
233 intval($contact['id'])
239 if(! strstr($handshake_xml,'<?xml')) {
240 logger('poller: response from ' . $url . ' did not contain XML.');
241 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
242 dbesc(datetime_convert()),
243 intval($contact['id'])
249 $res = parse_xml_string($handshake_xml);
251 if(intval($res->status) == 1) {
252 logger("poller: $url replied status 1 - marking for death ");
254 // we may not be friends anymore. Will keep trying for one month.
255 // set the last-update so we don't keep polling
257 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
258 dbesc(datetime_convert()),
259 intval($contact['id'])
262 mark_for_death($contact);
265 if($contact['term-date'] != '0000-00-00 00:00:00') {
266 logger("poller: $url back from the dead - removing mark for death");
267 unmark_for_death($contact);
271 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
276 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
277 $challenge = hex2bin((string) $res->challenge);
281 if(($contact['duplex']) && strlen($contact['prvkey'])) {
282 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
283 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
286 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
287 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
290 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
292 if(strpos($final_dfrn_id,':') == 1)
293 $final_dfrn_id = substr($final_dfrn_id,2);
295 if($final_dfrn_id != $orig_id) {
296 logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
297 // did not decode properly - cannot trust this site
301 $postvars['dfrn_id'] = $idtosend;
302 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
303 $postvars['perm'] = 'rw';
305 $xml = post_url($contact['poll'],$postvars);
307 elseif(($contact['network'] === NETWORK_OSTATUS)
308 || ($contact['network'] === NETWORK_DIASPORA)
309 || ($contact['network'] === NETWORK_FEED) ) {
311 // Upgrading DB fields from an older Friendika version
312 // Will only do this once per notify-enabled OStatus contact
313 // or if relationship changes
315 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
317 if($stat_writeable != $contact['writable']) {
318 q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d LIMIT 1",
319 intval($stat_writeable),
320 intval($contact['id'])
324 // Are we allowed to import from this person?
326 if($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly'])
329 $xml = fetch_url($contact['poll']);
331 elseif($contact['network'] === NETWORK_MAIL) {
333 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
338 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
339 intval($importer_uid)
341 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
342 intval($importer_uid)
344 if(count($x) && count($mailconf)) {
345 $mailbox = construct_mailbox_name($mailconf[0]);
347 openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
348 $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
351 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
352 dbesc(datetime_convert()),
353 intval($mailconf[0]['id']),
354 intval($importer_uid)
360 $msgs = email_poll($mbox,$contact['addr']);
363 foreach($msgs as $msg_uid) {
365 $meta = email_msg_meta($mbox,$msg_uid);
366 $headers = email_msg_headers($mbox,$msg_uid);
368 // look for a 'references' header and try and match with a parent item we have locally.
370 $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
371 $datarray['uri'] = trim($meta->message_id,'<>');
374 $refs_arr = explode(' ', $raw_refs);
375 if(count($refs_arr)) {
376 for($x = 0; $x < count($refs_arr); $x ++)
377 $refs_arr[$x] = "'" . str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x])) . "'";
379 $qstr = implode(',',$refs_arr);
380 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
381 intval($importer_uid)
384 $datarray['parent-uri'] = $r[0]['uri'];
388 if(! x($datarray,'parent-uri'))
389 $datarray['parent-uri'] = $datarray['uri'];
391 // Have we seen it before?
392 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
393 intval($importer_uid),
394 dbesc($datarray['uri'])
398 if($meta->deleted && ! $r[0]['deleted']) {
399 q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d LIMIT 1",
400 dbesc(datetime_convert()),
406 $datarray['title'] = notags(trim($meta->subject));
407 $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
409 $r = email_get_msg($mbox,$msg_uid);
412 $datarray['body'] = escape_tags($r['body']);
414 // some mailing lists have the original author as 'from' - add this sender info to msg body.
415 // todo: adding a gravatar for the original author would be cool
417 if(! stristr($meta->from,$contact['addr']))
418 $datarray['body'] = t('From: ') . escape_tags($meta->from) . "\n\n" . $datarray['body'];
420 $datarray['uid'] = $importer_uid;
421 $datarray['contact-id'] = $contact['id'];
422 if($datarray['parent-uri'] === $datarray['uri'])
423 $datarray['private'] = 1;
424 $datarray['author-name'] = $contact['name'];
425 $datarray['author-link'] = 'mailbox';
426 $datarray['author-avatar'] = $contact['photo'];
428 $stored_item = item_store($datarray);
429 q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
430 dbesc($datarray['parent-uri']),
431 intval($importer_uid)
433 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
442 elseif($contact['network'] === NETWORK_FACEBOOK) {
443 // This is picked up by the Facebook plugin on a cron hook.
448 logger('poller: received xml : ' . $xml, LOGGER_DATA);
450 if(! strstr($xml,'<?xml')) {
451 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
452 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
453 dbesc(datetime_convert()),
454 intval($contact['id'])
460 consume_feed($xml,$importer,$contact,$hub,1, true);
462 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
464 consume_feed($xml,$importer,$contact,$hub,1);
467 if((strlen($hub)) && ($hub_update) && (($contact['rel'] == CONTACT_IS_FRIEND) || (($contact['network'] === NETWORK_OSTATUS) && (! $contact['readonly'])))) {
468 logger('poller: subscribing to hub(s) : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
469 $hubs = explode(',', $hub);
471 foreach($hubs as $h) {
475 subscribe_to_hub($h,$importer,$contact);
481 $updated = datetime_convert();
483 $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d LIMIT 1",
486 intval($contact['id'])
489 // loop - next contact
497 if (array_search(__file__,get_included_files())===0){
498 poller_run($argv,$argc);