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