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