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