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