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('include/items.php');
31 require_once('include/Contact.php');
32 require_once('include/email.php');
33 require_once('include/socgraph.php');
34 require_once('include/pidfile.php');
35 require_once('include/queue_fn.php');
37 load_config('config');
38 load_config('system');
40 $a->set_baseurl(get_config('system','url'));
44 logger('onepoll: start');
52 if(($argc > 1) && (intval($argv[1])))
53 $contact_id = intval($argv[1]);
55 if(($argc > 2) && ($argv[2] == "force"))
59 logger('onepoll: no contact');
63 // Don't check this stuff if the function is called by the poller
64 if (App::callstack() != "poller_run") {
65 $lockpath = get_lockpath();
66 if ($lockpath != '') {
67 $pidfile = new pidfile($lockpath, 'onepoll'.$contact_id);
68 if ($pidfile->is_already_running()) {
69 logger("onepoll: Already running for contact ".$contact_id);
70 if ($pidfile->running_time() > 9*60) {
72 logger("killed stale process");
79 $d = datetime_convert();
81 // Only poll from those with suitable relationships,
82 // and which have a polling address and ignore Diaspora since
83 // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
85 $contacts = q("SELECT `contact`.* FROM `contact`
86 WHERE ( `rel` = %d OR `rel` = %d ) AND `poll` != ''
87 AND NOT `network` IN ( '%s', '%s' )
88 AND `contact`.`id` = %d
89 AND `self` = 0 AND `contact`.`blocked` = 0 AND `contact`.`readonly` = 0
90 AND `contact`.`archive` = 0 LIMIT 1",
91 intval(CONTACT_IS_SHARING),
92 intval(CONTACT_IS_FRIEND),
93 dbesc(NETWORK_FACEBOOK),
94 dbesc(NETWORK_PUMPIO),
98 if(! count($contacts))
101 $contact = $contacts[0];
103 // load current friends if possible.
104 if (($contact['poco'] != "") AND ($contact['success_update'] > $contact['failure_update'])) {
105 $r = q("SELECT count(*) as total from glink
106 where `cid` = %d and updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
107 intval($contact['id'])
111 poco_load($contact['id'],$importer_uid,0,$contact['poco']);
114 /// @TODO Check why we don't poll the Diaspora feed at the moment (some guid problem in the items?)
115 /// @TODO Check whether this is possible with Redmatrix
116 if ($contact["network"] == NETWORK_DIASPORA) {
117 if (poco_do_update($contact["created"], $contact["last-item"], $contact["failure_update"], $contact["success_update"])) {
118 $last_updated = poco_last_updated($contact["url"]);
119 $updated = datetime_convert();
121 q("UPDATE `contact` SET `last-item` = '%s', `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d",
122 dbesc($last_updated),
125 intval($contact['id'])
128 q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
131 intval($contact['id'])
140 $t = $contact['last-update'];
142 if($contact['subhub']) {
143 $poll_interval = get_config('system','pushpoll_frequency');
144 $contact['priority'] = (($poll_interval !== false) ? intval($poll_interval) : 3);
147 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
154 $importer_uid = $contact['uid'];
156 $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",
157 intval($importer_uid)
164 logger("onepoll: poll: ({$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
166 $last_update = (($contact['last-update'] === '0000-00-00 00:00:00')
167 ? datetime_convert('UTC','UTC','now - 7 days', ATOM_TIME)
168 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
171 // Update the contact entry
172 if(($contact['network'] === NETWORK_OSTATUS) || ($contact['network'] === NETWORK_DIASPORA) || ($contact['network'] === NETWORK_DFRN)) {
173 if (!poco_reachable($contact['url'])) {
174 logger("Skipping probably dead contact ".$contact['url']);
178 if (!update_contact($contact["id"])) {
179 mark_for_death($contact);
182 unmark_for_death($contact);
185 if($contact['network'] === NETWORK_DFRN) {
188 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
189 if(intval($contact['duplex']) && $contact['dfrn-id'])
190 $idtosend = '0:' . $orig_id;
191 if(intval($contact['duplex']) && $contact['issued-id'])
192 $idtosend = '1:' . $orig_id;
194 // they have permission to write to us. We already filtered this in the contact query.
197 // But this may be our first communication, so set the writable flag if it isn't set already.
199 if(! intval($contact['writable']))
200 q("update contact set writable = 1 where id = %d", intval($contact['id']));
203 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
204 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
205 . '&type=data&last_update=' . $last_update
208 $handshake_xml = fetch_url($url);
209 $html_code = $a->get_curl_code();
211 logger('onepoll: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
214 if((! strlen($handshake_xml)) || ($html_code >= 400) || (! $html_code)) {
215 logger("poller: $url appears to be dead - marking for death ");
217 // dead connection - might be a transient event, or this might
218 // mean the software was uninstalled or the domain expired.
219 // Will keep trying for one month.
221 mark_for_death($contact);
223 // set the last-update so we don't keep polling
224 $r = q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
225 dbesc(datetime_convert()),
226 dbesc(datetime_convert()),
227 intval($contact['id'])
233 if(! strstr($handshake_xml,'<')) {
234 logger('poller: response from ' . $url . ' did not contain XML.');
236 mark_for_death($contact);
238 $r = q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
239 dbesc(datetime_convert()),
240 dbesc(datetime_convert()),
241 intval($contact['id'])
247 $res = parse_xml_string($handshake_xml);
249 if(intval($res->status) == 1) {
250 logger("poller: $url replied status 1 - marking for death ");
252 // we may not be friends anymore. Will keep trying for one month.
253 // set the last-update so we don't keep polling
256 $r = q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
257 dbesc(datetime_convert()),
258 dbesc(datetime_convert()),
259 intval($contact['id'])
261 mark_for_death($contact);
264 if($contact['term-date'] != '0000-00-00 00:00:00') {
265 logger("poller: $url back from the dead - removing mark for death");
266 unmark_for_death($contact);
270 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
273 if(((float) $res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
274 q("update contact set poco = '%s' where id = %d",
275 dbesc(str_replace('/profile/','/poco/', $contact['url'])),
276 intval($contact['id'])
282 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
283 $challenge = hex2bin((string) $res->challenge);
287 if(($contact['duplex']) && strlen($contact['prvkey'])) {
288 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
289 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
292 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
293 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
296 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
298 if(strpos($final_dfrn_id,':') == 1)
299 $final_dfrn_id = substr($final_dfrn_id,2);
301 if($final_dfrn_id != $orig_id) {
302 logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
303 // did not decode properly - cannot trust this site
307 $postvars['dfrn_id'] = $idtosend;
308 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
309 $postvars['perm'] = 'rw';
311 $xml = post_url($contact['poll'],$postvars);
314 elseif(($contact['network'] === NETWORK_OSTATUS)
315 || ($contact['network'] === NETWORK_DIASPORA)
316 || ($contact['network'] === NETWORK_FEED) ) {
318 // Upgrading DB fields from an older Friendica version
319 // Will only do this once per notify-enabled OStatus contact
320 // or if relationship changes
322 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
324 // Contacts from OStatus are always writable
325 if($contact['network'] === NETWORK_OSTATUS)
328 if($stat_writeable != $contact['writable']) {
329 q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d",
330 intval($stat_writeable),
331 intval($contact['id'])
335 // Are we allowed to import from this person?
337 if($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly'])
340 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
341 $xml = fetch_url($contact['poll'], false, $redirects, 0, Null, $cookiejar);
344 elseif($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {
346 logger("Mail: Fetching", LOGGER_DEBUG);
348 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
352 logger("Mail: Enabled", LOGGER_DEBUG);
355 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
356 intval($importer_uid)
358 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
359 intval($importer_uid)
361 if(count($x) && count($mailconf)) {
362 $mailbox = construct_mailbox_name($mailconf[0]);
364 openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
365 $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
367 logger("Mail: Connect to " . $mailconf[0]['user']);
369 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d",
370 dbesc(datetime_convert()),
371 intval($mailconf[0]['id']),
372 intval($importer_uid)
374 logger("Mail: Connected to " . $mailconf[0]['user']);
376 logger("Mail: Connection error ".$mailconf[0]['user']." ".print_r(imap_errors(), true));
380 $msgs = email_poll($mbox,$contact['addr']);
383 logger("Mail: Parsing ".count($msgs)." mails for ".$mailconf[0]['user'], LOGGER_DEBUG);
385 $metas = email_msg_meta($mbox,implode(',',$msgs));
386 if(count($metas) != count($msgs)) {
387 logger("onepoll: for " . $mailconf[0]['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
390 $msgs = array_combine($msgs, $metas);
392 foreach($msgs as $msg_uid => $meta) {
393 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
396 $datarray['verb'] = ACTIVITY_POST;
397 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
398 // $meta = email_msg_meta($mbox,$msg_uid);
399 // $headers = email_msg_headers($mbox,$msg_uid);
401 $datarray['uri'] = msgid2iri(trim($meta->message_id,'<>'));
403 // Have we seen it before?
404 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
405 intval($importer_uid),
406 dbesc($datarray['uri'])
410 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],LOGGER_DEBUG);
412 // Only delete when mails aren't automatically moved or deleted
413 if (($mailconf[0]['action'] != 1) AND ($mailconf[0]['action'] != 3))
414 if($meta->deleted && ! $r[0]['deleted']) {
415 q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d",
416 dbesc(datetime_convert()),
421 switch ($mailconf[0]['action']) {
423 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'].". Doing nothing.", LOGGER_DEBUG);
426 logger("Mail: Deleting ".$msg_uid." for ".$mailconf[0]['user']);
427 imap_delete($mbox, $msg_uid, FT_UID);
430 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf[0]['user']);
431 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
434 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']." for ".$mailconf[0]['user']);
435 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
436 if ($mailconf[0]['movetofolder'] != "")
437 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
444 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
446 // $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
447 $raw_refs = ((property_exists($meta,'references')) ? str_replace("\t",'',$meta->references) : '');
448 if(! trim($raw_refs))
449 $raw_refs = ((property_exists($meta,'in_reply_to')) ? str_replace("\t",'',$meta->in_reply_to) : '');
450 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
453 $refs_arr = explode(' ', $raw_refs);
454 if(count($refs_arr)) {
455 for($x = 0; $x < count($refs_arr); $x ++)
456 $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x]))) . "'";
458 $qstr = implode(',',$refs_arr);
459 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
460 intval($importer_uid)
463 $datarray['parent-uri'] = $r[0]['parent-uri']; // Set the parent as the top-level item
464 // $datarray['parent-uri'] = $r[0]['uri'];
467 // Decoding the header
468 $subject = imap_mime_header_decode($meta->subject);
469 $datarray['title'] = "";
470 foreach($subject as $subpart)
471 if ($subpart->charset != "default")
472 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
474 $datarray['title'] .= $subpart->text;
476 $datarray['title'] = notags(trim($datarray['title']));
478 //$datarray['title'] = notags(trim($meta->subject));
479 $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
482 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") or
483 (substr(strtolower($datarray['title']), 0, 3) == "re-") or
486 // Remove Reply-signs in the subject
487 $datarray['title'] = RemoveReply($datarray['title']);
489 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
490 if(!x($datarray,'parent-uri') and $reply) {
491 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `title` = \"%s\" AND `uid` = %d ORDER BY `created` DESC LIMIT 1",
492 dbesc(protect_sprintf($datarray['title'])),
493 intval($importer_uid));
495 $datarray['parent-uri'] = $r[0]['parent-uri'];
498 if(! x($datarray,'parent-uri'))
499 $datarray['parent-uri'] = $datarray['uri'];
502 $r = email_get_msg($mbox,$msg_uid, $reply);
504 logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf[0]['user']);
507 $datarray['body'] = escape_tags($r['body']);
508 $datarray['body'] = limit_body_size($datarray['body']);
510 logger("Mail: Importing ".$msg_uid." for ".$mailconf[0]['user']);
512 // some mailing lists have the original author as 'from' - add this sender info to msg body.
513 /// @TODO Adding a gravatar for the original author would be cool
515 if(! stristr($meta->from,$contact['addr'])) {
516 $from = imap_mime_header_decode($meta->from);
518 foreach($from as $frompart)
519 if ($frompart->charset != "default")
520 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
522 $fromdecoded .= $frompart->text;
524 $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->get_hostname());
526 $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
528 if (isset($fromarr[0]->personal))
529 $fromname = $fromarr[0]->personal;
531 $fromname = $frommail;
533 //$datarray['body'] = "[b]".t('From: ') . escape_tags($fromdecoded) . "[/b]\n\n" . $datarray['body'];
535 $datarray['author-name'] = $fromname;
536 $datarray['author-link'] = "mailto:".$frommail;
537 $datarray['author-avatar'] = $contact['photo'];
539 $datarray['owner-name'] = $contact['name'];
540 $datarray['owner-link'] = "mailto:".$contact['addr'];
541 $datarray['owner-avatar'] = $contact['photo'];
544 $datarray['author-name'] = $contact['name'];
545 $datarray['author-link'] = 'mailbox';
546 $datarray['author-avatar'] = $contact['photo'];
549 $datarray['uid'] = $importer_uid;
550 $datarray['contact-id'] = $contact['id'];
551 if($datarray['parent-uri'] === $datarray['uri'])
552 $datarray['private'] = 1;
553 if(($contact['network'] === NETWORK_MAIL) && (! get_pconfig($importer_uid,'system','allow_public_email_replies'))) {
554 $datarray['private'] = 1;
555 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
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",
566 switch ($mailconf[0]['action']) {
568 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'].". Doing nothing.", LOGGER_DEBUG);
571 logger("Mail: Deleting ".$msg_uid." for ".$mailconf[0]['user']);
572 imap_delete($mbox, $msg_uid, FT_UID);
575 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf[0]['user']);
576 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
579 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']." for ".$mailconf[0]['user']);
580 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
581 if ($mailconf[0]['movetofolder'] != "")
582 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
588 logger("Mail: no mails for ".$mailconf[0]['user']);
590 logger("Mail: closing connection for ".$mailconf[0]['user']);
594 elseif($contact['network'] === NETWORK_FACEBOOK) {
595 // This is picked up by the Facebook plugin on a cron hook.
597 } elseif($contact['network'] === NETWORK_PUMPIO) {
598 // This is picked up by the pump.io plugin on a cron hook.
603 logger('poller: received xml : ' . $xml, LOGGER_DATA);
604 if(! strstr($xml,'<')) {
605 logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
606 $r = q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
607 dbesc(datetime_convert()),
608 dbesc(datetime_convert()),
609 intval($contact['id'])
615 logger("Consume feed of contact ".$contact['id']);
617 consume_feed($xml,$importer,$contact,$hub,1,1);
619 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
621 consume_feed($xml,$importer,$contact,$hub,1,2);
623 $hubmode = 'subscribe';
624 if($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly'])
625 $hubmode = 'unsubscribe';
627 if(($contact['network'] === NETWORK_OSTATUS || $contact['network'] == NETWORK_FEED) && (! $contact['hub-verify']))
633 logger("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$contact['network']." Relation: ".$contact['rel']." Update: ".$hub_update);
635 if((strlen($hub)) && ($hub_update) && (($contact['rel'] != CONTACT_IS_FOLLOWER) || $contact['network'] == NETWORK_FEED) ) {
636 logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
637 $hubs = explode(',', $hub);
639 foreach($hubs as $h) {
643 subscribe_to_hub($h,$importer,$contact,$hubmode);
648 $updated = datetime_convert();
650 $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d",
653 intval($contact['id'])
656 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
658 dbesc($contact['nurl'])
661 } elseif (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_FEED))) {
662 $updated = datetime_convert();
664 $r = q("UPDATE `contact` SET `last-update` = '%s', `failure_update` = '%s' WHERE `id` = %d",
667 intval($contact['id'])
670 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
672 dbesc($contact['nurl'])
675 $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d",
677 intval($contact['id'])
684 if (array_search(__file__,get_included_files())===0){
685 onepoll_run($_SERVER["argv"],$_SERVER["argc"]);