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