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