]> git.mxchange.org Git - friendica.git/blob - include/items.php
4b1523ff65397c4ac84330002708ea10484716b9
[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`.`moderated` = 0 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(!x($res, 'author-avatar') || !$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(!x($res, 'author-avatar') || !$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(!x($res, 'owner-avatar') || !$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(x($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                 $parent_deleted = 0;
746                 $allow_cid = $arr['allow_cid'];
747                 $allow_gid = $arr['allow_gid'];
748                 $deny_cid  = $arr['deny_cid'];
749                 $deny_gid  = $arr['deny_gid'];
750         }
751         else { 
752
753                 // find the parent and snarf the item id and ACL's
754                 // and anything else we need to inherit
755
756                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
757                         dbesc($arr['parent-uri']),
758                         intval($arr['uid'])
759                 );
760
761                 if(count($r)) {
762
763                         // is the new message multi-level threaded?
764                         // even though we don't support it now, preserve the info
765                         // and re-attach to the conversation parent.
766
767                         if($r[0]['uri'] != $r[0]['parent-uri']) {
768                                 $arr['thr-parent'] = $arr['parent-uri'];
769                                 $arr['parent-uri'] = $r[0]['parent-uri'];
770                                 $z = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d 
771                                         ORDER BY `id` ASC LIMIT 1",
772                                         dbesc($r[0]['parent-uri']),
773                                         dbesc($r[0]['parent-uri']),
774                                         intval($arr['uid'])
775                                 );
776                                 if($z && count($z))
777                                         $r = $z;
778                         }
779
780                         $parent_id      = $r[0]['id'];
781                         $parent_deleted = $r[0]['deleted'];
782                         $allow_cid      = $r[0]['allow_cid'];
783                         $allow_gid      = $r[0]['allow_gid'];
784                         $deny_cid       = $r[0]['deny_cid'];
785                         $deny_gid       = $r[0]['deny_gid'];
786                         $arr['wall']    = $r[0]['wall'];
787                 }
788                 else {
789
790                         // Allow one to see reply tweets from status.net even when
791                         // we don't have or can't see the original post.
792
793                         if($force_parent) {
794                                 logger('item_store: $force_parent=true, reply converted to top-level post.');
795                                 $parent_id = 0;
796                                 $arr['thr-parent'] = $arr['parent-uri'];
797                                 $arr['parent-uri'] = $arr['uri'];
798                                 $arr['gravity'] = 0;
799                         }
800                         else {
801                                 logger('item_store: item parent was not found - ignoring item');
802                                 return 0;
803                         }
804                         
805                         $parent_deleted = 0;
806                 }
807         }
808
809         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
810                 dbesc($arr['uri']),
811                 intval($arr['uid'])
812         );
813         if($r && count($r)) {
814                 logger('item-store: duplicate item ignored. ' . print_r($arr,true));
815                 return 0;
816         }
817
818         call_hooks('post_remote',$arr);
819
820         if(x($arr,'cancel')) {
821                 logger('item_store: post cancelled by plugin.');
822                 return 0;
823         }
824
825         dbesc_array($arr);
826
827         logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
828
829         $r = dbq("INSERT INTO `item` (`" 
830                         . implode("`, `", array_keys($arr)) 
831                         . "`) VALUES ('" 
832                         . implode("', '", array_values($arr)) 
833                         . "')" );
834
835         // find the item we just created
836
837         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC ",
838                 $arr['uri'],           // already dbesc'd
839                 intval($arr['uid'])
840         );
841
842         if(count($r)) {
843                 $current_post = $r[0]['id'];
844                 logger('item_store: created item ' . $current_post);
845         }
846         else {
847                 logger('item_store: could not locate created item');
848                 return 0;
849         }
850         if(count($r) > 1) {
851                 logger('item_store: duplicated post occurred. Removing duplicates.');
852                 q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
853                         $arr['uri'],
854                         intval($arr['uid']),
855                         intval($current_post)
856                 );
857         }
858
859         if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))      
860                 $parent_id = $current_post;
861
862         if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
863                 $private = 1;
864         else
865                 $private = $arr['private']; 
866
867         // Set parent id - and also make sure to inherit the parent's ACL's.
868
869         $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
870                 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
871                 intval($parent_id),
872                 dbesc($allow_cid),
873                 dbesc($allow_gid),
874                 dbesc($deny_cid),
875                 dbesc($deny_gid),
876                 intval($private),
877                 intval($parent_deleted),
878                 intval($current_post)
879         );
880
881         // update the commented timestamp on the parent
882
883         q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
884                 dbesc(datetime_convert()),
885                 dbesc(datetime_convert()),
886                 intval($parent_id)
887         );
888
889         if($dsprsig) {
890                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
891                         intval($current_post),
892                         dbesc($dsprsig->signed_text),
893                         dbesc($dsprsig->signature),
894                         dbesc($dsprsig->signer)
895                 );
896         }
897
898
899         /**
900          * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
901          */
902
903         if($arr['last-child']) {
904                 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
905                         dbesc($arr['uri']),
906                         intval($arr['uid']),
907                         intval($current_post)
908                 );
909         }
910
911         tag_deliver($arr['uid'],$current_post);
912
913         return $current_post;
914 }
915
916 function get_item_contact($item,$contacts) {
917         if(! count($contacts) || (! is_array($item)))
918                 return false;
919         foreach($contacts as $contact) {
920                 if($contact['id'] == $item['contact-id']) {
921                         return $contact;
922                         break; // NOTREACHED
923                 }
924         }
925         return false;
926 }
927
928
929 function tag_deliver($uid,$item_id) {
930
931         // look for mention tags and setup a second delivery chain for forum/community posts if appropriate
932
933         $a = get_app();
934
935         $mention = false;
936
937         $u = q("select uid, nickname, language, username, email, `page-flags`, `notify-flags` from user where uid = %d limit 1",
938                 intval($uid)
939         );
940         if(! count($u))
941                 return;
942
943         $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
944
945         $i = q("select * from item where id = %d and uid = %d limit 1",
946                 intval($item_id),
947                 intval($uid)
948         );
949         if(! count($i))
950                 return;
951
952         $item = $i[0];
953
954         $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
955
956         // Diaspora uses their own hardwired link URL in @-tags
957         // instead of the one we supply with webfinger
958
959         $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
960
961         $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
962         if($cnt) {
963                 foreach($matches as $mtch) {
964                         if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
965                                 $mention = true;
966                                 logger('tag_deliver: mention found: ' . $mtch[2]);
967                         }
968                 }
969         }
970
971         if(! $mention)
972                 return;
973
974         // send a notification
975
976         require_once('include/enotify.php');
977         notification(array(
978                 'type'         => NOTIFY_TAGSELF,
979                 'notify_flags' => $u[0]['notify-flags'],
980                 'language'     => $u[0]['language'],
981                 'to_name'      => $u[0]['username'],
982                 'to_email'     => $u[0]['email'],
983                 'uid'          => $u[0]['uid'],
984                 'item'         => $item,
985                 'link'         => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item['id'],
986                 'source_name'  => $item['author-name'],
987                 'source_link'  => $item['author-link'],
988                 'source_photo' => $item['author-avatar'],
989                 'verb'         => ACTIVITY_TAG,
990                 'otype'        => 'item'
991         ));
992
993         if(! $community_page)
994                 return;
995
996         // tgroup delivery - setup a second delivery chain
997         // prevent delivery looping - only proceed
998         // if the message originated elsewhere and is a top-level post
999
1000         if(($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent']))
1001                 return;
1002
1003         // now change this copy of the post to a forum head message and deliver to all the tgroup members
1004
1005
1006         $c = q("select name, url, thumb from contact where self = 1 and uid = %d limit 1",
1007                 intval($u[0]['uid'])
1008         );
1009         if(! count($c))
1010                 return;
1011
1012         q("update item set wall = 1, origin = 1, forum_mode = 1, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s'  where id = %d limit 1",
1013                 dbesc($c[0]['name']),
1014                 dbesc($c[0]['url']),
1015                 dbesc($c[0]['thumb']),
1016                 intval($item_id)
1017         );
1018
1019         proc_run('php','include/notifier.php','tgroup',$item_id);                       
1020
1021 }
1022
1023
1024
1025
1026
1027
1028 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
1029
1030         $a = get_app();
1031
1032 //      if((! strlen($contact['issued-id'])) && (! $contact['duplex']) && (! ($owner['page-flags'] == PAGE_COMMUNITY)))
1033 //              return 3;
1034
1035         $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1036
1037         if($contact['duplex'] && $contact['dfrn-id'])
1038                 $idtosend = '0:' . $orig_id;
1039         if($contact['duplex'] && $contact['issued-id'])
1040                 $idtosend = '1:' . $orig_id;            
1041
1042         $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
1043
1044         $rino_enable = get_config('system','rino_encrypt');
1045
1046         if(! $rino_enable)
1047                 $rino = 0;
1048
1049         $ssl_val = intval(get_config('system','ssl_policy'));
1050         $ssl_policy = '';
1051         switch($ssl_val){
1052                 case SSL_POLICY_FULL:
1053                         $ssl_policy = 'full';
1054                         break;
1055                 case SSL_POLICY_SELFSIGN:
1056                         $ssl_policy = 'self';
1057                         break;                  
1058                 case SSL_POLICY_NONE:
1059                 default:
1060                         $ssl_policy = 'none';
1061                         break;
1062         }
1063
1064         $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
1065
1066         logger('dfrn_deliver: ' . $url);
1067
1068         $xml = fetch_url($url);
1069
1070         $curl_stat = $a->get_curl_code();
1071         if(! $curl_stat)
1072                 return(-1); // timed out
1073
1074         logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1075
1076         if(! $xml)
1077                 return 3;
1078
1079         if(strpos($xml,'<?xml') === false) {
1080                 logger('dfrn_deliver: no valid XML returned');
1081                 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1082                 return 3;
1083         }
1084
1085         $res = parse_xml_string($xml);
1086
1087         if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
1088                 return (($res->status) ? $res->status : 3);
1089
1090         $postvars     = array();
1091         $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1092         $challenge    = hex2bin((string) $res->challenge);
1093         $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1094         $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
1095
1096         $final_dfrn_id = '';
1097
1098
1099         if(($contact['duplex'] && strlen($contact['pubkey'])) 
1100                 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1101                 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1102                 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1103                 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1104         }
1105         else {
1106                 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1107                 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1108         }
1109
1110         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1111
1112         if(strpos($final_dfrn_id,':') == 1)
1113                 $final_dfrn_id = substr($final_dfrn_id,2);
1114
1115         if($final_dfrn_id != $orig_id) {
1116                 logger('dfrn_deliver: wrong dfrn_id.');
1117                 // did not decode properly - cannot trust this site 
1118                 return 3;
1119         }
1120
1121         $postvars['dfrn_id']      = $idtosend;
1122         $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1123         if($dissolve)
1124                 $postvars['dissolve'] = '1';
1125
1126
1127         if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1128                 $postvars['data'] = $atom;
1129                 $postvars['perm'] = 'rw';
1130         }
1131         else {
1132                 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1133                 $postvars['perm'] = 'r';
1134         }
1135
1136         $postvars['ssl_policy'] = $ssl_policy;
1137
1138         if($rino && $rino_allowed && (! $dissolve)) {
1139                 $key = substr(random_string(),0,16);
1140                 $data = bin2hex(aes_encrypt($postvars['data'],$key));
1141                 $postvars['data'] = $data;
1142                 logger('rino: sent key = ' . $key, LOGGER_DEBUG);       
1143
1144
1145                 if($dfrn_version >= 2.1) {      
1146                         if(($contact['duplex'] && strlen($contact['pubkey'])) 
1147                                 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1148                                 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1149
1150                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1151                         }
1152                         else {
1153                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1154                         }
1155                 }
1156                 else {
1157                         if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1158                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1159                         }
1160                         else {
1161                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1162                         }
1163                 }
1164
1165                 logger('md5 rawkey ' . md5($postvars['key']));
1166
1167                 $postvars['key'] = bin2hex($postvars['key']);
1168         }
1169
1170         logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1171
1172         $xml = post_url($contact['notify'],$postvars);
1173
1174         logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1175
1176         $curl_stat = $a->get_curl_code();
1177         if((! $curl_stat) || (! strlen($xml)))
1178                 return(-1); // timed out
1179
1180         if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1181                 return(-1);
1182
1183         if(strpos($xml,'<?xml') === false) {
1184                 logger('dfrn_deliver: phase 2: no valid XML returned');
1185                 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1186                 return 3;
1187         }
1188
1189         $res = parse_xml_string($xml);
1190
1191         return $res->status; 
1192 }
1193
1194
1195 /**
1196  *
1197  * consume_feed - process atom feed and update anything/everything we might need to update
1198  *
1199  * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1200  *
1201  * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1202  *             It is this person's stuff that is going to be updated.
1203  * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1204  *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST 
1205  *             have a contact record.
1206  * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or 
1207  *        might not) try and subscribe to it.
1208  * $datedir sorts in reverse order
1209  * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been 
1210  *      imported prior to its children being seen in the stream unless we are certain
1211  *      of how the feed is arranged/ordered.
1212  * With $pass = 1, we only pull parent items out of the stream.
1213  * With $pass = 2, we only pull children (comments/likes).
1214  *
1215  * So running this twice, first with pass 1 and then with pass 2 will do the right
1216  * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1217  * model where comments can have sub-threads. That would require some massive sorting
1218  * to get all the feed items into a mostly linear ordering, and might still require
1219  * recursion.  
1220  */
1221
1222 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
1223
1224         require_once('library/simplepie/simplepie.inc');
1225
1226         if(! strlen($xml)) {
1227                 logger('consume_feed: empty input');
1228                 return;
1229         }
1230                 
1231         $feed = new SimplePie();
1232         $feed->set_raw_data($xml);
1233         if($datedir)
1234                 $feed->enable_order_by_date(true);
1235         else
1236                 $feed->enable_order_by_date(false);
1237         $feed->init();
1238
1239         if($feed->error())
1240                 logger('consume_feed: Error parsing XML: ' . $feed->error());
1241
1242         $permalink = $feed->get_permalink();
1243
1244         // Check at the feed level for updated contact name and/or photo
1245
1246         $name_updated  = '';
1247         $new_name = '';
1248         $photo_timestamp = '';
1249         $photo_url = '';
1250         $birthday = '';
1251
1252         $hubs = $feed->get_links('hub');
1253
1254         if(count($hubs))
1255                 $hub = implode(',', $hubs);
1256
1257         $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1258         if(! $rawtags)
1259                 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1260         if($rawtags) {
1261                 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1262                 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1263                         $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1264                         $new_name = $elems['name'][0]['data'];
1265                 } 
1266                 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1267                         $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1268                         $photo_url = $elems['link'][0]['attribs']['']['href'];
1269                 }
1270
1271                 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1272                         $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1273                 }
1274         }
1275
1276         if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1277                 logger('consume_feed: Updating photo for ' . $contact['name']);
1278                 require_once("Photo.php");
1279                 $photo_failure = false;
1280                 $have_photo = false;
1281
1282                 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1283                         intval($contact['id']),
1284                         intval($contact['uid'])
1285                 );
1286                 if(count($r)) {
1287                         $resource_id = $r[0]['resource-id'];
1288                         $have_photo = true;
1289                 }
1290                 else {
1291                         $resource_id = photo_new_resource();
1292                 }
1293                         
1294                 $img_str = fetch_url($photo_url,true);
1295                 $img = new Photo($img_str);
1296                 if($img->is_valid()) {
1297                         if($have_photo) {
1298                                 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1299                                         dbesc($resource_id),
1300                                         intval($contact['id']),
1301                                         intval($contact['uid'])
1302                                 );
1303                         }
1304                                 
1305                         $img->scaleImageSquare(175);
1306                                 
1307                         $hash = $resource_id;
1308                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1309                                 
1310                         $img->scaleImage(80);
1311                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1312
1313                         $img->scaleImage(48);
1314                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1315
1316                         $a = get_app();
1317
1318                         q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'  
1319                                 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1320                                 dbesc(datetime_convert()),
1321                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
1322                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
1323                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
1324                                 intval($contact['uid']),
1325                                 intval($contact['id'])
1326                         );
1327                 }
1328         }
1329
1330         if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1331                 $r = q("select * from contact where uid = %d and id = %d limit 1",
1332                         intval($contact['uid']),
1333                         intval($contact['id'])
1334                 );
1335
1336                 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1337                         dbesc(notags(trim($new_name))),
1338                         dbesc(datetime_convert()),
1339                         intval($contact['uid']),
1340                         intval($contact['id'])
1341                 );
1342
1343                 // do our best to update the name on content items
1344
1345                 if(count($r)) {
1346                         q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
1347                                 dbesc(notags(trim($new_name))),
1348                                 dbesc($r[0]['name']),
1349                                 dbesc($r[0]['url']),
1350                                 intval($contact['uid'])
1351                         );
1352                 }
1353         }
1354
1355         if(strlen($birthday)) {
1356                 if(substr($birthday,0,4) != $contact['bdyear']) {
1357                         logger('consume_feed: updating birthday: ' . $birthday);
1358
1359                         /**
1360                          *
1361                          * Add new birthday event for this person
1362                          *
1363                          * $bdtext is just a readable placeholder in case the event is shared
1364                          * with others. We will replace it during presentation to our $importer
1365                          * to contain a sparkle link and perhaps a photo. 
1366                          *
1367                          */
1368                          
1369                         $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1370
1371
1372                         $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1373                                 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1374                                 intval($contact['uid']),
1375                                 intval($contact['id']),
1376                                 dbesc(datetime_convert()),
1377                                 dbesc(datetime_convert()),
1378                                 dbesc(datetime_convert('UTC','UTC', $birthday)),
1379                                 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1380                                 dbesc($bdtext),
1381                                 dbesc('birthday')
1382                         );
1383                         
1384
1385                         // update bdyear
1386
1387                         q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1388                                 dbesc(substr($birthday,0,4)),
1389                                 intval($contact['uid']),
1390                                 intval($contact['id'])
1391                         );
1392
1393                         // This function is called twice without reloading the contact
1394                         // Make sure we only create one event. This is why &$contact 
1395                         // is a reference var in this function
1396
1397                         $contact['bdyear'] = substr($birthday,0,4);
1398                 }
1399
1400         }
1401
1402
1403         // process any deleted entries
1404
1405         $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1406         if(is_array($del_entries) && count($del_entries) && $pass != 2) {
1407                 foreach($del_entries as $dentry) {
1408                         $deleted = false;
1409                         if(isset($dentry['attribs']['']['ref'])) {
1410                                 $uri = $dentry['attribs']['']['ref'];
1411                                 $deleted = true;
1412                                 if(isset($dentry['attribs']['']['when'])) {
1413                                         $when = $dentry['attribs']['']['when'];
1414                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1415                                 }
1416                                 else
1417                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1418                         }
1419                         if($deleted && is_array($contact)) {
1420                                 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id` 
1421                                         WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d LIMIT 1",
1422                                         dbesc($uri),
1423                                         intval($importer['uid']),
1424                                         intval($contact['id'])
1425                                 );
1426                                 if(count($r)) {
1427                                         $item = $r[0];
1428
1429                                         if(! $item['deleted'])
1430                                                 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1431
1432                                         if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTVITY_OBJ_TAGTERM)) {
1433                                                 $xo = parse_xml_string($item['object'],false);
1434                                                 $xt = parse_xml_string($item['target'],false);
1435                                                 if($xt->type === ACTIVITY_OBJ_NOTE) {
1436                                                         $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1437                                                                 dbesc($xt->id),
1438                                                                 intval($importer['importer_uid'])
1439                                                         );
1440                                                         if(count($i)) {
1441
1442                                                                 // For tags, the owner cannot remove the tag on the author's copy of the post.
1443
1444                                                                 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1445                                                                 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1446                                                                 $author_copy = (($item['origin']) ? true : false);
1447
1448                                                                 if($owner_remove && $author_copy)
1449                                                                         continue;
1450                                                                 if($author_remove || $owner_remove) {
1451                                                                         $tags = explode(',',$i[0]['tag']);
1452                                                                         $newtags = array();
1453                                                                         if(count($tags)) {
1454                                                                                 foreach($tags as $tag)
1455                                                                                         if(trim($tag) !== trim($xo->body))
1456                                                                                                 $newtags[] = trim($tag);
1457                                                                         }
1458                                                                         q("update item set tag = '%s' where id = %d limit 1",
1459                                                                                 dbesc(implode(',',$newtags)),
1460                                                                                 intval($i[0]['id'])
1461                                                                         );
1462                                                                 }
1463                                                         }
1464                                                 }
1465                                         }
1466
1467                                         if($item['uri'] == $item['parent-uri']) {
1468                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1469                                                         `body` = '', `title` = ''
1470                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
1471                                                         dbesc($when),
1472                                                         dbesc(datetime_convert()),
1473                                                         dbesc($item['uri']),
1474                                                         intval($importer['uid'])
1475                                                 );
1476                                         }
1477                                         else {
1478                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1479                                                         `body` = '', `title` = '' 
1480                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1481                                                         dbesc($when),
1482                                                         dbesc(datetime_convert()),
1483                                                         dbesc($uri),
1484                                                         intval($importer['uid'])
1485                                                 );
1486                                                 if($item['last-child']) {
1487                                                         // ensure that last-child is set in case the comment that had it just got wiped.
1488                                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1489                                                                 dbesc(datetime_convert()),
1490                                                                 dbesc($item['parent-uri']),
1491                                                                 intval($item['uid'])
1492                                                         );
1493                                                         // who is the last child now? 
1494                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d 
1495                                                                 ORDER BY `created` DESC LIMIT 1",
1496                                                                         dbesc($item['parent-uri']),
1497                                                                         intval($importer['uid'])
1498                                                         );
1499                                                         if(count($r)) {
1500                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1501                                                                         intval($r[0]['id'])
1502                                                                 );
1503                                                         }
1504                                                 }       
1505                                         }
1506                                 }       
1507                         }
1508                 }
1509         }
1510
1511         // Now process the feed
1512
1513         if($feed->get_item_quantity()) {                
1514
1515                 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1516
1517         // in inverse date order
1518                 if ($datedir)
1519                         $items = array_reverse($feed->get_items());
1520                 else
1521                         $items = $feed->get_items();
1522
1523
1524                 foreach($items as $item) {
1525
1526                         $is_reply = false;              
1527                         $item_id = $item->get_id();
1528                         $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1529                         if(isset($rawthread[0]['attribs']['']['ref'])) {
1530                                 $is_reply = true;
1531                                 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1532                         }
1533
1534                         if(($is_reply) && is_array($contact)) {
1535
1536                                 if($pass == 1)
1537                                         continue;
1538
1539                                 // Have we seen it? If not, import it.
1540         
1541                                 $item_id  = $item->get_id();
1542                                 $datarray = get_atom_elements($feed,$item);
1543
1544
1545                                 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1546                                         $datarray['author-name'] = $contact['name'];
1547                                 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1548                                         $datarray['author-link'] = $contact['url'];
1549                                 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1550                                         $datarray['author-avatar'] = $contact['thumb'];
1551
1552                                 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1553                                         logger('consume_feed: no author information! ' . print_r($datarray,true));
1554                                         continue;
1555                                 }
1556
1557                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1558                                         dbesc($item_id),
1559                                         intval($importer['uid'])
1560                                 );
1561
1562                                 // Update content if 'updated' changes
1563
1564                                 if(count($r)) {
1565                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1566                                                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1567                                                         dbesc($datarray['title']),
1568                                                         dbesc($datarray['body']),
1569                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1570                                                         dbesc($item_id),
1571                                                         intval($importer['uid'])
1572                                                 );
1573                                         }
1574
1575                                         // update last-child if it changes
1576
1577                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1578                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1579                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1580                                                         dbesc(datetime_convert()),
1581                                                         dbesc($parent_uri),
1582                                                         intval($importer['uid'])
1583                                                 );
1584                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1585                                                         intval($allow[0]['data']),
1586                                                         dbesc(datetime_convert()),
1587                                                         dbesc($item_id),
1588                                                         intval($importer['uid'])
1589                                                 );
1590                                         }
1591                                         continue;
1592                                 }
1593
1594                                 $force_parent = false;
1595                                 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1596                                         if($contact['network'] === NETWORK_OSTATUS)
1597                                                 $force_parent = true;
1598                                         if(strlen($datarray['title']))
1599                                                 unset($datarray['title']);
1600                                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1601                                                 dbesc(datetime_convert()),
1602                                                 dbesc($parent_uri),
1603                                                 intval($importer['uid'])
1604                                         );
1605                                         $datarray['last-child'] = 1;
1606                                 }
1607
1608                                 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1609                                         // one way feed - no remote comment ability
1610                                         $datarray['last-child'] = 0;
1611                                 }
1612                                 $datarray['parent-uri'] = $parent_uri;
1613                                 $datarray['uid'] = $importer['uid'];
1614                                 $datarray['contact-id'] = $contact['id'];
1615                                 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1616                                         $datarray['type'] = 'activity';
1617                                         $datarray['gravity'] = GRAVITY_LIKE;
1618                                         // only one like or dislike per person
1619                                         $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
1620                                                 intval($datarray['uid']),
1621                                                 intval($datarray['contact-id']),
1622                                                 dbesc($datarray['verb'])
1623                                         );
1624                                         if($r && count($r))
1625                                                 continue; 
1626                                 }
1627
1628                                 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1629                                         $xo = parse_xml_string($datarray['object'],false);
1630                                         $xt = parse_xml_string($datarray['target'],false);
1631
1632                                         if($xt->type == ACTIVITY_OBJ_NOTE) {
1633                                                 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
1634                                                         dbesc($xt->id),
1635                                                         intval($importer['importer_uid'])
1636                                                 );
1637                                                 if(! count($r))
1638                                                         continue;
1639
1640                                                 // extract tag, if not duplicate, add to parent item
1641                                                 if($xo->id && $xo->content) {
1642                                                         $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
1643                                                         if(! (stristr($r[0]['tag'],$newtag))) {
1644                                                                 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
1645                                                                         dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
1646                                                                         intval($r[0]['id'])
1647                                                                 );
1648                                                         }
1649                                                 }
1650                                         }
1651                                 }
1652
1653                                 $r = item_store($datarray,$force_parent);
1654                                 continue;
1655                         }
1656
1657                         else {
1658
1659                                 // Head post of a conversation. Have we seen it? If not, import it.
1660
1661                                 $item_id  = $item->get_id();
1662
1663                                 $datarray = get_atom_elements($feed,$item);
1664
1665                                 if(is_array($contact)) {
1666                                         if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1667                                                 $datarray['author-name'] = $contact['name'];
1668                                         if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1669                                                 $datarray['author-link'] = $contact['url'];
1670                                         if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1671                                                 $datarray['author-avatar'] = $contact['thumb'];
1672                                 }
1673
1674                                 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1675                                         logger('consume_feed: no author information! ' . print_r($datarray,true));
1676                                         continue;
1677                                 }
1678
1679                                 // special handling for events
1680
1681                                 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1682                                         $ev = bbtoevent($datarray['body']);
1683                                         if(x($ev,'desc') && x($ev,'start')) {
1684                                                 $ev['uid'] = $importer['uid'];
1685                                                 $ev['uri'] = $item_id;
1686                                                 $ev['edited'] = $datarray['edited'];
1687                                                 $ev['private'] = $datarray['private'];
1688
1689                                                 if(is_array($contact))
1690                                                         $ev['cid'] = $contact['id'];
1691                                                 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1692                                                         dbesc($item_id),
1693                                                         intval($importer['uid'])
1694                                                 );
1695                                                 if(count($r))
1696                                                         $ev['id'] = $r[0]['id'];
1697                                                 $xyz = event_store($ev);
1698                                                 continue;
1699                                         }
1700                                 }
1701
1702                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1703                                         dbesc($item_id),
1704                                         intval($importer['uid'])
1705                                 );
1706
1707                                 // Update content if 'updated' changes
1708
1709                                 if(count($r)) {
1710                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1711                                                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1712                                                         dbesc($datarray['title']),
1713                                                         dbesc($datarray['body']),
1714                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1715                                                         dbesc($item_id),
1716                                                         intval($importer['uid'])
1717                                                 );
1718                                         }
1719
1720                                         // update last-child if it changes
1721
1722                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1723                                         if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1724                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1725                                                         intval($allow[0]['data']),
1726                                                         dbesc(datetime_convert()),
1727                                                         dbesc($item_id),
1728                                                         intval($importer['uid'])
1729                                                 );
1730                                         }
1731                                         continue;
1732                                 }
1733
1734                                 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1735                                         logger('consume-feed: New follower');
1736                                         new_follower($importer,$contact,$datarray,$item);
1737                                         return;
1738                                 }
1739                                 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW))  {
1740                                         lose_follower($importer,$contact,$datarray,$item);
1741                                         return;
1742                                 }
1743
1744                                 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
1745                                         logger('consume-feed: New friend request');
1746                                         new_follower($importer,$contact,$datarray,$item,true);
1747                                         return;
1748                                 }
1749                                 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND))  {
1750                                         lose_sharer($importer,$contact,$datarray,$item);
1751                                         return;
1752                                 }
1753
1754
1755                                 if(! is_array($contact))
1756                                         return;
1757
1758                                 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1759                                         if(strlen($datarray['title']))
1760                                                 unset($datarray['title']);
1761                                         $datarray['last-child'] = 1;
1762                                 }
1763
1764                                 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1765                                         // one way feed - no remote comment ability
1766                                         $datarray['last-child'] = 0;
1767                                 }
1768
1769                                 // This is my contact on another system, but it's really me.
1770                                 // Turn this into a wall post.
1771
1772                                 if($contact['remote_self'])
1773                                         $datarray['wall'] = 1;
1774
1775                                 $datarray['parent-uri'] = $item_id;
1776                                 $datarray['uid'] = $importer['uid'];
1777                                 $datarray['contact-id'] = $contact['id'];
1778
1779                                 if(! link_compare($datarray['owner-link'],$contact['url'])) {
1780                                         // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery, 
1781                                         // but otherwise there's a possible data mixup on the sender's system.
1782                                         // the tgroup delivery code called from item_store will correct it if it's a forum,
1783                                         // but we're going to unconditionally correct it here so that the post will always be owned by our contact. 
1784                                         logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
1785                                         $datarray['owner-name']   = $contact['name'];
1786                                         $datarray['owner-link']   = $contact['url'];
1787                                         $datarray['owner-avatar'] = $contact['thumb'];
1788                                 }
1789
1790                                 $r = item_store($datarray);
1791                                 continue;
1792
1793                         }
1794                 }
1795         }
1796 }
1797
1798 function local_delivery($importer,$data) {
1799
1800         $a = get_app();
1801
1802         if($importer['readonly']) {
1803                 // We aren't receiving stuff from this person. But we will quietly ignore them
1804                 // rather than a blatant "go away" message.
1805                 logger('local_delivery: ignoring');
1806                 return 0;
1807                 //NOTREACHED
1808         }
1809
1810         // Consume notification feed. This may differ from consuming a public feed in several ways
1811         // - might contain email or friend suggestions
1812         // - might contain remote followup to our message
1813         //              - in which case we need to accept it and then notify other conversants
1814         // - we may need to send various email notifications
1815
1816         $feed = new SimplePie();
1817         $feed->set_raw_data($data);
1818         $feed->enable_order_by_date(false);
1819         $feed->init();
1820
1821         $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
1822         if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
1823                 $base = $reloc[0]['child'][NAMESPACE_DFRN];
1824                 $newloc = array();
1825                 $newloc['uid'] = $importer['importer_uid'];
1826                 $newloc['cid'] = $importer['id'];
1827                 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
1828                 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
1829                 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
1830                 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
1831                 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
1832                 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
1833                 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
1834                 $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data']));
1835                 $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
1836                 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));
1837                 
1838                 // TODO
1839                 // merge with current record, current contents have priority
1840                 // update record, set url-updated
1841                 // update profile photos
1842                 // schedule a scan?
1843
1844         }
1845
1846         // handle friend suggestion notification
1847
1848         $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
1849         if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
1850                 $base = $sugg[0]['child'][NAMESPACE_DFRN];
1851                 $fsugg = array();
1852                 $fsugg['uid'] = $importer['importer_uid'];
1853                 $fsugg['cid'] = $importer['id'];
1854                 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
1855                 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
1856                 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
1857                 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
1858                 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
1859
1860                 // Does our member already have a friend matching this description?
1861
1862                 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1863                         dbesc($fsugg['name']),
1864                         dbesc(normalise_link($fsugg['url'])),
1865                         intval($fsugg['uid'])
1866                 );
1867                 if(count($r))
1868                         return 0;
1869
1870                 // Do we already have an fcontact record for this person?
1871
1872                 $fid = 0;
1873                 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1874                         dbesc($fsugg['url']),
1875                         dbesc($fsugg['name']),
1876                         dbesc($fsugg['request'])
1877                 );
1878                 if(count($r)) {
1879                         $fid = $r[0]['id'];
1880                 }
1881                 if(! $fid)
1882                         $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
1883                         dbesc($fsugg['name']),
1884                         dbesc($fsugg['url']),
1885                         dbesc($fsugg['photo']),
1886                         dbesc($fsugg['request'])
1887                 );
1888                 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1889                         dbesc($fsugg['url']),
1890                         dbesc($fsugg['name']),
1891                         dbesc($fsugg['request'])
1892                 );
1893                 if(count($r)) {
1894                         $fid = $r[0]['id'];
1895                 }
1896                 // database record did not get created. Quietly give up.
1897                 else
1898                         return 0;
1899
1900                 $hash = random_string();
1901  
1902                 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
1903                         VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
1904                         intval($fsugg['uid']),
1905                         intval($fid),
1906                         intval($fsugg['cid']),
1907                         dbesc($fsugg['body']),
1908                         dbesc($hash),
1909                         dbesc(datetime_convert()),
1910                         intval(0)
1911                 );
1912
1913                 notification(array(
1914                         'type'         => NOTIFY_SUGGEST,
1915                         'notify_flags' => $importer['notify-flags'],
1916                         'language'     => $importer['language'],
1917                         'to_name'      => $importer['username'],
1918                         'to_email'     => $importer['email'],
1919                         'uid'          => $importer['importer_uid'],
1920                         'item'         => $fsugg,
1921                         'link'         => $a->get_baseurl() . '/notifications/intros',
1922                         'source_name'  => $importer['name'],
1923                         'source_link'  => $importer['url'],
1924                         'source_photo' => $importer['photo'],
1925                         'verb'         => ACTIVITY_REQ_FRIEND,
1926                         'otype'        => 'intro'
1927                 ));
1928
1929                 return 0;
1930         }
1931
1932         $ismail = false;
1933
1934         $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
1935         if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
1936
1937                 logger('local_delivery: private message received');
1938
1939                 $ismail = true;
1940                 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
1941
1942                 $msg = array();
1943                 $msg['uid'] = $importer['importer_uid'];
1944                 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
1945                 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
1946                 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
1947                 $msg['contact-id'] = $importer['id'];
1948                 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
1949                 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
1950                 $msg['seen'] = 0;
1951                 $msg['replied'] = 0;
1952                 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
1953                 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
1954                 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
1955                 
1956                 dbesc_array($msg);
1957
1958                 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg)) 
1959                         . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
1960
1961                 // send notifications.
1962
1963                 require_once('include/enotify.php');
1964
1965                 $notif_params = array(
1966                         'type' => NOTIFY_MAIL,
1967                         'notify_flags' => $importer['notify-flags'],
1968                         'language' => $importer['language'],
1969                         'to_name' => $importer['username'],
1970                         'to_email' => $importer['email'],
1971                         'uid' => $importer['importer_uid'],
1972                         'item' => $msg,
1973                         'source_name' => $msg['from-name'],
1974                         'source_link' => $importer['url'],
1975                         'source_photo' => $importer['thumb'],
1976                         'verb' => ACTIVITY_POST,
1977                         'otype' => 'mail'
1978                 );
1979                         
1980                 notification($notif_params);
1981                 return 0;
1982
1983                 // NOTREACHED
1984         }       
1985         
1986         logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
1987
1988         // process any deleted entries
1989
1990         $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1991         if(is_array($del_entries) && count($del_entries)) {
1992                 foreach($del_entries as $dentry) {
1993                         $deleted = false;
1994                         if(isset($dentry['attribs']['']['ref'])) {
1995                                 $uri = $dentry['attribs']['']['ref'];
1996                                 $deleted = true;
1997                                 if(isset($dentry['attribs']['']['when'])) {
1998                                         $when = $dentry['attribs']['']['when'];
1999                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
2000                                 }
2001                                 else
2002                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
2003                         }
2004                         if($deleted) {
2005
2006                                 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
2007                                         WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d LIMIT 1",
2008                                         dbesc($uri),
2009                                         intval($importer['importer_uid']),
2010                                         intval($importer['id'])
2011                                 );
2012
2013                                 if(count($r)) {
2014                                         $item = $r[0];
2015
2016                                         if($item['deleted'])
2017                                                 continue;
2018
2019                                         logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
2020
2021                                         if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTVITY_OBJ_TAGTERM)) {
2022                                                 $xo = parse_xml_string($item['object'],false);
2023                                                 $xt = parse_xml_string($item['target'],false);
2024                                                 if($xt->type === ACTIVITY_OBJ_NOTE) {
2025                                                         $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
2026                                                                 dbesc($xt->id),
2027                                                                 intval($importer['importer_uid'])
2028                                                         );
2029                                                         if(count($i)) {
2030
2031                                                                 // For tags, the owner cannot remove the tag on the author's copy of the post.
2032                                                                 
2033                                                                 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
2034                                                                 $author_remove = (($item['origin'] && $item['self']) ? true : false);
2035                                                                 $author_copy = (($item['origin']) ? true : false); 
2036
2037                                                                 if($owner_remove && $author_copy)
2038                                                                         continue;
2039                                                                 if($author_remove || $owner_remove) {                                                           
2040                                                                         $tags = explode(',',$i[0]['tag']);
2041                                                                         $newtags = array();
2042                                                                         if(count($tags)) {
2043                                                                                 foreach($tags as $tag)
2044                                                                                         if(trim($tag) !== trim($xo->body))
2045                                                                                                 $newtags[] = trim($tag);
2046                                                                         }
2047                                                                         q("update item set tag = '%s' where id = %d limit 1",
2048                                                                                 dbesc(implode(',',$newtags)),
2049                                                                                 intval($i[0]['id'])
2050                                                                         );
2051                                                                 }
2052                                                         }
2053                                                 }
2054                                         }
2055
2056                                         if($item['uri'] == $item['parent-uri']) {
2057                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
2058                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
2059                                                         dbesc($when),
2060                                                         dbesc(datetime_convert()),
2061                                                         dbesc($item['uri']),
2062                                                         intval($importer['importer_uid'])
2063                                                 );
2064                                         }
2065                                         else {
2066                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' 
2067                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2068                                                         dbesc($when),
2069                                                         dbesc(datetime_convert()),
2070                                                         dbesc($uri),
2071                                                         intval($importer['importer_uid'])
2072                                                 );
2073                                                 if($item['last-child']) {
2074                                                         // ensure that last-child is set in case the comment that had it just got wiped.
2075                                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2076                                                                 dbesc(datetime_convert()),
2077                                                                 dbesc($item['parent-uri']),
2078                                                                 intval($item['uid'])
2079                                                         );
2080                                                         // who is the last child now? 
2081                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
2082                                                                 ORDER BY `created` DESC LIMIT 1",
2083                                                                         dbesc($item['parent-uri']),
2084                                                                         intval($importer['importer_uid'])
2085                                                         );
2086                                                         if(count($r)) {
2087                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2088                                                                         intval($r[0]['id'])
2089                                                                 );
2090                                                         }       
2091                                                 }
2092                                         }       
2093                                 }
2094                         }
2095                 }
2096         }
2097
2098
2099         foreach($feed->get_items() as $item) {
2100
2101                 $is_reply = false;              
2102                 $item_id = $item->get_id();
2103                 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
2104                 if(isset($rawthread[0]['attribs']['']['ref'])) {
2105                         $is_reply = true;
2106                         $parent_uri = $rawthread[0]['attribs']['']['ref'];
2107                 }
2108
2109                 if($is_reply) {
2110                         $community = false;
2111
2112                         if($importer['page-flags'] == PAGE_COMMUNITY) {
2113                                 $sql_extra = '';
2114                                 $community = true;
2115                                 logger('local_delivery: possible community reply');
2116                         }
2117                         else
2118                                 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2119  
2120                         // was the top-level post for this reply written by somebody on this site? 
2121                         // Specifically, the recipient? 
2122
2123                         $is_a_remote_comment = false;
2124
2125                         $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`, 
2126                                 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item` 
2127                                 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id` 
2128                                 WHERE `item`.`uri` = '%s' AND `item`.`parent-uri` = '%s'
2129                                 AND `item`.`uid` = %d 
2130                                 $sql_extra
2131                                 LIMIT 1",
2132                                 dbesc($parent_uri),
2133                                 dbesc($parent_uri),
2134                                 intval($importer['importer_uid'])
2135                         );
2136                         if($r && count($r))
2137                                 $is_a_remote_comment = true;                    
2138
2139                         // Does this have the characteristics of a community comment?
2140                         // If it's a reply to a wall post on a community page it's a 
2141                         // valid community comment. Also forum_mode makes it valid for sure. 
2142                         // If neither, it's not.
2143
2144                         if($is_a_remote_comment && $community) {
2145                                 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2146                                         $is_a_remote_comment = false;
2147                                         logger('local_delivery: not a community reply');
2148                                 }
2149                         }
2150
2151                         if($is_a_remote_comment) {
2152                                 logger('local_delivery: received remote comment');
2153                                 $is_like = false;
2154                                 // remote reply to our post. Import and then notify everybody else.
2155                                 $datarray = get_atom_elements($feed,$item);
2156
2157
2158                                 // TODO: make this next part work against both delivery threads of a community post
2159
2160 //                              if((! link_compare($datarray['author-link'],$importer['url'])) && (! $community)) {
2161 //                                      logger('local_delivery: received relay claiming to be from ' . $importer['url'] . ' however comment author url is ' . $datarray['author-link'] ); 
2162                                         // they won't know what to do so don't report an error. Just quietly die.
2163 //                                      return 0;
2164 //                              }                                       
2165
2166                                 $datarray['type'] = 'remote-comment';
2167                                 $datarray['wall'] = 1;
2168                                 $datarray['parent-uri'] = $parent_uri;
2169                                 $datarray['uid'] = $importer['importer_uid'];
2170                                 $datarray['owner-name'] = $r[0]['name'];
2171                                 $datarray['owner-link'] = $r[0]['url'];
2172                                 $datarray['owner-avatar'] = $r[0]['thumb'];
2173                                 $datarray['contact-id'] = $importer['id'];
2174                                 if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
2175                                         $is_like = true;
2176                                         $datarray['type'] = 'activity';
2177                                         $datarray['gravity'] = GRAVITY_LIKE;
2178                                         $datarray['last-child'] = 0;
2179                                         // only one like or dislike per person
2180                                         $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
2181                                                 intval($datarray['uid']),
2182                                                 intval($datarray['contact-id']),
2183                                                 dbesc($datarray['verb'])
2184                                         );
2185                                         if($r && count($r))
2186                                                 continue; 
2187                                 }
2188
2189                                 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2190
2191
2192                                         $xo = parse_xml_string($datarray['object'],false);
2193                                         $xt = parse_xml_string($datarray['target'],false);
2194
2195                                         if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id == $r[0]['uri'])) {
2196
2197                                                 // extract tag, if not duplicate, and this user allows tags, add to parent item                                         
2198
2199                                                 if($xo->id && $xo->content) {
2200                                                         $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2201
2202                                                         if(! (stristr($r[0]['tag'],$newtag))) {
2203                                                                 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
2204                                                                         intval($importer['importer_uid'])
2205                                                                 );
2206                                                                 if(count($i) && ! ($i[0]['blocktags'])) {
2207                                                                         q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2208                                                                                 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
2209                                                                                 intval($r[0]['id'])
2210                                                                         );
2211                                                                 }
2212                                                         }
2213                                                 }                                                                                                       
2214                                         }
2215                                 }
2216
2217 //                              if($community) {
2218 //                                      $newtag = '@[url=' . $a->get_baseurl() . '/profile/' . $importer['nickname'] . ']' . $importer['username'] . '[/url]';
2219 //                                      if(! stristr($datarray['tag'],$newtag)) {
2220 //                                              if(strlen($datarray['tag']))
2221 //                                                      $datarray['tag'] .= ',';
2222 //                                              $datarray['tag'] .= $newtag;
2223 //                                      }
2224 //                              }
2225
2226
2227                                 $posted_id = item_store($datarray);
2228                                 $parent = 0;
2229
2230                                 if($posted_id) {
2231                                         $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2232                                                 intval($posted_id),
2233                                                 intval($importer['importer_uid'])
2234                                         );
2235                                         if(count($r))
2236                                                 $parent = $r[0]['parent'];
2237                         
2238                                         if(! $is_like) {
2239                                                 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2240                                                         dbesc(datetime_convert()),
2241                                                         intval($importer['importer_uid']),
2242                                                         intval($r[0]['parent'])
2243                                                 );
2244
2245                                                 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2246                                                         dbesc(datetime_convert()),
2247                                                         intval($importer['importer_uid']),
2248                                                         intval($posted_id)
2249                                                 );
2250                                         }
2251
2252                                         if($posted_id && $parent) {
2253                                 
2254                                                 proc_run('php',"include/notifier.php","comment-import","$posted_id");
2255                                         
2256                                                 if((! $is_like) && (! $importer['self'])) {
2257
2258                                                         require_once('include/enotify.php');
2259
2260                                                         notification(array(
2261                                                                 'type'         => NOTIFY_COMMENT,
2262                                                                 'notify_flags' => $importer['notify-flags'],
2263                                                                 'language'     => $importer['language'],
2264                                                                 'to_name'      => $importer['username'],
2265                                                                 'to_email'     => $importer['email'],
2266                                                                 'uid'          => $importer['importer_uid'],
2267                                                                 'item'         => $datarray,
2268                                                                 'link'             => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2269                                                                 'source_name'  => stripslashes($datarray['author-name']),
2270                                                                 'source_link'  => $datarray['author-link'],
2271                                                                 'source_photo' => ((link_compare($datarray['author-link'],$importer['url'])) 
2272                                                                         ? $importer['thumb'] : $datarray['author-avatar']),
2273                                                                 'verb'         => ACTIVITY_POST,
2274                                                                 'otype'        => 'item',
2275                                                                 'parent'       => $parent,
2276
2277                                                         ));
2278
2279                                                 }
2280                                         }
2281
2282                                         return 0;
2283                                         // NOTREACHED
2284                                 }
2285                         }
2286                         else {
2287
2288                                 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
2289
2290                                 $item_id  = $item->get_id();
2291                                 $datarray = get_atom_elements($feed,$item);
2292
2293                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2294                                         dbesc($item_id),
2295                                         intval($importer['importer_uid'])
2296                                 );
2297
2298                                 // Update content if 'updated' changes
2299
2300                                 if(count($r)) {
2301                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
2302                                                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2303                                                         dbesc($datarray['title']),
2304                                                         dbesc($datarray['body']),
2305                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2306                                                         dbesc($item_id),
2307                                                         intval($importer['importer_uid'])
2308                                                 );
2309                                         }
2310
2311                                         // update last-child if it changes
2312
2313                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2314                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
2315                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2316                                                         dbesc(datetime_convert()),
2317                                                         dbesc($parent_uri),
2318                                                         intval($importer['importer_uid'])
2319                                                 );
2320                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2321                                                         intval($allow[0]['data']),
2322                                                         dbesc(datetime_convert()),
2323                                                         dbesc($item_id),
2324                                                         intval($importer['importer_uid'])
2325                                                 );
2326                                         }
2327                                         continue;
2328                                 }
2329
2330                                 $datarray['parent-uri'] = $parent_uri;
2331                                 $datarray['uid'] = $importer['importer_uid'];
2332                                 $datarray['contact-id'] = $importer['id'];
2333                                 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
2334                                         $datarray['type'] = 'activity';
2335                                         $datarray['gravity'] = GRAVITY_LIKE;
2336                                         // only one like or dislike per person
2337                                         $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
2338                                                 intval($datarray['uid']),
2339                                                 intval($datarray['contact-id']),
2340                                                 dbesc($datarray['verb'])
2341                                         );
2342                                         if($r && count($r))
2343                                                 continue; 
2344
2345                                 }
2346
2347                                 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2348
2349                                         $xo = parse_xml_string($datarray['object'],false);
2350                                         $xt = parse_xml_string($datarray['target'],false);
2351
2352                                         if($xt->type == ACTIVITY_OBJ_NOTE) {
2353                                                 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2354                                                         dbesc($xt->id),
2355                                                         intval($importer['importer_uid'])
2356                                                 );
2357                                                 if(! count($r))
2358                                                         continue;                               
2359
2360                                                 // extract tag, if not duplicate, add to parent item                                            
2361                                                 if($xo->content) {
2362                                                         if(! (stristr($r[0]['tag'],trim($xo->content)))) {
2363                                                                 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2364                                                                         dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2365                                                                         intval($r[0]['id'])
2366                                                                 );
2367                                                         }
2368                                                 }                                                                                                       
2369                                         }
2370                                 }
2371
2372                                 $posted_id = item_store($datarray);
2373
2374                                 // find out if our user is involved in this conversation and wants to be notified.
2375                         
2376                                 if($datarray['type'] != 'activity') {
2377
2378                                         $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 ",
2379                                                 dbesc($parent_uri),
2380                                                 intval($importer['importer_uid'])
2381                                         );
2382
2383                                         if(count($myconv)) {
2384                                                 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
2385
2386                                                 // first make sure this isn't our own post coming back to us from a wall-to-wall event
2387                                                 if(! link_compare($datarray['author-link'],$importer_url)) {
2388
2389                                                         
2390                                                         foreach($myconv as $conv) {
2391
2392                                                                 // now if we find a match, it means we're in this conversation
2393         
2394                                                                 if(! link_compare($conv['author-link'],$importer_url))
2395                                                                         continue;
2396
2397                                                                 require_once('include/enotify.php');
2398                                                                 
2399                                                                 $conv_parent = $conv['parent'];
2400
2401                                                                 notification(array(
2402                                                                         'type'         => NOTIFY_COMMENT,
2403                                                                         'notify_flags' => $importer['notify-flags'],
2404                                                                         'language'     => $importer['language'],
2405                                                                         'to_name'      => $importer['username'],
2406                                                                         'to_email'     => $importer['email'],
2407                                                                         'uid'          => $importer['importer_uid'],
2408                                                                         'item'         => $datarray,
2409                                                                         'link'             => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2410                                                                         'source_name'  => stripslashes($datarray['author-name']),
2411                                                                         'source_link'  => $datarray['author-link'],
2412                                                                         'source_photo' => ((link_compare($datarray['author-link'],$importer['url'])) 
2413                                                                                 ? $importer['thumb'] : $datarray['author-avatar']),
2414                                                                         'verb'         => ACTIVITY_POST,
2415                                                                         'otype'        => 'item',
2416                                                                         'parent'       => $conv_parent,
2417
2418                                                                 ));
2419
2420                                                                 // only send one notification
2421                                                                 break;
2422                                                         }
2423                                                 }
2424                                         }
2425                                 }
2426                                 continue;
2427                         }
2428                 }
2429
2430                 else {
2431
2432                         // Head post of a conversation. Have we seen it? If not, import it.
2433
2434
2435                         $item_id  = $item->get_id();
2436                         $datarray = get_atom_elements($feed,$item);
2437
2438                         if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
2439                                 $ev = bbtoevent($datarray['body']);
2440                                 if(x($ev,'desc') && x($ev,'start')) {
2441                                         $ev['cid'] = $importer['id'];
2442                                         $ev['uid'] = $importer['uid'];
2443                                         $ev['uri'] = $item_id;
2444                                         $ev['edited'] = $datarray['edited'];
2445                                         $ev['private'] = $datarray['private'];
2446
2447                                         $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2448                                                 dbesc($item_id),
2449                                                 intval($importer['uid'])
2450                                         );
2451                                         if(count($r))
2452                                                 $ev['id'] = $r[0]['id'];
2453                                         $xyz = event_store($ev);
2454                                         continue;
2455                                 }
2456                         }
2457
2458                         $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2459                                 dbesc($item_id),
2460                                 intval($importer['importer_uid'])
2461                         );
2462
2463                         // Update content if 'updated' changes
2464
2465                         if(count($r)) {
2466                                 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
2467                                         $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2468                                                 dbesc($datarray['title']),
2469                                                 dbesc($datarray['body']),
2470                                                 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2471                                                 dbesc($item_id),
2472                                                 intval($importer['importer_uid'])
2473                                         );
2474                                 }
2475
2476                                 // update last-child if it changes
2477
2478                                 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2479                                 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2480                                         $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2481                                                 intval($allow[0]['data']),
2482                                                 dbesc(datetime_convert()),
2483                                                 dbesc($item_id),
2484                                                 intval($importer['importer_uid'])
2485                                         );
2486                                 }
2487                                 continue;
2488                         }
2489
2490                         // This is my contact on another system, but it's really me.
2491                         // Turn this into a wall post.
2492
2493                         if($importer['remote_self'])
2494                                 $datarray['wall'] = 1;
2495
2496                         $datarray['parent-uri'] = $item_id;
2497                         $datarray['uid'] = $importer['importer_uid'];
2498                         $datarray['contact-id'] = $importer['id'];
2499
2500                         if(! link_compare($datarray['owner-link'],$contact['url'])) {
2501                                 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery, 
2502                                 // but otherwise there's a possible data mixup on the sender's system.
2503                                 // the tgroup delivery code called from item_store will correct it if it's a forum,
2504                                 // but we're going to unconditionally correct it here so that the post will always be owned by our contact. 
2505                                 logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
2506                                 $datarray['owner-name']   = $importer['senderName'];
2507                                 $datarray['owner-link']   = $importer['url'];
2508                                 $datarray['owner-avatar'] = $importer['thumb'];
2509                         }
2510
2511                         $r = item_store($datarray);
2512                         continue;
2513                 }
2514         }
2515
2516         return 0;
2517         // NOTREACHED
2518
2519 }
2520
2521
2522 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
2523         $url = notags(trim($datarray['author-link']));
2524         $name = notags(trim($datarray['author-name']));
2525         $photo = notags(trim($datarray['author-avatar']));
2526
2527         $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
2528         if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
2529                 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
2530
2531         if(is_array($contact)) {
2532                 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
2533                         || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
2534                         $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
2535                                 intval(CONTACT_IS_FRIEND),
2536                                 intval($contact['id']),
2537                                 intval($importer['uid'])
2538                         );
2539                 }
2540                 // send email notification to owner?
2541         }
2542         else {
2543         
2544                 // create contact record
2545
2546                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`, 
2547                         `blocked`, `readonly`, `pending`, `writable` )
2548                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
2549                         intval($importer['uid']),
2550                         dbesc(datetime_convert()),
2551                         dbesc($url),
2552                         dbesc(normalise_link($url)),
2553                         dbesc($name),
2554                         dbesc($nick),
2555                         dbesc($photo),
2556                         dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
2557                         intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
2558                 );
2559                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
2560                                 intval($importer['uid']),
2561                                 dbesc($url)
2562                 );
2563                 if(count($r))
2564                                 $contact_record = $r[0];
2565
2566                 // create notification  
2567                 $hash = random_string();
2568
2569                 if(is_array($contact_record)) {
2570                         $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
2571                                 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
2572                                 intval($importer['uid']),
2573                                 intval($contact_record['id']),
2574                                 dbesc($hash),
2575                                 dbesc(datetime_convert())
2576                         );
2577                 }
2578                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
2579                         intval($importer['uid'])
2580                 );
2581                 $a = get_app();
2582                 if(count($r)) {
2583                         if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
2584                                 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
2585                                 $email = replace_macros($email_tpl, array(
2586                                         '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
2587                                         '$url' => $url,
2588                                         '$myname' => $r[0]['username'],
2589                                         '$siteurl' => $a->get_baseurl(),
2590                                         '$sitename' => $a->config['sitename']
2591                                 ));
2592                                 $res = mail($r[0]['email'], 
2593                                         (($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],
2594                                         $email,
2595                                         'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
2596                                         . 'Content-type: text/plain; charset=UTF-8' . "\n"
2597                                         . 'Content-transfer-encoding: 8bit' );
2598                         
2599                         }
2600                 }
2601         }
2602 }
2603
2604 function lose_follower($importer,$contact,$datarray,$item) {
2605
2606         if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
2607                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2608                         intval(CONTACT_IS_SHARING),
2609                         intval($contact['id'])
2610                 );
2611         }
2612         else {
2613                 contact_remove($contact['id']);
2614         }
2615 }
2616
2617 function lose_sharer($importer,$contact,$datarray,$item) {
2618
2619         if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
2620                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2621                         intval(CONTACT_IS_FOLLOWER),
2622                         intval($contact['id'])
2623                 );
2624         }
2625         else {
2626                 contact_remove($contact['id']);
2627         }
2628 }
2629
2630
2631 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
2632
2633         if(is_array($importer)) {
2634                 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
2635                         intval($importer['uid'])
2636                 );
2637         }
2638
2639         // Diaspora has different message-ids in feeds than they do 
2640         // through the direct Diaspora protocol. If we try and use
2641         // the feed, we'll get duplicates. So don't.
2642
2643         if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
2644                 return;
2645
2646         $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
2647
2648         // Use a single verify token, even if multiple hubs
2649
2650         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
2651
2652         $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
2653
2654         logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: '  . $push_url . ' with verifier ' . $verify_token);
2655
2656         if(! strlen($contact['hub-verify'])) {
2657                 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
2658                         dbesc($verify_token),
2659                         intval($contact['id'])
2660                 );
2661         }
2662
2663         post_url($url,$params);                 
2664         return;
2665
2666 }
2667
2668
2669 function atom_author($tag,$name,$uri,$h,$w,$photo) {
2670         $o = '';
2671         if(! $tag)
2672                 return $o;
2673         $name = xmlify($name);
2674         $uri = xmlify($uri);
2675         $h = intval($h);
2676         $w = intval($w);
2677         $photo = xmlify($photo);
2678
2679
2680         $o .= "<$tag>\r\n";
2681         $o .= "<name>$name</name>\r\n";
2682         $o .= "<uri>$uri</uri>\r\n";
2683         $o .= '<link rel="photo"  type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2684         $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2685
2686         call_hooks('atom_author', $o);
2687
2688         $o .= "</$tag>\r\n";
2689         return $o;
2690 }
2691
2692 function atom_entry($item,$type,$author,$owner,$comment = false) {
2693
2694         $a = get_app();
2695
2696         if(! $item['parent'])
2697                 return;
2698
2699         if($item['deleted'])
2700                 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
2701
2702
2703         if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
2704                 $body = fix_private_photos($item['body'],$owner['uid']);
2705         else
2706                 $body = $item['body'];
2707
2708
2709         $o = "\r\n\r\n<entry>\r\n";
2710
2711         if(is_array($author))
2712                 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
2713         else
2714                 $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']));
2715         if(strlen($item['owner-name']))
2716                 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
2717
2718         if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']))
2719                 $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";
2720
2721         $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
2722         $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
2723         $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
2724         $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
2725         $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
2726         $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
2727         $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
2728         if($comment)
2729                 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
2730
2731         if($item['location']) {
2732                 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
2733                 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
2734         }
2735
2736         if($item['coord'])
2737                 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
2738
2739         if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
2740                 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
2741
2742         if($item['extid'])
2743                 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
2744         if($item['bookmark'])
2745                 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
2746
2747         if($item['app'])
2748                 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
2749
2750         if($item['guid'])
2751                 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
2752
2753         if($item['signed_text']) {
2754                 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
2755                 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
2756         }
2757
2758         $verb = construct_verb($item);
2759         $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
2760         $actobj = construct_activity_object($item);
2761         if(strlen($actobj))
2762                 $o .= $actobj;
2763         $actarg = construct_activity_target($item);
2764         if(strlen($actarg))
2765                 $o .= $actarg;
2766
2767         $tags = item_getfeedtags($item);
2768         if(count($tags)) {
2769                 foreach($tags as $t) {
2770                         $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
2771                 }
2772         }
2773
2774         $o .= item_getfeedattach($item);
2775
2776         $mentioned = get_mentions($item);
2777         if($mentioned)
2778                 $o .= $mentioned;
2779         
2780         call_hooks('atom_entry', $o);
2781
2782         $o .= '</entry>' . "\r\n";
2783         
2784         return $o;
2785 }
2786
2787 function fix_private_photos($s,$uid) {
2788         $a = get_app();
2789         logger('fix_private_photos');
2790
2791         if(preg_match("/\[img\](.*?)\[\/img\]/is",$s,$matches)) {
2792                 $image = $matches[1];
2793                 logger('fix_private_photos: found photo ' . $image);
2794                 if(stristr($image ,$a->get_baseurl() . '/photo/')) {
2795                         $i = basename($image);
2796                         $i = str_replace('.jpg','',$i);
2797                         $x = strpos($i,'-');
2798                         if($x) {
2799                                 $res = substr($i,$x+1);
2800                                 $i = substr($i,0,$x);
2801                                 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
2802                                         dbesc($i),
2803                                         intval($res),
2804                                         intval($uid)
2805                                 );
2806                                 if(count($r)) {
2807                                         logger('replacing photo');
2808                                         $s = str_replace($image, 'data:image/jpg;base64,' . base64_encode($r[0]['data']), $s);
2809                                 }
2810                         }
2811                         logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
2812                 }       
2813         }
2814         return($s);
2815 }
2816
2817
2818
2819 function item_getfeedtags($item) {
2820         $ret = array();
2821         $matches = false;
2822         $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
2823         if($cnt) {
2824                 for($x = 0; $x < $cnt; $x ++) {
2825                         if($matches[1][$x])
2826                                 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
2827                 }
2828         }
2829         $matches = false; 
2830         $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
2831         if($cnt) {
2832                 for($x = 0; $x < $cnt; $x ++) {
2833                         if($matches[1][$x])
2834                                 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
2835                 }
2836         } 
2837         return $ret;
2838 }
2839
2840 function item_getfeedattach($item) {
2841         $ret = '';
2842         $arr = explode(',',$item['attach']);
2843         if(count($arr)) {
2844                 foreach($arr as $r) {
2845                         $matches = false;
2846                         $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
2847                         if($cnt) {
2848                                 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
2849                                 if(intval($matches[2]))
2850                                         $ret .= 'length="' . intval($matches[2]) . '" ';
2851                                 if($matches[4] !== ' ')
2852                                         $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
2853                                 $ret .= ' />' . "\r\n";
2854                         }
2855                 }
2856         }
2857         return $ret;
2858 }
2859
2860
2861         
2862 function item_expire($uid,$days) {
2863
2864         if((! $uid) || (! $days))
2865                 return;
2866
2867         $r = q("SELECT * FROM `item` 
2868                 WHERE `uid` = %d 
2869                 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY 
2870                 AND `id` = `parent` 
2871                 AND `deleted` = 0",
2872                 intval($uid),
2873                 intval($days)
2874         );
2875
2876         if(! count($r))
2877                 return;
2878
2879         $expire_items = get_pconfig($uid, 'expire','items');
2880         $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
2881         
2882         $expire_notes = get_pconfig($uid, 'expire','notes');
2883         $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
2884
2885         $expire_starred = get_pconfig($uid, 'expire','starred');
2886         $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
2887         
2888         $expire_photos = get_pconfig($uid, 'expire','photos');
2889         $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
2890  
2891         logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2892
2893         foreach($r as $item) {
2894
2895                 // Only expire posts, not photos and photo comments
2896
2897                 if($expire_photos==0 && strlen($item['resource-id']))
2898                         continue;
2899                 if($expire_starred==0 && intval($item['starred']))
2900                         continue;
2901                 if($expire_notes==0 && $item['type']=='note')
2902                         continue;
2903                 if($expire_items==0 && $item['type']!='note')
2904                         continue;
2905
2906                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
2907                         dbesc(datetime_convert()),
2908                         dbesc(datetime_convert()),
2909                         intval($item['id'])
2910                 );
2911
2912                 // kill the kids
2913
2914                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2915                         dbesc(datetime_convert()),
2916                         dbesc(datetime_convert()),
2917                         dbesc($item['parent-uri']),
2918                         intval($item['uid'])
2919                 );
2920
2921         }
2922
2923         proc_run('php',"include/notifier.php","expire","$uid");
2924         
2925 }
2926
2927
2928 function drop_items($items) {
2929         $uid = 0;
2930
2931         if((! local_user()) && (! $remote_user()))
2932                 return;
2933
2934         if(count($items)) {
2935                 foreach($items as $item) {
2936                         $owner = drop_item($item,false);
2937                         if($owner && ! $uid)
2938                                 $uid = $owner;
2939                 }
2940         }
2941
2942         // multiple threads may have been deleted, send an expire notification
2943
2944         if($uid)
2945                 proc_run('php',"include/notifier.php","expire","$uid");
2946 }
2947
2948
2949 function drop_item($id,$interactive = true) {
2950
2951         $a = get_app();
2952
2953         // locate item to be deleted
2954
2955         $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
2956                 intval($id)
2957         );
2958
2959         if(! count($r)) {
2960                 if(! $interactive)
2961                         return 0;
2962                 notice( t('Item not found.') . EOL);
2963                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
2964         }
2965
2966         $item = $r[0];
2967
2968         $owner = $item['uid'];
2969
2970         // check if logged in user is either the author or owner of this item
2971
2972         if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
2973
2974                 // delete the item
2975
2976                 $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
2977                         dbesc(datetime_convert()),
2978                         dbesc(datetime_convert()),
2979                         intval($item['id'])
2980                 );
2981
2982                 // If item is a link to a photo resource, nuke all the associated photos 
2983                 // (visitors will not have photo resources)
2984                 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
2985                 // generate a resource-id and therefore aren't intimately linked to the item. 
2986
2987                 if(strlen($item['resource-id'])) {
2988                         q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
2989                                 dbesc($item['resource-id']),
2990                                 intval($item['uid'])
2991                         );
2992                         // ignore the result
2993                 }
2994
2995                 // If item is a link to an event, nuke the event record.
2996
2997                 if(intval($item['event-id'])) {
2998                         q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2999                                 intval($item['event-id']),
3000                                 intval($item['uid'])
3001                         );
3002                         // ignore the result
3003                 }
3004
3005
3006                 // If it's the parent of a comment thread, kill all the kids
3007
3008                 if($item['uri'] == $item['parent-uri']) {
3009                         $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
3010                                 WHERE `parent-uri` = '%s' AND `uid` = %d ",
3011                                 dbesc(datetime_convert()),
3012                                 dbesc(datetime_convert()),
3013                                 dbesc($item['parent-uri']),
3014                                 intval($item['uid'])
3015                         );
3016                         // ignore the result
3017                 }
3018                 else {
3019                         // ensure that last-child is set in case the comment that had it just got wiped.
3020                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
3021                                 dbesc(datetime_convert()),
3022                                 dbesc($item['parent-uri']),
3023                                 intval($item['uid'])
3024                         );
3025                         // who is the last child now? 
3026                         $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",
3027                                 dbesc($item['parent-uri']),
3028                                 intval($item['uid'])
3029                         );
3030                         if(count($r)) {
3031                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
3032                                         intval($r[0]['id'])
3033                                 );
3034                         }       
3035                 }
3036                 $drop_id = intval($item['id']);
3037                         
3038                 // send the notification upstream/downstream as the case may be
3039
3040                 if(! $interactive)
3041                         return $owner;
3042
3043                 proc_run('php',"include/notifier.php","drop","$drop_id");
3044                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3045                 //NOTREACHED
3046         }
3047         else {
3048                 if(! $interactive)
3049                         return 0;
3050                 notice( t('Permission denied.') . EOL);
3051                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3052                 //NOTREACHED
3053         }
3054         
3055 }