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