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