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