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