]> git.mxchange.org Git - friendica.git/blob - include/items.php
don't use load_view_file() except in email templates and install of htconfig - to...
[friendica.git] / include / items.php
1 <?php
2
3 require_once('bbcode.php');
4 require_once('oembed.php');
5 require_once('include/salmon.php');
6
7 function get_feed_for(&$a, $dfrn_id, $owner_nick, $last_update, $direction = 0) {
8
9
10         // default permissions - anonymous user
11
12         if(! strlen($owner_nick))
13                 killme();
14
15         $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' AND `deny_cid`  = '' AND `deny_gid`  = '' ";
16
17         $r = q("SELECT `contact`.*, `user`.`uid` AS `user_uid`, `user`.`nickname`, `user`.`timezone`
18                 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
19                 WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
20                 dbesc($owner_nick)
21         );
22
23         if(! count($r))
24                 killme();
25
26         $owner = $r[0];
27         $owner_id = $owner['user_uid'];
28         $owner_nick = $owner['nickname'];
29
30         $birthday = feed_birthday($owner_id,$owner['timezone']);
31
32         if(strlen($dfrn_id)) {
33
34                 $sql_extra = '';
35                 switch($direction) {
36                         case (-1):
37                                 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
38                                 $my_id = $dfrn_id;
39                                 break;
40                         case 0:
41                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
42                                 $my_id = '1:' . $dfrn_id;
43                                 break;
44                         case 1:
45                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
46                                 $my_id = '0:' . $dfrn_id;
47                                 break;
48                         default:
49                                 return false;
50                                 break; // NOTREACHED
51                 }
52
53                 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
54                         intval($owner_id)
55                 );
56
57                 if(! count($r))
58                         killme();
59
60                 $contact = $r[0];
61                 $groups = init_groups_visitor($contact['id']);
62
63                 if(count($groups)) {
64                         for($x = 0; $x < count($groups); $x ++) 
65                                 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
66                         $gs = implode('|', $groups);
67                 }
68                 else
69                         $gs = '<<>>' ; // Impossible to match 
70
71                 $sql_extra = sprintf(" 
72                         AND ( `allow_cid` = '' OR     `allow_cid` REGEXP '<%d>' ) 
73                         AND ( `deny_cid`  = '' OR NOT `deny_cid`  REGEXP '<%d>' ) 
74                         AND ( `allow_gid` = '' OR     `allow_gid` REGEXP '%s' )
75                         AND ( `deny_gid`  = '' OR NOT `deny_gid`  REGEXP '%s') 
76                 ",
77                         intval($contact['id']),
78                         intval($contact['id']),
79                         dbesc($gs),
80                         dbesc($gs)
81                 );
82         }
83
84         if($dfrn_id === '' || $dfrn_id === '*')
85                 $sort = 'DESC';
86         else
87                 $sort = 'ASC';
88
89         if(! strlen($last_update))
90                 $last_update = 'now -30 days';
91
92         $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
93
94         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
95                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, 
96                 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
97                 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`, 
98                 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`
99                 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
100                 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`parent` != 0 
101                 AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
102                 AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
103                 $sql_extra
104                 ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
105                 intval($owner_id),
106                 dbesc($check_date),
107                 dbesc($check_date),
108                 dbesc($sort)
109         );
110
111         // Will check further below if this actually returned results.
112         // We will provide an empty feed if that is the case.
113
114         $items = $r;
115
116         $feed_template = file_get_contents('view/atom_feed.tpl');
117
118         $atom = '';
119
120         $hubxml = feed_hublinks();
121
122         $salmon = feed_salmonlinks($owner_nick);
123
124         $atom .= replace_macros($feed_template, array(
125                 '$version'      => xmlify(FRIENDIKA_VERSION),
126                 '$feed_id'      => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
127                 '$feed_title'   => xmlify($owner['name']),
128                 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
129                 '$hub'          => $hubxml,
130                 '$salmon'       => $salmon,
131                 '$name'         => xmlify($owner['name']),
132                 '$profile_page' => xmlify($owner['url']),
133                 '$photo'        => xmlify($owner['photo']),
134                 '$thumb'        => xmlify($owner['thumb']),
135                 '$picdate'      => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
136                 '$uridate'      => xmlify(datetime_convert('UTC','UTC',$owner['uri-date']    . '+00:00' , ATOM_TIME)) ,
137                 '$namdate'      => xmlify(datetime_convert('UTC','UTC',$owner['name-date']   . '+00:00' , ATOM_TIME)) , 
138                 '$birthday'     => ((strlen($birthday)) ? '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>' : '')
139         ));
140
141         call_hooks('atom_feed', $atom);
142
143         if(! count($items)) {
144
145                 call_hooks('atom_feed_end', $atom);
146
147                 $atom .= '</feed>' . "\r\n";
148                 return $atom;
149         }
150
151         foreach($items as $item) {
152
153                 // public feeds get html, our own nodes use bbcode
154
155                 if($dfrn_id === '') {
156                         $type = 'html';
157                 }
158                 else {
159                         $type = 'text';
160                 }
161
162                 $atom .= atom_entry($item,$type,null,$owner,true);
163         }
164
165         call_hooks('atom_feed_end', $atom);
166
167         $atom .= '</feed>' . "\r\n";
168
169         return $atom;
170 }
171
172
173 function construct_verb($item) {
174         if($item['verb'])
175                 return $item['verb'];
176         return ACTIVITY_POST;
177 }
178
179 function construct_activity_object($item) {
180
181         if($item['object']) {
182                 $o = '<as:object>' . "\r\n";
183                 $r = parse_xml_string($item['object']);
184                 if($r->type)
185                         $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
186                 if($r->id)
187                         $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
188                 if($r->title)
189                         $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
190                 if($r->link) {
191                         if(substr($r->link,0,1) === '<') 
192                                 $o .= $r->link;
193                         else
194                                 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
195                 }
196                 if($r->content)
197                         $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
198                 $o .= '</as:object>' . "\r\n";
199                 return $o;
200         }
201
202         return '';
203
204
205 function construct_activity_target($item) {
206
207         if($item['target']) {
208                 $o = '<as:target>' . "\r\n";
209                 $r = parse_xml_string($item['target']);
210                 if($r->type)
211                         $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
212                 if($r->id)
213                         $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
214                 if($r->title)
215                         $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
216                 if($r->link) {
217                         if(substr($r->link,0,1) === '<') 
218                                 $o .= $r->link;
219                         else
220                                 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
221                 }
222                 if($r->content)
223                         $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
224                 $o .= '</as:target>' . "\r\n";
225                 return $o;
226         }
227
228         return '';
229
230
231
232
233
234 function get_atom_elements($feed,$item) {
235
236         require_once('library/HTMLPurifier.auto.php');
237         require_once('include/html2bbcode.php');
238
239         $best_photo = array();
240
241         $res = array();
242
243         $author = $item->get_author();
244         if($author) { 
245                 $res['author-name'] = unxmlify($author->get_name());
246                 $res['author-link'] = unxmlify($author->get_link());
247         }
248         else {
249                 $res['author-name'] = unxmlify($feed->get_title());
250                 $res['author-link'] = unxmlify($feed->get_permalink());
251         }
252         $res['uri'] = unxmlify($item->get_id());
253         $res['title'] = unxmlify($item->get_title());
254         $res['body'] = unxmlify($item->get_content());
255         $res['plink'] = unxmlify($item->get_link(0));
256
257         // look for a photo. We should check media size and find the best one,
258         // but for now let's just find any author photo
259
260         $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
261
262         if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
263                 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
264                 foreach($base as $link) {
265                         if(! $res['author-avatar']) {
266                                 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
267                                         $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
268                         }
269                 }
270         }                       
271
272         $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
273
274         if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
275                 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
276                 if($base && count($base)) {
277                         foreach($base as $link) {
278                                 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
279                                         $res['author-link'] = unxmlify($link['attribs']['']['href']);
280                                 if(! $res['author-avatar']) {
281                                         if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
282                                                 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
283                                 }
284                         }
285                 }
286         }
287
288         // No photo/profile-link on the item - look at the feed level
289
290         if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
291                 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
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($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
296                                         $res['author-link'] = unxmlify($link['attribs']['']['href']);
297                                 if(! $res['author-avatar']) {
298                                         if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
299                                                 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
300                                 }
301                         }
302                 }                       
303
304                 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
305
306                 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
307                         $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
308
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(! (x($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
322
323         /**
324          * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
325          */
326
327         $have_real_body = false;
328
329         $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
330         if($rawenv) {
331                 $have_real_body = true;
332                 $res['body'] = $rawenv[0]['data'];
333                 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
334                 // make sure nobody is trying to sneak some html tags by us
335                 $res['body'] = notags(base64url_decode($res['body']));
336         }
337
338         $maxlen = get_max_import_size();
339         if($maxlen && (strlen($res['body']) > $maxlen))
340                 $res['body'] = substr($res['body'],0, $maxlen);
341
342         // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust 
343         // the content type. Our own network only emits text normally, though it might have been converted to 
344         // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
345         // have to assume it is all html and needs to be purified.
346
347         // It doesn't matter all that much security wise - because before this content is used anywhere, we are 
348         // going to escape any tags we find regardless, but this lets us import a limited subset of html from 
349         // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining 
350         // html.
351
352         if((strpos($res['body'],'<') !== false) || (strpos($res['body'],'>') !== false)) {
353
354                 $res['body'] = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
355                         '[youtube]$1[/youtube]', $res['body']);
356
357                 $res['body'] = oembed_html2bbcode($res['body']);
358
359                 $config = HTMLPurifier_Config::createDefault();
360                 $config->set('Cache.DefinitionImpl', null);
361
362                 // we shouldn't need a whitelist, because the bbcode converter
363                 // will strip out any unsupported tags.
364                 // $config->set('HTML.Allowed', 'p,b,a[href],i'); 
365
366                 $purifier = new HTMLPurifier($config);
367                 $res['body'] = $purifier->purify($res['body']);
368
369                 $res['body'] = html2bbcode($res['body']);
370         }
371
372         $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
373         if($allow && $allow[0]['data'] == 1)
374                 $res['last-child'] = 1;
375         else
376                 $res['last-child'] = 0;
377
378         $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
379         if($private && $private[0]['data'] == 1)
380                 $res['private'] = 1;
381         else
382                 $res['private'] = 0;
383
384
385         $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
386         if($rawlocation)
387                 $res['location'] = unxmlify($rawlocation[0]['data']);
388
389
390         $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
391         if($rawcreated)
392                 $res['created'] = unxmlify($rawcreated[0]['data']);
393
394
395         $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
396         if($rawedited)
397                 $res['edited'] = unxmlify($rawedited[0]['data']);
398
399         if((x($res,'edited')) && (! (x($res,'created'))))
400                 $res['created'] = $res['edited']; 
401
402         if(! $res['created'])
403                 $res['created'] = $item->get_date('c');
404
405         if(! $res['edited'])
406                 $res['edited'] = $item->get_date('c');
407
408
409         // Disallow time travelling posts
410
411         $d1 = strtotime($res['created']);
412         $d2 = strtotime($res['edited']);
413         $d3 = strtotime('now');
414
415         if($d1 > $d3)
416                 $res['created'] = datetime_convert();
417         if($d2 > $d3)
418                 $res['edited'] = datetime_convert();
419
420         $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
421         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
422                 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
423         elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
424                 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
425         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
426                 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
427         elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
428                 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
429
430         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
431                 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
432
433                 foreach($base as $link) {
434                         if(! $res['owner-avatar']) {
435                                 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')                 
436                                         $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
437                         }
438                 }
439         }
440
441         $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
442         if($rawgeo)
443                 $res['coord'] = unxmlify($rawgeo[0]['data']);
444
445
446         $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
447
448         // select between supported verbs
449
450         if($rawverb) {
451                 $res['verb'] = unxmlify($rawverb[0]['data']);
452         }
453
454         // translate OStatus unfollow to activity streams if it happened to get selected
455                 
456         if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
457                 $res['verb'] = ACTIVITY_UNFOLLOW;
458
459
460         $cats = $item->get_categories();
461         if($cats) {
462                 $tag_arr = array();
463                 foreach($cats as $cat) {
464                         $term = $cat->get_term();
465                         if(! $term)
466                                 $term = $cat->get_label();
467                         $scheme = $cat->get_scheme();
468                         if($scheme && $term && stristr($scheme,'X-DFRN:'))
469                                 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
470                         elseif($term)
471                                 $tag_arr[] = notags(trim($term));
472                 }
473                 $res['tag'] =  implode(',', $tag_arr);
474         }
475
476         $attach = $item->get_enclosures();
477         if($attach) {
478                 $att_arr = array();
479                 foreach($attach as $att) {
480                         $len   = intval($att->get_length());
481                         $link  = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
482                         $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
483                         $type  = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
484                         if(strpos($type,';'))
485                                 $type = substr($type,0,strpos($type,';'));
486                         if((! $link) || (strpos($link,'http') !== 0))
487                                 continue;
488
489                         if(! $title)
490                                 $title = ' ';
491                         if(! $type)
492                                 $type = 'application/octet-stream';
493
494                         $att_arr[] = '[attach]href="' . $link . '" size="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]'; 
495                 }
496                 $res['attach'] = implode(',', $att_arr);
497         }
498
499         $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
500
501         if($rawobj) {
502                 $res['object'] = '<object>' . "\n";
503                 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
504                         $res['object-type'] = $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'];
505                         $res['object'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
506                 }       
507                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
508                         $res['object'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
509                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
510                         $res['object'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
511                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
512                         $res['object'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
513                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
514                         $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
515                         if(! $body)
516                                 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
517                         // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
518                         $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
519                         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
520
521                                 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
522                                         '[youtube]$1[/youtube]', $body);
523
524                                 $config = HTMLPurifier_Config::createDefault();
525                                 $config->set('Cache.DefinitionImpl', null);
526
527                                 $purifier = new HTMLPurifier($config);
528                                 $body = $purifier->purify($body);
529                                 $body = html2bbcode($body);
530                         }
531
532                         $res['object'] .= '<content>' . $body . '</content>' . "\n";
533                 }
534
535                 $res['object'] .= '</object>' . "\n";
536         }
537
538         $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
539
540         if($rawobj) {
541                 $res['target'] = '<target>' . "\n";
542                 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
543                         $res['target'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
544                 }       
545                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
546                         $res['target'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
547
548                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
549                         $res['target'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
550                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
551                         $res['target'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
552                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
553                         $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
554                         if(! $body)
555                                 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
556                         // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
557                         $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
558                         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
559
560                                 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
561                                         '[youtube]$1[/youtube]', $body);
562
563                                 $config = HTMLPurifier_Config::createDefault();
564                                 $config->set('Cache.DefinitionImpl', null);
565
566                                 $purifier = new HTMLPurifier($config);
567                                 $body = $purifier->purify($body);
568                                 $body = html2bbcode($body);
569                         }
570
571                         $res['target'] .= '<content>' . $body . '</content>' . "\n";
572                 }
573
574                 $res['target'] .= '</target>' . "\n";
575         }
576
577         $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
578
579         call_hooks('parse_atom', $arr);
580
581         return $res;
582 }
583
584 function encode_rel_links($links) {
585         $o = '';
586         if(! ((is_array($links)) && (count($links))))
587                 return $o;
588         foreach($links as $link) {
589                 $o .= '<link ';
590                 if($link['attribs']['']['rel'])
591                         $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
592                 if($link['attribs']['']['type'])
593                         $o .= 'type="' . $link['attribs']['']['type'] . '" ';
594                 if($link['attribs']['']['href'])
595                         $o .= 'href="' . $link['attribs']['']['href'] . '" ';
596                 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
597                         $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
598                 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
599                         $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
600                 $o .= ' />' . "\n" ;
601         }
602         return xmlify($o);
603 }
604
605 function item_store($arr,$force_parent = false) {
606
607         if($arr['gravity'])
608                 $arr['gravity'] = intval($arr['gravity']);
609         elseif($arr['parent-uri'] == $arr['uri'])
610                 $arr['gravity'] = 0;
611         elseif(activity_match($arr['verb'],ACTIVITY_POST))
612                 $arr['gravity'] = 6;
613         else      
614                 $arr['gravity'] = 6;   // extensible catchall
615
616         if(! x($arr,'type'))
617                 $arr['type']      = 'remote';
618
619         // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
620
621         if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false)) 
622                 $arr['body'] = strip_tags($arr['body']);
623
624
625         $arr['wall']          = ((x($arr,'wall'))          ? intval($arr['wall'])                : 0);
626         $arr['uri']           = ((x($arr,'uri'))           ? notags(trim($arr['uri']))           : random_string());
627         $arr['author-name']   = ((x($arr,'author-name'))   ? notags(trim($arr['author-name']))   : '');
628         $arr['author-link']   = ((x($arr,'author-link'))   ? notags(trim($arr['author-link']))   : '');
629         $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
630         $arr['owner-name']    = ((x($arr,'owner-name'))    ? notags(trim($arr['owner-name']))    : '');
631         $arr['owner-link']    = ((x($arr,'owner-link'))    ? notags(trim($arr['owner-link']))    : '');
632         $arr['owner-avatar']  = ((x($arr,'owner-avatar'))  ? notags(trim($arr['owner-avatar']))  : '');
633         $arr['created']       = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
634         $arr['edited']        = ((x($arr,'edited')  !== false) ? datetime_convert('UTC','UTC',$arr['edited'])  : datetime_convert());
635         $arr['changed']       = datetime_convert();
636         $arr['title']         = ((x($arr,'title'))         ? notags(trim($arr['title']))         : '');
637         $arr['location']      = ((x($arr,'location'))      ? notags(trim($arr['location']))      : '');
638         $arr['coord']         = ((x($arr,'coord'))         ? notags(trim($arr['coord']))         : '');
639         $arr['last-child']    = ((x($arr,'last-child'))    ? intval($arr['last-child'])          : 0 );
640         $arr['visible']       = ((x($arr,'visible') !== false) ? intval($arr['visible'])         : 1 );
641         $arr['deleted']       = 0;
642         $arr['parent-uri']    = ((x($arr,'parent-uri'))    ? notags(trim($arr['parent-uri']))    : '');
643         $arr['verb']          = ((x($arr,'verb'))          ? notags(trim($arr['verb']))          : '');
644         $arr['object-type']   = ((x($arr,'object-type'))   ? notags(trim($arr['object-type']))   : '');
645         $arr['object']        = ((x($arr,'object'))        ? trim($arr['object'])                : '');
646         $arr['target-type']   = ((x($arr,'target-type'))   ? notags(trim($arr['target-type']))   : '');
647         $arr['target']        = ((x($arr,'target'))        ? trim($arr['target'])                : '');
648         $arr['plink']         = ((x($arr,'plink'))         ? notags(trim($arr['plink']))         : '');
649         $arr['allow_cid']     = ((x($arr,'allow_cid'))     ? trim($arr['allow_cid'])             : '');
650         $arr['allow_gid']     = ((x($arr,'allow_gid'))     ? trim($arr['allow_gid'])             : '');
651         $arr['deny_cid']      = ((x($arr,'deny_cid'))      ? trim($arr['deny_cid'])              : '');
652         $arr['deny_gid']      = ((x($arr,'deny_gid'))      ? trim($arr['deny_gid'])              : '');
653         $arr['private']       = ((x($arr,'private'))       ? intval($arr['private'])             : 0 );
654         $arr['body']          = ((x($arr,'body'))          ? trim($arr['body'])                  : '');
655         $arr['tag']           = ((x($arr,'tag'))           ? notags(trim($arr['tag']))           : '');
656         $arr['attach']        = ((x($arr,'attach'))        ? notags(trim($arr['attach']))        : '');
657
658         if($arr['parent-uri'] === $arr['uri']) {
659                 $parent_id = 0;
660                 $allow_cid = $arr['allow_cid'];
661                 $allow_gid = $arr['allow_gid'];
662                 $deny_cid  = $arr['deny_cid'];
663                 $deny_gid  = $arr['deny_gid'];
664         }
665         else { 
666
667                 // find the parent and snarf the item id and ACL's
668                 // and anything else we need to inherit
669
670                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
671                         dbesc($arr['parent-uri']),
672                         intval($arr['uid'])
673                 );
674
675                 if(count($r)) {
676
677                         // is the new message multi-level threaded?
678                         // even though we don't support it now, preserve the info
679                         // and re-attach to the conversation parent.
680
681                         if($r[0]['uri'] != $r[0]['parent-uri']) {
682                                 $arr['thr-parent'] = $arr['parent-uri'];
683                                 $arr['parent-uri'] = $r[0]['parent-uri'];
684                         }
685
686                         $parent_id      = $r[0]['id'];
687                         $parent_deleted = $r[0]['deleted'];
688                         $allow_cid      = $r[0]['allow_cid'];
689                         $allow_gid      = $r[0]['allow_gid'];
690                         $deny_cid       = $r[0]['deny_cid'];
691                         $deny_gid       = $r[0]['deny_gid'];
692                         $arr['wall']    = $r[0]['wall'];
693                 }
694                 else {
695
696                         // Allow one to see reply tweets from status.net even when
697                         // we don't have or can't see the original post.
698
699                         if($force_parent) {
700                                 logger('item_store: $force_parent=true, reply converted to top-level post.');
701                                 $parent_id = 0;
702                                 $arr['thr-parent'] = $arr['parent-uri'];
703                                 $arr['parent-uri'] = $arr['uri'];
704                                 $arr['gravity'] = 0;
705                         }
706                         else {
707                                 logger('item_store: item parent was not found - ignoring item');
708                                 return 0;
709                         }
710                 }
711         }
712
713         call_hooks('post_remote',$arr);
714
715         dbesc_array($arr);
716
717         logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
718
719         $r = dbq("INSERT INTO `item` (`" 
720                         . implode("`, `", array_keys($arr)) 
721                         . "`) VALUES ('" 
722                         . implode("', '", array_values($arr)) 
723                         . "')" );
724
725         // find the item we just created
726
727         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
728                 $arr['uri'],           // already dbesc'd
729                 intval($arr['uid'])
730         );
731         if(count($r)) {
732                 $current_post = $r[0]['id'];
733                 logger('item_store: created item ' . $current_post);
734         }
735         else {
736                 logger('item_store: could not locate created item');
737                 return 0;
738         }
739
740         if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))      
741                 $parent_id = $current_post;
742
743         if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
744                 $private = 1;
745         else
746                 $private = $arr['private']; 
747
748         // Set parent id - and also make sure to inherit the parent's ACL's.
749
750         $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
751                 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
752                 intval($parent_id),
753                 dbesc($allow_cid),
754                 dbesc($allow_gid),
755                 dbesc($deny_cid),
756                 dbesc($deny_gid),
757                 intval($private),
758                 intval($parent_deleted),
759                 intval($current_post)
760         );
761
762         /**
763          * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
764          */
765
766         if($arr['last-child']) {
767                 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
768                         dbesc($arr['uri']),
769                         intval($arr['uid']),
770                         intval($current_post)
771                 );
772         }
773
774         return $current_post;
775 }
776
777 function get_item_contact($item,$contacts) {
778         if(! count($contacts) || (! is_array($item)))
779                 return false;
780         foreach($contacts as $contact) {
781                 if($contact['id'] == $item['contact-id']) {
782                         return $contact;
783                         break; // NOTREACHED
784                 }
785         }
786         return false;
787 }
788
789
790 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
791
792         $a = get_app();
793
794         if((! strlen($contact['issued-id'])) && (! $contact['duplex']) && (! ($owner['page-flags'] == PAGE_COMMUNITY)))
795                 return 3;
796
797         $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
798
799         if($contact['duplex'] && $contact['dfrn-id'])
800                 $idtosend = '0:' . $orig_id;
801         if($contact['duplex'] && $contact['issued-id'])
802                 $idtosend = '1:' . $orig_id;            
803
804         $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
805
806         $rino_enable = get_config('system','rino_encrypt');
807
808         if(! $rino_enable)
809                 $rino = 0;
810
811         $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
812
813         logger('dfrn_deliver: ' . $url);
814
815         $xml = fetch_url($url);
816
817         $curl_stat = $a->get_curl_code();
818         if(! $curl_stat)
819                 return(-1); // timed out
820
821         logger('dfrn_deliver: ' . $xml);
822
823         if(! $xml)
824                 return 3;
825
826         if(strpos($xml,'<?xml') === false) {
827                 logger('dfrn_deliver: no valid XML returned');
828                 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
829                 return 3;
830         }
831
832         $res = parse_xml_string($xml);
833
834         if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
835                 return (($res->status) ? $res->status : 3);
836
837         $postvars     = array();
838         $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
839         $challenge    = hex2bin((string) $res->challenge);
840         $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
841         $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
842
843         $final_dfrn_id = '';
844
845
846         if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
847                 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
848                 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
849         }
850         else {
851                 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
852                 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
853         }
854
855         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
856
857         if(strpos($final_dfrn_id,':') == 1)
858                 $final_dfrn_id = substr($final_dfrn_id,2);
859
860         if($final_dfrn_id != $orig_id) {
861                 logger('dfrn_deliver: wrong dfrn_id.');
862                 // did not decode properly - cannot trust this site 
863                 return 3;
864         }
865
866         $postvars['dfrn_id']      = $idtosend;
867         $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
868         if($dissolve)
869                 $postvars['dissolve'] = '1';
870
871
872         if((($contact['rel']) && ($contact['rel'] != REL_FAN) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
873                 $postvars['data'] = $atom;
874                 $postvars['perm'] = 'rw';
875         }
876         else {
877                 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
878                 $postvars['perm'] = 'r';
879         }
880
881         if($rino && $rino_allowed && (! $dissolve)) {
882                 $key = substr(random_string(),0,16);
883                 $data = bin2hex(aes_encrypt($postvars['data'],$key));
884                 $postvars['data'] = $data;
885                 logger('rino: sent key = ' . $key);     
886
887
888                 if($dfrn_version >= 2.1) {      
889                         if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
890                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
891                         }
892                         else {
893                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
894                         }
895                 }
896                 else {
897                         if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
898                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
899                         }
900                         else {
901                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
902                         }
903                 }
904
905                 logger('md5 rawkey ' . md5($postvars['key']));
906
907                 $postvars['key'] = bin2hex($postvars['key']);
908         }
909
910         logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
911
912         $xml = post_url($contact['notify'],$postvars);
913
914         logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
915
916         $curl_stat = $a->get_curl_code();
917         if((! $curl_stat) || (! strlen($xml)))
918                 return(-1); // timed out
919
920         if(strpos($xml,'<?xml') === false) {
921                 logger('dfrn_deliver: phase 2: no valid XML returned');
922                 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
923                 return 3;
924         }
925
926         $res = parse_xml_string($xml);
927
928         return $res->status; 
929 }
930
931
932 /**
933  *
934  * consume_feed - process atom feed and update anything/everything we might need to update
935  *
936  * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
937  *
938  * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
939  *             It is this person's stuff that is going to be updated.
940  * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
941  *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST 
942  *             have a contact record.
943  * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or 
944  *        might not) try and subscribe to it.
945  *
946  */
947
948 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $secure_feed = false) {
949
950         require_once('simplepie/simplepie.inc');
951
952         $feed = new SimplePie();
953         $feed->set_raw_data($xml);
954         if($datedir)
955                 $feed->enable_order_by_date(true);
956         else
957                 $feed->enable_order_by_date(false);
958         $feed->init();
959
960         if($feed->error())
961                 logger('consume_feed: Error parsing XML: ' . $feed->error());
962
963         $permalink = $feed->get_permalink();
964
965         // Check at the feed level for updated contact name and/or photo
966
967         $name_updated  = '';
968         $new_name = '';
969         $photo_timestamp = '';
970         $photo_url = '';
971         $birthday = '';
972
973         $hubs = $feed->get_links('hub');
974
975         if(count($hubs))
976                 $hub = implode(',', $hubs);
977
978         $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
979         if($rawtags) {
980                 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
981                 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
982                         $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
983                         $new_name = $elems['name'][0]['data'];
984                 } 
985                 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
986                         $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
987                         $photo_url = $elems['link'][0]['attribs']['']['href'];
988                 }
989
990                 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
991                         $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
992                 }
993         }
994
995         if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
996                 logger('consume_feed: Updating photo for ' . $contact['name']);
997                 require_once("Photo.php");
998                 $photo_failure = false;
999                 $have_photo = false;
1000
1001                 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1002                         intval($contact['id']),
1003                         intval($contact['uid'])
1004                 );
1005                 if(count($r)) {
1006                         $resource_id = $r[0]['resource-id'];
1007                         $have_photo = true;
1008                 }
1009                 else {
1010                         $resource_id = photo_new_resource();
1011                 }
1012                         
1013                 $img_str = fetch_url($photo_url,true);
1014                 $img = new Photo($img_str);
1015                 if($img->is_valid()) {
1016                         if($have_photo) {
1017                                 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1018                                         dbesc($resource_id),
1019                                         intval($contact['id']),
1020                                         intval($contact['uid'])
1021                                 );
1022                         }
1023                                 
1024                         $img->scaleImageSquare(175);
1025                                 
1026                         $hash = $resource_id;
1027                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 4);
1028                                 
1029                         $img->scaleImage(80);
1030                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 5);
1031
1032                         $img->scaleImage(48);
1033                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 6);
1034
1035                         $a = get_app();
1036
1037                         q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'  
1038                                 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1039                                 dbesc(datetime_convert()),
1040                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
1041                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
1042                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
1043                                 intval($contact['uid']),
1044                                 intval($contact['id'])
1045                         );
1046                 }
1047         }
1048
1049         if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1050                 q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1051                         dbesc(notags(trim($new_name))),
1052                         dbesc(datetime_convert()),
1053                         intval($contact['uid']),
1054                         intval($contact['id'])
1055                 );
1056         }
1057
1058         if(strlen($birthday)) {
1059                 if(substr($birthday,0,4) != $contact['bdyear']) {
1060                         logger('consume_feed: updating birthday: ' . $birthday);
1061
1062                         /**
1063                          *
1064                          * Add new birthday event for this person
1065                          *
1066                          * $bdtext is just a readable placeholder in case the event is shared
1067                          * with others. We will replace it during presentation to our $importer
1068                          * to contain a sparkle link and perhaps a photo. 
1069                          *
1070                          */
1071                          
1072                         $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1073
1074
1075                         $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1076                                 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1077                                 intval($contact['uid']),
1078                                 intval($contact['id']),
1079                                 dbesc(datetime_convert()),
1080                                 dbesc(datetime_convert()),
1081                                 dbesc(datetime_convert('UTC','UTC', $birthday)),
1082                                 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1083                                 dbesc($bdtext),
1084                                 dbesc('birthday')
1085                         );
1086                         
1087
1088                         // update bdyear
1089
1090                         q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1091                                 dbesc(substr($birthday,0,4)),
1092                                 intval($contact['uid']),
1093                                 intval($contact['id'])
1094                         );
1095
1096                         // This function is called twice without reloading the contact
1097                         // Make sure we only create one event. This is why &$contact 
1098                         // is a reference var in this function
1099
1100                         $contact['bdyear'] = substr($birthday,0,4);
1101                 }
1102
1103         }
1104
1105
1106         // process any deleted entries
1107
1108         $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1109         if(is_array($del_entries) && count($del_entries)) {
1110                 foreach($del_entries as $dentry) {
1111                         $deleted = false;
1112                         if(isset($dentry['attribs']['']['ref'])) {
1113                                 $uri = $dentry['attribs']['']['ref'];
1114                                 $deleted = true;
1115                                 if(isset($dentry['attribs']['']['when'])) {
1116                                         $when = $dentry['attribs']['']['when'];
1117                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1118                                 }
1119                                 else
1120                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1121                         }
1122                         if($deleted && is_array($contact)) {
1123                                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `contact-id` = %d LIMIT 1",
1124                                         dbesc($uri),
1125                                         intval($importer['uid']),
1126                                         intval($contact['id'])
1127                                 );
1128                                 if(count($r)) {
1129                                         $item = $r[0];
1130
1131                                         if(! $item['deleted'])
1132                                                 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1133
1134                                         if($item['uri'] == $item['parent-uri']) {
1135                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1136                                                         `body` = '', `title` = ''
1137                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
1138                                                         dbesc($when),
1139                                                         dbesc(datetime_convert()),
1140                                                         dbesc($item['uri']),
1141                                                         intval($importer['uid'])
1142                                                 );
1143                                         }
1144                                         else {
1145                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1146                                                         `body` = '', `title` = '' 
1147                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1148                                                         dbesc($when),
1149                                                         dbesc(datetime_convert()),
1150                                                         dbesc($uri),
1151                                                         intval($importer['uid'])
1152                                                 );
1153                                                 if($item['last-child']) {
1154                                                         // ensure that last-child is set in case the comment that had it just got wiped.
1155                                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1156                                                                 dbesc(datetime_convert()),
1157                                                                 dbesc($item['parent-uri']),
1158                                                                 intval($item['uid'])
1159                                                         );
1160                                                         // who is the last child now? 
1161                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d 
1162                                                                 ORDER BY `created` DESC LIMIT 1",
1163                                                                         dbesc($item['parent-uri']),
1164                                                                         intval($importer['uid'])
1165                                                         );
1166                                                         if(count($r)) {
1167                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1168                                                                         intval($r[0]['id'])
1169                                                                 );
1170                                                         }
1171                                                 }       
1172                                         }
1173                                 }       
1174                         }
1175                 }
1176         }
1177
1178         // Now process the feed
1179
1180         if($feed->get_item_quantity()) {                
1181
1182                 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1183
1184         // in inverse date order
1185                 if ($datedir)
1186                         $items = array_reverse($feed->get_items());
1187                 else
1188                         $items = $feed->get_items();
1189
1190
1191                 foreach($items as $item) {
1192
1193                         $is_reply = false;              
1194                         $item_id = $item->get_id();
1195                         $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1196                         if(isset($rawthread[0]['attribs']['']['ref'])) {
1197                                 $is_reply = true;
1198                                 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1199                         }
1200
1201                         if(($is_reply) && is_array($contact)) {
1202
1203                                 // Have we seen it? If not, import it.
1204         
1205                                 $item_id  = $item->get_id();
1206                                 $datarray = get_atom_elements($feed,$item);
1207
1208                                 if(! x($datarray,'author-name'))
1209                                         $datarray['author-name'] = $contact['name'];
1210                                 if(! x($datarray,'author-link'))
1211                                         $datarray['author-link'] = $contact['url'];
1212                                 if(! x($datarray,'author-avatar'))
1213                                         $datarray['author-avatar'] = $contact['thumb'];
1214
1215                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1216                                         dbesc($item_id),
1217                                         intval($importer['uid'])
1218                                 );
1219
1220                                 // Update content if 'updated' changes
1221
1222                                 if(count($r)) {
1223                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1224                                                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1225                                                         dbesc($datarray['body']),
1226                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1227                                                         dbesc($item_id),
1228                                                         intval($importer['uid'])
1229                                                 );
1230                                         }
1231
1232                                         // update last-child if it changes
1233
1234                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1235                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1236                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1237                                                         dbesc(datetime_convert()),
1238                                                         dbesc($parent_uri),
1239                                                         intval($importer['uid'])
1240                                                 );
1241                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1242                                                         intval($allow[0]['data']),
1243                                                         dbesc(datetime_convert()),
1244                                                         dbesc($item_id),
1245                                                         intval($importer['uid'])
1246                                                 );
1247                                         }
1248                                         continue;
1249                                 }
1250
1251                                 $force_parent = false;
1252                                 if($contact['network'] === 'stat') {
1253                                         $force_parent = true;
1254                                         if(strlen($datarray['title']))
1255                                                 unset($datarray['title']);
1256                                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1257                                                 dbesc(datetime_convert()),
1258                                                 dbesc($parent_uri),
1259                                                 intval($importer['uid'])
1260                                         );
1261                                         $datarray['last-child'] = 1;
1262                                 }
1263
1264                                 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1265                                         // one way feed - no remote comment ability
1266                                         $datarray['last-child'] = 0;
1267                                 }
1268                                 $datarray['parent-uri'] = $parent_uri;
1269                                 $datarray['uid'] = $importer['uid'];
1270                                 $datarray['contact-id'] = $contact['id'];
1271                                 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1272                                         $datarray['type'] = 'activity';
1273                                         $datarray['gravity'] = GRAVITY_LIKE;
1274                                 }
1275
1276                                 $r = item_store($datarray,$force_parent);
1277                                 continue;
1278                         }
1279
1280                         else {
1281
1282                                 // Head post of a conversation. Have we seen it? If not, import it.
1283
1284                                 $item_id  = $item->get_id();
1285
1286                                 $datarray = get_atom_elements($feed,$item);
1287
1288                                 if(is_array($contact)) {
1289                                         if(! x($datarray,'author-name'))
1290                                                 $datarray['author-name'] = $contact['name'];
1291                                         if(! x($datarray,'author-link'))
1292                                                 $datarray['author-link'] = $contact['url'];
1293                                         if(! x($datarray,'author-avatar'))
1294                                                 $datarray['author-avatar'] = $contact['thumb'];
1295                                 }
1296
1297                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1298                                         dbesc($item_id),
1299                                         intval($importer['uid'])
1300                                 );
1301
1302                                 // Update content if 'updated' changes
1303
1304                                 if(count($r)) {
1305                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1306                                                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1307                                                         dbesc($datarray['body']),
1308                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1309                                                         dbesc($item_id),
1310                                                         intval($importer['uid'])
1311                                                 );
1312                                         }
1313
1314                                         // update last-child if it changes
1315
1316                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1317                                         if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1318                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1319                                                         intval($allow[0]['data']),
1320                                                         dbesc(datetime_convert()),
1321                                                         dbesc($item_id),
1322                                                         intval($importer['uid'])
1323                                                 );
1324                                         }
1325                                         continue;
1326                                 }
1327
1328                                 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1329                                         logger('consume-feed: New follower');
1330                                         new_follower($importer,$contact,$datarray,$item);
1331                                         return;
1332                                 }
1333                                 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW))  {
1334                                         lose_follower($importer,$contact,$datarray,$item);
1335                                         return;
1336                                 }
1337                                 if(! is_array($contact))
1338                                         return;
1339
1340                                 if($contact['network'] === 'stat' || stristr($permalink,'twitter.com')) {
1341                                         if(strlen($datarray['title']))
1342                                                 unset($datarray['title']);
1343                                         $datarray['last-child'] = 1;
1344                                 }
1345
1346                                 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1347                                         // one way feed - no remote comment ability
1348                                         $datarray['last-child'] = 0;
1349                                 }
1350
1351                                 $datarray['parent-uri'] = $item_id;
1352                                 $datarray['uid'] = $importer['uid'];
1353                                 $datarray['contact-id'] = $contact['id'];
1354                                 $r = item_store($datarray);
1355                                 continue;
1356
1357                         }
1358                 }
1359         }
1360 }
1361
1362 function new_follower($importer,$contact,$datarray,$item) {
1363         $url = notags(trim($datarray['author-link']));
1364         $name = notags(trim($datarray['author-name']));
1365         $photo = notags(trim($datarray['author-avatar']));
1366
1367         $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1368         if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
1369                 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1370
1371         if(is_array($contact)) {
1372                 if($contact['network'] == 'stat' && $contact['rel'] == REL_FAN) {
1373                         $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
1374                                 intval(REL_BUD),
1375                                 intval($contact['id']),
1376                                 intval($importer['uid'])
1377                         );
1378                 }
1379
1380                 // send email notification to owner?
1381         }
1382         else {
1383         
1384                 // create contact record - set to readonly
1385
1386                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `name`, `nick`, `photo`, `network`, `rel`, 
1387                         `blocked`, `readonly`, `pending`, `writable` )
1388                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 1, 1, 1 ) ",
1389                         intval($importer['uid']),
1390                         dbesc(datetime_convert()),
1391                         dbesc($url),
1392                         dbesc($name),
1393                         dbesc($nick),
1394                         dbesc($photo),
1395                         dbesc('stat'),
1396                         intval(REL_VIP)
1397                 );
1398                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 AND `rel` = %d LIMIT 1",
1399                                 intval($importer['uid']),
1400                                 dbesc($url),
1401                                 intval(REL_VIP)
1402                 );
1403                 if(count($r))
1404                                 $contact_record = $r[0];
1405
1406                 // create notification  
1407                 $hash = random_string();
1408
1409                 if(is_array($contact_record)) {
1410                         $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
1411                                 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
1412                                 intval($importer['uid']),
1413                                 intval($contact_record['id']),
1414                                 dbesc($hash),
1415                                 dbesc(datetime_convert())
1416                         );
1417                 }
1418                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1419                         intval($importer['uid'])
1420                 );
1421                 $a = get_app();
1422                 if(count($r)) {
1423                         if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
1424                                 $email_tpl = load_view_file('view/follow_notify_eml.tpl');
1425                                 $email = replace_macros($email_tpl, array(
1426                                         '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
1427                                         '$url' => $url,
1428                                         '$myname' => $r[0]['username'],
1429                                         '$siteurl' => $a->get_baseurl(),
1430                                         '$sitename' => $a->config['sitename']
1431                                 ));
1432                                 $res = mail($r[0]['email'], 
1433                                         t("You have a new follower at ") . $a->config['sitename'],
1434                                         $email,
1435                                         'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
1436                                         . 'Content-type: text/plain; charset=UTF-8' . "\n"
1437                                         . 'Content-transfer-encoding: 8bit' );
1438                         
1439                         }
1440                 }
1441         }
1442 }
1443
1444 function lose_follower($importer,$contact,$datarray,$item) {
1445
1446         if(($contact['rel'] == REL_BUD) || ($contact['rel'] == REL_FAN)) {
1447                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
1448                         intval(REL_FAN),
1449                         intval($contact['id'])
1450                 );
1451         }
1452         else {
1453                 contact_remove($contact['id']);
1454         }
1455 }
1456
1457
1458 function subscribe_to_hub($url,$importer,$contact) {
1459
1460         if(is_array($importer)) {
1461                 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
1462                         intval($importer['uid'])
1463                 );
1464         }
1465         if(! count($r))
1466                 return;
1467
1468         $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
1469
1470         // Use a single verify token, even if multiple hubs
1471
1472         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
1473
1474         $params= 'hub.mode=subscribe&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
1475
1476         logger('subscribe_to_hub: subscribing ' . $contact['name'] . ' to hub ' . $url . ' with verifier ' . $verify_token);
1477
1478         if(! strlen($contact['hub-verify'])) {
1479                 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
1480                         dbesc($verify_token),
1481                         intval($contact['id'])
1482                 );
1483         }
1484
1485         post_url($url,$params);                 
1486         return;
1487
1488 }
1489
1490
1491 function atom_author($tag,$name,$uri,$h,$w,$photo) {
1492         $o = '';
1493         if(! $tag)
1494                 return $o;
1495         $name = xmlify($name);
1496         $uri = xmlify($uri);
1497         $h = intval($h);
1498         $w = intval($w);
1499         $photo = xmlify($photo);
1500
1501
1502         $o .= "<$tag>\r\n";
1503         $o .= "<name>$name</name>\r\n";
1504         $o .= "<uri>$uri</uri>\r\n";
1505         $o .= '<link rel="photo"  type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1506         $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1507
1508         call_hooks('atom_author', $o);
1509
1510         $o .= "</$tag>\r\n";
1511         return $o;
1512 }
1513
1514 function atom_entry($item,$type,$author,$owner,$comment = false) {
1515
1516         $a = get_app();
1517
1518         if($item['deleted'])
1519                 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
1520
1521
1522         if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
1523                 $body = fix_private_photos($item['body'],$owner['uid']);
1524         else
1525                 $body = $item['body'];
1526
1527
1528         $o = "\r\n\r\n<entry>\r\n";
1529
1530         if(is_array($author))
1531                 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
1532         else
1533                 $o .= atom_author('author',$item['name'],$item['url'],80,80,$item['thumb']);
1534         if(strlen($item['owner-name']))
1535                 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
1536
1537         if($item['parent'] != $item['id'])
1538                 $o .= '<thr:in-reply-to ref="' . xmlify($item['parent-uri']) . '" type="text/html" href="' .  xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
1539
1540         $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
1541         $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
1542         $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
1543         $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
1544         $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
1545         $o .= '<content type="' . $type . '" >' . xmlify(($type === 'html') ? bbcode($body) : $body) . '</content>' . "\r\n";
1546         $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
1547         if($comment)
1548                 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
1549
1550         if($item['location']) {
1551                 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
1552                 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
1553         }
1554
1555         if($item['coord'])
1556                 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
1557
1558         if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
1559                 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
1560
1561         $verb = construct_verb($item);
1562         $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
1563         $actobj = construct_activity_object($item);
1564         if(strlen($actobj))
1565                 $o .= $actobj;
1566         $actarg = construct_activity_target($item);
1567         if(strlen($actarg))
1568                 $o .= $actarg;
1569
1570         $tags = item_getfeedtags($item);
1571         if(count($tags)) {
1572                 foreach($tags as $t) {
1573                         $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
1574                 }
1575         }
1576
1577         $o .= item_getfeedattach($item);
1578
1579         $mentioned = get_mentions($item);
1580         if($mentioned)
1581                 $o .= $mentioned;
1582         
1583         call_hooks('atom_entry', $o);
1584
1585         $o .= '</entry>' . "\r\n";
1586         
1587         return $o;
1588 }
1589
1590 function fix_private_photos($s,$uid) {
1591         $a = get_app();
1592         logger('fix_private_photos');
1593
1594         if(preg_match("/\[img\](.+?)\[\/img\]/is",$s,$matches)) {
1595                 $image = $matches[1];
1596                 logger('fix_private_photos: found photo ' . $image);
1597                 if(stristr($image ,$a->get_baseurl() . '/photo/')) {
1598                         $i = basename($image);
1599                         $i = str_replace('.jpg','',$i);
1600                         $x = strpos($i,'-');
1601                         if($x) {
1602                                 $res = substr($i,$x+1);
1603                                 $i = substr($i,0,$x);
1604                                 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
1605                                         dbesc($i),
1606                                         intval($res),
1607                                         intval($uid)
1608                                 );
1609                                 if(count($r)) {
1610                                         logger('replacing photo');
1611                                         $s = str_replace($image, 'data:image/jpg;base64,' . base64_encode($r[0]['data']), $s);
1612                                 }
1613                         }
1614                         logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
1615                 }       
1616         }
1617         return($s);
1618 }
1619
1620
1621
1622 function item_getfeedtags($item) {
1623         $ret = array();
1624         $matches = false;
1625         $cnt = preg_match_all('|\#\[url\=(.+?)\](.+?)\[\/url\]|',$item['tag'],$matches);
1626         if($cnt) {
1627                 for($x = 0; $x < count($matches); $x ++) {
1628                         if($matches[1][$x])
1629                                 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
1630                 }
1631         }
1632         $matches = false; 
1633         $cnt = preg_match_all('|\@\[url\=(.+?)\](.+?)\[\/url\]|',$item['tag'],$matches);
1634         if($cnt) {
1635                 for($x = 0; $x < count($matches); $x ++) {
1636                         if($matches[1][$x])
1637                                 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
1638                 }
1639         } 
1640         return $ret;
1641 }
1642
1643 function item_getfeedattach($item) {
1644         $ret = '';
1645         $arr = explode(',',$item['attach']);
1646         if(count($arr)) {
1647                 foreach($arr as $r) {
1648                         $matches = false;
1649                         $cnt = preg_match('|\[attach\]href=\"(.+?)\" size=\"(.+?)\" type=\"(.+?)\" title=\"(.+?)\"\[\/attach\]|',$r,$matches);
1650                         if($cnt) {
1651                                 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
1652                                 if(intval($matches[2]))
1653                                         $ret .= 'size="' . intval($matches[2]) . '" ';
1654                                 if($matches[4] !== ' ')
1655                                         $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
1656                                 $ret .= ' />' . "\r\n";
1657                         }
1658                 }
1659         }
1660         return $ret;
1661 }
1662
1663
1664         
1665 function item_expire($uid,$days) {
1666
1667         if((! $uid) || (! $days))
1668                 return;
1669
1670         $r = q("SELECT * FROM `item` 
1671                 WHERE `uid` = %d 
1672                 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY 
1673                 AND `id` = `parent` 
1674                 AND `deleted` = 0",
1675                 intval($uid),
1676                 intval($days)
1677         );
1678
1679         if(! count($r))
1680                 return;
1681  
1682         logger('expire: # items=' . count($r) );
1683
1684         foreach($r as $item) {
1685
1686                 // Only expire posts, not photos and photo comments
1687
1688                 if(strlen($item['resource-id']))
1689                         continue;
1690
1691                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
1692                         dbesc(datetime_convert()),
1693                         dbesc(datetime_convert()),
1694                         intval($item['id'])
1695                 );
1696
1697                 // kill the kids
1698
1699                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1700                         dbesc(datetime_convert()),
1701                         dbesc(datetime_convert()),
1702                         dbesc($item['parent-uri']),
1703                         intval($item['uid'])
1704                 );
1705
1706         }
1707
1708         proc_run('php',"include/notifier.php","expire","$uid");
1709
1710 }