]> git.mxchange.org Git - friendica.git/blob - include/items.php
d726e961c91d4375961c68b36db2b04603074a7c
[friendica.git] / include / items.php
1 <?php
2
3 require_once('bbcode.php');
4
5 function get_feed_for(&$a, $dfrn_id, $owner_id, $last_update, $direction = 0) {
6
7
8         // default permissions - anonymous user
9
10         $sql_extra = " 
11                 AND `allow_cid` = '' 
12                 AND `allow_gid` = '' 
13                 AND `deny_cid`  = '' 
14                 AND `deny_gid`  = '' 
15         ";
16
17         if(strlen($owner_id) && ! intval($owner_id)) {
18                 $r = q("SELECT `uid`, `nickname` FROM `user` WHERE `nickname` = '%s' LIMIT 1",
19                         dbesc($owner_id)
20                 );
21                 if(count($r)) {
22                         $owner_id = $r[0]['uid'];
23                         $owner_nick = $r[0]['nickname'];
24                 }
25         }
26
27         $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
28                 intval($owner_id)
29         );
30         if(count($r))
31                 $owner = $r[0];
32         else
33                 killme();
34
35         if($dfrn_id && $dfrn_id != '*') {
36
37                 $sql_extra = '';
38                 switch($direction) {
39                         case (-1):
40                                 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
41                                 $my_id = $dfrn_id;
42                                 break;
43                         case 0:
44                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
45                                 $my_id = '1:' . $dfrn_id;
46                                 break;
47                         case 1:
48                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
49                                 $my_id = '0:' . $dfrn_id;
50                                 break;
51                         default:
52                                 return false;
53                                 break; // NOTREACHED
54                 }
55
56                 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
57                         intval($owner_id)
58                 );
59
60                 if(! count($r))
61                         return false;
62
63                 $contact = $r[0];
64                 $groups = init_groups_visitor($contact['id']);
65
66                 if(count($groups)) {
67                         for($x = 0; $x < count($groups); $x ++) 
68                                 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
69                         $gs = implode('|', $groups);
70                 }
71                 else
72                         $gs = '<<>>' ; // Impossible to match 
73
74                 $sql_extra = sprintf(" 
75                         AND ( `allow_cid` = '' OR     `allow_cid` REGEXP '<%d>' ) 
76                         AND ( `deny_cid`  = '' OR NOT `deny_cid`  REGEXP '<%d>' ) 
77                         AND ( `allow_gid` = '' OR     `allow_gid` REGEXP '%s' )
78                         AND ( `deny_gid`  = '' OR NOT `deny_gid`  REGEXP '%s') 
79                 ",
80                         intval($contact['id']),
81                         intval($contact['id']),
82                         dbesc($gs),
83                         dbesc($gs)
84                 );
85         }
86
87         if($dfrn_id === '' || $dfrn_id === '*')
88                 $sort = 'DESC';
89         else
90                 $sort = 'ASC';
91
92         if(! strlen($last_update))
93                 $last_update = 'now - 30 days';
94
95         $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
96
97         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
98                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, 
99                 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
100                 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`, 
101                 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`
102                 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
103                 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 
104                 AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
105                 AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
106                 $sql_extra
107                 ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
108                 intval($owner_id),
109                 dbesc($check_date),
110                 dbesc($check_date),
111                 dbesc($sort)
112         );
113
114         // Will check further below if this actually returned results.
115         // We will provide an empty feed in any case.
116
117         $items = $r;
118
119         $feed_template = load_view_file('view/atom_feed.tpl');
120         $tomb_template = load_view_file('view/atom_tomb.tpl');
121         $item_template = load_view_file('view/atom_item.tpl');
122         $cmnt_template = load_view_file('view/atom_cmnt.tpl');
123
124         $atom = '';
125
126         $hub = get_config('system','huburl');
127
128         $hubxml = ((strlen($hub)) ? '<link rel="hub" href="' . xmlify($hub) . '" />' . "\n" : '');
129
130
131         $atom .= replace_macros($feed_template, array(
132                         '$feed_id'      => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
133                         '$feed_title'   => xmlify($owner['name']),
134                         '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00' , ATOM_TIME)) ,
135                         '$hub'          => $hubxml,
136                         '$name'         => xmlify($owner['name']),
137                         '$profile_page' => xmlify($owner['url']),
138                         '$photo'        => xmlify($owner['photo']),
139                         '$thumb'        => xmlify($owner['thumb']),
140                         '$picdate'      => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
141                         '$uridate'      => xmlify(datetime_convert('UTC','UTC',$owner['uri-date']    . '+00:00' , ATOM_TIME)) ,
142                         '$namdate'      => xmlify(datetime_convert('UTC','UTC',$owner['name-date']   . '+00:00' , ATOM_TIME)) 
143         ));
144
145
146         if(! count($items)) {
147                 $atom .= '</feed>' . "\r\n";
148                 return $atom;
149         }
150
151         foreach($items as $item) {
152
153                 // public feeds get html, our own nodes use bbcode
154
155                 if($dfrn_id === '*') {
156                         $item['body'] = bbcode($item['body']);
157                         $type = 'html';
158                 }
159                 else {
160                         $type = 'text';
161                 }
162
163                 if($item['deleted']) {
164                         $atom .= replace_macros($tomb_template, array(
165                                 '$id'      => xmlify($item['uri']),
166                                 '$updated' => xmlify(datetime_convert('UTC', 'UTC', $item['edited'] . '+00:00' , ATOM_TIME))
167                         ));
168                 }
169                 else {
170                         $verb = construct_verb($item);
171                         $actobj = construct_activity($item);
172
173                         if($item['parent'] == $item['id']) {
174                                 $atom .= replace_macros($item_template, array(
175                                         '$name'               => xmlify($item['name']),
176                                         '$profile_page'       => xmlify($item['url']),
177                                         '$thumb'              => xmlify($item['thumb']),
178                                         '$owner_name'         => xmlify($item['owner-name']),
179                                         '$owner_profile_page' => xmlify($item['owner-link']),
180                                         '$owner_thumb'        => xmlify($item['owner-avatar']),
181                                         '$item_id'            => xmlify($item['uri']),
182                                         '$title'              => xmlify($item['title']),
183                                         '$published'          => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME)),
184                                         '$updated'            => xmlify(datetime_convert('UTC', 'UTC', $item['edited']  . '+00:00' , ATOM_TIME)),
185                                         '$location'           => xmlify($item['location']),
186                                         '$type'               => $type,
187                                         '$alt'           => xmlify($a->get_baseurl() . '/display/' . $owner_nick . '/' . $item['id']),
188                                         '$content'            => xmlify($item['body']),
189                                         '$verb'               => xmlify($verb),
190                                         '$actobj'             => $actobj,  // do not xmlify
191                                         '$comment_allow'      => ((($item['last-child']) && ($contact['rel']) && ($contact['rel'] != REL_FAN)) ? 1 : 0)
192                                 ));
193                         }
194                         else {
195                                 $atom .= replace_macros($cmnt_template, array(
196                                         '$name'          => xmlify($item['name']),
197                                         '$profile_page'  => xmlify($item['url']),
198                                         '$thumb'         => xmlify($item['thumb']),
199                                         '$item_id'       => xmlify($item['uri']),
200                                         '$title'         => xmlify($item['title']),
201                                         '$published'     => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME)),
202                                         '$updated'       => xmlify(datetime_convert('UTC', 'UTC', $item['edited']  . '+00:00' , ATOM_TIME)),
203                                         '$type'          => $type,
204                                         '$content'       => xmlify($item['body']),
205                                         '$alt'           => xmlify($a->get_baseurl() . '/display/' . $owner_nick . '/' . $item['id']),
206                                         '$verb'          => xmlify($verb),
207                                         '$actobj'        => $actobj, // do not xmlify
208                                         '$parent_id'     => xmlify($item['parent-uri']),
209                                         '$comment_allow' => (($item['last-child']) ? 1 : 0)
210                                 ));
211                         }
212                 }
213         }
214
215         $atom .= '</feed>' . "\r\n";
216         return $atom;
217 }
218
219
220 function construct_verb($item) {
221         if($item['verb'])
222                 return $item['verb'];
223         return ACTIVITY_POST;
224 }
225
226 function construct_activity($item) {
227
228         if($item['object']) {
229                 $o = '<as:object>' . "\r\n";
230                 $r = @simplexml_load_string($item['object']);
231                 if($r->type)
232                         $o .= '<as:object-type>' . $r->type . '</as:object-type>' . "\r\n";
233                 if($r->id)
234                         $o .= '<id>' . $r->id . '</id>' . "\r\n";
235                 if($r->link)
236                         $o .= '<link rel="alternate" type="text/html" href="' . $r->link . '" />' . "\r\n";
237                 if($r->title)
238                         $o .= '<title>' . $r->title . '</title>' . "\r\n";
239                 if($r->content)
240                         $o .= '<content type="html" >' . bbcode($r->content) . '</content>' . "\r\n";
241                 $o .= '</as:object>' . "\r\n";
242                 return $o;
243         }
244
245         return '';
246
247
248
249
250
251 function get_atom_elements($item) {
252
253         require_once('library/HTMLPurifier.auto.php');
254         require_once('include/html2bbcode.php');
255
256         $res = array();
257
258         $raw_author = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
259         if($raw_author) {
260                 if($raw_author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'][0]['attribs']['']['rel'] === 'photo')
261                 $res['author-avatar'] = unxmlify($raw_author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'][0]['attribs']['']['href']);
262         }
263
264         $author = $item->get_author();
265         $res['author-name'] = unxmlify($author->get_name());
266         $res['author-link'] = unxmlify($author->get_link());
267         if(! $res['author-avatar'])
268                 $res['author-avatar'] = unxmlify($author->get_avatar());
269         $res['uri'] = unxmlify($item->get_id());
270         $res['title'] = unxmlify($item->get_title());
271         $res['body'] = unxmlify($item->get_content());
272
273         $maxlen = get_max_import_size();
274         if($maxlen && (strlen($res['body']) > $maxlen))
275                 $res['body'] = substr($res['body'],0, $maxlen);
276
277         // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust 
278         // the content type. Our own network only emits text normally, though it might have been converted to 
279         // html if we used a pubsubhubbub transport. But if we see even one html open tag in our text, we will
280         // have to assume it is all html and needs to be purified.
281
282         // It doesn't matter all that much security wise - because before this content is used anywhere, we are 
283         // going to escape any tags we find regardless, but this lets us import a limited subset of html from 
284         // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining 
285         // html.
286
287
288         if(strpos($res['body'],'<')) {
289
290                 $res['body'] = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
291                         '[youtube]$1[/youtube]', $res['body']);
292
293                 $config = HTMLPurifier_Config::createDefault();
294                 $config->set('Core.DefinitionCache', null);
295
296                 // we shouldn't need a whitelist, because the bbcode converter
297                 // will strip out any unsupported tags.
298                 // $config->set('HTML.Allowed', 'p,b,a[href],i'); 
299
300                 $purifier = new HTMLPurifier($config);
301                 $res['body'] = $purifier->purify($res['body']);
302         }
303
304         
305         $res['body'] = html2bbcode($res['body']);
306
307
308         $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
309         if($allow && $allow[0]['data'] == 1)
310                 $res['last-child'] = 1;
311         else
312                 $res['last-child'] = 0;
313
314         $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
315         if($rawcreated)
316                 $res['created'] = unxmlify($rawcreated[0]['data']);
317
318         $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
319         if($rawlocation)
320                 $res['location'] = unxmlify($rawlocation[0]['data']);
321
322
323         $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
324         if($rawedited)
325                 $res['edited'] = unxmlify($rawcreated[0]['data']);
326
327         $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
328         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
329                 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
330         elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
331                 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
332         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
333                 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
334         elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
335                 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
336
337         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'][0]['attribs']['']['rel'] === 'photo')
338                 $res['owner-avatar'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'][0]['attribs']['']['href']);
339         elseif($rawowner[0]['child'][NAMESPACE_DFRN]['avatar'][0]['data'])
340                 $res['owner-avatar'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']);
341
342         $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
343         // select between supported verbs
344         if($rawverb)
345                 $res['verb'] = unxmlify($rawverb[0]['data']);
346
347         $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
348
349
350         if($rawobj) {
351                 $res['object'] = '<object>' . "\n";
352                 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
353                         $res['object-type'] = $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'];
354                         $res['object'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
355                 }       
356                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
357                         $res['object'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
358                 
359                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'][0]['attribs']['']['rel'] === 'alternate')
360                         $res['object'] .= '<link>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'][0]['attribs']['']['href'] . '</link>' . "\n";
361                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
362                         $res['object'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
363                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
364                         $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
365                         if(! $body)
366                                 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
367                         if(strpos($body,'<')) {
368
369                                 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
370                                         '[youtube]$1[/youtube]', $body);
371
372                                 $config = HTMLPurifier_Config::createDefault();
373                                 $config->set('Core.DefinitionCache', null);
374
375                                 $purifier = new HTMLPurifier($config);
376                                 $body = $purifier->purify($body);
377                         }
378
379                         $body = html2bbcode($body);
380                         $res['object'] .= '<content>' . $body . '</content>' . "\n";
381                 }
382
383                 $res['object'] .= '</object>' . "\n";
384         }
385
386         return $res;
387 }
388
389 function item_store($arr) {
390
391 //print_r($arr);
392
393
394         if($arr['gravity'])
395                 $arr['gravity'] = intval($arr['gravity']);
396         elseif($arr['parent-uri'] == $arr['uri'])
397                 $arr['gravity'] = 0;
398         elseif($arr['verb'] == ACTIVITY_POST)
399                 $arr['gravity'] = 6;
400
401         if(! x($arr,'type'))
402                 $arr['type'] = 'remote';
403         $arr['wall'] = ((intval($arr['wall'])) ? 1 : 0);
404         $arr['uri'] = notags(trim($arr['uri']));
405         $arr['author-name'] = notags(trim($arr['author-name']));
406         $arr['author-link'] = notags(trim($arr['author-link']));
407         $arr['author-avatar'] = notags(trim($arr['author-avatar']));
408         $arr['owner-name'] = notags(trim($arr['owner-name']));
409         $arr['owner-link'] = notags(trim($arr['owner-link']));
410         $arr['owner-avatar'] = notags(trim($arr['owner-avatar']));
411         $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
412         $arr['edited']  = ((x($arr,'edited')  !== false) ? datetime_convert('UTC','UTC',$arr['edited'])  : datetime_convert());
413         $arr['changed'] = datetime_convert();
414         $arr['title'] = notags(trim($arr['title']));
415         $arr['location'] = notags(trim($arr['location']));
416         $arr['body'] = escape_tags(trim($arr['body']));
417         $arr['last-child'] = intval($arr['last-child']);
418         $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1);
419         $arr['deleted'] = 0;
420         $arr['parent-uri'] = notags(trim($arr['parent-uri']));
421         $arr['verb'] = notags(trim($arr['verb']));
422         $arr['object-type'] = notags(trim($arr['object-type']));
423         $arr['object'] = trim($arr['object']);
424
425         $parent_id = 0;
426         $parent_missing = false;
427
428         dbesc_array($arr);
429
430         $r = q("INSERT INTO `item` (`" 
431                         . implode("`, `", array_keys($arr)) 
432                         . "`) VALUES ('" 
433                         . implode("', '", array_values($arr)) 
434                         . "')" );
435
436         // find the parent and snarf the item id and ACL's
437
438         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
439                 dbesc($arr['parent-uri']),
440                 intval($arr['uid'])
441         );
442
443         if(count($r)) {
444                 $parent_id = $r[0]['id'];
445                 $allow_cid = $r[0]['allow_cid'];
446                 $allow_gid = $r[0]['allow_gid'];
447                 $deny_cid  = $r[0]['deny_cid'];
448                 $deny_gid  = $r[0]['deny_gid'];
449         }
450         else {
451                 $parent_missing = true;
452         }
453
454         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
455                 $arr['uri'],           // already dbesc'd
456                 intval($arr['uid'])
457         );
458         if(count($r))
459                 $current_post = $r[0]['id'];
460         else
461                 return 0;
462
463         if($parent_missing) {
464
465                 // perhaps the parent was deleted, but in any case, this thread is dead
466                 // and unfortunately our brand new item now has to be destroyed
467
468                 q("DELETE FROM `item` WHERE `id` = %d LIMIT 1",
469                         intval($current_post)
470                 );
471                 return 0;
472         }
473
474         // Set parent id - all of the parent's ACL's are also inherited by this post
475
476         $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
477                 `deny_cid` = '%s', `deny_gid` = '%s' WHERE `id` = %d LIMIT 1",
478                 intval($parent_id),
479                 dbesc($allow_cid),
480                 dbesc($allow_gid),
481                 dbesc($deny_cid),
482                 dbesc($deny_gid),
483                 intval($current_post)
484         );
485
486         return $current_post;
487 }
488
489 function get_item_contact($item,$contacts) {
490         if(! count($contacts) || (! is_array($item)))
491                 return false;
492         foreach($contacts as $contact) {
493                 if($contact['id'] == $item['contact-id']) {
494                         return $contact;
495                         break; // NOTREACHED
496                 }
497         }
498         return false;
499 }
500
501
502 function dfrn_deliver($contact,$atom,$debugging = false) {
503
504
505         if((! strlen($contact['dfrn-id'])) && (! $contact['duplex']))
506                 return 3;
507
508         $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
509
510         if($contact['duplex'] && $contact['dfrn-id'])
511                 $idtosend = '0:' . $orig_id;
512         if($contact['duplex'] && $contact['issued-id'])
513                 $idtosend = '1:' . $orig_id;            
514
515         $url = $contact['notify'] . '?dfrn_id=' . $idtosend;
516
517         if($debugging)
518                 echo "URL: $url";
519
520         $xml = fetch_url($url);
521
522         if($debugging)
523                 echo $xml;
524
525         if(! $xml)
526                 return 3;
527
528         $res = simplexml_load_string($xml);
529
530         if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
531                 return (($res->status) ? $res->status : 3);
532
533         $postvars     = array();
534         $sent_dfrn_id = hex2bin($res->dfrn_id);
535         $challenge    = hex2bin($res->challenge);
536
537         $final_dfrn_id = '';
538
539         if($contact['duplex'] && strlen($contact['prvkey'])) {
540                 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
541                 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
542         }
543         else {
544                 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
545                 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
546         }
547
548         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
549
550         if(strpos($final_dfrn_id,':') == 1)
551                 $final_dfrn_id = substr($final_dfrn_id,2);
552
553         if($final_dfrn_id != $orig_id) {
554                 // did not decode properly - cannot trust this site 
555                 return 3;
556         }
557
558         $postvars['dfrn_id'] = $idtosend;
559
560
561         if(($contact['rel']) && ($contact['rel'] != REL_FAN) && (! $contact['blocked']) && (! $contact['readonly'])) {
562                 $postvars['data'] = $atom;
563         }
564         else {
565                 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
566         }
567
568         $xml = post_url($contact['notify'],$postvars);
569
570         if($debugging)
571                 echo $xml;
572
573         $res = simplexml_load_string($xml);
574
575         return $res->status;
576  
577 }
578
579
580 function consume_feed($xml,$importer,$contact, &$hub) {
581
582         require_once('simplepie/simplepie.inc');
583
584         $feed = new SimplePie();
585         $feed->set_raw_data($xml);
586         $feed->enable_order_by_date(false);
587         $feed->init();
588
589         // Check at the feed level for updated contact name and/or photo
590
591         $name_updated  = '';
592         $new_name = '';
593         $photo_timestamp = '';
594         $photo_url = '';
595
596
597         $foundhub = $feed->get_link(0,'hub');
598
599         if(strlen($foundhub))
600                 $hub = $foundhub;
601
602         $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
603         if($rawtags) {
604                 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
605                 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
606                         $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
607                         $new_name = $elems['name'][0]['data'];
608                 } 
609                 if(($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
610                         $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
611                         $photo_url = $elems['link'][0]['attribs']['']['href'];
612                 }
613         }
614         if(! $photo_timestamp) {
615                 $photo_rawupdate = $feed->get_feed_tags(NAMESPACE_DFRN,'icon-updated');
616                 if($photo_rawupdate) {
617                         $photo_timestamp = datetime_convert('UTC','UTC',$photo_rawupdate[0]['data']);
618                         $photo_url = $feed->get_image_url();
619                 }
620         }
621         if(($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
622
623                 require_once("Photo.php");
624                 $photo_failure = false;
625
626                 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
627                         intval($contact['id']),
628                         intval($contact['uid'])
629                 );
630                 if(count($r)) {
631                         $resource_id = $r[0]['resource-id'];
632                         $img_str = fetch_url($photo_url,true);
633                         $img = new Photo($img_str);
634                         if($img) {
635                                 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND contact-id` = %d AND `uid` = %d",
636                                         dbesc($resource_id),
637                                         intval($contact['id']),
638                                         intval($contact['uid'])
639                                 );
640
641                                 $img->scaleImageSquare(175);
642                                 
643                                 $hash = $resource_id;
644                                 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 4);
645                                 
646                                 $img->scaleImage(80);
647                                 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 5);
648                                 if($r)
649                                         q("UPDATE `contact` SET `avatar-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
650                                                 dbesc(datetime_convert()),
651                                                 intval($contact['uid']),
652                                                 intval($contact['id'])
653                                         );
654                         }
655                 }
656         }
657
658         if(($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
659                 q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
660                         dbesc(notags(trim($new_name))),
661                         dbesc(datetime_convert()),
662                         intval($contact['uid']),
663                         intval($contact['id'])
664                 );
665         }
666
667         // Now process the feed
668         if($feed->get_item_quantity()) {                
669                 foreach($feed->get_items() as $item) {
670
671                         $deleted = false;
672
673                         $rawdelete = $item->get_item_tags( NAMESPACE_TOMB, 'deleted-entry');
674                         if(isset($rawdelete[0]['attribs']['']['ref'])) {
675                                 $uri = $rawthread[0]['attribs']['']['ref'];
676                                 $deleted = true;
677                                 if(isset($rawdelete[0]['attribs']['']['when'])) {
678                                         $when = $rawthread[0]['attribs']['']['when'];
679                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
680                                 }
681                                 else
682                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
683                         }
684                         if($deleted) {
685                                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
686                                         dbesc($uri),
687                                         intval($importer['uid'])
688                                 );
689                                 if(count($r)) {
690                                         $item = $r[0];
691                                         if($item['uri'] == $item['parent-uri']) {
692                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
693                                                         `body` = '', `title` = ''
694                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
695                                                         dbesc($when),
696                                                         dbesc(datetime_convert()),
697                                                         dbesc($item['uri']),
698                                                         intval($importer['uid'])
699                                                 );
700                                         }
701                                         else {
702                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
703                                                         `body` = '', `title` = '' 
704                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
705                                                         dbesc($when),
706                                                         dbesc(datetime_convert()),
707                                                         dbesc($uri),
708                                                         intval($importer['uid'])
709                                                 );
710                                                 if($item['last-child']) {
711                                                         // ensure that last-child is set in case the comment that had it just got wiped.
712                                                         $q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
713                                                                 dbesc(datetime_convert()),
714                                                                 dbesc($item['parent-uri']),
715                                                                 intval($item['uid'])
716                                                         );
717                                                         // who is the last child now? 
718                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d 
719                                                                 ORDER BY `edited` DESC LIMIT 1",
720                                                                         dbesc($item['parent-uri']),
721                                                                         intval($importer['uid'])
722                                                         );
723                                                         if(count($r)) {
724                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
725                                                                         intval($r[0]['id'])
726                                                                 );
727                                                         }
728                                                 }       
729                                         }
730                                 }       
731                                 continue;
732                         }
733
734
735                         $is_reply = false;              
736                         $item_id = $item->get_id();
737                         $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
738                         if(isset($rawthread[0]['attribs']['']['ref'])) {
739                                 $is_reply = true;
740                                 $parent_uri = $rawthread[0]['attribs']['']['ref'];
741                         }
742
743
744                         if($is_reply) {
745         
746                                 // Have we seen it? If not, import it.
747         
748                                 $item_id = $item->get_id();
749         
750                                 $r = q("SELECT `uid`, `last-child`, `edited` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
751                                         dbesc($item_id),
752                                         intval($importer['uid'])
753                                 );
754                                 // FIXME update content if 'updated' changes
755                                 if(count($r)) {
756                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
757                                         if($allow && $allow[0]['data'] != $r[0]['last-child']) {
758                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
759                                                         dbesc(datetime_convert()),
760                                                         dbesc($parent_uri),
761                                                         intval($importer['uid'])
762                                                 );
763                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
764                                                         intval($allow[0]['data']),
765                                                         dbesc(datetime_convert()),
766                                                         dbesc($item_id),
767                                                         intval($importer['uid'])
768                                                 );
769
770                                         }
771                                         continue;
772                                 }
773                                 $datarray = get_atom_elements($item);
774                                 $datarray['parent-uri'] = $parent_uri;
775                                 $datarray['uid'] = $importer['uid'];
776                                 $datarray['contact-id'] = $contact['id'];
777                                 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
778                                         $datarray['type'] = 'activity';
779                                         $datarray['gravity'] = GRAVITY_LIKE;
780                                 }
781
782                                 $r = item_store($datarray);
783                                 continue;
784                         }
785
786                         else {
787                                 // Head post of a conversation. Have we seen it? If not, import it.
788
789                                 $item_id = $item->get_id();
790                                 $r = q("SELECT `uid`, `last-child`, `edited` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
791                                         dbesc($item_id),
792                                         intval($importer['uid'])
793                                 );
794                                 if(count($r)) {
795                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
796                                         if($allow && $allow[0]['data'] != $r[0]['last-child']) {
797                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
798                                                         intval($allow[0]['data']),
799                                                         dbesc(datetime_convert()),
800                                                         dbesc($item_id),
801                                                         intval($importer['uid'])
802                                                 );
803                                         }
804                                         continue;
805                                 }
806                                 $datarray = get_atom_elements($item);
807                                 $datarray['parent-uri'] = $item_id;
808                                 $datarray['uid'] = $importer['uid'];
809                                 $datarray['contact-id'] = $contact['id'];
810                                 $r = item_store($datarray);
811                                 continue;
812
813                         }
814                 }
815         }
816
817 }
818
819
820 function subscribe_to_hub($url,$importer,$contact) {
821
822         if(is_array($importer)) {
823                 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
824                         intval($importer['uid'])
825                 );
826         }
827         if(! count($r))
828                 return;
829
830         $params = array();
831
832         $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
833
834         $verify_token = random_string();
835
836         $params['hub.mode'] = 'subscribe';
837         $params['hub.callback'] = urlencode($push_url);
838         $params['hub.topic'] = urlencode($contact['poll']);
839         $params['hub.verify'] = 'async';
840         $params['hub.verify_token'] = $verify_token;
841
842         $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
843                 dbesc($verify_token),
844                 intval($contact['id'])
845         );
846
847         post_url($url,$params);                 
848         return;
849
850 }