]> git.mxchange.org Git - friendica.git/blob - include/items.php
more branding
[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                 $owner['nickname'] = $owner_nick;
33         }
34         else
35                 killme();
36
37         if($dfrn_id && $dfrn_id != '*') {
38
39                 $sql_extra = '';
40                 switch($direction) {
41                         case (-1):
42                                 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
43                                 $my_id = $dfrn_id;
44                                 break;
45                         case 0:
46                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
47                                 $my_id = '1:' . $dfrn_id;
48                                 break;
49                         case 1:
50                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
51                                 $my_id = '0:' . $dfrn_id;
52                                 break;
53                         default:
54                                 return false;
55                                 break; // NOTREACHED
56                 }
57
58                 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
59                         intval($owner_id)
60                 );
61
62                 if(! count($r))
63                         return false;
64
65                 $contact = $r[0];
66                 $groups = init_groups_visitor($contact['id']);
67
68                 if(count($groups)) {
69                         for($x = 0; $x < count($groups); $x ++) 
70                                 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
71                         $gs = implode('|', $groups);
72                 }
73                 else
74                         $gs = '<<>>' ; // Impossible to match 
75
76                 $sql_extra = sprintf(" 
77                         AND ( `allow_cid` = '' OR     `allow_cid` REGEXP '<%d>' ) 
78                         AND ( `deny_cid`  = '' OR NOT `deny_cid`  REGEXP '<%d>' ) 
79                         AND ( `allow_gid` = '' OR     `allow_gid` REGEXP '%s' )
80                         AND ( `deny_gid`  = '' OR NOT `deny_gid`  REGEXP '%s') 
81                 ",
82                         intval($contact['id']),
83                         intval($contact['id']),
84                         dbesc($gs),
85                         dbesc($gs)
86                 );
87         }
88
89         if($dfrn_id === '' || $dfrn_id === '*')
90                 $sort = 'DESC';
91         else
92                 $sort = 'ASC';
93
94         if(! strlen($last_update))
95                 $last_update = 'now -30 days';
96
97         $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
98
99         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
100                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, 
101                 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
102                 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`, 
103                 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`
104                 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
105                 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 
106                 AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
107                 AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
108                 $sql_extra
109                 ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
110                 intval($owner_id),
111                 dbesc($check_date),
112                 dbesc($check_date),
113                 dbesc($sort)
114         );
115
116         // Will check further below if this actually returned results.
117         // We will provide an empty feed in any case.
118
119         $items = $r;
120
121         $feed_template = load_view_file('view/atom_feed.tpl');
122
123         $atom = '';
124
125         $hub = get_config('system','huburl');
126
127         $hubxml = '';
128         if(strlen($hub)) {
129                 $hubs = explode(',', $hub);
130                 if(count($hubs)) {
131                         foreach($hubs as $h) {
132                                 $h = trim($h);
133                                 if(! strlen($h))
134                                         continue;
135                                 $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
136                         }
137                 }
138         }
139
140         $salmon = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $owner_nick) . '" />' . "\n" ; 
141         $salmon .= '<link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $owner_nick) . '" />' . "\n" ; 
142         $salmon .= '<link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $owner_nick) . '" />' . "\n" ; 
143
144
145         $atom .= replace_macros($feed_template, array(
146                 '$feed_id'      => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
147                 '$feed_title'   => xmlify($owner['name']),
148                 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
149                 '$hub'          => $hubxml,
150                 '$salmon'       => $salmon,
151                 '$name'         => xmlify($owner['name']),
152                 '$profile_page' => xmlify($owner['url']),
153                 '$photo'        => xmlify($owner['photo']),
154                 '$thumb'        => xmlify($owner['thumb']),
155                 '$picdate'      => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
156                 '$uridate'      => xmlify(datetime_convert('UTC','UTC',$owner['uri-date']    . '+00:00' , ATOM_TIME)) ,
157                 '$namdate'      => xmlify(datetime_convert('UTC','UTC',$owner['name-date']   . '+00:00' , ATOM_TIME)) 
158         ));
159
160
161         if(! count($items)) {
162                 $atom .= '</feed>' . "\r\n";
163                 return $atom;
164         }
165
166         foreach($items as $item) {
167
168                 // public feeds get html, our own nodes use bbcode
169
170                 if($dfrn_id === '*') {
171                         $type = 'html';
172                 }
173                 else {
174                         $type = 'text';
175                 }
176
177                 $atom .= atom_entry($item,$type,null,$owner,true);
178         }
179
180         $atom .= '</feed>' . "\r\n";
181         return $atom;
182 }
183
184
185 function construct_verb($item) {
186         if($item['verb'])
187                 return $item['verb'];
188         return ACTIVITY_POST;
189 }
190
191 function construct_activity($item) {
192
193         if($item['object']) {
194                 $o = '<as:object>' . "\r\n";
195                 $r = @simplexml_load_string($item['object']);
196                 if($r->type)
197                         $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
198                 if($r->id)
199                         $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
200                 if($r->link)
201                         $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
202                 if($r->title)
203                         $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
204                 if($r->content)
205                         $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
206                 $o .= '</as:object>' . "\r\n";
207                 return $o;
208         }
209
210         return '';
211
212
213
214
215
216 function get_atom_elements($feed,$item) {
217
218         require_once('library/HTMLPurifier.auto.php');
219         require_once('include/html2bbcode.php');
220
221         $best_photo = array();
222
223         $res = array();
224
225         $author = $item->get_author();
226         $res['author-name'] = unxmlify($author->get_name());
227         $res['author-link'] = unxmlify($author->get_link());
228         $res['uri'] = unxmlify($item->get_id());
229         $res['title'] = unxmlify($item->get_title());
230         $res['body'] = unxmlify($item->get_content());
231
232
233         // look for a photo. We should check media size and find the best one,
234         // but for now let's just find any author photo
235
236         $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
237
238         if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
239                 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
240                 foreach($base as $link) {
241                         if(! $res['author-avatar']) {
242                                 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
243                                         $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
244                         }
245                 }
246         }                       
247
248         $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
249
250         if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
251                 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
252                 if($base && count($base)) {
253                         foreach($base as $link) {
254                                 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
255                                         $res['author-link'] = unxmlify($link['attribs']['']['href']);
256                                 if(! $res['author-avatar']) {
257                                         if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
258                                                 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
259                                 }
260                         }
261                 }
262         }
263
264         // No photo/profile-link on the item - look at the feed level
265
266         if((! $res['author-link']) || (! $res['author-avatar'])) {
267                 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
268                 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
269                         $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
270                         foreach($base as $link) {
271                                 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
272                                         $res['author-link'] = unxmlify($link['attribs']['']['href']);
273                                 if(! $res['author-avatar']) {
274                                         if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
275                                                 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
276                                 }
277                         }
278                 }                       
279
280                 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
281
282                 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
283                         $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
284
285                         if($base && count($base)) {
286                                 foreach($base as $link) {
287                                         if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
288                                                 $res['author-link'] = unxmlify($link['attribs']['']['href']);
289                                         if(! $res['author-avatar']) {
290                                                 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
291                                                         $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
292                                         }
293                                 }
294                         }
295                 }
296         }
297
298
299         $maxlen = get_max_import_size();
300         if($maxlen && (strlen($res['body']) > $maxlen))
301                 $res['body'] = substr($res['body'],0, $maxlen);
302
303         // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust 
304         // the content type. Our own network only emits text normally, though it might have been converted to 
305         // html if we used a pubsubhubbub transport. But if we see even one html open tag in our text, we will
306         // have to assume it is all html and needs to be purified.
307
308         // It doesn't matter all that much security wise - because before this content is used anywhere, we are 
309         // going to escape any tags we find regardless, but this lets us import a limited subset of html from 
310         // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining 
311         // html.
312
313
314         if(strpos($res['body'],'<')) {
315
316                 $res['body'] = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
317                         '[youtube]$1[/youtube]', $res['body']);
318
319                 $config = HTMLPurifier_Config::createDefault();
320                 $config->set('Cache.DefinitionImpl', null);
321
322                 // we shouldn't need a whitelist, because the bbcode converter
323                 // will strip out any unsupported tags.
324                 // $config->set('HTML.Allowed', 'p,b,a[href],i'); 
325
326                 $purifier = new HTMLPurifier($config);
327                 $res['body'] = $purifier->purify($res['body']);
328         }
329
330         
331         $res['body'] = html2bbcode($res['body']);
332
333
334         $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
335         if($allow && $allow[0]['data'] == 1)
336                 $res['last-child'] = 1;
337         else
338                 $res['last-child'] = 0;
339
340         $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
341         if($rawcreated)
342                 $res['created'] = unxmlify($rawcreated[0]['data']);
343
344         $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
345         if($rawlocation)
346                 $res['location'] = unxmlify($rawlocation[0]['data']);
347
348
349         $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
350         if($rawedited)
351                 $res['edited'] = unxmlify($rawcreated[0]['data']);
352
353         $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
354         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
355                 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
356         elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
357                 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
358         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
359                 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
360         elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
361                 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
362
363         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
364                 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
365
366                 foreach($base as $link) {
367                         if(! $res['owner-avatar']) {
368                                 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')                 
369                                         $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
370                         }
371                 }
372         }
373
374         $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
375         if($rawgeo)
376                 $res['coord'] = unxmlify($rawgeo[0]['data']);
377
378
379         $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
380         // select between supported verbs
381         if($rawverb)
382                 $res['verb'] = unxmlify($rawverb[0]['data']);
383
384         $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
385
386         if($rawobj) {
387                 $res['object'] = '<object>' . "\n";
388                 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
389                         $res['object-type'] = $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'];
390                         $res['object'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
391                 }       
392                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
393                         $res['object'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
394                 
395                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'][0]['attribs']['']['rel'] === 'alternate')
396                         $res['object'] .= '<link>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'][0]['attribs']['']['href'] . '</link>' . "\n";
397                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
398                         $res['object'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
399                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
400                         $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
401                         if(! $body)
402                                 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
403                         if(strpos($body,'<')) {
404
405                                 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
406                                         '[youtube]$1[/youtube]', $body);
407
408                                 $config = HTMLPurifier_Config::createDefault();
409                                 $config->set('Cache.DefinitionImpl', null);
410
411                                 $purifier = new HTMLPurifier($config);
412                                 $body = $purifier->purify($body);
413                         }
414
415                         $body = html2bbcode($body);
416                         $res['object'] .= '<content>' . $body . '</content>' . "\n";
417                 }
418
419                 $res['object'] .= '</object>' . "\n";
420         }
421
422         return $res;
423 }
424
425 function item_store($arr) {
426
427         if($arr['gravity'])
428                 $arr['gravity'] = intval($arr['gravity']);
429         elseif($arr['parent-uri'] == $arr['uri'])
430                 $arr['gravity'] = 0;
431         elseif(activity_match($arr['verb'],ACTIVITY_POST))
432                 $arr['gravity'] = 6;
433
434         if(! x($arr,'type'))
435                 $arr['type'] = 'remote';
436         $arr['wall'] = ((intval($arr['wall'])) ? 1 : 0);
437         $arr['uri'] = notags(trim($arr['uri']));
438         $arr['author-name'] = notags(trim($arr['author-name']));
439         $arr['author-link'] = notags(trim($arr['author-link']));
440         $arr['author-avatar'] = notags(trim($arr['author-avatar']));
441         $arr['owner-name'] = notags(trim($arr['owner-name']));
442         $arr['owner-link'] = notags(trim($arr['owner-link']));
443         $arr['owner-avatar'] = notags(trim($arr['owner-avatar']));
444         $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
445         $arr['edited']  = ((x($arr,'edited')  !== false) ? datetime_convert('UTC','UTC',$arr['edited'])  : datetime_convert());
446         $arr['changed'] = datetime_convert();
447         $arr['title'] = notags(trim($arr['title']));
448         $arr['location'] = notags(trim($arr['location']));
449         $arr['coord'] = notags(trim($arr['coord']));
450         $arr['body'] = escape_tags(trim($arr['body']));
451         $arr['last-child'] = intval($arr['last-child']);
452         $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1);
453         $arr['deleted'] = 0;
454         $arr['parent-uri'] = notags(trim($arr['parent-uri']));
455         $arr['verb'] = notags(trim($arr['verb']));
456         $arr['object-type'] = notags(trim($arr['object-type']));
457         $arr['object'] = trim($arr['object']);
458
459         $parent_id = 0;
460         $parent_missing = false;
461
462         dbesc_array($arr);
463
464         $r = q("INSERT INTO `item` (`" 
465                         . implode("`, `", array_keys($arr)) 
466                         . "`) VALUES ('" 
467                         . implode("', '", array_values($arr)) 
468                         . "')" );
469
470         // find the parent and snarf the item id and ACL's
471
472         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
473                 dbesc($arr['parent-uri']),
474                 intval($arr['uid'])
475         );
476
477         if(count($r)) {
478                 $parent_id = $r[0]['id'];
479                 $allow_cid = $r[0]['allow_cid'];
480                 $allow_gid = $r[0]['allow_gid'];
481                 $deny_cid  = $r[0]['deny_cid'];
482                 $deny_gid  = $r[0]['deny_gid'];
483         }
484         else {
485                 $parent_missing = true;
486         }
487
488         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
489                 $arr['uri'],           // already dbesc'd
490                 intval($arr['uid'])
491         );
492         if(count($r))
493                 $current_post = $r[0]['id'];
494         else
495                 return 0;
496
497         if($parent_missing) {
498
499                 // perhaps the parent was deleted, but in any case, this thread is dead
500                 // and unfortunately our brand new item now has to be destroyed
501
502                 q("DELETE FROM `item` WHERE `id` = %d LIMIT 1",
503                         intval($current_post)
504                 );
505                 return 0;
506         }
507
508         // Set parent id - all of the parent's ACL's are also inherited by this post
509
510         $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
511                 `deny_cid` = '%s', `deny_gid` = '%s' WHERE `id` = %d LIMIT 1",
512                 intval($parent_id),
513                 dbesc($allow_cid),
514                 dbesc($allow_gid),
515                 dbesc($deny_cid),
516                 dbesc($deny_gid),
517                 intval($current_post)
518         );
519
520         return $current_post;
521 }
522
523 function get_item_contact($item,$contacts) {
524         if(! count($contacts) || (! is_array($item)))
525                 return false;
526         foreach($contacts as $contact) {
527                 if($contact['id'] == $item['contact-id']) {
528                         return $contact;
529                         break; // NOTREACHED
530                 }
531         }
532         return false;
533 }
534
535
536 function dfrn_deliver($owner,$contact,$atom) {
537
538
539         if((! strlen($contact['dfrn-id'])) && (! $contact['duplex']) && (! ($owner['page-flags'] == PAGE_COMMUNITY)))
540                 return 3;
541
542         $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
543
544         if($contact['duplex'] && $contact['dfrn-id'])
545                 $idtosend = '0:' . $orig_id;
546         if($contact['duplex'] && $contact['issued-id'])
547                 $idtosend = '1:' . $orig_id;            
548
549         $url = $contact['notify'] . '?dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION ;
550
551         logger('dfrn_deliver: ' . $url);
552
553         $xml = fetch_url($url);
554
555         logger('dfrn_deliver: ' . $xml);
556
557         if(! $xml)
558                 return 3;
559
560         $res = simplexml_load_string($xml);
561
562         if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
563                 return (($res->status) ? $res->status : 3);
564
565         $postvars     = array();
566         $sent_dfrn_id = hex2bin($res->dfrn_id);
567         $challenge    = hex2bin($res->challenge);
568
569         $final_dfrn_id = '';
570
571
572
573         if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
574                 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
575                 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
576         }
577         else {
578                 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
579                 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
580         }
581
582         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
583
584         if(strpos($final_dfrn_id,':') == 1)
585                 $final_dfrn_id = substr($final_dfrn_id,2);
586
587         if($final_dfrn_id != $orig_id) {
588                 logger('dfrn_deliver: wrong dfrn_id.');
589                 // did not decode properly - cannot trust this site 
590                 return 3;
591         }
592
593         $postvars['dfrn_id']      = $idtosend;
594         $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
595
596         if(($contact['rel']) && ($contact['rel'] != REL_FAN) && (! $contact['blocked']) && (! $contact['readonly'])) {
597                 $postvars['data'] = $atom;
598         }
599         elseif($owner['page-flags'] == PAGE_COMMUNITY) {
600                 $postvars['data'] = $atom;
601         }
602         else {
603                 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
604         }
605
606         $xml = post_url($contact['notify'],$postvars);
607
608         logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true) . "\n" . "RECEIVING: " . $xml);
609
610         $res = simplexml_load_string($xml);
611
612         return $res->status;
613  
614 }
615
616
617 /*
618  *
619  * consume_feed - process atom feed and update anything/everything we might need to update
620  *
621  * $xml = the (atom) feed to consume - no RSS spoken here, it might partially work since simplepie 
622  *        handles both, but we don't claim it will work well, and are reasonably certain it won't.
623  * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
624  *             It is this person's stuff that is going to be updated.
625  * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
626  *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST 
627  *             have a contact record.
628  * $hub = should wefind ahub declation in the feed, pass it back to our calling process, who might (or 
629  *        might not) try and subscribe to it.
630  *
631  */
632
633 function consume_feed($xml,$importer,$contact, &$hub) {
634
635         require_once('simplepie/simplepie.inc');
636
637         $feed = new SimplePie();
638         $feed->set_raw_data($xml);
639         $feed->enable_order_by_date(false);
640         $feed->init();
641
642         // Check at the feed level for updated contact name and/or photo
643         $debugging = get_config('system','debugging');
644
645         $name_updated  = '';
646         $new_name = '';
647         $photo_timestamp = '';
648         $photo_url = '';
649
650
651         $hubs = $feed->get_links('hub');
652
653         if(count($hubs))
654                 $hub = implode(',', $hubs);
655
656         $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
657         if($rawtags) {
658                 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
659                 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
660                         $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
661                         $new_name = $elems['name'][0]['data'];
662                 } 
663                 if(($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
664                         $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
665                         $photo_url = $elems['link'][0]['attribs']['']['href'];
666                 }
667         }
668         if(! $photo_timestamp) {
669                 $photo_rawupdate = $feed->get_feed_tags(NAMESPACE_DFRN,'icon-updated');
670                 if($photo_rawupdate) {
671                         $photo_timestamp = datetime_convert('UTC','UTC',$photo_rawupdate[0]['data']);
672                         $photo_url = $feed->get_image_url();
673                 }
674         }
675         if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
676
677                 require_once("Photo.php");
678                 $photo_failure = false;
679
680                 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
681                         intval($contact['id']),
682                         intval($contact['uid'])
683                 );
684                 if(count($r)) {
685                         $resource_id = $r[0]['resource-id'];
686                         $img_str = fetch_url($photo_url,true);
687                         $img = new Photo($img_str);
688                         if($img->is_valid()) {
689                                 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND contact-id` = %d AND `uid` = %d",
690                                         dbesc($resource_id),
691                                         intval($contact['id']),
692                                         intval($contact['uid'])
693                                 );
694
695                                 $img->scaleImageSquare(175);
696                                 
697                                 $hash = $resource_id;
698                                 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 4);
699                                 
700                                 $img->scaleImage(80);
701                                 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 5);
702                                 if($r)
703                                         q("UPDATE `contact` SET `avatar-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
704                                                 dbesc(datetime_convert()),
705                                                 intval($contact['uid']),
706                                                 intval($contact['id'])
707                                         );
708                         }
709                 }
710         }
711
712         if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
713                 q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
714                         dbesc(notags(trim($new_name))),
715                         dbesc(datetime_convert()),
716                         intval($contact['uid']),
717                         intval($contact['id'])
718                 );
719         }
720
721         // Now process the feed
722         if($feed->get_item_quantity()) {                
723                 foreach($feed->get_items() as $item) {
724
725                         $deleted = false;
726
727                         $rawdelete = $item->get_item_tags( NAMESPACE_TOMB, 'deleted-entry');
728                         if(isset($rawdelete[0]['attribs']['']['ref'])) {
729                                 $uri = $rawthread[0]['attribs']['']['ref'];
730                                 $deleted = true;
731                                 if(isset($rawdelete[0]['attribs']['']['when'])) {
732                                         $when = $rawthread[0]['attribs']['']['when'];
733                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
734                                 }
735                                 else
736                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
737                         }
738                         if($deleted && is_array($contact)) {
739                                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `contact-id` = %d LIMIT 1",
740                                         dbesc($uri),
741                                         intval($importer['uid']),
742                                         intval($contact['id'])
743                                 );
744                                 if(count($r)) {
745                                         $item = $r[0];
746                                         if($item['uri'] == $item['parent-uri']) {
747                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
748                                                         `body` = '', `title` = ''
749                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
750                                                         dbesc($when),
751                                                         dbesc(datetime_convert()),
752                                                         dbesc($item['uri']),
753                                                         intval($importer['uid'])
754                                                 );
755                                         }
756                                         else {
757                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
758                                                         `body` = '', `title` = '' 
759                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
760                                                         dbesc($when),
761                                                         dbesc(datetime_convert()),
762                                                         dbesc($uri),
763                                                         intval($importer['uid'])
764                                                 );
765                                                 if($item['last-child']) {
766                                                         // ensure that last-child is set in case the comment that had it just got wiped.
767                                                         $q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
768                                                                 dbesc(datetime_convert()),
769                                                                 dbesc($item['parent-uri']),
770                                                                 intval($item['uid'])
771                                                         );
772                                                         // who is the last child now? 
773                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d 
774                                                                 ORDER BY `created` DESC LIMIT 1",
775                                                                         dbesc($item['parent-uri']),
776                                                                         intval($importer['uid'])
777                                                         );
778                                                         if(count($r)) {
779                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
780                                                                         intval($r[0]['id'])
781                                                                 );
782                                                         }
783                                                 }       
784                                         }
785                                 }       
786                                 continue;
787                         }
788
789
790                         $is_reply = false;              
791                         $item_id = $item->get_id();
792                         $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
793                         if(isset($rawthread[0]['attribs']['']['ref'])) {
794                                 $is_reply = true;
795                                 $parent_uri = $rawthread[0]['attribs']['']['ref'];
796                         }
797
798
799                         if(($is_reply) && is_array($contact)) {
800         
801                                 // Have we seen it? If not, import it.
802         
803                                 $item_id = $item->get_id();
804         
805                                 $r = q("SELECT `uid`, `last-child`, `edited` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
806                                         dbesc($item_id),
807                                         intval($importer['uid'])
808                                 );
809                                 // FIXME update content if 'updated' changes
810                                 if(count($r)) {
811                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
812                                         if($allow && $allow[0]['data'] != $r[0]['last-child']) {
813                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
814                                                         dbesc(datetime_convert()),
815                                                         dbesc($parent_uri),
816                                                         intval($importer['uid'])
817                                                 );
818                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
819                                                         intval($allow[0]['data']),
820                                                         dbesc(datetime_convert()),
821                                                         dbesc($item_id),
822                                                         intval($importer['uid'])
823                                                 );
824
825                                         }
826                                         continue;
827                                 }
828                                 $datarray = get_atom_elements($feed,$item);
829                                 if($contact['network'] === 'stat' && strlen($datarray['title']))
830                                         unset($datarray['title']);
831                                 $datarray['parent-uri'] = $parent_uri;
832                                 $datarray['uid'] = $importer['uid'];
833                                 $datarray['contact-id'] = $contact['id'];
834                                 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
835                                         $datarray['type'] = 'activity';
836                                         $datarray['gravity'] = GRAVITY_LIKE;
837                                 }
838
839                                 $r = item_store($datarray);
840                                 continue;
841                         }
842
843                         else {
844                                 // Head post of a conversation. Have we seen it? If not, import it.
845
846                                 $item_id = $item->get_id();
847                                 $r = q("SELECT `uid`, `last-child`, `edited` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
848                                         dbesc($item_id),
849                                         intval($importer['uid'])
850                                 );
851                                 if(count($r)) {
852                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
853                                         if($allow && $allow[0]['data'] != $r[0]['last-child']) {
854                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
855                                                         intval($allow[0]['data']),
856                                                         dbesc(datetime_convert()),
857                                                         dbesc($item_id),
858                                                         intval($importer['uid'])
859                                                 );
860                                         }
861                                         continue;
862                                 }
863                                 $datarray = get_atom_elements($feed,$item);
864
865                                 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
866                                         logger('consume-feed: New follower');
867                                         new_follower($importer,$contact,$datarray,$item);
868                                         return;
869                                 }
870                                 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW))  {
871                                         lose_follower($importer,$contact,$datarray,$item);
872                                         return;
873                                 }
874                                 if(! is_array($contact))
875                                         return;
876
877                                 if($contact['network'] === 'stat') {
878                                         if(strlen($datarray['title']))
879                                                 unset($datarray['title']);
880                                         if(($contact['rel'] == REL_VIP) || ($contact['rel'] == REL_BUD))
881                                                 $datarray['last-child'] = 1;
882                                 }
883                                 $datarray['parent-uri'] = $item_id;
884                                 $datarray['uid'] = $importer['uid'];
885                                 $datarray['contact-id'] = $contact['id'];
886                                 $r = item_store($datarray);
887                                 continue;
888
889                         }
890                 }
891         }
892
893 }
894
895 function new_follower($importer,$contact,$datarray,$item) {
896         $url = notags(trim($datarray['author-link']));
897         $name = notags(trim($datarray['author-name']));
898         $photo = notags(trim($datarray['author-avatar']));
899
900         $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
901         if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
902                 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
903
904         if(is_array($contact)) {
905                 if($contact['network'] == 'stat' && $contact['rel'] == REL_FAN) {
906                         $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
907                                 intval(REL_BUD),
908                                 intval($contact['id']),
909                                 intval($importer['uid'])
910                         );
911                 }
912
913                 // send email notification to owner?
914         }
915         else {
916         
917                 // create contact record - set to readonly
918
919                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `name`, `nick`, `photo`, `network`, `rel`, 
920                         `blocked`, `readonly`, `pending` )
921                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 1, 1 ) ",
922                         intval($importer['uid']),
923                         dbesc(datetime_convert()),
924                         dbesc($url),
925                         dbesc($name),
926                         dbesc($nick),
927                         dbesc($photo),
928                         dbesc('stat'),
929                         intval(REL_VIP)
930                 );
931                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 AND `rel` = %d LIMIT 1",
932                                 intval($importer['uid']),
933                                 dbesc($url),
934                                 intval(REL_VIP)
935                 );
936                 if(count($r))
937                                 $contact_record = $r[0];
938
939                 // create notification  
940                 $hash = random_string();
941
942                 if(is_array($contact_record)) {
943                         $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
944                                 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
945                                 intval($importer['uid']),
946                                 intval($contact_record['id']),
947                                 dbesc($hash),
948                                 dbesc(datetime_convert())
949                         );
950                 }
951         }
952 }
953
954 function lose_follower($importer,$contact,$datarray,$item) {
955
956         if(($contact['rel'] == REL_BUD) || ($contact['rel'] == REL_FAN)) {
957                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
958                         intval(REL_FAN),
959                         intval($contact['id'])
960                 );
961         }
962         else {
963                 contact_remove($contact['id']);
964         }
965 }
966
967
968 function subscribe_to_hub($url,$importer,$contact) {
969
970         if(is_array($importer)) {
971                 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
972                         intval($importer['uid'])
973                 );
974         }
975         if(! count($r))
976                 return;
977
978         $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
979
980         // Use a single verify token, even if multiple hubs
981
982         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
983
984         $params= 'hub.mode=subscribe&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
985
986         if(! strlen($contact['hub-verify'])) {
987                 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
988                         dbesc($verify_token),
989                         intval($contact['id'])
990                 );
991         }
992
993         post_url($url,$params);                 
994         return;
995
996 }
997
998
999 function atom_author($tag,$name,$uri,$h,$w,$photo) {
1000         $o = '';
1001         if(! $tag)
1002                 return $o;
1003         $name = xmlify($name);
1004         $uri = xmlify($uri);
1005         $h = intval($h);
1006         $w = intval($w);
1007         $photo = xmlify($photo);
1008
1009
1010         $o .= "<$tag>\r\n";
1011         $o .= "<name>$name</name>\r\n";
1012         $o .= "<uri>$uri</uri>\r\n";
1013         $o .= '<link rel="photo"  type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1014         $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1015         $o .= "</$tag>\r\n";
1016         return $o;
1017 }
1018
1019 function atom_entry($item,$type,$author,$owner,$comment = false) {
1020
1021         if($item['deleted'])
1022                 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
1023
1024         $a = get_app();
1025
1026         $o = "\r\n\r\n<entry>\r\n";
1027
1028         if(is_array($author))
1029                 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
1030         else
1031                 $o .= atom_author('author',$item['name'],$item['url'],80,80,$item['thumb']);
1032         if(strlen($item['owner-name']))
1033                 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
1034
1035         if($item['parent'] != $item['id'])
1036                 $o .= '<thr:in-reply-to ref="' . xmlify($item['parent-uri']) . '" type="text/html" href="' .  xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
1037
1038         $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
1039         $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
1040         $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
1041         $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
1042         $o .= '<content type="' . $type . '" >' . xmlify(($type === 'html') ? bbcode($item['body']) : $item['body']) . '</content>' . "\r\n";
1043         $o .= '<link rel="alternate" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
1044         if($comment)
1045                 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
1046         if($item['location'])
1047                 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
1048         if($item['coord'])
1049                 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
1050
1051         $verb = construct_verb($item);
1052         $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
1053         $actobj = construct_activity($item);
1054         if(strlen($actobj))
1055                 $o .= $actobj;
1056
1057         $mentioned = get_mentions($item);
1058         if($mentioned)
1059                 $o .= $mentioned;
1060         
1061         $o .= '</entry>' . "\r\n";
1062         
1063         return $o;
1064 }
1065