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