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