]> git.mxchange.org Git - friendica.git/blob - include/items.php
d37f7708f99beacfeb1db6d8401e2bc7ea1b49c3
[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
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 && activity_match($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 && activity_match($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(activity_match($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) {
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         logger('dfrn_deliver: ' . $url);
606
607         $xml = fetch_url($url);
608
609         logger('dfrn_deliver: ' . $xml);
610
611         if(! $xml)
612                 return 3;
613
614         $res = simplexml_load_string($xml);
615
616         if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
617                 return (($res->status) ? $res->status : 3);
618
619         $postvars     = array();
620         $sent_dfrn_id = hex2bin($res->dfrn_id);
621         $challenge    = hex2bin($res->challenge);
622
623         $final_dfrn_id = '';
624
625
626
627         if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
628                 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
629                 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
630         }
631         else {
632                 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
633                 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
634         }
635
636         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
637
638         if(strpos($final_dfrn_id,':') == 1)
639                 $final_dfrn_id = substr($final_dfrn_id,2);
640
641         if($final_dfrn_id != $orig_id) {
642                 logger('dfrn_deliver: wrong dfrn_id.');
643                 // did not decode properly - cannot trust this site 
644                 return 3;
645         }
646
647         $postvars['dfrn_id']      = $idtosend;
648         $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
649
650         if(($contact['rel']) && ($contact['rel'] != REL_FAN) && (! $contact['blocked']) && (! $contact['readonly'])) {
651                 $postvars['data'] = $atom;
652         }
653         elseif($owner['page-flags'] == PAGE_COMMUNITY) {
654                 $postvars['data'] = $atom;
655         }
656         else {
657                 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
658         }
659
660         $xml = post_url($contact['notify'],$postvars);
661
662         logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true) . "\n" . "RECEIVING: " . $xml);
663
664         $res = simplexml_load_string($xml);
665
666         return $res->status;
667  
668 }
669
670
671 /*
672  *
673  * consume_feed - process atom feed and update anything/everything we might need to update
674  *
675  * $xml = the (atom) feed to consume - no RSS spoken here, it might partially work since simplepie 
676  *        handles both, but we don't claim it will work well, and are reasonably certain it won't.
677  * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
678  *             It is this person's stuff that is going to be updated.
679  * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
680  *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST 
681  *             have a contact record.
682  * $hub = should wefind ahub declation in the feed, pass it back to our calling process, who might (or 
683  *        might not) try and subscribe to it.
684  *
685  */
686
687 function consume_feed($xml,$importer,$contact, &$hub) {
688
689         require_once('simplepie/simplepie.inc');
690
691         $feed = new SimplePie();
692         $feed->set_raw_data($xml);
693         $feed->enable_order_by_date(false);
694         $feed->init();
695
696         // Check at the feed level for updated contact name and/or photo
697         $debugging = get_config('system','debugging');
698
699         $name_updated  = '';
700         $new_name = '';
701         $photo_timestamp = '';
702         $photo_url = '';
703
704
705         $hubs = $feed->get_links('hub');
706
707         if(count($hubs))
708                 $hub = implode(',', $hubs);
709
710         $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
711         if($rawtags) {
712                 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
713                 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
714                         $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
715                         $new_name = $elems['name'][0]['data'];
716                 } 
717                 if(($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
718                         $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
719                         $photo_url = $elems['link'][0]['attribs']['']['href'];
720                 }
721         }
722         if(! $photo_timestamp) {
723                 $photo_rawupdate = $feed->get_feed_tags(NAMESPACE_DFRN,'icon-updated');
724                 if($photo_rawupdate) {
725                         $photo_timestamp = datetime_convert('UTC','UTC',$photo_rawupdate[0]['data']);
726                         $photo_url = $feed->get_image_url();
727                 }
728         }
729         if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
730
731                 require_once("Photo.php");
732                 $photo_failure = false;
733
734                 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
735                         intval($contact['id']),
736                         intval($contact['uid'])
737                 );
738                 if(count($r)) {
739                         $resource_id = $r[0]['resource-id'];
740                         $img_str = fetch_url($photo_url,true);
741                         $img = new Photo($img_str);
742                         if($img->is_valid()) {
743                                 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND contact-id` = %d AND `uid` = %d",
744                                         dbesc($resource_id),
745                                         intval($contact['id']),
746                                         intval($contact['uid'])
747                                 );
748
749                                 $img->scaleImageSquare(175);
750                                 
751                                 $hash = $resource_id;
752                                 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 4);
753                                 
754                                 $img->scaleImage(80);
755                                 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 5);
756                                 if($r)
757                                         q("UPDATE `contact` SET `avatar-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
758                                                 dbesc(datetime_convert()),
759                                                 intval($contact['uid']),
760                                                 intval($contact['id'])
761                                         );
762                         }
763                 }
764         }
765
766         if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
767                 q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
768                         dbesc(notags(trim($new_name))),
769                         dbesc(datetime_convert()),
770                         intval($contact['uid']),
771                         intval($contact['id'])
772                 );
773         }
774
775         // Now process the feed
776         if($feed->get_item_quantity()) {                
777                 foreach($feed->get_items() as $item) {
778
779                         $deleted = false;
780
781                         $rawdelete = $item->get_item_tags( NAMESPACE_TOMB, 'deleted-entry');
782                         if(isset($rawdelete[0]['attribs']['']['ref'])) {
783                                 $uri = $rawthread[0]['attribs']['']['ref'];
784                                 $deleted = true;
785                                 if(isset($rawdelete[0]['attribs']['']['when'])) {
786                                         $when = $rawthread[0]['attribs']['']['when'];
787                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
788                                 }
789                                 else
790                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
791                         }
792                         if($deleted && is_array($contact)) {
793                                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `contact-id` = %d LIMIT 1",
794                                         dbesc($uri),
795                                         intval($importer['uid']),
796                                         intval($contact['id'])
797                                 );
798                                 if(count($r)) {
799                                         $item = $r[0];
800                                         if($item['uri'] == $item['parent-uri']) {
801                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
802                                                         `body` = '', `title` = ''
803                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
804                                                         dbesc($when),
805                                                         dbesc(datetime_convert()),
806                                                         dbesc($item['uri']),
807                                                         intval($importer['uid'])
808                                                 );
809                                         }
810                                         else {
811                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
812                                                         `body` = '', `title` = '' 
813                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
814                                                         dbesc($when),
815                                                         dbesc(datetime_convert()),
816                                                         dbesc($uri),
817                                                         intval($importer['uid'])
818                                                 );
819                                                 if($item['last-child']) {
820                                                         // ensure that last-child is set in case the comment that had it just got wiped.
821                                                         $q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
822                                                                 dbesc(datetime_convert()),
823                                                                 dbesc($item['parent-uri']),
824                                                                 intval($item['uid'])
825                                                         );
826                                                         // who is the last child now? 
827                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d 
828                                                                 ORDER BY `created` DESC LIMIT 1",
829                                                                         dbesc($item['parent-uri']),
830                                                                         intval($importer['uid'])
831                                                         );
832                                                         if(count($r)) {
833                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
834                                                                         intval($r[0]['id'])
835                                                                 );
836                                                         }
837                                                 }       
838                                         }
839                                 }       
840                                 continue;
841                         }
842
843
844                         $is_reply = false;              
845                         $item_id = $item->get_id();
846                         $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
847                         if(isset($rawthread[0]['attribs']['']['ref'])) {
848                                 $is_reply = true;
849                                 $parent_uri = $rawthread[0]['attribs']['']['ref'];
850                         }
851
852
853                         if(($is_reply) && is_array($contact)) {
854         
855                                 // Have we seen it? If not, import it.
856         
857                                 $item_id = $item->get_id();
858         
859                                 $r = q("SELECT `uid`, `last-child`, `edited` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
860                                         dbesc($item_id),
861                                         intval($importer['uid'])
862                                 );
863                                 // FIXME update content if 'updated' changes
864                                 if(count($r)) {
865                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
866                                         if($allow && $allow[0]['data'] != $r[0]['last-child']) {
867                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
868                                                         dbesc(datetime_convert()),
869                                                         dbesc($parent_uri),
870                                                         intval($importer['uid'])
871                                                 );
872                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
873                                                         intval($allow[0]['data']),
874                                                         dbesc(datetime_convert()),
875                                                         dbesc($item_id),
876                                                         intval($importer['uid'])
877                                                 );
878
879                                         }
880                                         continue;
881                                 }
882                                 $datarray = get_atom_elements($feed,$item);
883                                 if($contact['network'] === 'stat' && strlen($datarray['title']))
884                                         unset($datarray['title']);
885                                 $datarray['parent-uri'] = $parent_uri;
886                                 $datarray['uid'] = $importer['uid'];
887                                 $datarray['contact-id'] = $contact['id'];
888                                 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
889                                         $datarray['type'] = 'activity';
890                                         $datarray['gravity'] = GRAVITY_LIKE;
891                                 }
892
893                                 $r = item_store($datarray);
894                                 continue;
895                         }
896
897                         else {
898                                 // Head post of a conversation. Have we seen it? If not, import it.
899
900                                 $item_id = $item->get_id();
901                                 $r = q("SELECT `uid`, `last-child`, `edited` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
902                                         dbesc($item_id),
903                                         intval($importer['uid'])
904                                 );
905                                 if(count($r)) {
906                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
907                                         if($allow && $allow[0]['data'] != $r[0]['last-child']) {
908                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
909                                                         intval($allow[0]['data']),
910                                                         dbesc(datetime_convert()),
911                                                         dbesc($item_id),
912                                                         intval($importer['uid'])
913                                                 );
914                                         }
915                                         continue;
916                                 }
917                                 $datarray = get_atom_elements($feed,$item);
918
919                                 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
920                                         logger('consume-feed: New follower');
921                                         new_follower($importer,$contact,$datarray,$item);
922                                         return;
923                                 }
924                                 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW))  {
925                                         lose_follower($importer,$contact,$datarray,$item);
926                                         return;
927                                 }
928                                 if(! is_array($contact))
929                                         return;
930
931                                 if($contact['network'] === 'stat') {
932                                         if(strlen($datarray['title']))
933                                                 unset($datarray['title']);
934                                         if(($contact['rel'] == REL_VIP) || ($contact['rel'] == REL_BUD))
935                                                 $datarray['last-child'] = 1;
936                                 }
937                                 $datarray['parent-uri'] = $item_id;
938                                 $datarray['uid'] = $importer['uid'];
939                                 $datarray['contact-id'] = $contact['id'];
940                                 $r = item_store($datarray);
941                                 continue;
942
943                         }
944                 }
945         }
946
947 }
948
949 function new_follower($importer,$contact,$datarray,$item) {
950         $url = notags(trim($datarray['author-link']));
951         $name = notags(trim($datarray['author-name']));
952         $photo = notags(trim($datarray['author-avatar']));
953
954         $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
955         if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
956                 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
957
958         if(is_array($contact)) {
959                 if($contact['network'] == 'stat' && $contact['rel'] == REL_FAN) {
960                         $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
961                                 intval(REL_BUD),
962                                 intval($contact['id']),
963                                 intval($importer['uid'])
964                         );
965                 }
966
967                 // send email notification to owner?
968         }
969         else {
970         
971                 // create contact record - set to readonly
972
973                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `name`, `nick`, `photo`, `network`, `rel`, 
974                         `blocked`, `readonly`, `pending` )
975                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 1, 1 ) ",
976                         intval($importer['uid']),
977                         dbesc(datetime_convert()),
978                         dbesc($url),
979                         dbesc($name),
980                         dbesc($nick),
981                         dbesc($photo),
982                         dbesc('stat'),
983                         intval(REL_VIP)
984                 );
985                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 AND `rel` = %d LIMIT 1",
986                                 intval($importer['uid']),
987                                 dbesc($url),
988                                 intval(REL_VIP)
989                 );
990                 if(count($r))
991                                 $contact_record = $r[0];
992
993                 // create notification  
994                 $hash = random_string();
995
996                 if(is_array($contact_record)) {
997                         $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
998                                 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
999                                 intval($importer['uid']),
1000                                 intval($contact_record['id']),
1001                                 dbesc($hash),
1002                                 dbesc(datetime_convert())
1003                         );
1004                 }
1005         }
1006 }
1007
1008 function lose_follower($importer,$contact,$datarray,$item) {
1009
1010         if(($contact['rel'] == REL_BUD) || ($contact['rel'] == REL_FAN)) {
1011                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
1012                         intval(REL_FAN),
1013                         intval($contact['id'])
1014                 );
1015         }
1016         else {
1017                 contact_remove($contact['id']);
1018         }
1019 }
1020
1021
1022 function subscribe_to_hub($url,$importer,$contact) {
1023
1024         if(is_array($importer)) {
1025                 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
1026                         intval($importer['uid'])
1027                 );
1028         }
1029         if(! count($r))
1030                 return;
1031
1032         $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
1033
1034         // Use a single verify token, even if multiple hubs
1035
1036         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
1037
1038         $params= 'hub.mode=subscribe&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
1039
1040         if(! strlen($contact['hub-verify'])) {
1041                 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
1042                         dbesc($verify_token),
1043                         intval($contact['id'])
1044                 );
1045         }
1046
1047         post_url($url,$params);                 
1048         return;
1049
1050 }