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