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