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');
27 require_once('include/socgraph.php');
28 require_once('include/pidfile.php');
30 load_config('config');
31 load_config('system');
33 $lockpath = get_config('system','lockpath');
34 if ($lockpath != '') {
35 $pidfile = new pidfile($lockpath, 'poller.lck');
36 if($pidfile->is_already_running()) {
37 logger("poller: Already running");
42 $a->set_baseurl(get_config('system','url'));
46 logger('poller: start');
48 // run queue delivery process in the background
50 proc_run('php',"include/queue.php");
52 // expire any expired accounts
54 q("UPDATE user SET `account_expired` = 1 where `account_expired` = 0
55 AND `account_expires_on` != '0000-00-00 00:00:00'
56 AND `account_expires_on` < UTC_TIMESTAMP() ");
58 $abandon_days = intval(get_config('system','account_abandon_days'));
64 // once daily run birthday_updates and then expire in background
66 $d1 = get_config('system','last_expire_day');
67 $d2 = intval(datetime_convert('UTC','UTC','now','d'));
69 if($d2 != intval($d1)) {
71 update_contact_birthdays();
75 set_config('system','last_expire_day',$d2);
76 proc_run('php','include/expire.php');
82 // clear item cache files if they are older than one day
83 $cache = get_config('system','itemcache');
84 if (($cache != '') and is_dir($cache)) {
85 if ($dh = opendir($cache)) {
86 while (($file = readdir($dh)) !== false) {
87 $fullpath = $cache."/".$file;
88 if ((filetype($fullpath) == "file") and filectime($fullpath) < (time() - 86400))
101 if(($argc > 1) && ($argv[1] == 'force'))
104 if(($argc > 1) && ($argv[1] == 'restart')) {
106 $generation = intval($argv[2]);
111 if(($argc > 1) && intval($argv[1])) {
112 $manual_id = intval($argv[1]);
116 $sql_extra = (($manual_id) ? " AND `id` = $manual_id " : "");
120 $d = datetime_convert();
123 proc_run('php','include/cronhooks.php');
125 // Only poll from those with suitable relationships,
126 // and which have a polling address and ignore Diaspora since
127 // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
129 $abandon_sql = (($abandon_days)
130 ? sprintf(" AND `user`.`login_date` > UTC_TIMESTAMP() - INTERVAL %d DAY ", intval($abandon_days))
134 $contacts = q("SELECT `contact`.`id` FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
135 WHERE ( `rel` = %d OR `rel` = %d ) AND `poll` != ''
136 AND NOT `network` IN ( '%s', '%s' )
138 AND `self` = 0 AND `contact`.`blocked` = 0 AND `contact`.`readonly` = 0
139 AND `user`.`account_expired` = 0 $abandon_sql ORDER BY RAND()",
140 intval(CONTACT_IS_SHARING),
141 intval(CONTACT_IS_FRIEND),
142 dbesc(NETWORK_DIASPORA),
143 dbesc(NETWORK_FACEBOOK)
146 if(! count($contacts)) {
150 foreach($contacts as $c) {
152 $res = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
156 if((! $res) || (! count($res)))
159 foreach($res as $contact) {
164 $contact['last-update'] = '0000-00-00 00:00:00';
166 if($contact['network'] === NETWORK_DFRN)
167 $contact['priority'] = 2;
169 if(!get_config('system','ostatus_use_priority') and ($contact['network'] === NETWORK_OSTATUS))
170 $contact['priority'] = 2;
172 if($contact['priority'] || $contact['subhub']) {
177 $t = $contact['last-update'];
179 // We should be getting everything via a hub. But just to be sure, let's check once a day.
180 // (You can make this more or less frequent if desired by setting 'pushpoll_frequency' appropriately)
181 // This also lets us update our subscription to the hub, and add or replace hubs in case it
182 // changed. We will only update hubs once a day, regardless of 'pushpoll_frequency'.
185 if($contact['subhub']) {
186 $interval = get_config('system','pushpoll_frequency');
187 $contact['priority'] = (($interval !== false) ? intval($interval) : 3);
190 if((datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day")) || $force)
197 * Based on $contact['priority'], should we poll this site now? Or later?
200 switch ($contact['priority']) {
202 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 month"))
206 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 week"))
210 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
214 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 12 hour"))
219 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 hour"))
223 if((! $update) && (! $force))
227 // Check to see if we are running out of memory - if so spawn a new process and kill this one
229 $avail_memory = return_bytes(ini_get('memory_limit'));
230 $memused = memory_get_peak_usage(true);
231 if(intval($avail_memory)) {
232 if(($memused / $avail_memory) > 0.95) {
233 if($generation + 1 > 10) {
234 logger('poller: maximum number of spawns exceeded. Terminating.');
237 logger('poller: memory exceeded. ' . $memused . ' bytes used. Spawning new poll.');
238 proc_run('php', 'include/poller.php', 'restart', (string) $generation + 1);
243 $importer_uid = $contact['uid'];
245 $r = q("SELECT `contact`.*, `user`.`page-flags` FROM `contact` LEFT JOIN `user` on `contact`.`uid` = `user`.`uid` WHERE `user`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
246 intval($importer_uid)
253 logger("poller: poll: ({$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
255 $last_update = (($contact['last-update'] === '0000-00-00 00:00:00')
256 ? datetime_convert('UTC','UTC','now - 30 days', ATOM_TIME)
257 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
260 if($contact['network'] === NETWORK_DFRN) {
262 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
264 if(intval($contact['duplex']) && $contact['dfrn-id'])
265 $idtosend = '0:' . $orig_id;
266 if(intval($contact['duplex']) && $contact['issued-id'])
267 $idtosend = '1:' . $orig_id;
269 // they have permission to write to us. We already filtered this in the contact query.
272 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
273 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
274 . '&type=data&last_update=' . $last_update
277 $handshake_xml = fetch_url($url);
279 logger('poller: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
282 if(! $handshake_xml) {
283 logger("poller: $url appears to be dead - marking for death ");
284 // dead connection - might be a transient event, or this might
285 // mean the software was uninstalled or the domain expired.
286 // Will keep trying for one month.
287 mark_for_death($contact);
289 // set the last-update so we don't keep polling
291 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
292 dbesc(datetime_convert()),
293 intval($contact['id'])
299 if(! strstr($handshake_xml,'<?xml')) {
300 logger('poller: response from ' . $url . ' did not contain XML.');
301 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
302 dbesc(datetime_convert()),
303 intval($contact['id'])
309 $res = parse_xml_string($handshake_xml);
311 if(intval($res->status) == 1) {
312 logger("poller: $url replied status 1 - marking for death ");
314 // we may not be friends anymore. Will keep trying for one month.
315 // set the last-update so we don't keep polling
317 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
318 dbesc(datetime_convert()),
319 intval($contact['id'])
322 mark_for_death($contact);
325 if($contact['term-date'] != '0000-00-00 00:00:00') {
326 logger("poller: $url back from the dead - removing mark for death");
327 unmark_for_death($contact);
331 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
334 if(((float) $res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
335 q("update contact set poco = '%s' where id = %d limit 1",
336 dbesc(str_replace('/profile/','/poco/', $contact['url'])),
337 intval($contact['id'])
343 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
344 $challenge = hex2bin((string) $res->challenge);
348 if(($contact['duplex']) && strlen($contact['prvkey'])) {
349 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
350 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
353 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
354 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
357 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
359 if(strpos($final_dfrn_id,':') == 1)
360 $final_dfrn_id = substr($final_dfrn_id,2);
362 if($final_dfrn_id != $orig_id) {
363 logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
364 // did not decode properly - cannot trust this site
368 $postvars['dfrn_id'] = $idtosend;
369 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
370 $postvars['perm'] = 'rw';
372 $xml = post_url($contact['poll'],$postvars);
374 elseif(($contact['network'] === NETWORK_OSTATUS)
375 || ($contact['network'] === NETWORK_DIASPORA)
376 || ($contact['network'] === NETWORK_FEED) ) {
378 // Upgrading DB fields from an older Friendica version
379 // Will only do this once per notify-enabled OStatus contact
380 // or if relationship changes
382 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
384 if($stat_writeable != $contact['writable']) {
385 q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d LIMIT 1",
386 intval($stat_writeable),
387 intval($contact['id'])
391 // Are we allowed to import from this person?
393 if($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly'])
396 $xml = fetch_url($contact['poll']);
398 elseif($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {
400 logger("Mail: Fetching");
402 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
406 logger("Mail: Enabled");
409 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
410 intval($importer_uid)
412 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
413 intval($importer_uid)
415 if(count($x) && count($mailconf)) {
416 $mailbox = construct_mailbox_name($mailconf[0]);
418 openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
419 $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
421 logger("Mail: Connect");
423 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
424 dbesc(datetime_convert()),
425 intval($mailconf[0]['id']),
426 intval($importer_uid)
431 logger("Mail: mbox");
433 $msgs = email_poll($mbox,$contact['addr']);
436 logger("Mail: Parsing ".count($msgs)." mails.");
438 foreach($msgs as $msg_uid) {
439 logger("Mail: Parsing mail ".$msg_uid);
442 $meta = email_msg_meta($mbox,$msg_uid);
443 $headers = email_msg_headers($mbox,$msg_uid);
445 // look for a 'references' header and try and match with a parent item we have locally.
447 $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
448 $datarray['uri'] = msgid2iri(trim($meta->message_id,'<>'));
451 $refs_arr = explode(' ', $raw_refs);
452 if(count($refs_arr)) {
453 for($x = 0; $x < count($refs_arr); $x ++)
454 $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x]))) . "'";
456 $qstr = implode(',',$refs_arr);
457 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
458 intval($importer_uid)
461 $datarray['parent-uri'] = $r[0]['uri'];
465 if(! x($datarray,'parent-uri'))
466 $datarray['parent-uri'] = $datarray['uri'];
468 // Have we seen it before?
469 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
470 intval($importer_uid),
471 dbesc($datarray['uri'])
475 logger("Mail: Seen before ".$msg_uid);
476 if($meta->deleted && ! $r[0]['deleted']) {
477 q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d LIMIT 1",
478 dbesc(datetime_convert()),
482 switch ($mailconf[0]['action']) {
486 logger("Mail: Deleting ".$msg_uid);
487 imap_delete($mbox, $msg_uid, FT_UID);
490 logger("Mail: Mark as seen ".$msg_uid);
491 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
494 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']);
495 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
496 if ($mailconf[0]['movetofolder'] != "")
497 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
503 // Decoding the header
504 $subject = imap_mime_header_decode($meta->subject);
505 $datarray['title'] = "";
506 foreach($subject as $subpart)
507 if ($subpart->charset != "default")
508 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
510 $datarray['title'] .= $subpart->text;
512 $datarray['title'] = notags(trim($datarray['title']));
514 //$datarray['title'] = notags(trim($meta->subject));
515 $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
518 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") or
519 (substr(strtolower($datarray['title']), 0, 3) == "re-") or
522 $r = email_get_msg($mbox,$msg_uid, $reply);
524 logger("Mail: can't fetch msg ".$msg_uid);
527 $datarray['body'] = escape_tags($r['body']);
529 logger("Mail: Importing ".$msg_uid);
531 // some mailing lists have the original author as 'from' - add this sender info to msg body.
532 // todo: adding a gravatar for the original author would be cool
534 if(! stristr($meta->from,$contact['addr'])) {
535 $from = imap_mime_header_decode($meta->from);
537 foreach($from as $frompart)
538 if ($frompart->charset != "default")
539 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
541 $fromdecoded .= $frompart->text;
543 $datarray['body'] = "[b]".t('From: ') . escape_tags($fromdecoded) . "[/b]\n\n" . $datarray['body'];
546 $datarray['uid'] = $importer_uid;
547 $datarray['contact-id'] = $contact['id'];
548 if($datarray['parent-uri'] === $datarray['uri'])
549 $datarray['private'] = 1;
550 if(($contact['network'] === NETWORK_MAIL) && (! get_pconfig($importer_uid,'system','allow_public_email_replies'))) {
551 $datarray['private'] = 1;
552 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
554 $datarray['author-name'] = $contact['name'];
555 $datarray['author-link'] = 'mailbox';
556 $datarray['author-avatar'] = $contact['photo'];
558 $stored_item = item_store($datarray);
559 q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
560 dbesc($datarray['parent-uri']),
561 intval($importer_uid)
563 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
566 switch ($mailconf[0]['action']) {
570 logger("Mail: Deleting ".$msg_uid);
571 imap_delete($mbox, $msg_uid, FT_UID);
574 logger("Mail: Mark as seen ".$msg_uid);
575 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
578 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']);
579 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
580 if ($mailconf[0]['movetofolder'] != "")
581 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
590 elseif($contact['network'] === NETWORK_FACEBOOK) {
591 // This is picked up by the Facebook plugin on a cron hook.
596 logger('poller: received xml : ' . $xml, LOGGER_DATA);
598 if(! strstr($xml,'<?xml')) {
599 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
600 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
601 dbesc(datetime_convert()),
602 intval($contact['id'])
608 consume_feed($xml,$importer,$contact,$hub,1,1);
610 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
612 consume_feed($xml,$importer,$contact,$hub,1,2);
614 $hubmode = 'subscribe';
615 if($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly'])
616 $hubmode = 'unsubscribe';
618 if((strlen($hub)) && ($hub_update) && ($contact['rel'] != CONTACT_IS_FOLLOWER)) {
619 logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
620 $hubs = explode(',', $hub);
622 foreach($hubs as $h) {
626 subscribe_to_hub($h,$importer,$contact,$hubmode);
633 $updated = datetime_convert();
635 $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d LIMIT 1",
638 intval($contact['id'])
642 // load current friends if possible.
644 if($contact['poco']) {
645 $r = q("SELECT count(*) as total from glink
646 where `cid` = %d and updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
647 intval($contact['id'])
651 if(! $r[0]['total']) {
652 poco_load($contact['id'],$importer_uid,$contact['poco']);
656 // loop - next contact
664 if (array_search(__file__,get_included_files())===0){
665 poller_run($argv,$argc);