3 require_once("boot.php");
4 require_once("include/follow.php");
6 function RemoveReply($subject) {
7 while (in_array(strtolower(substr($subject, 0, 3)), array("re:", "aw:")))
8 $subject = trim(substr($subject, 4));
13 function onepoll_run(&$argv, &$argc){
21 @include(".htconfig.php");
22 require_once("include/dba.php");
23 $db = new dba($db_host, $db_user, $db_pass, $db_data);
24 unset($db_host, $db_user, $db_pass, $db_data);
28 require_once('include/session.php');
29 require_once('include/datetime.php');
30 require_once('library/simplepie/simplepie.inc');
31 require_once('include/items.php');
32 require_once('include/Contact.php');
33 require_once('include/email.php');
34 require_once('include/socgraph.php');
35 require_once('include/pidfile.php');
36 require_once('include/queue_fn.php');
38 load_config('config');
39 load_config('system');
41 $a->set_baseurl(get_config('system','url'));
45 logger('onepoll: start');
53 if(($argc > 1) && (intval($argv[1])))
54 $contact_id = intval($argv[1]);
56 if(($argc > 2) && ($argv[2] == "force"))
60 logger('onepoll: no contact');
64 $lockpath = get_lockpath();
65 if ($lockpath != '') {
66 $pidfile = new pidfile($lockpath, 'onepoll'.$contact_id);
67 if ($pidfile->is_already_running()) {
68 logger("onepoll: Already running for contact ".$contact_id);
69 if ($pidfile->running_time() > 9*60) {
71 logger("killed stale process");
77 $d = datetime_convert();
79 // Only poll from those with suitable relationships,
80 // and which have a polling address and ignore Diaspora since
81 // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
83 $contacts = q("SELECT `contact`.* FROM `contact`
84 WHERE ( `rel` = %d OR `rel` = %d ) AND `poll` != ''
85 AND NOT `network` IN ( '%s', '%s' )
86 AND `contact`.`id` = %d
87 AND `self` = 0 AND `contact`.`blocked` = 0 AND `contact`.`readonly` = 0
88 AND `contact`.`archive` = 0 LIMIT 1",
89 intval(CONTACT_IS_SHARING),
90 intval(CONTACT_IS_FRIEND),
91 dbesc(NETWORK_FACEBOOK),
92 dbesc(NETWORK_PUMPIO),
96 if(! count($contacts))
99 $contact = $contacts[0];
101 // load current friends if possible.
102 if (($contact['poco'] != "") AND ($contact['success_update'] > $contact['failure_update'])) {
103 $r = q("SELECT count(*) as total from glink
104 where `cid` = %d and updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
105 intval($contact['id'])
109 poco_load($contact['id'],$importer_uid,0,$contact['poco']);
112 /// @TODO Check why we don't poll the Diaspora feed at the moment (some guid problem in the items?)
113 /// @TODO Check whether this is possible with Redmatrix
114 if ($contact["network"] == NETWORK_DIASPORA) {
115 if (poco_do_update($contact["created"], $contact["last-item"], $contact["failure_update"], $contact["success_update"])) {
116 $last_updated = poco_last_updated($contact["url"]);
117 $updated = datetime_convert();
119 q("UPDATE `contact` SET `last-item` = '%s', `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d",
120 dbesc($last_updated),
123 intval($contact['id'])
126 q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
129 intval($contact['id'])
138 $t = $contact['last-update'];
140 if($contact['subhub']) {
141 $poll_interval = get_config('system','pushpoll_frequency');
142 $contact['priority'] = (($poll_interval !== false) ? intval($poll_interval) : 3);
145 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
152 $importer_uid = $contact['uid'];
154 $r = q("SELECT `contact`.*, `user`.`page-flags` FROM `contact` INNER JOIN `user` on `contact`.`uid` = `user`.`uid` WHERE `user`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
155 intval($importer_uid)
162 logger("onepoll: poll: ({$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
164 $last_update = (($contact['last-update'] === '0000-00-00 00:00:00')
165 ? datetime_convert('UTC','UTC','now - 7 days', ATOM_TIME)
166 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
169 // Update the contact entry
170 if(($contact['network'] === NETWORK_OSTATUS) || ($contact['network'] === NETWORK_DIASPORA) || ($contact['network'] === NETWORK_DFRN)) {
171 if (!poco_reachable($contact['url'])) {
172 logger("Skipping probably dead contact ".$contact['url']);
176 if (!update_contact($contact["id"])) {
177 mark_for_death($contact);
180 unmark_for_death($contact);
183 if($contact['network'] === NETWORK_DFRN) {
186 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
187 if(intval($contact['duplex']) && $contact['dfrn-id'])
188 $idtosend = '0:' . $orig_id;
189 if(intval($contact['duplex']) && $contact['issued-id'])
190 $idtosend = '1:' . $orig_id;
192 // they have permission to write to us. We already filtered this in the contact query.
195 // But this may be our first communication, so set the writable flag if it isn't set already.
197 if(! intval($contact['writable']))
198 q("update contact set writable = 1 where id = %d", intval($contact['id']));
201 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
202 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
203 . '&type=data&last_update=' . $last_update
206 $handshake_xml = fetch_url($url);
207 $html_code = $a->get_curl_code();
209 logger('onepoll: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
212 if((! strlen($handshake_xml)) || ($html_code >= 400) || (! $html_code)) {
213 logger("poller: $url appears to be dead - marking for death ");
215 // dead connection - might be a transient event, or this might
216 // mean the software was uninstalled or the domain expired.
217 // Will keep trying for one month.
219 mark_for_death($contact);
221 // set the last-update so we don't keep polling
222 $r = q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
223 dbesc(datetime_convert()),
224 dbesc(datetime_convert()),
225 intval($contact['id'])
231 if(! strstr($handshake_xml,'<')) {
232 logger('poller: response from ' . $url . ' did not contain XML.');
234 mark_for_death($contact);
236 $r = q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
237 dbesc(datetime_convert()),
238 dbesc(datetime_convert()),
239 intval($contact['id'])
245 $res = parse_xml_string($handshake_xml);
247 if(intval($res->status) == 1) {
248 logger("poller: $url replied status 1 - marking for death ");
250 // we may not be friends anymore. Will keep trying for one month.
251 // set the last-update so we don't keep polling
254 $r = q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
255 dbesc(datetime_convert()),
256 dbesc(datetime_convert()),
257 intval($contact['id'])
259 mark_for_death($contact);
262 if($contact['term-date'] != '0000-00-00 00:00:00') {
263 logger("poller: $url back from the dead - removing mark for death");
264 unmark_for_death($contact);
268 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
271 if(((float) $res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
272 q("update contact set poco = '%s' where id = %d",
273 dbesc(str_replace('/profile/','/poco/', $contact['url'])),
274 intval($contact['id'])
280 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
281 $challenge = hex2bin((string) $res->challenge);
285 if(($contact['duplex']) && strlen($contact['prvkey'])) {
286 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
287 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
290 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
291 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
294 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
296 if(strpos($final_dfrn_id,':') == 1)
297 $final_dfrn_id = substr($final_dfrn_id,2);
299 if($final_dfrn_id != $orig_id) {
300 logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
301 // did not decode properly - cannot trust this site
305 $postvars['dfrn_id'] = $idtosend;
306 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
307 $postvars['perm'] = 'rw';
309 $xml = post_url($contact['poll'],$postvars);
312 elseif(($contact['network'] === NETWORK_OSTATUS)
313 || ($contact['network'] === NETWORK_DIASPORA)
314 || ($contact['network'] === NETWORK_FEED) ) {
316 // Upgrading DB fields from an older Friendica version
317 // Will only do this once per notify-enabled OStatus contact
318 // or if relationship changes
320 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
322 // Contacts from OStatus are always writable
323 if($contact['network'] === NETWORK_OSTATUS)
326 if($stat_writeable != $contact['writable']) {
327 q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d",
328 intval($stat_writeable),
329 intval($contact['id'])
333 // Are we allowed to import from this person?
335 if($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly'])
338 $xml = fetch_url($contact['poll']);
340 elseif($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {
342 logger("Mail: Fetching", LOGGER_DEBUG);
344 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
348 logger("Mail: Enabled", LOGGER_DEBUG);
351 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
352 intval($importer_uid)
354 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
355 intval($importer_uid)
357 if(count($x) && count($mailconf)) {
358 $mailbox = construct_mailbox_name($mailconf[0]);
360 openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
361 $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
363 logger("Mail: Connect to " . $mailconf[0]['user']);
365 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d",
366 dbesc(datetime_convert()),
367 intval($mailconf[0]['id']),
368 intval($importer_uid)
370 logger("Mail: Connected to " . $mailconf[0]['user']);
372 logger("Mail: Connection error ".$mailconf[0]['user']." ".print_r(imap_errors(), true));
376 $msgs = email_poll($mbox,$contact['addr']);
379 logger("Mail: Parsing ".count($msgs)." mails for ".$mailconf[0]['user'], LOGGER_DEBUG);
381 $metas = email_msg_meta($mbox,implode(',',$msgs));
382 if(count($metas) != count($msgs)) {
383 logger("onepoll: for " . $mailconf[0]['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
386 $msgs = array_combine($msgs, $metas);
388 foreach($msgs as $msg_uid => $meta) {
389 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
392 $datarray['verb'] = ACTIVITY_POST;
393 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
394 // $meta = email_msg_meta($mbox,$msg_uid);
395 // $headers = email_msg_headers($mbox,$msg_uid);
397 $datarray['uri'] = msgid2iri(trim($meta->message_id,'<>'));
399 // Have we seen it before?
400 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
401 intval($importer_uid),
402 dbesc($datarray['uri'])
406 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],LOGGER_DEBUG);
408 // Only delete when mails aren't automatically moved or deleted
409 if (($mailconf[0]['action'] != 1) AND ($mailconf[0]['action'] != 3))
410 if($meta->deleted && ! $r[0]['deleted']) {
411 q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d",
412 dbesc(datetime_convert()),
417 switch ($mailconf[0]['action']) {
419 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'].". Doing nothing.", LOGGER_DEBUG);
422 logger("Mail: Deleting ".$msg_uid." for ".$mailconf[0]['user']);
423 imap_delete($mbox, $msg_uid, FT_UID);
426 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf[0]['user']);
427 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
430 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']." for ".$mailconf[0]['user']);
431 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
432 if ($mailconf[0]['movetofolder'] != "")
433 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
440 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
442 // $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
443 $raw_refs = ((property_exists($meta,'references')) ? str_replace("\t",'',$meta->references) : '');
444 if(! trim($raw_refs))
445 $raw_refs = ((property_exists($meta,'in_reply_to')) ? str_replace("\t",'',$meta->in_reply_to) : '');
446 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
449 $refs_arr = explode(' ', $raw_refs);
450 if(count($refs_arr)) {
451 for($x = 0; $x < count($refs_arr); $x ++)
452 $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x]))) . "'";
454 $qstr = implode(',',$refs_arr);
455 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
456 intval($importer_uid)
459 $datarray['parent-uri'] = $r[0]['parent-uri']; // Set the parent as the top-level item
460 // $datarray['parent-uri'] = $r[0]['uri'];
463 // Decoding the header
464 $subject = imap_mime_header_decode($meta->subject);
465 $datarray['title'] = "";
466 foreach($subject as $subpart)
467 if ($subpart->charset != "default")
468 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
470 $datarray['title'] .= $subpart->text;
472 $datarray['title'] = notags(trim($datarray['title']));
474 //$datarray['title'] = notags(trim($meta->subject));
475 $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
478 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") or
479 (substr(strtolower($datarray['title']), 0, 3) == "re-") or
482 // Remove Reply-signs in the subject
483 $datarray['title'] = RemoveReply($datarray['title']);
485 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
486 if(!x($datarray,'parent-uri') and $reply) {
487 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `title` = \"%s\" AND `uid` = %d ORDER BY `created` DESC LIMIT 1",
488 dbesc(protect_sprintf($datarray['title'])),
489 intval($importer_uid));
491 $datarray['parent-uri'] = $r[0]['parent-uri'];
494 if(! x($datarray,'parent-uri'))
495 $datarray['parent-uri'] = $datarray['uri'];
498 $r = email_get_msg($mbox,$msg_uid, $reply);
500 logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf[0]['user']);
503 $datarray['body'] = escape_tags($r['body']);
504 $datarray['body'] = limit_body_size($datarray['body']);
506 logger("Mail: Importing ".$msg_uid." for ".$mailconf[0]['user']);
508 // some mailing lists have the original author as 'from' - add this sender info to msg body.
509 /// @TODO Adding a gravatar for the original author would be cool
511 if(! stristr($meta->from,$contact['addr'])) {
512 $from = imap_mime_header_decode($meta->from);
514 foreach($from as $frompart)
515 if ($frompart->charset != "default")
516 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
518 $fromdecoded .= $frompart->text;
520 $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->get_hostname());
522 $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
524 if (isset($fromarr[0]->personal))
525 $fromname = $fromarr[0]->personal;
527 $fromname = $frommail;
529 //$datarray['body'] = "[b]".t('From: ') . escape_tags($fromdecoded) . "[/b]\n\n" . $datarray['body'];
531 $datarray['author-name'] = $fromname;
532 $datarray['author-link'] = "mailto:".$frommail;
533 $datarray['author-avatar'] = $contact['photo'];
535 $datarray['owner-name'] = $contact['name'];
536 $datarray['owner-link'] = "mailto:".$contact['addr'];
537 $datarray['owner-avatar'] = $contact['photo'];
540 $datarray['author-name'] = $contact['name'];
541 $datarray['author-link'] = 'mailbox';
542 $datarray['author-avatar'] = $contact['photo'];
545 $datarray['uid'] = $importer_uid;
546 $datarray['contact-id'] = $contact['id'];
547 if($datarray['parent-uri'] === $datarray['uri'])
548 $datarray['private'] = 1;
549 if(($contact['network'] === NETWORK_MAIL) && (! get_pconfig($importer_uid,'system','allow_public_email_replies'))) {
550 $datarray['private'] = 1;
551 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
554 $stored_item = item_store($datarray);
555 q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
556 dbesc($datarray['parent-uri']),
557 intval($importer_uid)
559 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
562 switch ($mailconf[0]['action']) {
564 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'].". Doing nothing.", LOGGER_DEBUG);
567 logger("Mail: Deleting ".$msg_uid." for ".$mailconf[0]['user']);
568 imap_delete($mbox, $msg_uid, FT_UID);
571 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf[0]['user']);
572 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
575 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']." for ".$mailconf[0]['user']);
576 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
577 if ($mailconf[0]['movetofolder'] != "")
578 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
584 logger("Mail: no mails for ".$mailconf[0]['user']);
586 logger("Mail: closing connection for ".$mailconf[0]['user']);
590 elseif($contact['network'] === NETWORK_FACEBOOK) {
591 // This is picked up by the Facebook plugin on a cron hook.
593 } elseif($contact['network'] === NETWORK_PUMPIO) {
594 // This is picked up by the pump.io plugin on a cron hook.
599 logger('poller: received xml : ' . $xml, LOGGER_DATA);
600 if(! strstr($xml,'<')) {
601 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
602 $r = q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
603 dbesc(datetime_convert()),
604 dbesc(datetime_convert()),
605 intval($contact['id'])
611 logger("Consume feed of contact ".$contact['id']);
613 consume_feed($xml,$importer,$contact,$hub,1,1);
615 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
617 consume_feed($xml,$importer,$contact,$hub,1,2);
619 $hubmode = 'subscribe';
620 if($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly'])
621 $hubmode = 'unsubscribe';
623 if(($contact['network'] === NETWORK_OSTATUS || $contact['network'] == NETWORK_FEED) && (! $contact['hub-verify']))
629 logger("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$contact['network']." Relation: ".$contact['rel']." Update: ".$hub_update);
631 if((strlen($hub)) && ($hub_update) && (($contact['rel'] != CONTACT_IS_FOLLOWER) || $contact['network'] == NETWORK_FEED) ) {
632 logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
633 $hubs = explode(',', $hub);
635 foreach($hubs as $h) {
639 subscribe_to_hub($h,$importer,$contact,$hubmode);
644 $updated = datetime_convert();
646 $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d",
649 intval($contact['id'])
652 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
654 dbesc($contact['nurl'])
657 } elseif (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_FEED))) {
658 $updated = datetime_convert();
660 $r = q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
663 intval($contact['id'])
666 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
668 dbesc($contact['nurl'])
671 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d",
673 intval($contact['id'])
680 if (array_search(__file__,get_included_files())===0){
681 onepoll_run($_SERVER["argv"],$_SERVER["argc"]);