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