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