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