]> git.mxchange.org Git - friendica.git/blob - include/onepoll.php
modified: view/theme/smoothly/style.css
[friendica.git] / include / onepoll.php
1 <?php
2
3 require_once("boot.php");
4
5 function onepoll_run($argv, $argc){
6         global $a, $db;
7
8         if(is_null($a)) {
9                 $a = new App;
10         }
11   
12         if(is_null($db)) {
13             @include(".htconfig.php");
14         require_once("dba.php");
15             $db = new dba($db_host, $db_user, $db_pass, $db_data);
16         unset($db_host, $db_user, $db_pass, $db_data);
17         };
18
19
20         require_once('include/session.php');
21         require_once('include/datetime.php');
22         require_once('library/simplepie/simplepie.inc');
23         require_once('include/items.php');
24         require_once('include/Contact.php');
25         require_once('include/email.php');
26         require_once('include/socgraph.php');
27         require_once('include/pidfile.php');
28         require_once('include/queue_fn.php');
29
30         load_config('config');
31         load_config('system');
32
33         $a->set_baseurl(get_config('system','url'));
34
35         load_hooks();
36
37         logger('onepoll: start');
38         
39         $manual_id  = 0;
40         $generation = 0;
41         $hub_update = false;
42         $force      = false;
43         $restart    = false;
44
45         if(($argc > 1) && (intval($argv[1])))
46                 $contact_id = intval($argv[1]);
47
48         if(! $contact_id) {
49                 logger('onepoll: no contact');
50                 return;
51         }
52         
53
54         $d = datetime_convert();
55
56         // Only poll from those with suitable relationships,
57         // and which have a polling address and ignore Diaspora since 
58         // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
59
60         $contacts = q("SELECT `contact`.* FROM `contact` 
61                 WHERE ( `rel` = %d OR `rel` = %d ) AND `poll` != ''
62                 AND NOT `network` IN ( '%s', '%s' )
63                 AND `contact`.`id` = %d
64                 AND `self` = 0 AND `contact`.`blocked` = 0 AND `contact`.`readonly` = 0 
65                 AND `contact`.`archive` = 0 LIMIT 1",
66                 intval(CONTACT_IS_SHARING),
67                 intval(CONTACT_IS_FRIEND),
68                 dbesc(NETWORK_DIASPORA),
69                 dbesc(NETWORK_FACEBOOK),
70                 intval($contact_id)
71         );
72
73         if(! count($contacts)) {
74                 return;
75         }
76
77         $contact = $contacts[0];
78
79         $xml = false;
80
81         $t = $contact['last-update'];
82
83         if($contact['subhub']) {
84                 $poll_interval = get_config('system','pushpoll_frequency');
85                 $contact['priority'] = (($poll_interval !== false) ? intval($poll_interval) : 3);
86                 $hub_update = false;
87
88                 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
89                                 $hub_update = true;
90         }
91         else
92                 $hub_update = false;
93
94
95         $importer_uid = $contact['uid'];
96                 
97         $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",
98                 intval($importer_uid)
99         );
100         if(! count($r))
101                 return;
102
103         $importer = $r[0];
104
105         logger("onepoll: poll: ({$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
106
107         $last_update = (($contact['last-update'] === '0000-00-00 00:00:00') 
108                 ? datetime_convert('UTC','UTC','now - 7 days', ATOM_TIME)
109                 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
110         );
111
112         if($contact['network'] === NETWORK_DFRN) {
113
114                 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
115                 if(intval($contact['duplex']) && $contact['dfrn-id'])
116                         $idtosend = '0:' . $orig_id;
117                 if(intval($contact['duplex']) && $contact['issued-id'])
118                         $idtosend = '1:' . $orig_id;
119
120                 // they have permission to write to us. We already filtered this in the contact query.
121                 $perm = 'rw';
122
123                 $url = $contact['poll'] . '?dfrn_id=' . $idtosend 
124                         . '&dfrn_version=' . DFRN_PROTOCOL_VERSION 
125                         . '&type=data&last_update=' . $last_update 
126                         . '&perm=' . $perm ;
127
128                 $handshake_xml = fetch_url($url);
129                 $html_code = $a->get_curl_code();
130
131                 logger('onepoll: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
132
133
134                 if((! strlen($handshake_xml)) || ($html_code >= 400) || (! $html_code)) {
135                         logger("poller: $url appears to be dead - marking for death ");
136
137                         // dead connection - might be a transient event, or this might
138                         // mean the software was uninstalled or the domain expired. 
139                         // Will keep trying for one month.
140
141                         mark_for_death($contact);
142
143                         // set the last-update so we don't keep polling
144                         $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
145                                 dbesc(datetime_convert()),
146                                 intval($contact['id'])
147                         );
148
149                         return;
150                 }
151
152                 if(! strstr($handshake_xml,'<?xml')) {
153                         logger('poller: response from ' . $url . ' did not contain XML.');
154
155                         mark_for_death($contact);
156
157                         $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
158                                 dbesc(datetime_convert()),
159                                 intval($contact['id'])
160                         );
161                         return;
162                 }
163
164
165                 $res = parse_xml_string($handshake_xml);
166         
167                 if(intval($res->status) == 1) {
168                         logger("poller: $url replied status 1 - marking for death ");
169
170                         // we may not be friends anymore. Will keep trying for one month.
171                         // set the last-update so we don't keep polling
172
173
174                         $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
175                                 dbesc(datetime_convert()),
176                                 intval($contact['id'])
177                         );
178                         mark_for_death($contact);
179                 }
180                 else {
181                         if($contact['term-date'] != '0000-00-00 00:00:00') {
182                                 logger("poller: $url back from the dead - removing mark for death");
183                                 unmark_for_death($contact);
184                         }
185                 }
186
187                 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
188                         return;
189
190                 if(((float) $res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
191                         q("update contact set poco = '%s' where id = %d limit 1",
192                                 dbesc(str_replace('/profile/','/poco/', $contact['url'])),
193                                 intval($contact['id'])
194                         );
195                 }
196
197                 $postvars = array();
198
199                 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
200                 $challenge    = hex2bin((string) $res->challenge);
201
202                 $final_dfrn_id = '';
203
204                 if(($contact['duplex']) && strlen($contact['prvkey'])) {
205                         openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
206                         openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
207                 }
208                 else {
209                         openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
210                         openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
211                 }
212
213                 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
214
215                 if(strpos($final_dfrn_id,':') == 1)
216                         $final_dfrn_id = substr($final_dfrn_id,2);
217
218                 if($final_dfrn_id != $orig_id) {
219                         logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);    
220                         // did not decode properly - cannot trust this site 
221                         return;
222                 }
223
224                 $postvars['dfrn_id'] = $idtosend;
225                 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
226                 $postvars['perm'] = 'rw';
227
228                 $xml = post_url($contact['poll'],$postvars);
229
230         }
231         elseif(($contact['network'] === NETWORK_OSTATUS) 
232                 || ($contact['network'] === NETWORK_DIASPORA)
233                 || ($contact['network'] === NETWORK_FEED) ) {
234
235                 // Upgrading DB fields from an older Friendica version
236                 // Will only do this once per notify-enabled OStatus contact
237                 // or if relationship changes
238
239                 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
240
241                 if($stat_writeable != $contact['writable']) {
242                         q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d LIMIT 1",
243                                 intval($stat_writeable),
244                                 intval($contact['id'])
245                         );
246                 }
247
248                 // Are we allowed to import from this person?
249
250                 if($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly'])
251                         return;
252
253                 $xml = fetch_url($contact['poll']);
254         }
255         elseif($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {
256
257                 logger("onepoll: mail: Fetching", LOGGER_DEBUG);
258
259                 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
260                 if($mail_disabled)
261                         return;
262
263                 logger("onepoll: Mail: Enabled", LOGGER_DEBUG);
264
265                 $mbox = null;
266                 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
267                         intval($importer_uid)
268                 );
269                 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
270                         intval($importer_uid)
271                 );
272                 if(count($x) && count($mailconf)) {
273                     $mailbox = construct_mailbox_name($mailconf[0]);
274                         $password = '';
275                         openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
276                         $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
277                         unset($password);
278                         logger("Mail: Connect to " . $mailconf[0]['user']);
279                         if($mbox) {
280                                 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
281                                         dbesc(datetime_convert()),
282                                         intval($mailconf[0]['id']),
283                                         intval($importer_uid)
284                                 );
285                         }
286                 }
287                 if($mbox) {
288
289                         $msgs = email_poll($mbox,$contact['addr']);
290
291                         if(count($msgs)) {
292                                 logger("Mail: Parsing ".count($msgs)." mails for ".$mailconf[0]['user'], LOGGER_DEBUG);
293
294                                 $metas = email_msg_meta($mbox,implode(',',$msgs));
295                                 $msgs = array_combine($msgs, $metas);
296                                 foreach($msgs as $msg_uid => $meta) {
297                                         logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
298
299                                         $datarray = array();
300 //                                      $meta = email_msg_meta($mbox,$msg_uid);
301 //                                      $headers = email_msg_headers($mbox,$msg_uid);
302
303                                         $datarray['uri'] = msgid2iri(trim($meta->message_id,'<>'));
304
305                                         // Have we seen it before?
306                                         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
307                                                 intval($importer_uid),
308                                                 dbesc($datarray['uri'])
309                                         );
310
311                                         if(count($r)) {
312                                                 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user']);
313                                                 if($meta->deleted && ! $r[0]['deleted']) {
314                                                         q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d LIMIT 1",
315                                                                 dbesc(datetime_convert()),
316                                                                 intval($r[0]['id'])
317                                                         );
318                                                 }
319                                                 /*switch ($mailconf[0]['action']) {
320                                                         case 0:
321                                                                 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'].". Doing nothing.", LOGGER_DEBUG);
322                                                                 break;
323                                                         case 1:
324                                                                 logger("Mail: Deleting ".$msg_uid." for ".$mailconf[0]['user']);
325                                                                 imap_delete($mbox, $msg_uid, FT_UID);
326                                                                 break;
327                                                         case 2:
328                                                                 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf[0]['user']);
329                                                                 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
330                                                                 break;
331                                                         case 3:
332                                                                 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']." for ".$mailconf[0]['user']);
333                                                                 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
334                                                                 if ($mailconf[0]['movetofolder'] != "")
335                                                                         imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
336                                                                 break;
337                                                 }*/
338                                                 continue;
339                                         }
340
341
342                                         // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
343
344 //                                      $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
345                                         $raw_refs = ((property_exists($meta,'references')) ? str_replace("\t",'',$meta->references) : '');
346                                         if(! trim($raw_refs))
347                                                 $raw_refs = ((property_exists($meta,'in_reply_to')) ? str_replace("\t",'',$meta->in_reply_to) : '');
348                                         $raw_refs = trim($raw_refs);  // Don't allow a blank reference in $refs_arr
349
350                                         if($raw_refs) {
351                                                 $refs_arr = explode(' ', $raw_refs);
352                                                 if(count($refs_arr)) {
353                                                         for($x = 0; $x < count($refs_arr); $x ++)
354                                                                 $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x]))) . "'";
355                                                 }
356                                                 $qstr = implode(',',$refs_arr);
357                                                 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
358                                                         intval($importer_uid)
359                                                 );
360                                                 if(count($r))
361                                                         $datarray['parent-uri'] = $r[0]['parent-uri'];  // Set the parent as the top-level item
362 //                                                      $datarray['parent-uri'] = $r[0]['uri'];
363                                         }
364
365
366                                         if(! x($datarray,'parent-uri'))
367                                                 $datarray['parent-uri'] = $datarray['uri'];
368
369                                         // Decoding the header
370                                         $subject = imap_mime_header_decode($meta->subject);
371                                         $datarray['title'] = "";
372                                         foreach($subject as $subpart)
373                                                 if ($subpart->charset != "default")
374                                                         $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
375                                                 else
376                                                         $datarray['title'] .= $subpart->text;
377
378                                         $datarray['title'] = notags(trim($datarray['title']));
379
380                                         //$datarray['title'] = notags(trim($meta->subject));
381                                         $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
382
383                                         // Is it  reply?
384                                         $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") or
385                                                 (substr(strtolower($datarray['title']), 0, 3) == "re-") or
386                                                 (raw_refs != ""));
387
388                                         $r = email_get_msg($mbox,$msg_uid, $reply);
389                                         if(! $r) {
390                                                 logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf[0]['user']);
391                                                 continue;
392                                         }
393                                         $datarray['body'] = escape_tags($r['body']);
394
395                                         logger("Mail: Importing ".$msg_uid." for ".$mailconf[0]['user']);
396
397                                         // some mailing lists have the original author as 'from' - add this sender info to msg body.
398                                         // todo: adding a gravatar for the original author would be cool
399
400                                         if(! stristr($meta->from,$contact['addr'])) {
401                                                 $from = imap_mime_header_decode($meta->from);
402                                                 $fromdecoded = "";
403                                                 foreach($from as $frompart)
404                                                         if ($frompart->charset != "default")
405                                                                 $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
406                                                         else
407                                                                 $fromdecoded .= $frompart->text;
408
409                                                 $datarray['body'] = "[b]".t('From: ') . escape_tags($fromdecoded) . "[/b]\n\n" . $datarray['body'];
410                                         }
411
412                                         $datarray['uid'] = $importer_uid;
413                                         $datarray['contact-id'] = $contact['id'];
414                                         if($datarray['parent-uri'] === $datarray['uri'])
415                                                 $datarray['private'] = 1;
416                                         if(($contact['network'] === NETWORK_MAIL) && (! get_pconfig($importer_uid,'system','allow_public_email_replies'))) {
417                                                 $datarray['private'] = 1;
418                                                 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
419                                         }
420                                         $datarray['author-name'] = $contact['name'];
421                                         $datarray['author-link'] = 'mailbox';
422                                         $datarray['author-avatar'] = $contact['photo'];
423
424                                         $stored_item = item_store($datarray);
425                                         q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
426                                                 dbesc($datarray['parent-uri']),
427                                                 intval($importer_uid)
428                                         );
429                                         q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
430                                                 intval($stored_item)
431                                         );
432                                         switch ($mailconf[0]['action']) {
433                                                 case 0:
434                                                         logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'].". Doing nothing.", LOGGER_DEBUG);
435                                                         break;
436                                                 case 1:
437                                                         logger("Mail: Deleting ".$msg_uid." for ".$mailconf[0]['user']);
438                                                         imap_delete($mbox, $msg_uid, FT_UID);
439                                                         break;
440                                                 case 2:
441                                                         logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf[0]['user']);
442                                                         imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
443                                                         break;
444                                                 case 3:
445                                                         logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']." for ".$mailconf[0]['user']);
446                                                         imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
447                                                         if ($mailconf[0]['movetofolder'] != "")
448                                                                 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
449                                                         break;
450                                         }
451                                 }
452                         }
453                         imap_close($mbox);
454                 }
455         }
456         elseif($contact['network'] === NETWORK_FACEBOOK) {
457                 // This is picked up by the Facebook plugin on a cron hook.
458                 // Ignored here.
459         }
460
461         if($xml) {
462                 logger('poller: received xml : ' . $xml, LOGGER_DATA);
463                 if((! strstr($xml,'<?xml')) && (! strstr($xml,'<rss'))) {
464                         logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
465                         $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
466                                 dbesc(datetime_convert()),
467                                 intval($contact['id'])
468                         );
469                         return;
470                 }
471
472
473                 consume_feed($xml,$importer,$contact,$hub,1,1);
474
475
476                 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
477         
478                 consume_feed($xml,$importer,$contact,$hub,1,2);
479
480                 $hubmode = 'subscribe';
481                 if($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly'])
482                         $hubmode = 'unsubscribe';
483
484                 if($contact['network'] === NETWORK_OSTATUS && (! $contact['hub-verify']))
485                         $hub_update = true;
486
487                 if((strlen($hub)) && ($hub_update) && ($contact['rel'] != CONTACT_IS_FOLLOWER)) {
488                         logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
489                         $hubs = explode(',', $hub);
490                         if(count($hubs)) {
491                                 foreach($hubs as $h) {
492                                         $h = trim($h);
493                                         if(! strlen($h))
494                                                 continue;
495                                         subscribe_to_hub($h,$importer,$contact,$hubmode);
496                                 }
497                         }
498                 }
499         }
500
501         $updated = datetime_convert();
502
503         $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d LIMIT 1",
504                 dbesc($updated),
505                 dbesc($updated),
506                 intval($contact['id'])
507         );
508
509
510         // load current friends if possible.
511
512         if($contact['poco']) {  
513                 $r = q("SELECT count(*) as total from glink 
514                         where `cid` = %d and updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
515                         intval($contact['id'])
516                 );
517         }
518         if(count($r)) {
519                 if(! $r[0]['total']) {
520                         poco_load($contact['id'],$importer_uid,0,$contact['poco']);
521                 }
522         }
523
524         return;
525 }
526
527 if (array_search(__file__,get_included_files())===0){
528   onepoll_run($argv,$argc);
529   killme();
530 }