]> git.mxchange.org Git - friendica.git/blob - include/items.php
add remove_user hook (it looks like dreamhost changed all my file permissions, this...
[friendica.git] / include / items.php
1 <?php
2
3 require_once('include/bbcode.php');
4 require_once('include/oembed.php');
5 require_once('include/salmon.php');
6 require_once('include/crypto.php');
7
8 function get_feed_for(&$a, $dfrn_id, $owner_nick, $last_update, $direction = 0) {
9
10         // default permissions - anonymous user
11
12         if(! strlen($owner_nick))
13                 killme();
14
15         $public_feed = (($dfrn_id) ? false : true);
16         $starred = false;
17         $converse = false;
18
19         if($public_feed && $a->argc > 2) {
20                 for($x = 2; $x < $a->argc; $x++) {
21                         if($a->argv[$x] == 'converse')
22                                 $converse = true;
23                         if($a->argv[$x] == 'starred')
24                                 $starred = true;
25                 }
26         }
27
28
29         $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' AND `deny_cid`  = '' AND `deny_gid`  = '' ";
30
31         $r = q("SELECT `contact`.*, `user`.`uid` AS `user_uid`, `user`.`nickname`, `user`.`timezone`
32                 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
33                 WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
34                 dbesc($owner_nick)
35         );
36
37         if(! count($r))
38                 killme();
39
40         $owner = $r[0];
41         $owner_id = $owner['user_uid'];
42         $owner_nick = $owner['nickname'];
43
44         $birthday = feed_birthday($owner_id,$owner['timezone']);
45
46         if(! $public_feed) {
47
48                 $sql_extra = '';
49                 switch($direction) {
50                         case (-1):
51                                 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
52                                 $my_id = $dfrn_id;
53                                 break;
54                         case 0:
55                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
56                                 $my_id = '1:' . $dfrn_id;
57                                 break;
58                         case 1:
59                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
60                                 $my_id = '0:' . $dfrn_id;
61                                 break;
62                         default:
63                                 return false;
64                                 break; // NOTREACHED
65                 }
66
67                 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
68                         intval($owner_id)
69                 );
70
71                 if(! count($r))
72                         killme();
73
74                 $contact = $r[0];
75                 $groups = init_groups_visitor($contact['id']);
76
77                 if(count($groups)) {
78                         for($x = 0; $x < count($groups); $x ++) 
79                                 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
80                         $gs = implode('|', $groups);
81                 }
82                 else
83                         $gs = '<<>>' ; // Impossible to match 
84
85                 $sql_extra = sprintf(" 
86                         AND ( `allow_cid` = '' OR     `allow_cid` REGEXP '<%d>' ) 
87                         AND ( `deny_cid`  = '' OR NOT `deny_cid`  REGEXP '<%d>' ) 
88                         AND ( `allow_gid` = '' OR     `allow_gid` REGEXP '%s' )
89                         AND ( `deny_gid`  = '' OR NOT `deny_gid`  REGEXP '%s') 
90                 ",
91                         intval($contact['id']),
92                         intval($contact['id']),
93                         dbesc($gs),
94                         dbesc($gs)
95                 );
96         }
97
98         if($public_feed)
99                 $sort = 'DESC';
100         else
101                 $sort = 'ASC';
102
103         if(! strlen($last_update))
104                 $last_update = 'now -30 days';
105
106         if($public_feed) {
107                 if(! $converse)
108                         $sql_extra .= " AND `contact`.`self` = 1 ";
109         }
110
111         $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
112
113         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
114                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, 
115                 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
116                 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`, 
117                 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`,
118                 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
119                 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
120                 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
121                 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`parent` != 0 
122                 AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
123                 AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
124                 $sql_extra
125                 ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
126                 intval($owner_id),
127                 dbesc($check_date),
128                 dbesc($check_date),
129                 dbesc($sort)
130         );
131
132         // Will check further below if this actually returned results.
133         // We will provide an empty feed if that is the case.
134
135         $items = $r;
136
137         $feed_template = get_markup_template(($dfrn_id) ? 'atom_feed_dfrn.tpl' : 'atom_feed.tpl');
138
139         $atom = '';
140
141         $hubxml = feed_hublinks();
142
143         $salmon = feed_salmonlinks($owner_nick);
144
145         $atom .= replace_macros($feed_template, array(
146                 '$version'      => xmlify(FRIENDICA_VERSION),
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                 '$birthday'     => ((strlen($birthday)) ? '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>' : '')
160         ));
161
162         call_hooks('atom_feed', $atom);
163
164         if(! count($items)) {
165
166                 call_hooks('atom_feed_end', $atom);
167
168                 $atom .= '</feed>' . "\r\n";
169                 return $atom;
170         }
171
172         foreach($items as $item) {
173
174                 // public feeds get html, our own nodes use bbcode
175
176                 if($public_feed) {
177                         $type = 'html';
178                         // catch any email that's in a public conversation and make sure it doesn't leak
179                         if($item['private'])
180                                 continue;
181                 }
182                 else {
183                         $type = 'text';
184                 }
185
186                 $atom .= atom_entry($item,$type,null,$owner,true);
187         }
188
189         call_hooks('atom_feed_end', $atom);
190
191         $atom .= '</feed>' . "\r\n";
192
193         return $atom;
194 }
195
196
197 function construct_verb($item) {
198         if($item['verb'])
199                 return $item['verb'];
200         return ACTIVITY_POST;
201 }
202
203 function construct_activity_object($item) {
204
205         if($item['object']) {
206                 $o = '<as:object>' . "\r\n";
207                 $r = parse_xml_string($item['object'],false);
208
209
210                 if(! $r)
211                         return '';
212                 if($r->type)
213                         $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
214                 if($r->id)
215                         $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
216                 if($r->title)
217                         $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
218                 if($r->link) {
219                         if(substr($r->link,0,1) === '<') {
220                                 // patch up some facebook "like" activity objects that got stored incorrectly
221                                 // for a couple of months prior to 9-Jun-2011 and generated bad XML.
222                                 // we can probably remove this hack here and in the following function in a few months time.
223                                 if(strstr($r->link,'&') && (! strstr($r->link,'&amp;')))
224                                         $r->link = str_replace('&','&amp;', $r->link);
225                                 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
226                                 $o .= $r->link;
227                         }                                       
228                         else
229                                 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
230                 }
231                 if($r->content)
232                         $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
233                 $o .= '</as:object>' . "\r\n";
234                 return $o;
235         }
236
237         return '';
238
239
240 function construct_activity_target($item) {
241
242         if($item['target']) {
243                 $o = '<as:target>' . "\r\n";
244                 $r = parse_xml_string($item['target'],false);
245                 if(! $r)
246                         return '';
247                 if($r->type)
248                         $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
249                 if($r->id)
250                         $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
251                 if($r->title)
252                         $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
253                 if($r->link) {
254                         if(substr($r->link,0,1) === '<') {
255                                 if(strstr($r->link,'&') && (! strstr($r->link,'&amp;')))
256                                         $r->link = str_replace('&','&amp;', $r->link);
257                                 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
258                                 $o .= $r->link;
259                         }                                       
260                         else
261                                 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
262                 }
263                 if($r->content)
264                         $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
265                 $o .= '</as:target>' . "\r\n";
266                 return $o;
267         }
268
269         return '';
270
271
272
273
274
275 function get_atom_elements($feed,$item) {
276
277         require_once('library/HTMLPurifier.auto.php');
278         require_once('include/html2bbcode.php');
279
280         $best_photo = array();
281
282         $res = array();
283
284         $author = $item->get_author();
285         if($author) { 
286                 $res['author-name'] = unxmlify($author->get_name());
287                 $res['author-link'] = unxmlify($author->get_link());
288         }
289         else {
290                 $res['author-name'] = unxmlify($feed->get_title());
291                 $res['author-link'] = unxmlify($feed->get_permalink());
292         }
293         $res['uri'] = unxmlify($item->get_id());
294         $res['title'] = unxmlify($item->get_title());
295         $res['body'] = unxmlify($item->get_content());
296         $res['plink'] = unxmlify($item->get_link(0));
297
298         if($res['plink'])
299                 $base_url = implode('/', array_slice(explode('/',$res['plink']),0,3));
300         else
301                 $base_url = '';
302
303         // look for a photo. We should check media size and find the best one,
304         // but for now let's just find any author photo
305
306         $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
307
308         if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
309                 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
310                 foreach($base as $link) {
311                         if(! $res['author-avatar']) {
312                                 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
313                                         $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
314                         }
315                 }
316         }                       
317
318         $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
319
320         if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
321                 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
322                 if($base && count($base)) {
323                         foreach($base as $link) {
324                                 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
325                                         $res['author-link'] = unxmlify($link['attribs']['']['href']);
326                                 if(! $res['author-avatar']) {
327                                         if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
328                                                 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
329                                 }
330                         }
331                 }
332         }
333
334         // No photo/profile-link on the item - look at the feed level
335
336         if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
337                 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
338                 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
339                         $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
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'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
345                                                 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
346                                 }
347                         }
348                 }                       
349
350                 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
351
352                 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
353                         $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
354
355                         if($base && count($base)) {
356                                 foreach($base as $link) {
357                                         if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
358                                                 $res['author-link'] = unxmlify($link['attribs']['']['href']);
359                                         if(! (x($res,'author-avatar'))) {
360                                                 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
361                                                         $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
362                                         }
363                                 }
364                         }
365                 }
366         }
367
368         $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
369         if($apps && $apps[0]['attribs']['']['source']) {
370                 $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
371                 if($res['app'] === 'web')
372                         $res['app'] = 'OStatus';
373         }                  
374
375         // base64 encoded json structure representing Diaspora signature
376
377         $dsig = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_signature');
378         if($dsig) {
379                 $res['dsprsig'] = unxmlify($dsig[0]['data']);
380         }
381
382         $dguid = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_guid');
383         if($dguid)
384                 $res['guid'] = unxmlify($dguid[0]['data']);
385
386         $bm = $item->get_item_tags(NAMESPACE_DFRN,'bookmark');
387         if($bm)
388                 $res['bookmark'] = ((unxmlify($bm[0]['data']) === 'true') ? 1 : 0);
389
390
391         /**
392          * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
393          */
394
395         $have_real_body = false;
396
397         $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
398         if($rawenv) {
399                 $have_real_body = true;
400                 $res['body'] = $rawenv[0]['data'];
401                 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
402                 // make sure nobody is trying to sneak some html tags by us
403                 $res['body'] = notags(base64url_decode($res['body']));
404         }
405
406         $maxlen = get_max_import_size();
407         if($maxlen && (strlen($res['body']) > $maxlen))
408                 $res['body'] = substr($res['body'],0, $maxlen);
409
410         // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust 
411         // the content type. Our own network only emits text normally, though it might have been converted to 
412         // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
413         // have to assume it is all html and needs to be purified.
414
415         // It doesn't matter all that much security wise - because before this content is used anywhere, we are 
416         // going to escape any tags we find regardless, but this lets us import a limited subset of html from 
417         // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining 
418         // html.
419
420         if((strpos($res['body'],'<') !== false) || (strpos($res['body'],'>') !== false)) {
421
422                 $res['body'] = reltoabs($res['body'],$base_url);
423
424                 $res['body'] = html2bb_video($res['body']);
425
426                 $res['body'] = oembed_html2bbcode($res['body']);
427
428                 $config = HTMLPurifier_Config::createDefault();
429                 $config->set('Cache.DefinitionImpl', null);
430
431                 // we shouldn't need a whitelist, because the bbcode converter
432                 // will strip out any unsupported tags.
433                 // $config->set('HTML.Allowed', 'p,b,a[href],i'); 
434
435                 $purifier = new HTMLPurifier($config);
436                 $res['body'] = $purifier->purify($res['body']);
437
438                 $res['body'] = html2bbcode($res['body']);
439         }
440
441         $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
442         if($allow && $allow[0]['data'] == 1)
443                 $res['last-child'] = 1;
444         else
445                 $res['last-child'] = 0;
446
447         $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
448         if($private && $private[0]['data'] == 1)
449                 $res['private'] = 1;
450         else
451                 $res['private'] = 0;
452
453         $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
454         if($extid && $extid[0]['data'])
455                 $res['extid'] = $extid[0]['data'];
456
457         $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
458         if($rawlocation)
459                 $res['location'] = unxmlify($rawlocation[0]['data']);
460
461
462         $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
463         if($rawcreated)
464                 $res['created'] = unxmlify($rawcreated[0]['data']);
465
466
467         $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
468         if($rawedited)
469                 $res['edited'] = unxmlify($rawedited[0]['data']);
470
471         if((x($res,'edited')) && (! (x($res,'created'))))
472                 $res['created'] = $res['edited']; 
473
474         if(! $res['created'])
475                 $res['created'] = $item->get_date('c');
476
477         if(! $res['edited'])
478                 $res['edited'] = $item->get_date('c');
479
480
481         // Disallow time travelling posts
482
483         $d1 = strtotime($res['created']);
484         $d2 = strtotime($res['edited']);
485         $d3 = strtotime('now');
486
487         if($d1 > $d3)
488                 $res['created'] = datetime_convert();
489         if($d2 > $d3)
490                 $res['edited'] = datetime_convert();
491
492         $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
493         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
494                 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
495         elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
496                 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
497         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
498                 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
499         elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
500                 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
501
502         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
503                 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
504
505                 foreach($base as $link) {
506                         if(! $res['owner-avatar']) {
507                                 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')                 
508                                         $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
509                         }
510                 }
511         }
512
513         $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
514         if($rawgeo)
515                 $res['coord'] = unxmlify($rawgeo[0]['data']);
516
517
518         $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
519
520         // select between supported verbs
521
522         if($rawverb) {
523                 $res['verb'] = unxmlify($rawverb[0]['data']);
524         }
525
526         // translate OStatus unfollow to activity streams if it happened to get selected
527                 
528         if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
529                 $res['verb'] = ACTIVITY_UNFOLLOW;
530
531         $cats = $item->get_categories();
532         if($cats) {
533                 $tag_arr = array();
534                 foreach($cats as $cat) {
535                         $term = $cat->get_term();
536                         if(! $term)
537                                 $term = $cat->get_label();
538                         $scheme = $cat->get_scheme();
539                         if($scheme && $term && stristr($scheme,'X-DFRN:'))
540                                 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
541                         elseif($term)
542                                 $tag_arr[] = notags(trim($term));
543                 }
544                 $res['tag'] =  implode(',', $tag_arr);
545         }
546
547         $attach = $item->get_enclosures();
548         if($attach) {
549                 $att_arr = array();
550                 foreach($attach as $att) {
551                         $len   = intval($att->get_length());
552                         $link  = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
553                         $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
554                         $type  = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
555                         if(strpos($type,';'))
556                                 $type = substr($type,0,strpos($type,';'));
557                         if((! $link) || (strpos($link,'http') !== 0))
558                                 continue;
559
560                         if(! $title)
561                                 $title = ' ';
562                         if(! $type)
563                                 $type = 'application/octet-stream';
564
565                         $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]'; 
566                 }
567                 $res['attach'] = implode(',', $att_arr);
568         }
569
570         $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
571
572         if($rawobj) {
573                 $res['object'] = '<object>' . "\n";
574                 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
575                         $res['object-type'] = $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'];
576                         $res['object'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
577                 }       
578                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
579                         $res['object'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
580                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
581                         $res['object'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
582                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
583                         $res['object'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
584                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
585                         $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
586                         if(! $body)
587                                 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
588                         // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
589                         $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
590                         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
591
592                                 $body = html2bb_video($body);
593
594                                 $config = HTMLPurifier_Config::createDefault();
595                                 $config->set('Cache.DefinitionImpl', null);
596
597                                 $purifier = new HTMLPurifier($config);
598                                 $body = $purifier->purify($body);
599                                 $body = html2bbcode($body);
600                         }
601
602                         $res['object'] .= '<content>' . $body . '</content>' . "\n";
603                 }
604
605                 $res['object'] .= '</object>' . "\n";
606         }
607
608         $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
609
610         if($rawobj) {
611                 $res['target'] = '<target>' . "\n";
612                 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
613                         $res['target'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
614                 }       
615                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
616                         $res['target'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
617
618                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
619                         $res['target'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
620                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
621                         $res['target'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
622                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
623                         $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
624                         if(! $body)
625                                 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
626                         // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
627                         $res['target'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
628                         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
629
630                                 $body = html2bb_video($body);
631
632                                 $config = HTMLPurifier_Config::createDefault();
633                                 $config->set('Cache.DefinitionImpl', null);
634
635                                 $purifier = new HTMLPurifier($config);
636                                 $body = $purifier->purify($body);
637                                 $body = html2bbcode($body);
638                         }
639
640                         $res['target'] .= '<content>' . $body . '</content>' . "\n";
641                 }
642
643                 $res['target'] .= '</target>' . "\n";
644         }
645
646         $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
647
648         call_hooks('parse_atom', $arr);
649
650         return $res;
651 }
652
653 function encode_rel_links($links) {
654         $o = '';
655         if(! ((is_array($links)) && (count($links))))
656                 return $o;
657         foreach($links as $link) {
658                 $o .= '<link ';
659                 if($link['attribs']['']['rel'])
660                         $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
661                 if($link['attribs']['']['type'])
662                         $o .= 'type="' . $link['attribs']['']['type'] . '" ';
663                 if($link['attribs']['']['href'])
664                         $o .= 'href="' . $link['attribs']['']['href'] . '" ';
665                 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
666                         $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
667                 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
668                         $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
669                 $o .= ' />' . "\n" ;
670         }
671         return xmlify($o);
672 }
673
674 function item_store($arr,$force_parent = false) {
675
676         // If a Diaspora signature structure was passed in, pull it out of the 
677         // item array and set it aside for later storage.
678
679         $dsprsig = null;
680         if(x($arr,'dsprsig')) {
681                 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
682                 unset($arr['dsprsig']);
683         }
684
685         if($arr['gravity'])
686                 $arr['gravity'] = intval($arr['gravity']);
687         elseif($arr['parent-uri'] === $arr['uri'])
688                 $arr['gravity'] = 0;
689         elseif(activity_match($arr['verb'],ACTIVITY_POST))
690                 $arr['gravity'] = 6;
691         else      
692                 $arr['gravity'] = 6;   // extensible catchall
693
694         if(! x($arr,'type'))
695                 $arr['type']      = 'remote';
696
697         // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
698
699         if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false)) 
700                 $arr['body'] = strip_tags($arr['body']);
701
702
703         $arr['wall']          = ((x($arr,'wall'))          ? intval($arr['wall'])                : 0);
704         $arr['uri']           = ((x($arr,'uri'))           ? notags(trim($arr['uri']))           : random_string());
705         $arr['extid']         = ((x($arr,'extid'))         ? notags(trim($arr['extid']))         : '');
706         $arr['author-name']   = ((x($arr,'author-name'))   ? notags(trim($arr['author-name']))   : '');
707         $arr['author-link']   = ((x($arr,'author-link'))   ? notags(trim($arr['author-link']))   : '');
708         $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
709         $arr['owner-name']    = ((x($arr,'owner-name'))    ? notags(trim($arr['owner-name']))    : '');
710         $arr['owner-link']    = ((x($arr,'owner-link'))    ? notags(trim($arr['owner-link']))    : '');
711         $arr['owner-avatar']  = ((x($arr,'owner-avatar'))  ? notags(trim($arr['owner-avatar']))  : '');
712         $arr['created']       = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
713         $arr['edited']        = ((x($arr,'edited')  !== false) ? datetime_convert('UTC','UTC',$arr['edited'])  : datetime_convert());
714         $arr['commented']     = datetime_convert();
715         $arr['received']      = datetime_convert();
716         $arr['changed']       = datetime_convert();
717         $arr['title']         = ((x($arr,'title'))         ? notags(trim($arr['title']))         : '');
718         $arr['location']      = ((x($arr,'location'))      ? notags(trim($arr['location']))      : '');
719         $arr['coord']         = ((x($arr,'coord'))         ? notags(trim($arr['coord']))         : '');
720         $arr['last-child']    = ((x($arr,'last-child'))    ? intval($arr['last-child'])          : 0 );
721         $arr['visible']       = ((x($arr,'visible') !== false) ? intval($arr['visible'])         : 1 );
722         $arr['deleted']       = 0;
723         $arr['parent-uri']    = ((x($arr,'parent-uri'))    ? notags(trim($arr['parent-uri']))    : '');
724         $arr['verb']          = ((x($arr,'verb'))          ? notags(trim($arr['verb']))          : '');
725         $arr['object-type']   = ((x($arr,'object-type'))   ? notags(trim($arr['object-type']))   : '');
726         $arr['object']        = ((x($arr,'object'))        ? trim($arr['object'])                : '');
727         $arr['target-type']   = ((x($arr,'target-type'))   ? notags(trim($arr['target-type']))   : '');
728         $arr['target']        = ((x($arr,'target'))        ? trim($arr['target'])                : '');
729         $arr['plink']         = ((x($arr,'plink'))         ? notags(trim($arr['plink']))         : '');
730         $arr['allow_cid']     = ((x($arr,'allow_cid'))     ? trim($arr['allow_cid'])             : '');
731         $arr['allow_gid']     = ((x($arr,'allow_gid'))     ? trim($arr['allow_gid'])             : '');
732         $arr['deny_cid']      = ((x($arr,'deny_cid'))      ? trim($arr['deny_cid'])              : '');
733         $arr['deny_gid']      = ((x($arr,'deny_gid'))      ? trim($arr['deny_gid'])              : '');
734         $arr['private']       = ((x($arr,'private'))       ? intval($arr['private'])             : 0 );
735         $arr['bookmark']      = ((x($arr,'bookmark'))      ? intval($arr['bookmark'])            : 0 );
736         $arr['body']          = ((x($arr,'body'))          ? trim($arr['body'])                  : '');
737         $arr['tag']           = ((x($arr,'tag'))           ? notags(trim($arr['tag']))           : '');
738         $arr['attach']        = ((x($arr,'attach'))        ? notags(trim($arr['attach']))        : '');
739         $arr['app']           = ((x($arr,'app'))           ? notags(trim($arr['app']))           : '');
740         $arr['origin']        = ((x($arr,'origin'))        ? intval($arr['origin'])              : 0 );
741         $arr['guid']          = ((x($arr,'guid'))          ? notags(trim($arr['guid']))          : get_guid());
742
743         if($arr['parent-uri'] === $arr['uri']) {
744                 $parent_id = 0;
745                 $allow_cid = $arr['allow_cid'];
746                 $allow_gid = $arr['allow_gid'];
747                 $deny_cid  = $arr['deny_cid'];
748                 $deny_gid  = $arr['deny_gid'];
749         }
750         else { 
751
752                 // find the parent and snarf the item id and ACL's
753                 // and anything else we need to inherit
754
755                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
756                         dbesc($arr['parent-uri']),
757                         intval($arr['uid'])
758                 );
759
760                 if(count($r)) {
761
762                         // is the new message multi-level threaded?
763                         // even though we don't support it now, preserve the info
764                         // and re-attach to the conversation parent.
765
766                         if($r[0]['uri'] != $r[0]['parent-uri']) {
767                                 $arr['thr-parent'] = $arr['parent-uri'];
768                                 $arr['parent-uri'] = $r[0]['parent-uri'];
769                                 $z = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d 
770                                         ORDER BY `id` ASC LIMIT 1",
771                                         dbesc($r[0]['parent-uri']),
772                                         dbesc($r[0]['parent-uri']),
773                                         intval($arr['uid'])
774                                 );
775                                 if($z && count($z))
776                                         $r = $z;
777                         }
778
779                         $parent_id      = $r[0]['id'];
780                         $parent_deleted = $r[0]['deleted'];
781                         $allow_cid      = $r[0]['allow_cid'];
782                         $allow_gid      = $r[0]['allow_gid'];
783                         $deny_cid       = $r[0]['deny_cid'];
784                         $deny_gid       = $r[0]['deny_gid'];
785                         $arr['wall']    = $r[0]['wall'];
786                 }
787                 else {
788
789                         // Allow one to see reply tweets from status.net even when
790                         // we don't have or can't see the original post.
791
792                         if($force_parent) {
793                                 logger('item_store: $force_parent=true, reply converted to top-level post.');
794                                 $parent_id = 0;
795                                 $arr['thr-parent'] = $arr['parent-uri'];
796                                 $arr['parent-uri'] = $arr['uri'];
797                                 $arr['gravity'] = 0;
798                         }
799                         else {
800                                 logger('item_store: item parent was not found - ignoring item');
801                                 return 0;
802                         }
803                 }
804         }
805
806         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
807                 dbesc($arr['uri']),
808                 intval($arr['uid'])
809         );
810         if($r && count($r)) {
811                 logger('item-store: duplicate item ignored. ' . print_r($arr,true));
812                 return 0;
813         }
814
815         call_hooks('post_remote',$arr);
816
817         dbesc_array($arr);
818
819         logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
820
821         $r = dbq("INSERT INTO `item` (`" 
822                         . implode("`, `", array_keys($arr)) 
823                         . "`) VALUES ('" 
824                         . implode("', '", array_values($arr)) 
825                         . "')" );
826
827         // find the item we just created
828
829         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC ",
830                 $arr['uri'],           // already dbesc'd
831                 intval($arr['uid'])
832         );
833
834         if(count($r)) {
835                 $current_post = $r[0]['id'];
836                 logger('item_store: created item ' . $current_post);
837         }
838         else {
839                 logger('item_store: could not locate created item');
840                 return 0;
841         }
842         if(count($r) > 1) {
843                 logger('item_store: duplicated post occurred. Removing duplicates.');
844                 q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
845                         $arr['uri'],
846                         intval($arr['uid']),
847                         intval($current_post)
848                 );
849         }
850
851         if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))      
852                 $parent_id = $current_post;
853
854         if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
855                 $private = 1;
856         else
857                 $private = $arr['private']; 
858
859         // Set parent id - and also make sure to inherit the parent's ACL's.
860
861         $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
862                 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
863                 intval($parent_id),
864                 dbesc($allow_cid),
865                 dbesc($allow_gid),
866                 dbesc($deny_cid),
867                 dbesc($deny_gid),
868                 intval($private),
869                 intval($parent_deleted),
870                 intval($current_post)
871         );
872
873         // update the commented timestamp on the parent
874
875         q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
876                 dbesc(datetime_convert()),
877                 dbesc(datetime_convert()),
878                 intval($parent_id)
879         );
880
881         if($dsprsig) {
882                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
883                         intval($current_post),
884                         dbesc($dsprsig->signed_text),
885                         dbesc($dsprsig->signature),
886                         dbesc($dsprsig->signer)
887                 );
888         }
889
890
891         /**
892          * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
893          */
894
895         if($arr['last-child']) {
896                 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
897                         dbesc($arr['uri']),
898                         intval($arr['uid']),
899                         intval($current_post)
900                 );
901         }
902
903         tgroup_deliver($arr['uid'],$current_post);
904
905         return $current_post;
906 }
907
908 function get_item_contact($item,$contacts) {
909         if(! count($contacts) || (! is_array($item)))
910                 return false;
911         foreach($contacts as $contact) {
912                 if($contact['id'] == $item['contact-id']) {
913                         return $contact;
914                         break; // NOTREACHED
915                 }
916         }
917         return false;
918 }
919
920
921 function tgroup_deliver($uid,$item_id) {
922
923
924         // setup a second delivery chain for forum/community posts if appropriate
925
926         $a = get_app();
927
928         $deliver_to_tgroup = false;
929
930         $u = q("select * from user where uid = %d and `page-flags` = %d limit 1",
931                 intval($uid),
932                 intval(PAGE_COMMUNITY)
933         );
934         if(! count($u))
935                 return;
936
937         $i = q("select * from item where id = %d and uid = %d limit 1",
938                 intval($item_id),
939                 intval($uid)
940         );
941         if(! count($i))
942                 return;
943
944         $item = $i[0];
945
946         // prevent delivery looping - only proceed
947         // if the message originated elsewhere and is a top-level post
948
949         if(($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent']))
950                 return;
951
952
953         $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
954
955         // Diaspora uses their own hardwired link URL in @-tags
956         // instead of the one we supply with webfinger
957
958         $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
959
960         $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
961         if($cnt) {
962                 foreach($matches as $mtch) {
963                         if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
964                                 $deliver_to_tgroup = true;
965                                 logger('tgroup_deliver: local group mention found: ' . $mtch[2]);
966                         }
967                 }
968         }
969
970         if(! $deliver_to_tgroup)
971                 return;
972
973         // now change this copy of the post to a forum head message and deliver to all the tgroup members
974
975
976         q("update item set wall = 1, origin = 1, forum_mode = 1 where id = %d limit 1",
977                 intval($item_id)
978         );
979
980         proc_run('php','include/notifier.php','tgroup',$item_id);                       
981
982 }
983
984
985
986
987
988
989 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
990
991         $a = get_app();
992
993         if((! strlen($contact['issued-id'])) && (! $contact['duplex']) && (! ($owner['page-flags'] == PAGE_COMMUNITY)))
994                 return 3;
995
996         $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
997
998         if($contact['duplex'] && $contact['dfrn-id'])
999                 $idtosend = '0:' . $orig_id;
1000         if($contact['duplex'] && $contact['issued-id'])
1001                 $idtosend = '1:' . $orig_id;            
1002
1003         $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
1004
1005         $rino_enable = get_config('system','rino_encrypt');
1006
1007         if(! $rino_enable)
1008                 $rino = 0;
1009
1010         $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
1011
1012         logger('dfrn_deliver: ' . $url);
1013
1014         $xml = fetch_url($url);
1015
1016         $curl_stat = $a->get_curl_code();
1017         if(! $curl_stat)
1018                 return(-1); // timed out
1019
1020         logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1021
1022         if(! $xml)
1023                 return 3;
1024
1025         if(strpos($xml,'<?xml') === false) {
1026                 logger('dfrn_deliver: no valid XML returned');
1027                 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1028                 return 3;
1029         }
1030
1031         $res = parse_xml_string($xml);
1032
1033         if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
1034                 return (($res->status) ? $res->status : 3);
1035
1036         $postvars     = array();
1037         $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1038         $challenge    = hex2bin((string) $res->challenge);
1039         $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1040         $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
1041
1042         $final_dfrn_id = '';
1043
1044
1045         if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1046                 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1047                 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1048         }
1049         else {
1050                 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1051                 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1052         }
1053
1054         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1055
1056         if(strpos($final_dfrn_id,':') == 1)
1057                 $final_dfrn_id = substr($final_dfrn_id,2);
1058
1059         if($final_dfrn_id != $orig_id) {
1060                 logger('dfrn_deliver: wrong dfrn_id.');
1061                 // did not decode properly - cannot trust this site 
1062                 return 3;
1063         }
1064
1065         $postvars['dfrn_id']      = $idtosend;
1066         $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1067         if($dissolve)
1068                 $postvars['dissolve'] = '1';
1069
1070
1071         if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1072                 $postvars['data'] = $atom;
1073                 $postvars['perm'] = 'rw';
1074         }
1075         else {
1076                 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1077                 $postvars['perm'] = 'r';
1078         }
1079
1080         if($rino && $rino_allowed && (! $dissolve)) {
1081                 $key = substr(random_string(),0,16);
1082                 $data = bin2hex(aes_encrypt($postvars['data'],$key));
1083                 $postvars['data'] = $data;
1084                 logger('rino: sent key = ' . $key, LOGGER_DEBUG);       
1085
1086
1087                 if($dfrn_version >= 2.1) {      
1088                         if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1089                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1090                         }
1091                         else {
1092                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1093                         }
1094                 }
1095                 else {
1096                         if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1097                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1098                         }
1099                         else {
1100                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1101                         }
1102                 }
1103
1104                 logger('md5 rawkey ' . md5($postvars['key']));
1105
1106                 $postvars['key'] = bin2hex($postvars['key']);
1107         }
1108
1109         logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1110
1111         $xml = post_url($contact['notify'],$postvars);
1112
1113         logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1114
1115         $curl_stat = $a->get_curl_code();
1116         if((! $curl_stat) || (! strlen($xml)))
1117                 return(-1); // timed out
1118
1119         if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1120                 return(-1);
1121
1122         if(strpos($xml,'<?xml') === false) {
1123                 logger('dfrn_deliver: phase 2: no valid XML returned');
1124                 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1125                 return 3;
1126         }
1127
1128         $res = parse_xml_string($xml);
1129
1130         return $res->status; 
1131 }
1132
1133
1134 /**
1135  *
1136  * consume_feed - process atom feed and update anything/everything we might need to update
1137  *
1138  * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1139  *
1140  * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1141  *             It is this person's stuff that is going to be updated.
1142  * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1143  *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST 
1144  *             have a contact record.
1145  * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or 
1146  *        might not) try and subscribe to it.
1147  * $datedir sorts in reverse order
1148  * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been 
1149  *      imported prior to its children being seen in the stream unless we are certain
1150  *      of how the feed is arranged/ordered.
1151  * With $pass = 1, we only pull parent items out of the stream.
1152  * With $pass = 2, we only pull children (comments/likes).
1153  *
1154  * So running this twice, first with pass 1 and then with pass 2 will do the right
1155  * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1156  * model where comments can have sub-threads. That would require some massive sorting
1157  * to get all the feed items into a mostly linear ordering, and might still require
1158  * recursion.  
1159  */
1160
1161 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
1162
1163         require_once('library/simplepie/simplepie.inc');
1164
1165         if(! strlen($xml)) {
1166                 logger('consume_feed: empty input');
1167                 return;
1168         }
1169                 
1170         $feed = new SimplePie();
1171         $feed->set_raw_data($xml);
1172         if($datedir)
1173                 $feed->enable_order_by_date(true);
1174         else
1175                 $feed->enable_order_by_date(false);
1176         $feed->init();
1177
1178         if($feed->error())
1179                 logger('consume_feed: Error parsing XML: ' . $feed->error());
1180
1181         $permalink = $feed->get_permalink();
1182
1183         // Check at the feed level for updated contact name and/or photo
1184
1185         $name_updated  = '';
1186         $new_name = '';
1187         $photo_timestamp = '';
1188         $photo_url = '';
1189         $birthday = '';
1190
1191         $hubs = $feed->get_links('hub');
1192
1193         if(count($hubs))
1194                 $hub = implode(',', $hubs);
1195
1196         $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1197         if(! $rawtags)
1198                 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1199         if($rawtags) {
1200                 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1201                 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1202                         $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1203                         $new_name = $elems['name'][0]['data'];
1204                 } 
1205                 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1206                         $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1207                         $photo_url = $elems['link'][0]['attribs']['']['href'];
1208                 }
1209
1210                 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1211                         $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1212                 }
1213         }
1214
1215         if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1216                 logger('consume_feed: Updating photo for ' . $contact['name']);
1217                 require_once("Photo.php");
1218                 $photo_failure = false;
1219                 $have_photo = false;
1220
1221                 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1222                         intval($contact['id']),
1223                         intval($contact['uid'])
1224                 );
1225                 if(count($r)) {
1226                         $resource_id = $r[0]['resource-id'];
1227                         $have_photo = true;
1228                 }
1229                 else {
1230                         $resource_id = photo_new_resource();
1231                 }
1232                         
1233                 $img_str = fetch_url($photo_url,true);
1234                 $img = new Photo($img_str);
1235                 if($img->is_valid()) {
1236                         if($have_photo) {
1237                                 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1238                                         dbesc($resource_id),
1239                                         intval($contact['id']),
1240                                         intval($contact['uid'])
1241                                 );
1242                         }
1243                                 
1244                         $img->scaleImageSquare(175);
1245                                 
1246                         $hash = $resource_id;
1247                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1248                                 
1249                         $img->scaleImage(80);
1250                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1251
1252                         $img->scaleImage(48);
1253                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1254
1255                         $a = get_app();
1256
1257                         q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'  
1258                                 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1259                                 dbesc(datetime_convert()),
1260                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
1261                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
1262                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
1263                                 intval($contact['uid']),
1264                                 intval($contact['id'])
1265                         );
1266                 }
1267         }
1268
1269         if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1270                 q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1271                         dbesc(notags(trim($new_name))),
1272                         dbesc(datetime_convert()),
1273                         intval($contact['uid']),
1274                         intval($contact['id'])
1275                 );
1276         }
1277
1278         if(strlen($birthday)) {
1279                 if(substr($birthday,0,4) != $contact['bdyear']) {
1280                         logger('consume_feed: updating birthday: ' . $birthday);
1281
1282                         /**
1283                          *
1284                          * Add new birthday event for this person
1285                          *
1286                          * $bdtext is just a readable placeholder in case the event is shared
1287                          * with others. We will replace it during presentation to our $importer
1288                          * to contain a sparkle link and perhaps a photo. 
1289                          *
1290                          */
1291                          
1292                         $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1293
1294
1295                         $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1296                                 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1297                                 intval($contact['uid']),
1298                                 intval($contact['id']),
1299                                 dbesc(datetime_convert()),
1300                                 dbesc(datetime_convert()),
1301                                 dbesc(datetime_convert('UTC','UTC', $birthday)),
1302                                 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1303                                 dbesc($bdtext),
1304                                 dbesc('birthday')
1305                         );
1306                         
1307
1308                         // update bdyear
1309
1310                         q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1311                                 dbesc(substr($birthday,0,4)),
1312                                 intval($contact['uid']),
1313                                 intval($contact['id'])
1314                         );
1315
1316                         // This function is called twice without reloading the contact
1317                         // Make sure we only create one event. This is why &$contact 
1318                         // is a reference var in this function
1319
1320                         $contact['bdyear'] = substr($birthday,0,4);
1321                 }
1322
1323         }
1324
1325
1326         // process any deleted entries
1327
1328         $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1329         if(is_array($del_entries) && count($del_entries) && $pass != 2) {
1330                 foreach($del_entries as $dentry) {
1331                         $deleted = false;
1332                         if(isset($dentry['attribs']['']['ref'])) {
1333                                 $uri = $dentry['attribs']['']['ref'];
1334                                 $deleted = true;
1335                                 if(isset($dentry['attribs']['']['when'])) {
1336                                         $when = $dentry['attribs']['']['when'];
1337                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1338                                 }
1339                                 else
1340                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1341                         }
1342                         if($deleted && is_array($contact)) {
1343                                 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id` 
1344                                         WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d LIMIT 1",
1345                                         dbesc($uri),
1346                                         intval($importer['uid']),
1347                                         intval($contact['id'])
1348                                 );
1349                                 if(count($r)) {
1350                                         $item = $r[0];
1351
1352                                         if(! $item['deleted'])
1353                                                 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1354
1355                                         if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTVITY_OBJ_TAGTERM)) {
1356                                                 $xo = parse_xml_string($item['object'],false);
1357                                                 $xt = parse_xml_string($item['target'],false);
1358                                                 if($xt->type === ACTIVITY_OBJ_NOTE) {
1359                                                         $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1360                                                                 dbesc($xt->id),
1361                                                                 intval($importer['importer_uid'])
1362                                                         );
1363                                                         if(count($i)) {
1364
1365                                                                 // For tags, the owner cannot remove the tag on the author's copy of the post.
1366
1367                                                                 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1368                                                                 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1369                                                                 $author_copy = (($item['origin']) ? true : false);
1370
1371                                                                 if($owner_remove && $author_copy)
1372                                                                         continue;
1373                                                                 if($author_remove || $owner_remove) {
1374                                                                         $tags = explode(',',$i[0]['tag']);
1375                                                                         $newtags = array();
1376                                                                         if(count($tags)) {
1377                                                                                 foreach($tags as $tag)
1378                                                                                         if(trim($tag) !== trim($xo->body))
1379                                                                                                 $newtags[] = trim($tag);
1380                                                                         }
1381                                                                         q("update item set tag = '%s' where id = %d limit 1",
1382                                                                                 dbesc(implode(',',$newtags)),
1383                                                                                 intval($i[0]['id'])
1384                                                                         );
1385                                                                 }
1386                                                         }
1387                                                 }
1388                                         }
1389
1390                                         if($item['uri'] == $item['parent-uri']) {
1391                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1392                                                         `body` = '', `title` = ''
1393                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
1394                                                         dbesc($when),
1395                                                         dbesc(datetime_convert()),
1396                                                         dbesc($item['uri']),
1397                                                         intval($importer['uid'])
1398                                                 );
1399                                         }
1400                                         else {
1401                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1402                                                         `body` = '', `title` = '' 
1403                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1404                                                         dbesc($when),
1405                                                         dbesc(datetime_convert()),
1406                                                         dbesc($uri),
1407                                                         intval($importer['uid'])
1408                                                 );
1409                                                 if($item['last-child']) {
1410                                                         // ensure that last-child is set in case the comment that had it just got wiped.
1411                                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1412                                                                 dbesc(datetime_convert()),
1413                                                                 dbesc($item['parent-uri']),
1414                                                                 intval($item['uid'])
1415                                                         );
1416                                                         // who is the last child now? 
1417                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d 
1418                                                                 ORDER BY `created` DESC LIMIT 1",
1419                                                                         dbesc($item['parent-uri']),
1420                                                                         intval($importer['uid'])
1421                                                         );
1422                                                         if(count($r)) {
1423                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1424                                                                         intval($r[0]['id'])
1425                                                                 );
1426                                                         }
1427                                                 }       
1428                                         }
1429                                 }       
1430                         }
1431                 }
1432         }
1433
1434         // Now process the feed
1435
1436         if($feed->get_item_quantity()) {                
1437
1438                 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1439
1440         // in inverse date order
1441                 if ($datedir)
1442                         $items = array_reverse($feed->get_items());
1443                 else
1444                         $items = $feed->get_items();
1445
1446
1447                 foreach($items as $item) {
1448
1449                         $is_reply = false;              
1450                         $item_id = $item->get_id();
1451                         $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1452                         if(isset($rawthread[0]['attribs']['']['ref'])) {
1453                                 $is_reply = true;
1454                                 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1455                         }
1456
1457                         if(($is_reply) && is_array($contact)) {
1458
1459                                 if($pass == 1)
1460                                         continue;
1461
1462                                 // Have we seen it? If not, import it.
1463         
1464                                 $item_id  = $item->get_id();
1465                                 $datarray = get_atom_elements($feed,$item);
1466
1467                                 if(! x($datarray,'author-name'))
1468                                         $datarray['author-name'] = $contact['name'];
1469                                 if(! x($datarray,'author-link'))
1470                                         $datarray['author-link'] = $contact['url'];
1471                                 if(! x($datarray,'author-avatar'))
1472                                         $datarray['author-avatar'] = $contact['thumb'];
1473
1474
1475                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1476                                         dbesc($item_id),
1477                                         intval($importer['uid'])
1478                                 );
1479
1480                                 // Update content if 'updated' changes
1481
1482                                 if(count($r)) {
1483                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1484                                                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1485                                                         dbesc($datarray['body']),
1486                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1487                                                         dbesc($item_id),
1488                                                         intval($importer['uid'])
1489                                                 );
1490                                         }
1491
1492                                         // update last-child if it changes
1493
1494                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1495                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1496                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1497                                                         dbesc(datetime_convert()),
1498                                                         dbesc($parent_uri),
1499                                                         intval($importer['uid'])
1500                                                 );
1501                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1502                                                         intval($allow[0]['data']),
1503                                                         dbesc(datetime_convert()),
1504                                                         dbesc($item_id),
1505                                                         intval($importer['uid'])
1506                                                 );
1507                                         }
1508                                         continue;
1509                                 }
1510
1511                                 $force_parent = false;
1512                                 if($contact['network'] === NETWORK_OSTATUS) {
1513                                         $force_parent = true;
1514                                         if(strlen($datarray['title']))
1515                                                 unset($datarray['title']);
1516                                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1517                                                 dbesc(datetime_convert()),
1518                                                 dbesc($parent_uri),
1519                                                 intval($importer['uid'])
1520                                         );
1521                                         $datarray['last-child'] = 1;
1522                                 }
1523
1524                                 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1525                                         // one way feed - no remote comment ability
1526                                         $datarray['last-child'] = 0;
1527                                 }
1528                                 $datarray['parent-uri'] = $parent_uri;
1529                                 $datarray['uid'] = $importer['uid'];
1530                                 $datarray['contact-id'] = $contact['id'];
1531                                 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1532                                         $datarray['type'] = 'activity';
1533                                         $datarray['gravity'] = GRAVITY_LIKE;
1534                                 }
1535
1536                                 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1537                                         $xo = parse_xml_string($datarray['object'],false);
1538                                         $xt = parse_xml_string($datarray['target'],false);
1539
1540                                         if($xt->type == ACTIVITY_OBJ_NOTE) {
1541                                                 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
1542                                                         dbesc($xt->id),
1543                                                         intval($importer['importer_uid'])
1544                                                 );
1545                                                 if(! count($r))
1546                                                         continue;
1547
1548                                                 // extract tag, if not duplicate, add to parent item
1549                                                 if($xo->id && $xo->content) {
1550                                                         $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
1551                                                         if(! (stristr($r[0]['tag'],$newtag))) {
1552                                                                 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
1553                                                                         dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
1554                                                                         intval($r[0]['id'])
1555                                                                 );
1556                                                         }
1557                                                 }
1558                                         }
1559                                 }
1560
1561                                 $r = item_store($datarray,$force_parent);
1562                                 continue;
1563                         }
1564
1565                         else {
1566
1567                                 // Head post of a conversation. Have we seen it? If not, import it.
1568
1569                                 $item_id  = $item->get_id();
1570
1571                                 $datarray = get_atom_elements($feed,$item);
1572
1573                                 if(is_array($contact)) {
1574                                         if(! x($datarray,'author-name'))
1575                                                 $datarray['author-name'] = $contact['name'];
1576                                         if(! x($datarray,'author-link'))
1577                                                 $datarray['author-link'] = $contact['url'];
1578                                         if(! x($datarray,'author-avatar'))
1579                                                 $datarray['author-avatar'] = $contact['thumb'];
1580                                 }
1581
1582                                 // special handling for events
1583
1584                                 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1585                                         $ev = bbtoevent($datarray['body']);
1586                                         if(x($ev,'desc') && x($ev,'start')) {
1587                                                 $ev['uid'] = $importer['uid'];
1588                                                 $ev['uri'] = $item_id;
1589                                                 $ev['edited'] = $datarray['edited'];
1590                                                 $ev['private'] = $datarray['private'];
1591
1592                                                 if(is_array($contact))
1593                                                         $ev['cid'] = $contact['id'];
1594                                                 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1595                                                         dbesc($item_id),
1596                                                         intval($importer['uid'])
1597                                                 );
1598                                                 if(count($r))
1599                                                         $ev['id'] = $r[0]['id'];
1600                                                 $xyz = event_store($ev);
1601                                                 continue;
1602                                         }
1603                                 }
1604
1605                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1606                                         dbesc($item_id),
1607                                         intval($importer['uid'])
1608                                 );
1609
1610                                 // Update content if 'updated' changes
1611
1612                                 if(count($r)) {
1613                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1614                                                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1615                                                         dbesc($datarray['body']),
1616                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1617                                                         dbesc($item_id),
1618                                                         intval($importer['uid'])
1619                                                 );
1620                                         }
1621
1622                                         // update last-child if it changes
1623
1624                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1625                                         if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1626                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1627                                                         intval($allow[0]['data']),
1628                                                         dbesc(datetime_convert()),
1629                                                         dbesc($item_id),
1630                                                         intval($importer['uid'])
1631                                                 );
1632                                         }
1633                                         continue;
1634                                 }
1635
1636                                 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1637                                         logger('consume-feed: New follower');
1638                                         new_follower($importer,$contact,$datarray,$item);
1639                                         return;
1640                                 }
1641                                 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW))  {
1642                                         lose_follower($importer,$contact,$datarray,$item);
1643                                         return;
1644                                 }
1645
1646                                 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
1647                                         logger('consume-feed: New friend request');
1648                                         new_follower($importer,$contact,$datarray,$item,true);
1649                                         return;
1650                                 }
1651                                 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND))  {
1652                                         lose_sharer($importer,$contact,$datarray,$item);
1653                                         return;
1654                                 }
1655
1656
1657                                 if(! is_array($contact))
1658                                         return;
1659
1660                                 if($contact['network'] === NETWORK_OSTATUS || stristr($permalink,'twitter.com')) {
1661                                         if(strlen($datarray['title']))
1662                                                 unset($datarray['title']);
1663                                         $datarray['last-child'] = 1;
1664                                 }
1665
1666                                 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1667                                         // one way feed - no remote comment ability
1668                                         $datarray['last-child'] = 0;
1669                                 }
1670
1671                                 // This is my contact on another system, but it's really me.
1672                                 // Turn this into a wall post.
1673
1674                                 if($contact['remote_self'])
1675                                         $datarray['wall'] = 1;
1676
1677                                 $datarray['parent-uri'] = $item_id;
1678                                 $datarray['uid'] = $importer['uid'];
1679                                 $datarray['contact-id'] = $contact['id'];
1680                                 $r = item_store($datarray);
1681                                 continue;
1682
1683                         }
1684                 }
1685         }
1686 }
1687
1688 function local_delivery($importer,$data) {
1689
1690         $a = get_app();
1691
1692         if($importer['readonly']) {
1693                 // We aren't receiving stuff from this person. But we will quietly ignore them
1694                 // rather than a blatant "go away" message.
1695                 logger('local_delivery: ignoring');
1696                 return 0;
1697                 //NOTREACHED
1698         }
1699
1700         // Consume notification feed. This may differ from consuming a public feed in several ways
1701         // - might contain email or friend suggestions
1702         // - might contain remote followup to our message
1703         //              - in which case we need to accept it and then notify other conversants
1704         // - we may need to send various email notifications
1705
1706         $feed = new SimplePie();
1707         $feed->set_raw_data($data);
1708         $feed->enable_order_by_date(false);
1709         $feed->init();
1710
1711         $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
1712         if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
1713                 $base = $reloc[0]['child'][NAMESPACE_DFRN];
1714                 $newloc = array();
1715                 $newloc['uid'] = $importer['importer_uid'];
1716                 $newloc['cid'] = $importer['id'];
1717                 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
1718                 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
1719                 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
1720                 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
1721                 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
1722                 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
1723                 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
1724                 $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data']));
1725                 $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
1726                 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));
1727                 
1728                 // TODO
1729                 // merge with current record, current contents have priority
1730                 // update record, set url-updated
1731                 // update profile photos
1732                 // schedule a scan?
1733
1734         }
1735
1736         // handle friend suggestion notification
1737
1738         $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
1739         if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
1740                 $base = $sugg[0]['child'][NAMESPACE_DFRN];
1741                 $fsugg = array();
1742                 $fsugg['uid'] = $importer['importer_uid'];
1743                 $fsugg['cid'] = $importer['id'];
1744                 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
1745                 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
1746                 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
1747                 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
1748                 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
1749
1750                 // Does our member already have a friend matching this description?
1751
1752                 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1753                         dbesc($fsugg['name']),
1754                         dbesc(normalise_link($fsugg['url'])),
1755                         intval($fsugg['uid'])
1756                 );
1757                 if(count($r))
1758                         return 0;
1759
1760                 // Do we already have an fcontact record for this person?
1761
1762                 $fid = 0;
1763                 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1764                         dbesc($fsugg['url']),
1765                         dbesc($fsugg['name']),
1766                         dbesc($fsugg['request'])
1767                 );
1768                 if(count($r)) {
1769                         $fid = $r[0]['id'];
1770                 }
1771                 if(! $fid)
1772                         $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
1773                         dbesc($fsugg['name']),
1774                         dbesc($fsugg['url']),
1775                         dbesc($fsugg['photo']),
1776                         dbesc($fsugg['request'])
1777                 );
1778                 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1779                         dbesc($fsugg['url']),
1780                         dbesc($fsugg['name']),
1781                         dbesc($fsugg['request'])
1782                 );
1783                 if(count($r)) {
1784                         $fid = $r[0]['id'];
1785                 }
1786                 // database record did not get created. Quietly give up.
1787                 else
1788                         return 0;
1789
1790                 $hash = random_string();
1791  
1792                 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
1793                         VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
1794                         intval($fsugg['uid']),
1795                         intval($fid),
1796                         intval($fsugg['cid']),
1797                         dbesc($fsugg['body']),
1798                         dbesc($hash),
1799                         dbesc(datetime_convert()),
1800                         intval(0)
1801                 );
1802
1803                 notification(array(
1804                         'type'         => NOTIFY_SUGGEST,
1805                         'notify_flags' => $importer['notify-flags'],
1806                         'language'     => $importer['language'],
1807                         'to_name'      => $importer['username'],
1808                         'to_email'     => $importer['email'],
1809                         'item'         => $fsugg,
1810                         'link'         => $a->get_baseurl() . '/notifications/intros',
1811                         'source_name'  => $importer['name'],
1812                         'source_link'  => $importer['url'],
1813                         'source_photo' => $importer['photo'],
1814                         'verb'         => ACTIVITY_REQ_FRIEND,
1815                         'otype'        => 'intro'
1816                 ));
1817
1818                 return 0;
1819         }
1820
1821         $ismail = false;
1822
1823         $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
1824         if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
1825
1826                 logger('local_delivery: private message received');
1827
1828                 $ismail = true;
1829                 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
1830
1831                 $msg = array();
1832                 $msg['uid'] = $importer['importer_uid'];
1833                 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
1834                 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
1835                 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
1836                 $msg['contact-id'] = $importer['id'];
1837                 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
1838                 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
1839                 $msg['seen'] = 0;
1840                 $msg['replied'] = 0;
1841                 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
1842                 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
1843                 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
1844                 
1845                 dbesc_array($msg);
1846
1847                 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg)) 
1848                         . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
1849
1850                 // send notifications.
1851
1852                 require_once('include/enotify.php');
1853
1854                 $notif_params = array(
1855                         'type' => NOTIFY_MAIL,
1856                         'notify_flags' => $importer['notify-flags'],
1857                         'language' => $importer['language'],
1858                         'to_name' => $importer['username'],
1859                         'to_email' => $importer['email'],
1860                         'item' => $msg,
1861                         'source_name' => $msg['from-name'],
1862                         'source_link' => $importer['url'],
1863                         'source_photo' => $importer['thumb'],
1864                         'verb' => ACTIVITY_POST,
1865                         'otype' => 'mail'
1866                 );
1867                         
1868                 notification($notif_params);
1869                 return 0;
1870
1871                 // NOTREACHED
1872         }       
1873         
1874         logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
1875
1876         // process any deleted entries
1877
1878         $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1879         if(is_array($del_entries) && count($del_entries)) {
1880                 foreach($del_entries as $dentry) {
1881                         $deleted = false;
1882                         if(isset($dentry['attribs']['']['ref'])) {
1883                                 $uri = $dentry['attribs']['']['ref'];
1884                                 $deleted = true;
1885                                 if(isset($dentry['attribs']['']['when'])) {
1886                                         $when = $dentry['attribs']['']['when'];
1887                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1888                                 }
1889                                 else
1890                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1891                         }
1892                         if($deleted) {
1893
1894                                 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
1895                                         WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d LIMIT 1",
1896                                         dbesc($uri),
1897                                         intval($importer['importer_uid']),
1898                                         intval($importer['id'])
1899                                 );
1900
1901                                 if(count($r)) {
1902                                         $item = $r[0];
1903
1904                                         if($item['deleted'])
1905                                                 continue;
1906
1907                                         logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1908
1909                                         if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTVITY_OBJ_TAGTERM)) {
1910                                                 $xo = parse_xml_string($item['object'],false);
1911                                                 $xt = parse_xml_string($item['target'],false);
1912                                                 if($xt->type === ACTIVITY_OBJ_NOTE) {
1913                                                         $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1914                                                                 dbesc($xt->id),
1915                                                                 intval($importer['importer_uid'])
1916                                                         );
1917                                                         if(count($i)) {
1918
1919                                                                 // For tags, the owner cannot remove the tag on the author's copy of the post.
1920                                                                 
1921                                                                 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1922                                                                 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1923                                                                 $author_copy = (($item['origin']) ? true : false); 
1924
1925                                                                 if($owner_remove && $author_copy)
1926                                                                         continue;
1927                                                                 if($author_remove || $owner_remove) {                                                           
1928                                                                         $tags = explode(',',$i[0]['tag']);
1929                                                                         $newtags = array();
1930                                                                         if(count($tags)) {
1931                                                                                 foreach($tags as $tag)
1932                                                                                         if(trim($tag) !== trim($xo->body))
1933                                                                                                 $newtags[] = trim($tag);
1934                                                                         }
1935                                                                         q("update item set tag = '%s' where id = %d limit 1",
1936                                                                                 dbesc(implode(',',$newtags)),
1937                                                                                 intval($i[0]['id'])
1938                                                                         );
1939                                                                 }
1940                                                         }
1941                                                 }
1942                                         }
1943
1944                                         if($item['uri'] == $item['parent-uri']) {
1945                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
1946                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
1947                                                         dbesc($when),
1948                                                         dbesc(datetime_convert()),
1949                                                         dbesc($item['uri']),
1950                                                         intval($importer['importer_uid'])
1951                                                 );
1952                                         }
1953                                         else {
1954                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' 
1955                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1956                                                         dbesc($when),
1957                                                         dbesc(datetime_convert()),
1958                                                         dbesc($uri),
1959                                                         intval($importer['importer_uid'])
1960                                                 );
1961                                                 if($item['last-child']) {
1962                                                         // ensure that last-child is set in case the comment that had it just got wiped.
1963                                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1964                                                                 dbesc(datetime_convert()),
1965                                                                 dbesc($item['parent-uri']),
1966                                                                 intval($item['uid'])
1967                                                         );
1968                                                         // who is the last child now? 
1969                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
1970                                                                 ORDER BY `created` DESC LIMIT 1",
1971                                                                         dbesc($item['parent-uri']),
1972                                                                         intval($importer['importer_uid'])
1973                                                         );
1974                                                         if(count($r)) {
1975                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1976                                                                         intval($r[0]['id'])
1977                                                                 );
1978                                                         }       
1979                                                 }
1980                                         }       
1981                                 }
1982                         }
1983                 }
1984         }
1985
1986
1987         foreach($feed->get_items() as $item) {
1988
1989                 $is_reply = false;              
1990                 $item_id = $item->get_id();
1991                 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
1992                 if(isset($rawthread[0]['attribs']['']['ref'])) {
1993                         $is_reply = true;
1994                         $parent_uri = $rawthread[0]['attribs']['']['ref'];
1995                 }
1996
1997                 if($is_reply) {
1998
1999                         $community = false;
2000
2001                         if($importer['page-flags'] == PAGE_COMMUNITY) {
2002                                 $sql_extra = '';
2003                                 $community = true;
2004                                 logger('local_delivery: community reply');
2005                         }
2006                         else
2007                                 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2008  
2009                         // was the top-level post for this reply written by somebody on this site? 
2010                         // Specifically, the recipient? 
2011
2012                         $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, 
2013                                 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item` 
2014                                 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id` 
2015                                 WHERE `item`.`uri` = '%s' AND `item`.`parent-uri` = '%s'
2016                                 AND `item`.`uid` = %d 
2017                                 $sql_extra
2018                                 LIMIT 1",
2019                                 dbesc($parent_uri),
2020                                 dbesc($parent_uri),
2021                                 intval($importer['importer_uid'])
2022                         );
2023
2024                         if($r && count($r)) {   
2025
2026                                 logger('local_delivery: received remote comment');
2027                                 $is_like = false;
2028                                 // remote reply to our post. Import and then notify everybody else.
2029                                 $datarray = get_atom_elements($feed,$item);
2030
2031
2032                 // TODO: make this next part work against both delivery threads of a community post
2033
2034 //                              if((! link_compare($datarray['author-link'],$importer['url'])) && (! $community)) {
2035 //                                      logger('local_delivery: received relay claiming to be from ' . $importer['url'] . ' however comment author url is ' . $datarray['author-link'] ); 
2036                                         // they won't know what to do so don't report an error. Just quietly die.
2037 //                                      return 0;
2038 //                              }                                       
2039
2040                                 $datarray['type'] = 'remote-comment';
2041                                 $datarray['wall'] = 1;
2042                                 $datarray['parent-uri'] = $parent_uri;
2043                                 $datarray['uid'] = $importer['importer_uid'];
2044                                 $datarray['owner-name'] = $r[0]['name'];
2045                                 $datarray['owner-link'] = $r[0]['url'];
2046                                 $datarray['owner-avatar'] = $r[0]['thumb'];
2047                                 $datarray['contact-id'] = $importer['id'];
2048                                 if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
2049                                         $is_like = true;
2050                                         $datarray['type'] = 'activity';
2051                                         $datarray['gravity'] = GRAVITY_LIKE;
2052                                         $datarray['last-child'] = 0;
2053                                 }
2054
2055                                 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2056
2057
2058                                         $xo = parse_xml_string($datarray['object'],false);
2059                                         $xt = parse_xml_string($datarray['target'],false);
2060
2061                                         if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id == $r[0]['uri'])) {
2062
2063                                                 // extract tag, if not duplicate, and this user allows tags, add to parent item                                         
2064
2065                                                 if($xo->id && $xo->content) {
2066                                                         $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2067
2068                                                         if(! (stristr($r[0]['tag'],$newtag))) {
2069                                                                 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
2070                                                                         intval($importer['importer_uid'])
2071                                                                 );
2072                                                                 if(count($i) && ! ($i[0]['blocktags'])) {
2073                                                                         q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2074                                                                                 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
2075                                                                                 intval($r[0]['id'])
2076                                                                         );
2077                                                                 }
2078                                                         }
2079                                                 }                                                                                                       
2080                                         }
2081                                 }
2082
2083 //                              if($community) {
2084 //                                      $newtag = '@[url=' . $a->get_baseurl() . '/profile/' . $importer['nickname'] . ']' . $importer['username'] . '[/url]';
2085 //                                      if(! stristr($datarray['tag'],$newtag)) {
2086 //                                              if(strlen($datarray['tag']))
2087 //                                                      $datarray['tag'] .= ',';
2088 //                                              $datarray['tag'] .= $newtag;
2089 //                                      }
2090 //                              }
2091
2092
2093                                 $posted_id = item_store($datarray);
2094                                 $parent = 0;
2095
2096                                 if($posted_id) {
2097                                         $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2098                                                 intval($posted_id),
2099                                                 intval($importer['importer_uid'])
2100                                         );
2101                                         if(count($r))
2102                                                 $parent = $r[0]['parent'];
2103                         
2104                                         if(! $is_like) {
2105                                                 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2106                                                         dbesc(datetime_convert()),
2107                                                         intval($importer['importer_uid']),
2108                                                         intval($r[0]['parent'])
2109                                                 );
2110
2111                                                 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2112                                                         dbesc(datetime_convert()),
2113                                                         intval($importer['importer_uid']),
2114                                                         intval($posted_id)
2115                                                 );
2116                                         }
2117
2118                                         if($posted_id && $parent) {
2119                                 
2120                                                 proc_run('php',"include/notifier.php","comment-import","$posted_id");
2121                                         
2122                                                 if((! $is_like) && (! $importer['self'])) {
2123
2124                                                         require_once('include/enotify.php');
2125
2126                                                         notification(array(
2127                                                                 'type'         => NOTIFY_COMMENT,
2128                                                                 'notify_flags' => $importer['notify-flags'],
2129                                                                 'language'     => $importer['language'],
2130                                                                 'to_name'      => $importer['username'],
2131                                                                 'to_email'     => $importer['email'],
2132                                                                 'item'         => $datarray,
2133                                                                 'link'             => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2134                                                                 'source_name'  => stripslashes($datarray['author-name']),
2135                                                                 'source_link'  => $datarray['author-link'],
2136                                                                 'source_photo' => ((link_compare($datarray['author-link'],$importer['url'])) 
2137                                                                         ? $importer['thumb'] : $datarray['author-avatar']),
2138                                                                 'verb'         => ACTIVITY_POST,
2139                                                                 'otype'        => 'item'
2140
2141                                                         ));
2142
2143                                                 }
2144                                         }
2145                                         return 0;
2146                                         // NOTREACHED
2147                                 }
2148                         }
2149                         else {
2150
2151                                 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
2152
2153                                 $item_id  = $item->get_id();
2154                                 $datarray = get_atom_elements($feed,$item);
2155
2156                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2157                                         dbesc($item_id),
2158                                         intval($importer['importer_uid'])
2159                                 );
2160
2161                                 // Update content if 'updated' changes
2162
2163                                 if(count($r)) {
2164                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
2165                                                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2166                                                         dbesc($datarray['body']),
2167                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2168                                                         dbesc($item_id),
2169                                                         intval($importer['importer_uid'])
2170                                                 );
2171                                         }
2172
2173                                         // update last-child if it changes
2174
2175                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2176                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
2177                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2178                                                         dbesc(datetime_convert()),
2179                                                         dbesc($parent_uri),
2180                                                         intval($importer['importer_uid'])
2181                                                 );
2182                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2183                                                         intval($allow[0]['data']),
2184                                                         dbesc(datetime_convert()),
2185                                                         dbesc($item_id),
2186                                                         intval($importer['importer_uid'])
2187                                                 );
2188                                         }
2189                                         continue;
2190                                 }
2191
2192                                 $datarray['parent-uri'] = $parent_uri;
2193                                 $datarray['uid'] = $importer['importer_uid'];
2194                                 $datarray['contact-id'] = $importer['id'];
2195                                 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
2196                                         $datarray['type'] = 'activity';
2197                                         $datarray['gravity'] = GRAVITY_LIKE;
2198                                 }
2199
2200                                 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2201
2202                                         $xo = parse_xml_string($datarray['object'],false);
2203                                         $xt = parse_xml_string($datarray['target'],false);
2204
2205                                         if($xt->type == ACTIVITY_OBJ_NOTE) {
2206                                                 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2207                                                         dbesc($xt->id),
2208                                                         intval($importer['importer_uid'])
2209                                                 );
2210                                                 if(! count($r))
2211                                                         continue;                               
2212
2213                                                 // extract tag, if not duplicate, add to parent item                                            
2214                                                 if($xo->content) {
2215                                                         if(! (stristr($r[0]['tag'],trim($xo->content)))) {
2216                                                                 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2217                                                                         dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2218                                                                         intval($r[0]['id'])
2219                                                                 );
2220                                                         }
2221                                                 }                                                                                                       
2222                                         }
2223                                 }
2224
2225                                 $posted_id = item_store($datarray);
2226
2227                                 // find out if our user is involved in this conversation and wants to be notified.
2228                         
2229                                 if($datarray['type'] != 'activity') {
2230
2231                                         $myconv = q("SELECT `author-link`, `author-avatar` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 ",
2232                                                 dbesc($parent_uri),
2233                                                 intval($importer['importer_uid'])
2234                                         );
2235
2236                                         if(count($myconv)) {
2237                                                 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
2238                                                 foreach($myconv as $conv) {
2239
2240                                                         if(! link_compare($conv['author-link'],$importer_url))
2241                                                                 continue;
2242
2243                                                         require_once('include/enotify.php');
2244
2245                                                         notification(array(
2246                                                                 'type'         => NOTIFY_COMMENT,
2247                                                                 'notify_flags' => $importer['notify-flags'],
2248                                                                 'language'     => $importer['language'],
2249                                                                 'to_name'      => $importer['username'],
2250                                                                 'to_email'     => $importer['email'],
2251                                                                 'item'         => $datarray,
2252                                                                 'link'             => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2253                                                                 'source_name'  => stripslashes($datarray['author-name']),
2254                                                                 'source_link'  => $datarray['author-link'],
2255                                                                 'source_photo' => ((link_compare($datarray['author-link'],$importer['url'])) 
2256                                                                         ? $importer['thumb'] : $datarray['author-avatar']),
2257                                                                 'verb'         => ACTIVITY_POST,
2258                                                                 'otype'        => 'item'
2259
2260                                                         ));
2261
2262                                                         break;
2263                                                 }
2264                                         }
2265                                 }
2266                                 continue;
2267                         }
2268                 }
2269
2270                 else {
2271
2272                         // Head post of a conversation. Have we seen it? If not, import it.
2273
2274
2275                         $item_id  = $item->get_id();
2276                         $datarray = get_atom_elements($feed,$item);
2277
2278                         if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
2279                                 $ev = bbtoevent($datarray['body']);
2280                                 if(x($ev,'desc') && x($ev,'start')) {
2281                                         $ev['cid'] = $importer['id'];
2282                                         $ev['uid'] = $importer['uid'];
2283                                         $ev['uri'] = $item_id;
2284                                         $ev['edited'] = $datarray['edited'];
2285                                         $ev['private'] = $datarray['private'];
2286
2287                                         $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2288                                                 dbesc($item_id),
2289                                                 intval($importer['uid'])
2290                                         );
2291                                         if(count($r))
2292                                                 $ev['id'] = $r[0]['id'];
2293                                         $xyz = event_store($ev);
2294                                         continue;
2295                                 }
2296                         }
2297
2298                         $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2299                                 dbesc($item_id),
2300                                 intval($importer['importer_uid'])
2301                         );
2302
2303                         // Update content if 'updated' changes
2304
2305                         if(count($r)) {
2306                                 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
2307                                         $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2308                                                 dbesc($datarray['body']),
2309                                                 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2310                                                 dbesc($item_id),
2311                                                 intval($importer['importer_uid'])
2312                                         );
2313                                 }
2314
2315                                 // update last-child if it changes
2316
2317                                 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2318                                 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2319                                         $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2320                                                 intval($allow[0]['data']),
2321                                                 dbesc(datetime_convert()),
2322                                                 dbesc($item_id),
2323                                                 intval($importer['importer_uid'])
2324                                         );
2325                                 }
2326                                 continue;
2327                         }
2328
2329                         // This is my contact on another system, but it's really me.
2330                         // Turn this into a wall post.
2331
2332                         if($contact['remote_self'])
2333                                 $datarray['wall'] = 1;
2334
2335                         $datarray['parent-uri'] = $item_id;
2336                         $datarray['uid'] = $importer['importer_uid'];
2337                         $datarray['contact-id'] = $importer['id'];
2338                         $r = item_store($datarray);
2339                         continue;
2340                 }
2341         }
2342
2343         return 0;
2344         // NOTREACHED
2345
2346 }
2347
2348
2349 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
2350         $url = notags(trim($datarray['author-link']));
2351         $name = notags(trim($datarray['author-name']));
2352         $photo = notags(trim($datarray['author-avatar']));
2353
2354         $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
2355         if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
2356                 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
2357
2358         if(is_array($contact)) {
2359                 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
2360                         || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
2361                         $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
2362                                 intval(CONTACT_IS_FRIEND),
2363                                 intval($contact['id']),
2364                                 intval($importer['uid'])
2365                         );
2366                 }
2367                 // send email notification to owner?
2368         }
2369         else {
2370         
2371                 // create contact record
2372
2373                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`, 
2374                         `blocked`, `readonly`, `pending`, `writable` )
2375                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
2376                         intval($importer['uid']),
2377                         dbesc(datetime_convert()),
2378                         dbesc($url),
2379                         dbesc(normalise_link($url)),
2380                         dbesc($name),
2381                         dbesc($nick),
2382                         dbesc($photo),
2383                         dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
2384                         intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
2385                 );
2386                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
2387                                 intval($importer['uid']),
2388                                 dbesc($url)
2389                 );
2390                 if(count($r))
2391                                 $contact_record = $r[0];
2392
2393                 // create notification  
2394                 $hash = random_string();
2395
2396                 if(is_array($contact_record)) {
2397                         $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
2398                                 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
2399                                 intval($importer['uid']),
2400                                 intval($contact_record['id']),
2401                                 dbesc($hash),
2402                                 dbesc(datetime_convert())
2403                         );
2404                 }
2405                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
2406                         intval($importer['uid'])
2407                 );
2408                 $a = get_app();
2409                 if(count($r)) {
2410                         if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
2411                                 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
2412                                 $email = replace_macros($email_tpl, array(
2413                                         '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
2414                                         '$url' => $url,
2415                                         '$myname' => $r[0]['username'],
2416                                         '$siteurl' => $a->get_baseurl(),
2417                                         '$sitename' => $a->config['sitename']
2418                                 ));
2419                                 $res = mail($r[0]['email'], 
2420                                         (($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],
2421                                         $email,
2422                                         'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
2423                                         . 'Content-type: text/plain; charset=UTF-8' . "\n"
2424                                         . 'Content-transfer-encoding: 8bit' );
2425                         
2426                         }
2427                 }
2428         }
2429 }
2430
2431 function lose_follower($importer,$contact,$datarray,$item) {
2432
2433         if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
2434                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2435                         intval(CONTACT_IS_SHARING),
2436                         intval($contact['id'])
2437                 );
2438         }
2439         else {
2440                 contact_remove($contact['id']);
2441         }
2442 }
2443
2444 function lose_sharer($importer,$contact,$datarray,$item) {
2445
2446         if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
2447                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2448                         intval(CONTACT_IS_FOLLOWER),
2449                         intval($contact['id'])
2450                 );
2451         }
2452         else {
2453                 contact_remove($contact['id']);
2454         }
2455 }
2456
2457
2458 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
2459
2460         if(is_array($importer)) {
2461                 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
2462                         intval($importer['uid'])
2463                 );
2464         }
2465
2466         // Diaspora has different message-ids in feeds than they do 
2467         // through the direct Diaspora protocol. If we try and use
2468         // the feed, we'll get duplicates. So don't.
2469
2470         if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
2471                 return;
2472
2473         $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
2474
2475         // Use a single verify token, even if multiple hubs
2476
2477         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
2478
2479         $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
2480
2481         logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: '  . $push_url . ' with verifier ' . $verify_token);
2482
2483         if(! strlen($contact['hub-verify'])) {
2484                 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
2485                         dbesc($verify_token),
2486                         intval($contact['id'])
2487                 );
2488         }
2489
2490         post_url($url,$params);                 
2491         return;
2492
2493 }
2494
2495
2496 function atom_author($tag,$name,$uri,$h,$w,$photo) {
2497         $o = '';
2498         if(! $tag)
2499                 return $o;
2500         $name = xmlify($name);
2501         $uri = xmlify($uri);
2502         $h = intval($h);
2503         $w = intval($w);
2504         $photo = xmlify($photo);
2505
2506
2507         $o .= "<$tag>\r\n";
2508         $o .= "<name>$name</name>\r\n";
2509         $o .= "<uri>$uri</uri>\r\n";
2510         $o .= '<link rel="photo"  type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2511         $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2512
2513         call_hooks('atom_author', $o);
2514
2515         $o .= "</$tag>\r\n";
2516         return $o;
2517 }
2518
2519 function atom_entry($item,$type,$author,$owner,$comment = false) {
2520
2521         $a = get_app();
2522
2523         if(! $item['parent'])
2524                 return;
2525
2526         if($item['deleted'])
2527                 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
2528
2529
2530         if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
2531                 $body = fix_private_photos($item['body'],$owner['uid']);
2532         else
2533                 $body = $item['body'];
2534
2535
2536         $o = "\r\n\r\n<entry>\r\n";
2537
2538         if(is_array($author))
2539                 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
2540         else
2541                 $o .= atom_author('author',(($item['author-name']) ? $item['author-name'] : $item['name']),(($item['author-link']) ? $item['author-link'] : $item['url']),80,80,(($item['author-avatar']) ? $item['author-avatar'] : $item['thumb']));
2542         if(strlen($item['owner-name']))
2543                 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
2544
2545         if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']))
2546                 $o .= '<thr:in-reply-to ref="' . xmlify($item['parent-uri']) . '" type="text/html" href="' .  xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['parent']) . '" />' . "\r\n";
2547
2548         $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
2549         $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
2550         $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
2551         $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
2552         $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
2553         $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
2554         $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
2555         if($comment)
2556                 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
2557
2558         if($item['location']) {
2559                 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
2560                 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
2561         }
2562
2563         if($item['coord'])
2564                 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
2565
2566         if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
2567                 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
2568
2569         if($item['extid'])
2570                 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
2571         if($item['bookmark'])
2572                 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
2573
2574         if($item['app'])
2575                 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
2576
2577         if($item['guid'])
2578                 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
2579
2580         if($item['signed_text']) {
2581                 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
2582                 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
2583         }
2584
2585         $verb = construct_verb($item);
2586         $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
2587         $actobj = construct_activity_object($item);
2588         if(strlen($actobj))
2589                 $o .= $actobj;
2590         $actarg = construct_activity_target($item);
2591         if(strlen($actarg))
2592                 $o .= $actarg;
2593
2594         $tags = item_getfeedtags($item);
2595         if(count($tags)) {
2596                 foreach($tags as $t) {
2597                         $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
2598                 }
2599         }
2600
2601         $o .= item_getfeedattach($item);
2602
2603         $mentioned = get_mentions($item);
2604         if($mentioned)
2605                 $o .= $mentioned;
2606         
2607         call_hooks('atom_entry', $o);
2608
2609         $o .= '</entry>' . "\r\n";
2610         
2611         return $o;
2612 }
2613
2614 function fix_private_photos($s,$uid) {
2615         $a = get_app();
2616         logger('fix_private_photos');
2617
2618         if(preg_match("/\[img\](.*?)\[\/img\]/is",$s,$matches)) {
2619                 $image = $matches[1];
2620                 logger('fix_private_photos: found photo ' . $image);
2621                 if(stristr($image ,$a->get_baseurl() . '/photo/')) {
2622                         $i = basename($image);
2623                         $i = str_replace('.jpg','',$i);
2624                         $x = strpos($i,'-');
2625                         if($x) {
2626                                 $res = substr($i,$x+1);
2627                                 $i = substr($i,0,$x);
2628                                 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
2629                                         dbesc($i),
2630                                         intval($res),
2631                                         intval($uid)
2632                                 );
2633                                 if(count($r)) {
2634                                         logger('replacing photo');
2635                                         $s = str_replace($image, 'data:image/jpg;base64,' . base64_encode($r[0]['data']), $s);
2636                                 }
2637                         }
2638                         logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
2639                 }       
2640         }
2641         return($s);
2642 }
2643
2644
2645
2646 function item_getfeedtags($item) {
2647         $ret = array();
2648         $matches = false;
2649         $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
2650         if($cnt) {
2651                 for($x = 0; $x < $cnt; $x ++) {
2652                         if($matches[1][$x])
2653                                 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
2654                 }
2655         }
2656         $matches = false; 
2657         $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
2658         if($cnt) {
2659                 for($x = 0; $x < $cnt; $x ++) {
2660                         if($matches[1][$x])
2661                                 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
2662                 }
2663         } 
2664         return $ret;
2665 }
2666
2667 function item_getfeedattach($item) {
2668         $ret = '';
2669         $arr = explode(',',$item['attach']);
2670         if(count($arr)) {
2671                 foreach($arr as $r) {
2672                         $matches = false;
2673                         $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
2674                         if($cnt) {
2675                                 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
2676                                 if(intval($matches[2]))
2677                                         $ret .= 'length="' . intval($matches[2]) . '" ';
2678                                 if($matches[4] !== ' ')
2679                                         $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
2680                                 $ret .= ' />' . "\r\n";
2681                         }
2682                 }
2683         }
2684         return $ret;
2685 }
2686
2687
2688         
2689 function item_expire($uid,$days) {
2690
2691         if((! $uid) || (! $days))
2692                 return;
2693
2694         $r = q("SELECT * FROM `item` 
2695                 WHERE `uid` = %d 
2696                 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY 
2697                 AND `id` = `parent` 
2698                 AND `deleted` = 0",
2699                 intval($uid),
2700                 intval($days)
2701         );
2702
2703         if(! count($r))
2704                 return;
2705
2706         $expire_items = get_pconfig($uid, 'expire','items');
2707         $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
2708         
2709         $expire_notes = get_pconfig($uid, 'expire','notes');
2710         $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
2711
2712         $expire_starred = get_pconfig($uid, 'expire','starred');
2713         $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
2714         
2715         $expire_photos = get_pconfig($uid, 'expire','photos');
2716         $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
2717  
2718         logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2719
2720         foreach($r as $item) {
2721
2722                 // Only expire posts, not photos and photo comments
2723
2724                 if($expire_photos==0 && strlen($item['resource-id']))
2725                         continue;
2726                 if($expire_starred==0 && intval($item['starred']))
2727                         continue;
2728                 if($expire_notes==0 && $item['type']=='note')
2729                         continue;
2730                 if($expire_items==0 && $item['type']!='note')
2731                         continue;
2732
2733                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
2734                         dbesc(datetime_convert()),
2735                         dbesc(datetime_convert()),
2736                         intval($item['id'])
2737                 );
2738
2739                 // kill the kids
2740
2741                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2742                         dbesc(datetime_convert()),
2743                         dbesc(datetime_convert()),
2744                         dbesc($item['parent-uri']),
2745                         intval($item['uid'])
2746                 );
2747
2748         }
2749
2750         proc_run('php',"include/notifier.php","expire","$uid");
2751         
2752 }
2753
2754
2755 function drop_items($items) {
2756         $uid = 0;
2757
2758         if(count($items)) {
2759                 foreach($items as $item) {
2760                         $owner = drop_item($item,false);
2761                         if($owner && ! $uid)
2762                                 $uid = $owner;
2763                 }
2764         }
2765
2766         // multiple threads may have been deleted, send an expire notification
2767
2768         if($uid)
2769                 proc_run('php',"include/notifier.php","expire","$uid");
2770 }
2771
2772
2773 function drop_item($id,$interactive = true) {
2774
2775         $a = get_app();
2776
2777         // locate item to be deleted
2778
2779         $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
2780                 intval($id)
2781         );
2782
2783         if(! count($r)) {
2784                 if(! $interactive)
2785                         return 0;
2786                 notice( t('Item not found.') . EOL);
2787                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
2788         }
2789
2790         $item = $r[0];
2791
2792         $owner = $item['uid'];
2793
2794         // check if logged in user is either the author or owner of this item
2795
2796         if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
2797
2798                 // delete the item
2799
2800                 $r = q("UPDATE `item` SET `deleted` = 1, `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
2801                         dbesc(datetime_convert()),
2802                         dbesc(datetime_convert()),
2803                         intval($item['id'])
2804                 );
2805
2806                 // If item is a link to a photo resource, nuke all the associated photos 
2807                 // (visitors will not have photo resources)
2808                 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
2809                 // generate a resource-id and therefore aren't intimately linked to the item. 
2810
2811                 if(strlen($item['resource-id'])) {
2812                         q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
2813                                 dbesc($item['resource-id']),
2814                                 intval($item['uid'])
2815                         );
2816                         // ignore the result
2817                 }
2818
2819                 // If item is a link to an event, nuke the event record.
2820
2821                 if(intval($item['event-id'])) {
2822                         q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2823                                 intval($item['event-id']),
2824                                 intval($item['uid'])
2825                         );
2826                         // ignore the result
2827                 }
2828
2829
2830                 // If it's the parent of a comment thread, kill all the kids
2831
2832                 if($item['uri'] == $item['parent-uri']) {
2833                         $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' 
2834                                 WHERE `parent-uri` = '%s' AND `uid` = %d ",
2835                                 dbesc(datetime_convert()),
2836                                 dbesc(datetime_convert()),
2837                                 dbesc($item['parent-uri']),
2838                                 intval($item['uid'])
2839                         );
2840                         // ignore the result
2841                 }
2842                 else {
2843                         // ensure that last-child is set in case the comment that had it just got wiped.
2844                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2845                                 dbesc(datetime_convert()),
2846                                 dbesc($item['parent-uri']),
2847                                 intval($item['uid'])
2848                         );
2849                         // who is the last child now? 
2850                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d ORDER BY `edited` DESC LIMIT 1",
2851                                 dbesc($item['parent-uri']),
2852                                 intval($item['uid'])
2853                         );
2854                         if(count($r)) {
2855                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2856                                         intval($r[0]['id'])
2857                                 );
2858                         }       
2859                 }
2860                 $drop_id = intval($item['id']);
2861                         
2862                 // send the notification upstream/downstream as the case may be
2863
2864                 if(! $interactive)
2865                         return $owner;
2866
2867                 proc_run('php',"include/notifier.php","drop","$drop_id");
2868                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
2869                 //NOTREACHED
2870         }
2871         else {
2872                 if(! $interactive)
2873                         return 0;
2874                 notice( t('Permission denied.') . EOL);
2875                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
2876                 //NOTREACHED
2877         }
2878         
2879 }