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