]> git.mxchange.org Git - friendica.git/blob - include/onepoll.php
redundant log entry
[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
89         $xml = false;
90
91         $t = $contact['last-update'];
92
93         if($contact['subhub']) {
94                 $poll_interval = get_config('system','pushpoll_frequency');
95                 $contact['priority'] = (($poll_interval !== false) ? intval($poll_interval) : 3);
96                 $hub_update = false;
97
98                 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
99                                 $hub_update = true;
100         }
101         else
102                 $hub_update = false;
103
104
105         $importer_uid = $contact['uid'];
106                 
107         $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",
108                 intval($importer_uid)
109         );
110         if(! count($r))
111                 return;
112
113         $importer = $r[0];
114
115         logger("onepoll: poll: ({$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
116
117         $last_update = (($contact['last-update'] === '0000-00-00 00:00:00') 
118                 ? datetime_convert('UTC','UTC','now - 7 days', ATOM_TIME)
119                 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
120         );
121
122         if($contact['network'] === NETWORK_DFRN) {
123
124                 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
125                 if(intval($contact['duplex']) && $contact['dfrn-id'])
126                         $idtosend = '0:' . $orig_id;
127                 if(intval($contact['duplex']) && $contact['issued-id'])
128                         $idtosend = '1:' . $orig_id;
129
130                 // they have permission to write to us. We already filtered this in the contact query.
131                 $perm = 'rw';
132
133                 $url = $contact['poll'] . '?dfrn_id=' . $idtosend 
134                         . '&dfrn_version=' . DFRN_PROTOCOL_VERSION 
135                         . '&type=data&last_update=' . $last_update 
136                         . '&perm=' . $perm ;
137
138                 $handshake_xml = fetch_url($url);
139                 $html_code = $a->get_curl_code();
140
141                 logger('onepoll: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
142
143
144                 if((! strlen($handshake_xml)) || ($html_code >= 400) || (! $html_code)) {
145                         logger("poller: $url appears to be dead - marking for death ");
146
147                         // dead connection - might be a transient event, or this might
148                         // mean the software was uninstalled or the domain expired. 
149                         // Will keep trying for one month.
150
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
165                         mark_for_death($contact);
166
167                         $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
168                                 dbesc(datetime_convert()),
169                                 intval($contact['id'])
170                         );
171                         return;
172                 }
173
174
175                 $res = parse_xml_string($handshake_xml);
176         
177                 if(intval($res->status) == 1) {
178                         logger("poller: $url replied status 1 - marking for death ");
179
180                         // we may not be friends anymore. Will keep trying for one month.
181                         // set the last-update so we don't keep polling
182
183
184                         $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
185                                 dbesc(datetime_convert()),
186                                 intval($contact['id'])
187                         );
188                         mark_for_death($contact);
189                 }
190                 else {
191                         if($contact['term-date'] != '0000-00-00 00:00:00') {
192                                 logger("poller: $url back from the dead - removing mark for death");
193                                 unmark_for_death($contact);
194                         }
195                 }
196
197                 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
198                         return;
199
200                 if(((float) $res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
201                         q("update contact set poco = '%s' where id = %d limit 1",
202                                 dbesc(str_replace('/profile/','/poco/', $contact['url'])),
203                                 intval($contact['id'])
204                         );
205                 }
206
207                 $postvars = array();
208
209                 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
210                 $challenge    = hex2bin((string) $res->challenge);
211
212                 $final_dfrn_id = '';
213
214                 if(($contact['duplex']) && strlen($contact['prvkey'])) {
215                         openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
216                         openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
217                 }
218                 else {
219                         openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
220                         openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
221                 }
222
223                 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
224
225                 if(strpos($final_dfrn_id,':') == 1)
226                         $final_dfrn_id = substr($final_dfrn_id,2);
227
228                 if($final_dfrn_id != $orig_id) {
229                         logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);    
230                         // did not decode properly - cannot trust this site 
231                         return;
232                 }
233
234                 $postvars['dfrn_id'] = $idtosend;
235                 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
236                 $postvars['perm'] = 'rw';
237
238                 $xml = post_url($contact['poll'],$postvars);
239
240         }
241         elseif(($contact['network'] === NETWORK_OSTATUS) 
242                 || ($contact['network'] === NETWORK_DIASPORA)
243                 || ($contact['network'] === NETWORK_FEED) ) {
244
245                 // Upgrading DB fields from an older Friendica version
246                 // Will only do this once per notify-enabled OStatus contact
247                 // or if relationship changes
248
249                 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
250
251                 if($stat_writeable != $contact['writable']) {
252                         q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d LIMIT 1",
253                                 intval($stat_writeable),
254                                 intval($contact['id'])
255                         );
256                 }
257
258                 // Are we allowed to import from this person?
259
260                 if($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly'])
261                         return;
262
263                 $xml = fetch_url($contact['poll']);
264         }
265         elseif($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {
266
267                 logger("onepoll: mail: Fetching", LOGGER_DEBUG);
268
269                 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
270                 if($mail_disabled)
271                         return;
272
273                 logger("onepoll: Mail: Enabled", LOGGER_DEBUG);
274
275                 $mbox = null;
276                 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
277                         intval($importer_uid)
278                 );
279                 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
280                         intval($importer_uid)
281                 );
282                 if(count($x) && count($mailconf)) {
283                     $mailbox = construct_mailbox_name($mailconf[0]);
284                         $password = '';
285                         openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
286                         $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
287                         unset($password);
288                         logger("Mail: Connect");
289                         if($mbox) {
290                                 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
291                                         dbesc(datetime_convert()),
292                                         intval($mailconf[0]['id']),
293                                         intval($importer_uid)
294                                 );
295                         }
296                 }
297                 if($mbox) {
298
299                         $msgs = email_poll($mbox,$contact['addr']);
300
301                         if(count($msgs)) {
302                                 logger("Mail: Parsing ".count($msgs)." mails.", LOGGER_DEBUG);
303
304                                 foreach($msgs as $msg_uid) {
305                                         logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
306
307                                         $datarray = array();
308                                         $meta = email_msg_meta($mbox,$msg_uid);
309                                         $headers = email_msg_headers($mbox,$msg_uid);
310
311                                         // look for a 'references' header and try and match with a parent item we have locally.
312
313                                         $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
314                                         $datarray['uri'] = msgid2iri(trim($meta->message_id,'<>'));
315
316                                         if($raw_refs) {
317                                                 $refs_arr = explode(' ', $raw_refs);
318                                                 if(count($refs_arr)) {
319                                                         for($x = 0; $x < count($refs_arr); $x ++)
320                                                                 $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x]))) . "'";
321                                                 }
322                                                 $qstr = implode(',',$refs_arr);
323                                                 $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
324                                                         intval($importer_uid)
325                                                 );
326                                                 if(count($r))
327                                                         $datarray['parent-uri'] = $r[0]['uri'];
328                                         }
329
330
331                                         if(! x($datarray,'parent-uri'))
332                                                 $datarray['parent-uri'] = $datarray['uri'];
333
334                                         // Have we seen it before?
335                                         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
336                                                 intval($importer_uid),
337                                                 dbesc($datarray['uri'])
338                                         );
339
340                                         if(count($r)) {
341 //                                              logger("Mail: Seen before ".$msg_uid);
342                                                 if($meta->deleted && ! $r[0]['deleted']) {
343                                                         q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d LIMIT 1",
344                                                                 dbesc(datetime_convert()),
345                                                                 intval($r[0]['id'])
346                                                         );
347                                                 }
348                                                 switch ($mailconf[0]['action']) {
349                                                         case 0:
350                                                                 break;
351                                                         case 1:
352                                                                 logger("Mail: Deleting ".$msg_uid);
353                                                                 imap_delete($mbox, $msg_uid, FT_UID);
354                                                                 break;
355                                                         case 2:
356                                                                 logger("Mail: Mark as seen ".$msg_uid);
357                                                                 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
358                                                                 break;
359                                                         case 3:
360                                                                 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']);
361                                                                 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
362                                                                 if ($mailconf[0]['movetofolder'] != "")
363                                                                         imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
364                                                                 break;
365                                                 }
366                                                 continue;
367                                         }
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);
391                                                 continue;
392                                         }
393                                         $datarray['body'] = escape_tags($r['body']);
394
395                                         logger("Mail: Importing ".$msg_uid);
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                                                         break;
435                                                 case 1:
436                                                         logger("Mail: Deleting ".$msg_uid);
437                                                         imap_delete($mbox, $msg_uid, FT_UID);
438                                                         break;
439                                                 case 2:
440                                                         logger("Mail: Mark as seen ".$msg_uid);
441                                                         imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
442                                                         break;
443                                                 case 3:
444                                                         logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']);
445                                                         imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
446                                                         if ($mailconf[0]['movetofolder'] != "")
447                                                                 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
448                                                         break;
449                                         }
450                                 }
451                         }
452                         imap_close($mbox);
453                 }
454         }
455         elseif($contact['network'] === NETWORK_FACEBOOK) {
456                 // This is picked up by the Facebook plugin on a cron hook.
457                 // Ignored here.
458         }
459
460         if($xml) {
461                 logger('poller: received xml : ' . $xml, LOGGER_DATA);
462                         if((! strstr($xml,'<?xml')) && (! strstr($xml,'<rss'))) {
463                         logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
464                         $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d LIMIT 1",
465                                 dbesc(datetime_convert()),
466                                 intval($contact['id'])
467                         );
468                         return;
469                 }
470
471
472                 consume_feed($xml,$importer,$contact,$hub,1,1);
473
474
475                 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
476         
477                 consume_feed($xml,$importer,$contact,$hub,1,2);
478
479                 $hubmode = 'subscribe';
480                 if($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly'])
481                         $hubmode = 'unsubscribe';
482
483                 if($contact['network'] === NETWORK_OSTATUS && (! $contact['hub-verify']))
484                         $hub_update = true;
485
486                 if((strlen($hub)) && ($hub_update) && ($contact['rel'] != CONTACT_IS_FOLLOWER)) {
487                         logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
488                         $hubs = explode(',', $hub);
489                         if(count($hubs)) {
490                                 foreach($hubs as $h) {
491                                         $h = trim($h);
492                                         if(! strlen($h))
493                                                 continue;
494                                         subscribe_to_hub($h,$importer,$contact,$hubmode);
495                                 }
496                         }
497                 }
498         }
499
500         $updated = datetime_convert();
501
502         $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d LIMIT 1",
503                 dbesc($updated),
504                 dbesc($updated),
505                 intval($contact['id'])
506         );
507
508
509         // load current friends if possible.
510
511         if($contact['poco']) {  
512                 $r = q("SELECT count(*) as total from glink 
513                         where `cid` = %d and updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
514                         intval($contact['id'])
515                 );
516         }
517         if(count($r)) {
518                 if(! $r[0]['total']) {
519                         poco_load($contact['id'],$importer_uid,0,$contact['poco']);
520                 }
521         }
522
523         return;
524 }
525
526 if (array_search(__file__,get_included_files())===0){
527   onepoll_run($argv,$argc);
528   killme();
529 }