3 require_once("boot.php");
4 require_once("include/quoteconvert.php");
7 function poller_run($argv, $argc){
15 @include(".htconfig.php");
16 require_once("dba.php");
17 $db = new dba($db_host, $db_user, $db_pass, $db_data);
18 unset($db_host, $db_user, $db_pass, $db_data);
22 require_once('include/session.php');
23 require_once('include/datetime.php');
24 require_once('library/simplepie/simplepie.inc');
25 require_once('include/items.php');
26 require_once('include/Contact.php');
27 require_once('include/email.php');
28 require_once('include/socgraph.php');
30 load_config('config');
31 load_config('system');
33 $a->set_baseurl(get_config('system','url'));
37 logger('poller: start');
39 // run queue delivery process in the background
41 proc_run('php',"include/queue.php");
43 // expire any expired accounts
45 q("UPDATE user SET `account_expired` = 1 where `account_expired` = 0
46 AND `account_expires_on` != '0000-00-00 00:00:00'
47 AND `account_expires_on` < UTC_TIMESTAMP() ");
49 $abandon_days = intval(get_config('system','account_abandon_days'));
55 // once daily run birthday_updates and then expire in background
57 $d1 = get_config('system','last_expire_day');
58 $d2 = intval(datetime_convert('UTC','UTC','now','d'));
60 if($d2 != intval($d1)) {
62 update_contact_birthdays();
66 set_config('system','last_expire_day',$d2);
67 proc_run('php','include/expire.php');
79 if(($argc > 1) && ($argv[1] == 'force'))
82 if(($argc > 1) && ($argv[1] == 'restart')) {
84 $generation = intval($argv[2]);
89 if(($argc > 1) && intval($argv[1])) {
90 $manual_id = intval($argv[1]);
94 $sql_extra = (($manual_id) ? " AND `id` = $manual_id " : "");
98 $d = datetime_convert();
101 proc_run('php','include/cronhooks.php');
103 // Only poll from those with suitable relationships,
104 // and which have a polling address and ignore Diaspora since
105 // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
107 $abandon_sql = (($abandon_days)
108 ? sprintf(" AND `user`.`login_date` > UTC_TIMESTAMP() - INTERVAL %d DAY ", intval($abandon_days))
112 $contacts = q("SELECT `contact`.`id` FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
113 WHERE ( `rel` = %d OR `rel` = %d ) AND `poll` != ''
114 AND NOT `network` IN ( '%s', '%s' )
116 AND `self` = 0 AND `contact`.`blocked` = 0 AND `contact`.`readonly` = 0
117 AND `user`.`account_expired` = 0 $abandon_sql ORDER BY RAND()",
118 intval(CONTACT_IS_SHARING),
119 intval(CONTACT_IS_FRIEND),
120 dbesc(NETWORK_DIASPORA),
121 dbesc(NETWORK_FACEBOOK)
124 if(! count($contacts)) {
128 foreach($contacts as $c) {
130 $res = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
134 if((! $res) || (! count($res)))
137 foreach($res as $contact) {
142 $contact['last-update'] = '0000-00-00 00:00:00';
144 if($contact['network'] === NETWORK_DFRN || $contact['network'] === NETWORK_OSTATUS)
145 $contact['priority'] = 2;
147 if($contact['priority'] || $contact['subhub']) {
152 $t = $contact['last-update'];
154 // We should be getting everything via a hub. But just to be sure, let's check once a day.
155 // (You can make this more or less frequent if desired by setting 'pushpoll_frequency' appropriately)
156 // This also lets us update our subscription to the hub, and add or replace hubs in case it
157 // changed. We will only update hubs once a day, regardless of 'pushpoll_frequency'.
160 if($contact['subhub']) {
161 $interval = get_config('system','pushpoll_frequency');
162 $contact['priority'] = (($interval !== false) ? intval($interval) : 3);
165 if((datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day")) || $force)
172 * Based on $contact['priority'], should we poll this site now? Or later?
175 switch ($contact['priority']) {
177 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 month"))
181 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 week"))
185 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
189 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 12 hour"))
194 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 hour"))
198 if((! $update) && (! $force))
202 // Check to see if we are running out of memory - if so spawn a new process and kill this one
204 $avail_memory = return_bytes(ini_get('memory_limit'));
205 $memused = memory_get_peak_usage(true);
206 if(intval($avail_memory)) {
207 if(($memused / $avail_memory) > 0.95) {
208 if($generation + 1 > 10) {
209 logger('poller: maximum number of spawns exceeded. Terminating.');
212 logger('poller: memory exceeded. ' . $memused . ' bytes used. Spawning new poll.');
213 proc_run('php', 'include/poller.php', 'restart', (string) $generation + 1);
218 $importer_uid = $contact['uid'];
220 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
221 intval($importer_uid)
228 logger("poller: poll: ({$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
230 $last_update = (($contact['last-update'] === '0000-00-00 00:00:00')
231 ? datetime_convert('UTC','UTC','now - 30 days', ATOM_TIME)
232 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
235 if($contact['network'] === NETWORK_DFRN) {
237 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
239 if(intval($contact['duplex']) && $contact['dfrn-id'])
240 $idtosend = '0:' . $orig_id;
241 if(intval($contact['duplex']) && $contact['issued-id'])
242 $idtosend = '1:' . $orig_id;
244 // they have permission to write to us. We already filtered this in the contact query.
247 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
248 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
249 . '&type=data&last_update=' . $last_update
252 $handshake_xml = fetch_url($url);
254 logger('poller: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
257 if(! $handshake_xml) {
258 logger("poller: $url appears to be dead - marking for death ");
259 // dead connection - might be a transient event, or this might
260 // mean the software was uninstalled or the domain expired.
261 // Will keep trying for one month.
262 mark_for_death($contact);
264 // set the last-update so we don't keep polling
266 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
267 dbesc(datetime_convert()),
268 intval($contact['id'])
274 if(! strstr($handshake_xml,'<?xml')) {
275 logger('poller: response from ' . $url . ' did not contain XML.');
276 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
277 dbesc(datetime_convert()),
278 intval($contact['id'])
284 $res = parse_xml_string($handshake_xml);
286 if(intval($res->status) == 1) {
287 logger("poller: $url replied status 1 - marking for death ");
289 // we may not be friends anymore. Will keep trying for one month.
290 // set the last-update so we don't keep polling
292 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
293 dbesc(datetime_convert()),
294 intval($contact['id'])
297 mark_for_death($contact);
300 if($contact['term-date'] != '0000-00-00 00:00:00') {
301 logger("poller: $url back from the dead - removing mark for death");
302 unmark_for_death($contact);
306 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
309 if(((float) $res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
310 q("update contact set poco = '%s' where id = %d limit 1",
311 dbesc(str_replace('/profile/','/poco/', $contact['url'])),
312 intval($contact['id'])
318 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
319 $challenge = hex2bin((string) $res->challenge);
323 if(($contact['duplex']) && strlen($contact['prvkey'])) {
324 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
325 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
328 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
329 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
332 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
334 if(strpos($final_dfrn_id,':') == 1)
335 $final_dfrn_id = substr($final_dfrn_id,2);
337 if($final_dfrn_id != $orig_id) {
338 logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
339 // did not decode properly - cannot trust this site
343 $postvars['dfrn_id'] = $idtosend;
344 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
345 $postvars['perm'] = 'rw';
347 $xml = post_url($contact['poll'],$postvars);
349 elseif(($contact['network'] === NETWORK_OSTATUS)
350 || ($contact['network'] === NETWORK_DIASPORA)
351 || ($contact['network'] === NETWORK_FEED) ) {
353 // Upgrading DB fields from an older Friendica version
354 // Will only do this once per notify-enabled OStatus contact
355 // or if relationship changes
357 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
359 if($stat_writeable != $contact['writable']) {
360 q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d LIMIT 1",
361 intval($stat_writeable),
362 intval($contact['id'])
366 // Are we allowed to import from this person?
368 if($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly'])
371 $xml = fetch_url($contact['poll']);
373 elseif($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {
375 logger("Mail: Fetching");
377 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
381 logger("Mail: Enabled");
384 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
385 intval($importer_uid)
387 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
388 intval($importer_uid)
390 if(count($x) && count($mailconf)) {
391 $mailbox = construct_mailbox_name($mailconf[0]);
393 openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
394 $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
396 logger("Mail: Connect");
398 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
399 dbesc(datetime_convert()),
400 intval($mailconf[0]['id']),
401 intval($importer_uid)
406 logger("Mail: mbox");
408 $msgs = email_poll($mbox,$contact['addr']);
411 logger("Mail: Parsing ".count($msgs)." mails.");
413 foreach($msgs as $msg_uid) {
414 logger("Mail: Parsing mail ".$msg_uid);
417 $meta = email_msg_meta($mbox,$msg_uid);
418 $headers = email_msg_headers($mbox,$msg_uid);
420 // look for a 'references' header and try and match with a parent item we have locally.
422 $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
423 $datarray['uri'] = msgid2iri(trim($meta->message_id,'<>'));
426 $refs_arr = explode(' ', $raw_refs);
427 if(count($refs_arr)) {
428 for($x = 0; $x < count($refs_arr); $x ++)
429 $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x]))) . "'";
431 $qstr = implode(',',$refs_arr);
432 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
433 intval($importer_uid)
436 $datarray['parent-uri'] = $r[0]['uri'];
440 if(! x($datarray,'parent-uri'))
441 $datarray['parent-uri'] = $datarray['uri'];
443 // Have we seen it before?
444 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
445 intval($importer_uid),
446 dbesc($datarray['uri'])
450 logger("Mail: Seen before ".$msg_uid);
451 if($meta->deleted && ! $r[0]['deleted']) {
452 q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d LIMIT 1",
453 dbesc(datetime_convert()),
457 switch ($mailconf[0]['action']) {
461 logger("Mail: Deleting ".$msg_uid);
462 imap_delete($mbox, $msg_uid, FT_UID);
465 logger("Mail: Mark as seen ".$msg_uid);
466 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
469 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']);
470 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
471 if ($mailconf[0]['movetofolder'] != "")
472 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
478 // Decoding the header
479 $subject = imap_mime_header_decode($meta->subject);
480 $datarray['title'] = "";
481 foreach($subject as $subpart)
482 if ($subpart->charset != "default")
483 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
485 $datarray['title'] .= $subpart->text;
487 $datarray['title'] = notags(trim($datarray['title']));
489 //$datarray['title'] = notags(trim($meta->subject));
490 $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
492 $r = email_get_msg($mbox,$msg_uid);
494 logger("Mail: can't fetch msg ".$msg_uid);
497 $datarray['body'] = escape_tags(convertquote($r['body'], false));
499 logger("Mail: Importing ".$msg_uid);
501 // some mailing lists have the original author as 'from' - add this sender info to msg body.
502 // todo: adding a gravatar for the original author would be cool
504 if(! stristr($meta->from,$contact['addr'])) {
505 $from = imap_mime_header_decode($meta->from);
507 foreach($from as $frompart)
508 if ($frompart->charset != "default")
509 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
511 $fromdecoded .= $frompart->text;
513 $datarray['body'] = "[b]".t('From: ') . escape_tags($fromdecoded) . "[/b]\n\n" . $datarray['body'];
516 $datarray['uid'] = $importer_uid;
517 $datarray['contact-id'] = $contact['id'];
518 if($datarray['parent-uri'] === $datarray['uri'])
519 $datarray['private'] = 1;
520 if(($contact['network'] === NETWORK_MAIL) && (! get_pconfig($importer_uid,'system','allow_public_email_replies'))) {
521 $datarray['private'] = 1;
522 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
524 $datarray['author-name'] = $contact['name'];
525 $datarray['author-link'] = 'mailbox';
526 $datarray['author-avatar'] = $contact['photo'];
528 $stored_item = item_store($datarray);
529 q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
530 dbesc($datarray['parent-uri']),
531 intval($importer_uid)
533 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
536 switch ($mailconf[0]['action']) {
540 logger("Mail: Deleting ".$msg_uid);
541 imap_delete($mbox, $msg_uid, FT_UID);
544 logger("Mail: Mark as seen ".$msg_uid);
545 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
548 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']);
549 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
550 if ($mailconf[0]['movetofolder'] != "")
551 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
560 elseif($contact['network'] === NETWORK_FACEBOOK) {
561 // This is picked up by the Facebook plugin on a cron hook.
566 logger('poller: received xml : ' . $xml, LOGGER_DATA);
568 if(! strstr($xml,'<?xml')) {
569 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
570 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
571 dbesc(datetime_convert()),
572 intval($contact['id'])
578 consume_feed($xml,$importer,$contact,$hub,1,1);
580 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
582 consume_feed($xml,$importer,$contact,$hub,1,2);
584 $hubmode = 'subscribe';
585 if($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly'])
586 $hubmode = 'unsubscribe';
588 if((strlen($hub)) && ($hub_update) && ($contact['rel'] != CONTACT_IS_FOLLOWER)) {
589 logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
590 $hubs = explode(',', $hub);
592 foreach($hubs as $h) {
596 subscribe_to_hub($h,$importer,$contact,$hubmode);
603 $updated = datetime_convert();
605 $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d LIMIT 1",
608 intval($contact['id'])
612 // load current friends if possible.
614 if($contact['poco']) {
615 $r = q("SELECT count(*) as total from glink
616 where `cid` = %d and updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
617 intval($contact['id'])
621 if(! $r[0]['total']) {
622 poco_load($contact['id'],$importer_uid,$contact['poco']);
626 // loop - next contact
634 if (array_search(__file__,get_included_files())===0){
635 poller_run($argv,$argc);