]> git.mxchange.org Git - friendica.git/blob - include/items.php
35db71946cbe3236c179a887344cee974e314e77
[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['target'] .= '<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['origin']        = ((x($arr,'origin'))        ? intval($arr['origin'])              : 0 );
734         $arr['guid']          = ((x($arr,'guid'))          ? notags(trim($arr['guid']))          : get_guid());
735
736         if($arr['parent-uri'] === $arr['uri']) {
737                 $parent_id = 0;
738                 $allow_cid = $arr['allow_cid'];
739                 $allow_gid = $arr['allow_gid'];
740                 $deny_cid  = $arr['deny_cid'];
741                 $deny_gid  = $arr['deny_gid'];
742         }
743         else { 
744
745                 // find the parent and snarf the item id and ACL's
746                 // and anything else we need to inherit
747
748                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
749                         dbesc($arr['parent-uri']),
750                         intval($arr['uid'])
751                 );
752
753                 if(count($r)) {
754
755                         // is the new message multi-level threaded?
756                         // even though we don't support it now, preserve the info
757                         // and re-attach to the conversation parent.
758
759                         if($r[0]['uri'] != $r[0]['parent-uri']) {
760                                 $arr['thr-parent'] = $arr['parent-uri'];
761                                 $arr['parent-uri'] = $r[0]['parent-uri'];
762                                 $z = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d 
763                                         ORDER BY `id` ASC LIMIT 1",
764                                         dbesc($r[0]['parent-uri']),
765                                         dbesc($r[0]['parent-uri']),
766                                         intval($arr['uid'])
767                                 );
768                                 if($z && count($z))
769                                         $r = $z;
770                         }
771
772                         $parent_id      = $r[0]['id'];
773                         $parent_deleted = $r[0]['deleted'];
774                         $allow_cid      = $r[0]['allow_cid'];
775                         $allow_gid      = $r[0]['allow_gid'];
776                         $deny_cid       = $r[0]['deny_cid'];
777                         $deny_gid       = $r[0]['deny_gid'];
778                         $arr['wall']    = $r[0]['wall'];
779                 }
780                 else {
781
782                         // Allow one to see reply tweets from status.net even when
783                         // we don't have or can't see the original post.
784
785                         if($force_parent) {
786                                 logger('item_store: $force_parent=true, reply converted to top-level post.');
787                                 $parent_id = 0;
788                                 $arr['thr-parent'] = $arr['parent-uri'];
789                                 $arr['parent-uri'] = $arr['uri'];
790                                 $arr['gravity'] = 0;
791                         }
792                         else {
793                                 logger('item_store: item parent was not found - ignoring item');
794                                 return 0;
795                         }
796                 }
797         }
798
799         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
800                 dbesc($arr['uri']),
801                 intval($arr['uid'])
802         );
803         if($r && count($r)) {
804                 logger('item-store: duplicate item ignored. ' . print_r($arr,true));
805                 return 0;
806         }
807
808         call_hooks('post_remote',$arr);
809
810         dbesc_array($arr);
811
812         logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
813
814         $r = dbq("INSERT INTO `item` (`" 
815                         . implode("`, `", array_keys($arr)) 
816                         . "`) VALUES ('" 
817                         . implode("', '", array_values($arr)) 
818                         . "')" );
819
820         // find the item we just created
821
822         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC ",
823                 $arr['uri'],           // already dbesc'd
824                 intval($arr['uid'])
825         );
826
827         if(count($r)) {
828                 $current_post = $r[0]['id'];
829                 logger('item_store: created item ' . $current_post);
830         }
831         else {
832                 logger('item_store: could not locate created item');
833                 return 0;
834         }
835         if(count($r) > 1) {
836                 logger('item_store: duplicated post occurred. Removing duplicates.');
837                 q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
838                         $arr['uri'],
839                         intval($arr['uid']),
840                         intval($current_post)
841                 );
842         }
843
844         if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))      
845                 $parent_id = $current_post;
846
847         if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
848                 $private = 1;
849         else
850                 $private = $arr['private']; 
851
852         // Set parent id - and also make sure to inherit the parent's ACL's.
853
854         $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
855                 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
856                 intval($parent_id),
857                 dbesc($allow_cid),
858                 dbesc($allow_gid),
859                 dbesc($deny_cid),
860                 dbesc($deny_gid),
861                 intval($private),
862                 intval($parent_deleted),
863                 intval($current_post)
864         );
865
866         // update the commented timestamp on the parent
867
868         q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
869                 dbesc(datetime_convert()),
870                 dbesc(datetime_convert()),
871                 intval($parent_id)
872         );
873
874         if($dsprsig) {
875                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
876                         intval($current_post),
877                         dbesc($dsprsig->signed_text),
878                         dbesc($dsprsig->signature),
879                         dbesc($dsprsig->signer)
880                 );
881         }
882
883
884         /**
885          * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
886          */
887
888         if($arr['last-child']) {
889                 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
890                         dbesc($arr['uri']),
891                         intval($arr['uid']),
892                         intval($current_post)
893                 );
894         }
895
896         return $current_post;
897 }
898
899 function get_item_contact($item,$contacts) {
900         if(! count($contacts) || (! is_array($item)))
901                 return false;
902         foreach($contacts as $contact) {
903                 if($contact['id'] == $item['contact-id']) {
904                         return $contact;
905                         break; // NOTREACHED
906                 }
907         }
908         return false;
909 }
910
911
912 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
913
914         $a = get_app();
915
916         if((! strlen($contact['issued-id'])) && (! $contact['duplex']) && (! ($owner['page-flags'] == PAGE_COMMUNITY)))
917                 return 3;
918
919         $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
920
921         if($contact['duplex'] && $contact['dfrn-id'])
922                 $idtosend = '0:' . $orig_id;
923         if($contact['duplex'] && $contact['issued-id'])
924                 $idtosend = '1:' . $orig_id;            
925
926         $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
927
928         $rino_enable = get_config('system','rino_encrypt');
929
930         if(! $rino_enable)
931                 $rino = 0;
932
933         $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
934
935         logger('dfrn_deliver: ' . $url);
936
937         $xml = fetch_url($url);
938
939         $curl_stat = $a->get_curl_code();
940         if(! $curl_stat)
941                 return(-1); // timed out
942
943         logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
944
945         if(! $xml)
946                 return 3;
947
948         if(strpos($xml,'<?xml') === false) {
949                 logger('dfrn_deliver: no valid XML returned');
950                 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
951                 return 3;
952         }
953
954         $res = parse_xml_string($xml);
955
956         if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
957                 return (($res->status) ? $res->status : 3);
958
959         $postvars     = array();
960         $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
961         $challenge    = hex2bin((string) $res->challenge);
962         $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
963         $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
964
965         $final_dfrn_id = '';
966
967
968         if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
969                 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
970                 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
971         }
972         else {
973                 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
974                 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
975         }
976
977         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
978
979         if(strpos($final_dfrn_id,':') == 1)
980                 $final_dfrn_id = substr($final_dfrn_id,2);
981
982         if($final_dfrn_id != $orig_id) {
983                 logger('dfrn_deliver: wrong dfrn_id.');
984                 // did not decode properly - cannot trust this site 
985                 return 3;
986         }
987
988         $postvars['dfrn_id']      = $idtosend;
989         $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
990         if($dissolve)
991                 $postvars['dissolve'] = '1';
992
993
994         if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
995                 $postvars['data'] = $atom;
996                 $postvars['perm'] = 'rw';
997         }
998         else {
999                 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1000                 $postvars['perm'] = 'r';
1001         }
1002
1003         if($rino && $rino_allowed && (! $dissolve)) {
1004                 $key = substr(random_string(),0,16);
1005                 $data = bin2hex(aes_encrypt($postvars['data'],$key));
1006                 $postvars['data'] = $data;
1007                 logger('rino: sent key = ' . $key, LOGGER_DEBUG);       
1008
1009
1010                 if($dfrn_version >= 2.1) {      
1011                         if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1012                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1013                         }
1014                         else {
1015                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1016                         }
1017                 }
1018                 else {
1019                         if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1020                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1021                         }
1022                         else {
1023                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1024                         }
1025                 }
1026
1027                 logger('md5 rawkey ' . md5($postvars['key']));
1028
1029                 $postvars['key'] = bin2hex($postvars['key']);
1030         }
1031
1032         logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1033
1034         $xml = post_url($contact['notify'],$postvars);
1035
1036         logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1037
1038         $curl_stat = $a->get_curl_code();
1039         if((! $curl_stat) || (! strlen($xml)))
1040                 return(-1); // timed out
1041
1042         if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1043                 return(-1);
1044
1045         if(strpos($xml,'<?xml') === false) {
1046                 logger('dfrn_deliver: phase 2: no valid XML returned');
1047                 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1048                 return 3;
1049         }
1050
1051         $res = parse_xml_string($xml);
1052
1053         return $res->status; 
1054 }
1055
1056
1057 /**
1058  *
1059  * consume_feed - process atom feed and update anything/everything we might need to update
1060  *
1061  * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1062  *
1063  * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1064  *             It is this person's stuff that is going to be updated.
1065  * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1066  *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST 
1067  *             have a contact record.
1068  * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or 
1069  *        might not) try and subscribe to it.
1070  * $datedir sorts in reverse order
1071  * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been 
1072  *      imported prior to its children being seen in the stream unless we are certain
1073  *      of how the feed is arranged/ordered.
1074  * With $pass = 1, we only pull parent items out of the stream.
1075  * With $pass = 2, we only pull children (comments/likes).
1076  *
1077  * So running this twice, first with pass 1 and then with pass 2 will do the right
1078  * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1079  * model where comments can have sub-threads. That would require some massive sorting
1080  * to get all the feed items into a mostly linear ordering, and might still require
1081  * recursion.  
1082  */
1083
1084 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
1085
1086         require_once('library/simplepie/simplepie.inc');
1087
1088         if(! strlen($xml)) {
1089                 logger('consume_feed: empty input');
1090                 return;
1091         }
1092                 
1093         $feed = new SimplePie();
1094         $feed->set_raw_data($xml);
1095         if($datedir)
1096                 $feed->enable_order_by_date(true);
1097         else
1098                 $feed->enable_order_by_date(false);
1099         $feed->init();
1100
1101         if($feed->error())
1102                 logger('consume_feed: Error parsing XML: ' . $feed->error());
1103
1104         $permalink = $feed->get_permalink();
1105
1106         // Check at the feed level for updated contact name and/or photo
1107
1108         $name_updated  = '';
1109         $new_name = '';
1110         $photo_timestamp = '';
1111         $photo_url = '';
1112         $birthday = '';
1113
1114         $hubs = $feed->get_links('hub');
1115
1116         if(count($hubs))
1117                 $hub = implode(',', $hubs);
1118
1119         $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1120         if(! $rawtags)
1121                 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1122         if($rawtags) {
1123                 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1124                 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1125                         $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1126                         $new_name = $elems['name'][0]['data'];
1127                 } 
1128                 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1129                         $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1130                         $photo_url = $elems['link'][0]['attribs']['']['href'];
1131                 }
1132
1133                 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1134                         $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1135                 }
1136         }
1137
1138         if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1139                 logger('consume_feed: Updating photo for ' . $contact['name']);
1140                 require_once("Photo.php");
1141                 $photo_failure = false;
1142                 $have_photo = false;
1143
1144                 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1145                         intval($contact['id']),
1146                         intval($contact['uid'])
1147                 );
1148                 if(count($r)) {
1149                         $resource_id = $r[0]['resource-id'];
1150                         $have_photo = true;
1151                 }
1152                 else {
1153                         $resource_id = photo_new_resource();
1154                 }
1155                         
1156                 $img_str = fetch_url($photo_url,true);
1157                 $img = new Photo($img_str);
1158                 if($img->is_valid()) {
1159                         if($have_photo) {
1160                                 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1161                                         dbesc($resource_id),
1162                                         intval($contact['id']),
1163                                         intval($contact['uid'])
1164                                 );
1165                         }
1166                                 
1167                         $img->scaleImageSquare(175);
1168                                 
1169                         $hash = $resource_id;
1170                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1171                                 
1172                         $img->scaleImage(80);
1173                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1174
1175                         $img->scaleImage(48);
1176                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1177
1178                         $a = get_app();
1179
1180                         q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'  
1181                                 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1182                                 dbesc(datetime_convert()),
1183                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
1184                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
1185                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
1186                                 intval($contact['uid']),
1187                                 intval($contact['id'])
1188                         );
1189                 }
1190         }
1191
1192         if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1193                 q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1194                         dbesc(notags(trim($new_name))),
1195                         dbesc(datetime_convert()),
1196                         intval($contact['uid']),
1197                         intval($contact['id'])
1198                 );
1199         }
1200
1201         if(strlen($birthday)) {
1202                 if(substr($birthday,0,4) != $contact['bdyear']) {
1203                         logger('consume_feed: updating birthday: ' . $birthday);
1204
1205                         /**
1206                          *
1207                          * Add new birthday event for this person
1208                          *
1209                          * $bdtext is just a readable placeholder in case the event is shared
1210                          * with others. We will replace it during presentation to our $importer
1211                          * to contain a sparkle link and perhaps a photo. 
1212                          *
1213                          */
1214                          
1215                         $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1216
1217
1218                         $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1219                                 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1220                                 intval($contact['uid']),
1221                                 intval($contact['id']),
1222                                 dbesc(datetime_convert()),
1223                                 dbesc(datetime_convert()),
1224                                 dbesc(datetime_convert('UTC','UTC', $birthday)),
1225                                 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1226                                 dbesc($bdtext),
1227                                 dbesc('birthday')
1228                         );
1229                         
1230
1231                         // update bdyear
1232
1233                         q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1234                                 dbesc(substr($birthday,0,4)),
1235                                 intval($contact['uid']),
1236                                 intval($contact['id'])
1237                         );
1238
1239                         // This function is called twice without reloading the contact
1240                         // Make sure we only create one event. This is why &$contact 
1241                         // is a reference var in this function
1242
1243                         $contact['bdyear'] = substr($birthday,0,4);
1244                 }
1245
1246         }
1247
1248
1249         // process any deleted entries
1250
1251         $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1252         if(is_array($del_entries) && count($del_entries) && $pass != 2) {
1253                 foreach($del_entries as $dentry) {
1254                         $deleted = false;
1255                         if(isset($dentry['attribs']['']['ref'])) {
1256                                 $uri = $dentry['attribs']['']['ref'];
1257                                 $deleted = true;
1258                                 if(isset($dentry['attribs']['']['when'])) {
1259                                         $when = $dentry['attribs']['']['when'];
1260                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1261                                 }
1262                                 else
1263                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1264                         }
1265                         if($deleted && is_array($contact)) {
1266                                 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id` 
1267                                         WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d LIMIT 1",
1268                                         dbesc($uri),
1269                                         intval($importer['uid']),
1270                                         intval($contact['id'])
1271                                 );
1272                                 if(count($r)) {
1273                                         $item = $r[0];
1274
1275                                         if(! $item['deleted'])
1276                                                 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1277
1278                                         if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTVITY_OBJ_TAGTERM)) {
1279                                                 $xo = parse_xml_string($item['object'],false);
1280                                                 $xt = parse_xml_string($item['target'],false);
1281                                                 if($xt->type === ACTIVITY_OBJ_NOTE) {
1282                                                         $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1283                                                                 dbesc($xt->id),
1284                                                                 intval($importer['importer_uid'])
1285                                                         );
1286                                                         if(count($i)) {
1287
1288                                                                 // For tags, the owner cannot remove the tag on the author's copy of the post.
1289
1290                                                                 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1291                                                                 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1292                                                                 $author_copy = (($item['origin']) ? true : false);
1293
1294                                                                 if($owner_remove && $author_copy)
1295                                                                         continue;
1296                                                                 if($author_remove || $owner_remove) {
1297                                                                         $tags = explode(',',$i[0]['tag']);
1298                                                                         $newtags = array();
1299                                                                         if(count($tags)) {
1300                                                                                 foreach($tags as $tag)
1301                                                                                         if(trim($tag) !== trim($xo->body))
1302                                                                                                 $newtags[] = trim($tag);
1303                                                                         }
1304                                                                         q("update item set tag = '%s' where id = %d limit 1",
1305                                                                                 dbesc(implode(',',$newtags)),
1306                                                                                 intval($i[0]['id'])
1307                                                                         );
1308                                                                 }
1309                                                         }
1310                                                 }
1311                                         }
1312
1313                                         if($item['uri'] == $item['parent-uri']) {
1314                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1315                                                         `body` = '', `title` = ''
1316                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
1317                                                         dbesc($when),
1318                                                         dbesc(datetime_convert()),
1319                                                         dbesc($item['uri']),
1320                                                         intval($importer['uid'])
1321                                                 );
1322                                         }
1323                                         else {
1324                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1325                                                         `body` = '', `title` = '' 
1326                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1327                                                         dbesc($when),
1328                                                         dbesc(datetime_convert()),
1329                                                         dbesc($uri),
1330                                                         intval($importer['uid'])
1331                                                 );
1332                                                 if($item['last-child']) {
1333                                                         // ensure that last-child is set in case the comment that had it just got wiped.
1334                                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1335                                                                 dbesc(datetime_convert()),
1336                                                                 dbesc($item['parent-uri']),
1337                                                                 intval($item['uid'])
1338                                                         );
1339                                                         // who is the last child now? 
1340                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d 
1341                                                                 ORDER BY `created` DESC LIMIT 1",
1342                                                                         dbesc($item['parent-uri']),
1343                                                                         intval($importer['uid'])
1344                                                         );
1345                                                         if(count($r)) {
1346                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1347                                                                         intval($r[0]['id'])
1348                                                                 );
1349                                                         }
1350                                                 }       
1351                                         }
1352                                 }       
1353                         }
1354                 }
1355         }
1356
1357         // Now process the feed
1358
1359         if($feed->get_item_quantity()) {                
1360
1361                 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1362
1363         // in inverse date order
1364                 if ($datedir)
1365                         $items = array_reverse($feed->get_items());
1366                 else
1367                         $items = $feed->get_items();
1368
1369
1370                 foreach($items as $item) {
1371
1372                         $is_reply = false;              
1373                         $item_id = $item->get_id();
1374                         $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1375                         if(isset($rawthread[0]['attribs']['']['ref'])) {
1376                                 $is_reply = true;
1377                                 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1378                         }
1379
1380                         if(($is_reply) && is_array($contact)) {
1381
1382                                 if($pass == 1)
1383                                         continue;
1384
1385                                 // Have we seen it? If not, import it.
1386         
1387                                 $item_id  = $item->get_id();
1388                                 $datarray = get_atom_elements($feed,$item);
1389
1390                                 if(! x($datarray,'author-name'))
1391                                         $datarray['author-name'] = $contact['name'];
1392                                 if(! x($datarray,'author-link'))
1393                                         $datarray['author-link'] = $contact['url'];
1394                                 if(! x($datarray,'author-avatar'))
1395                                         $datarray['author-avatar'] = $contact['thumb'];
1396
1397
1398                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1399                                         dbesc($item_id),
1400                                         intval($importer['uid'])
1401                                 );
1402
1403                                 // Update content if 'updated' changes
1404
1405                                 if(count($r)) {
1406                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1407                                                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1408                                                         dbesc($datarray['body']),
1409                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1410                                                         dbesc($item_id),
1411                                                         intval($importer['uid'])
1412                                                 );
1413                                         }
1414
1415                                         // update last-child if it changes
1416
1417                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1418                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1419                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1420                                                         dbesc(datetime_convert()),
1421                                                         dbesc($parent_uri),
1422                                                         intval($importer['uid'])
1423                                                 );
1424                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1425                                                         intval($allow[0]['data']),
1426                                                         dbesc(datetime_convert()),
1427                                                         dbesc($item_id),
1428                                                         intval($importer['uid'])
1429                                                 );
1430                                         }
1431                                         continue;
1432                                 }
1433
1434                                 $force_parent = false;
1435                                 if($contact['network'] === NETWORK_OSTATUS) {
1436                                         $force_parent = true;
1437                                         if(strlen($datarray['title']))
1438                                                 unset($datarray['title']);
1439                                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1440                                                 dbesc(datetime_convert()),
1441                                                 dbesc($parent_uri),
1442                                                 intval($importer['uid'])
1443                                         );
1444                                         $datarray['last-child'] = 1;
1445                                 }
1446
1447                                 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1448                                         // one way feed - no remote comment ability
1449                                         $datarray['last-child'] = 0;
1450                                 }
1451                                 $datarray['parent-uri'] = $parent_uri;
1452                                 $datarray['uid'] = $importer['uid'];
1453                                 $datarray['contact-id'] = $contact['id'];
1454                                 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1455                                         $datarray['type'] = 'activity';
1456                                         $datarray['gravity'] = GRAVITY_LIKE;
1457                                 }
1458
1459                                 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1460                                         $xo = parse_xml_string($datarray['object'],false);
1461                                         $xt = parse_xml_string($datarray['target'],false);
1462
1463                                         if($xt->type == ACTIVITY_OBJ_NOTE) {
1464                                                 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
1465                                                         dbesc($xt->id),
1466                                                         intval($importer['importer_uid'])
1467                                                 );
1468                                                 if(! count($r))
1469                                                         continue;
1470
1471                                                 // extract tag, if not duplicate, add to parent item
1472                                                 if($xo->content) {
1473                                                         if(! (stristr($r[0]['tag'],trim($xo->content)))) {
1474                                                                 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
1475                                                                         dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
1476                                                                         intval($r[0]['id'])
1477                                                                 );
1478                                                         }
1479                                                 }
1480                                         }
1481                                 }
1482
1483                                 $r = item_store($datarray,$force_parent);
1484                                 continue;
1485                         }
1486
1487                         else {
1488
1489                                 // Head post of a conversation. Have we seen it? If not, import it.
1490
1491                                 $item_id  = $item->get_id();
1492
1493                                 $datarray = get_atom_elements($feed,$item);
1494
1495                                 if(is_array($contact)) {
1496                                         if(! x($datarray,'author-name'))
1497                                                 $datarray['author-name'] = $contact['name'];
1498                                         if(! x($datarray,'author-link'))
1499                                                 $datarray['author-link'] = $contact['url'];
1500                                         if(! x($datarray,'author-avatar'))
1501                                                 $datarray['author-avatar'] = $contact['thumb'];
1502                                 }
1503
1504                                 // special handling for events
1505
1506                                 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1507                                         $ev = bbtoevent($datarray['body']);
1508                                         if(x($ev,'desc') && x($ev,'start')) {
1509                                                 $ev['uid'] = $importer['uid'];
1510                                                 $ev['uri'] = $item_id;
1511                                                 $ev['edited'] = $datarray['edited'];
1512                                                 $ev['private'] = $datarray['private'];
1513
1514                                                 if(is_array($contact))
1515                                                         $ev['cid'] = $contact['id'];
1516                                                 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1517                                                         dbesc($item_id),
1518                                                         intval($importer['uid'])
1519                                                 );
1520                                                 if(count($r))
1521                                                         $ev['id'] = $r[0]['id'];
1522                                                 $xyz = event_store($ev);
1523                                                 continue;
1524                                         }
1525                                 }
1526
1527                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1528                                         dbesc($item_id),
1529                                         intval($importer['uid'])
1530                                 );
1531
1532                                 // Update content if 'updated' changes
1533
1534                                 if(count($r)) {
1535                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1536                                                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1537                                                         dbesc($datarray['body']),
1538                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1539                                                         dbesc($item_id),
1540                                                         intval($importer['uid'])
1541                                                 );
1542                                         }
1543
1544                                         // update last-child if it changes
1545
1546                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1547                                         if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1548                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1549                                                         intval($allow[0]['data']),
1550                                                         dbesc(datetime_convert()),
1551                                                         dbesc($item_id),
1552                                                         intval($importer['uid'])
1553                                                 );
1554                                         }
1555                                         continue;
1556                                 }
1557
1558                                 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1559                                         logger('consume-feed: New follower');
1560                                         new_follower($importer,$contact,$datarray,$item);
1561                                         return;
1562                                 }
1563                                 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW))  {
1564                                         lose_follower($importer,$contact,$datarray,$item);
1565                                         return;
1566                                 }
1567
1568                                 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
1569                                         logger('consume-feed: New friend request');
1570                                         new_follower($importer,$contact,$datarray,$item,true);
1571                                         return;
1572                                 }
1573                                 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND))  {
1574                                         lose_sharer($importer,$contact,$datarray,$item);
1575                                         return;
1576                                 }
1577
1578
1579                                 if(! is_array($contact))
1580                                         return;
1581
1582                                 if($contact['network'] === NETWORK_OSTATUS || stristr($permalink,'twitter.com')) {
1583                                         if(strlen($datarray['title']))
1584                                                 unset($datarray['title']);
1585                                         $datarray['last-child'] = 1;
1586                                 }
1587
1588                                 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1589                                         // one way feed - no remote comment ability
1590                                         $datarray['last-child'] = 0;
1591                                 }
1592
1593                                 // This is my contact on another system, but it's really me.
1594                                 // Turn this into a wall post.
1595
1596                                 if($contact['remote_self'])
1597                                         $datarray['wall'] = 1;
1598
1599                                 $datarray['parent-uri'] = $item_id;
1600                                 $datarray['uid'] = $importer['uid'];
1601                                 $datarray['contact-id'] = $contact['id'];
1602                                 $r = item_store($datarray);
1603                                 continue;
1604
1605                         }
1606                 }
1607         }
1608 }
1609
1610 function local_delivery($importer,$data) {
1611
1612         $a = get_app();
1613
1614         if($importer['readonly']) {
1615                 // We aren't receiving stuff from this person. But we will quietly ignore them
1616                 // rather than a blatant "go away" message.
1617                 logger('local_delivery: ignoring');
1618                 return 0;
1619                 //NOTREACHED
1620         }
1621
1622         // Consume notification feed. This may differ from consuming a public feed in several ways
1623         // - might contain email or friend suggestions
1624         // - might contain remote followup to our message
1625         //              - in which case we need to accept it and then notify other conversants
1626         // - we may need to send various email notifications
1627
1628         $feed = new SimplePie();
1629         $feed->set_raw_data($data);
1630         $feed->enable_order_by_date(false);
1631         $feed->init();
1632
1633         $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
1634         if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
1635                 $base = $reloc[0]['child'][NAMESPACE_DFRN];
1636                 $newloc = array();
1637                 $newloc['uid'] = $importer['importer_uid'];
1638                 $newloc['cid'] = $importer['id'];
1639                 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
1640                 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
1641                 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
1642                 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
1643                 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
1644                 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
1645                 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
1646                 $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data']));
1647                 $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
1648                 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));
1649                 
1650                 // TODO
1651                 // merge with current record, current contents have priority
1652                 // update record, set url-updated
1653                 // update profile photos
1654                 // schedule a scan?
1655
1656         }
1657
1658         // handle friend suggestion notification
1659
1660         $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
1661         if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
1662                 $base = $sugg[0]['child'][NAMESPACE_DFRN];
1663                 $fsugg = array();
1664                 $fsugg['uid'] = $importer['importer_uid'];
1665                 $fsugg['cid'] = $importer['id'];
1666                 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
1667                 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
1668                 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
1669                 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
1670                 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
1671
1672                 // Does our member already have a friend matching this description?
1673
1674                 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1675                         dbesc($fsugg['name']),
1676                         dbesc(normalise_link($fsugg['url'])),
1677                         intval($fsugg['uid'])
1678                 );
1679                 if(count($r))
1680                         return 0;
1681
1682                 // Do we already have an fcontact record for this person?
1683
1684                 $fid = 0;
1685                 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1686                         dbesc($fsugg['url']),
1687                         dbesc($fsugg['name']),
1688                         dbesc($fsugg['request'])
1689                 );
1690                 if(count($r)) {
1691                         $fid = $r[0]['id'];
1692                 }
1693                 if(! $fid)
1694                         $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
1695                         dbesc($fsugg['name']),
1696                         dbesc($fsugg['url']),
1697                         dbesc($fsugg['photo']),
1698                         dbesc($fsugg['request'])
1699                 );
1700                 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1701                         dbesc($fsugg['url']),
1702                         dbesc($fsugg['name']),
1703                         dbesc($fsugg['request'])
1704                 );
1705                 if(count($r)) {
1706                         $fid = $r[0]['id'];
1707                 }
1708                 // database record did not get created. Quietly give up.
1709                 else
1710                         return 0;
1711
1712                 $hash = random_string();
1713  
1714                 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
1715                         VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
1716                         intval($fsugg['uid']),
1717                         intval($fid),
1718                         intval($fsugg['cid']),
1719                         dbesc($fsugg['body']),
1720                         dbesc($hash),
1721                         dbesc(datetime_convert()),
1722                         intval(0)
1723                 );
1724
1725                 // TODO - send email notify (which may require a new notification preference)
1726
1727                 return 0;
1728         }
1729
1730         $ismail = false;
1731
1732         $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
1733         if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
1734
1735                 logger('local_delivery: private message received');
1736
1737                 $ismail = true;
1738                 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
1739
1740                 $msg = array();
1741                 $msg['uid'] = $importer['importer_uid'];
1742                 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
1743                 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
1744                 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
1745                 $msg['contact-id'] = $importer['id'];
1746                 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
1747                 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
1748                 $msg['seen'] = 0;
1749                 $msg['replied'] = 0;
1750                 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
1751                 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
1752                 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
1753                 
1754                 dbesc_array($msg);
1755
1756                 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg)) 
1757                         . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
1758
1759                 // send email notification if requested.
1760
1761                 require_once('bbcode.php');
1762                 if($importer['notify-flags'] & NOTIFY_MAIL) {
1763
1764                         push_lang($importer['language']);
1765
1766                         // name of the automated email sender
1767                         $msg['notificationfromname']    = t('Administrator');
1768                         // noreply address to send from
1769                         $msg['notificationfromemail']   = t('noreply') . '@' . $a->get_hostname();                              
1770
1771                         // text version
1772                         // process the message body to display properly in text mode
1773                         //              1) substitute a \n character for the "\" then "n", so it behaves properly (it doesn't come in as a \n character)
1774                         //              2) remove escape slashes
1775                         //              3) decode any bbcode from the message editor
1776                         //              4) decode any encoded html tags
1777                         //              5) remove html tags
1778                         $msg['textversion']
1779                                 = strip_tags(html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n"), "\n",$msg['body']))),ENT_QUOTES,'UTF-8'));
1780                                 
1781                         // html version
1782                         // process the message body to display properly in text mode
1783                         //              1) substitute a <br /> tag for the "\" then "n", so it behaves properly (it doesn't come in as a \n character)
1784                         //              2) remove escape slashes
1785                         //              3) decode any bbcode from the message editor
1786                         //              4) decode any encoded html tags
1787                         $msg['htmlversion']     
1788                                 = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r","\\n\\n" ,"\\n"), "<br />\n",$msg['body']))));
1789
1790                         // load the template for private message notifications
1791                         $tpl = get_intltext_template('mail_received_html_body_eml.tpl');
1792                         $email_html_body_tpl = replace_macros($tpl,array(
1793                                 '$username'     => $importer['username'],
1794                                 '$siteName'             => $a->config['sitename'],                      // name of this site
1795                                 '$siteurl'              => $a->get_baseurl(),                           // descriptive url of this site
1796                                 '$thumb'                => $importer['thumb'],                          // thumbnail url for sender icon
1797                                 '$email'                => $importer['email'],                          // email address to send to
1798                                 '$url'                  => $importer['url'],                            // full url for the site
1799                                 '$from'                 => $msg['from-name'],                           // name of the person sending the message
1800                                 '$title'                => stripslashes($msg['title']),                 // subject of the message
1801                                 '$htmlversion'  => $msg['htmlversion'],                                 // html version of the message
1802                                 '$mimeboundary' => $msg['mimeboundary'],                                // mime message divider
1803                                 '$hostname'             => $a->get_hostname()                           // name of this host
1804                         ));
1805                         
1806                         // load the template for private message notifications
1807                         $tpl = get_intltext_template('mail_received_text_body_eml.tpl');
1808                         $email_text_body_tpl = replace_macros($tpl,array(
1809                                 '$username'     => $importer['username'],
1810                                 '$siteName'             => $a->config['sitename'],                      // name of this site
1811                                 '$siteurl'              => $a->get_baseurl(),                           // descriptive url of this site
1812                                 '$thumb'                => $importer['thumb'],                          // thumbnail url for sender icon
1813                                 '$email'                => $importer['email'],                          // email address to send to
1814                                 '$url'                  => $importer['url'],                            // full url for the site
1815                                 '$from'                 => $msg['from-name'],                           // name of the person sending the message
1816                                 '$title'                => stripslashes($msg['title']),                 // subject of the message
1817                                 '$textversion'  => $msg['textversion'],                                 // text version of the message
1818                                 '$mimeboundary' => $msg['mimeboundary'],                                // mime message divider
1819                                 '$hostname'             => $a->get_hostname()                           // name of this host
1820                         ));
1821
1822                         // use the EmailNotification library to send the message
1823                         require_once("include/EmailNotification.php");
1824                         EmailNotification::sendTextHtmlEmail(
1825                                 $msg['notificationfromname'],
1826                                 $msg['notificationfromemail'],
1827                                 $msg['notificationfromemail'],
1828                                 $importer['email'],
1829                                 t('New mail received at ') . $a->config['sitename'],
1830                                 $email_html_body_tpl,
1831                                 $email_text_body_tpl
1832                         );
1833
1834                         pop_lang();
1835                 }
1836                 return 0;
1837                 // NOTREACHED
1838         }       
1839         
1840         logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
1841
1842         // process any deleted entries
1843
1844         $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1845         if(is_array($del_entries) && count($del_entries)) {
1846                 foreach($del_entries as $dentry) {
1847                         $deleted = false;
1848                         if(isset($dentry['attribs']['']['ref'])) {
1849                                 $uri = $dentry['attribs']['']['ref'];
1850                                 $deleted = true;
1851                                 if(isset($dentry['attribs']['']['when'])) {
1852                                         $when = $dentry['attribs']['']['when'];
1853                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1854                                 }
1855                                 else
1856                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1857                         }
1858                         if($deleted) {
1859
1860                                 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
1861                                         WHERE `uri` = '%s' AND `uid` = %d AND `contact-id` = %d LIMIT 1",
1862                                         dbesc($uri),
1863                                         intval($importer['importer_uid']),
1864                                         intval($importer['id'])
1865                                 );
1866
1867                                 if(count($r)) {
1868                                         $item = $r[0];
1869
1870                                         if($item['deleted'])
1871                                                 continue;
1872
1873                                         logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1874
1875                                         if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTVITY_OBJ_TAGTERM)) {
1876                                                 $xo = parse_xml_string($item['object'],false);
1877                                                 $xt = parse_xml_string($item['target'],false);
1878                                                 if($xt->type === ACTIVITY_OBJ_NOTE) {
1879                                                         $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1880                                                                 dbesc($xt->id),
1881                                                                 intval($importer['importer_uid'])
1882                                                         );
1883                                                         if(count($i)) {
1884
1885                                                                 // For tags, the owner cannot remove the tag on the author's copy of the post.
1886                                                                 
1887                                                                 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1888                                                                 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1889                                                                 $author_copy = (($item['origin']) ? true : false); 
1890
1891                                                                 if($owner_remove && $author_copy)
1892                                                                         continue;
1893                                                                 if($author_remove || $owner_remove) {                                                           
1894                                                                         $tags = explode(',',$i[0]['tag']);
1895                                                                         $newtags = array();
1896                                                                         if(count($tags)) {
1897                                                                                 foreach($tags as $tag)
1898                                                                                         if(trim($tag) !== trim($xo->body))
1899                                                                                                 $newtags[] = trim($tag);
1900                                                                         }
1901                                                                         q("update item set tag = '%s' where id = %d limit 1",
1902                                                                                 dbesc(implode(',',$newtags)),
1903                                                                                 intval($i[0]['id'])
1904                                                                         );
1905                                                                 }
1906                                                         }
1907                                                 }
1908                                         }
1909
1910                                         if($item['uri'] == $item['parent-uri']) {
1911                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
1912                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
1913                                                         dbesc($when),
1914                                                         dbesc(datetime_convert()),
1915                                                         dbesc($item['uri']),
1916                                                         intval($importer['importer_uid'])
1917                                                 );
1918                                         }
1919                                         else {
1920                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' 
1921                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1922                                                         dbesc($when),
1923                                                         dbesc(datetime_convert()),
1924                                                         dbesc($uri),
1925                                                         intval($importer['importer_uid'])
1926                                                 );
1927                                                 if($item['last-child']) {
1928                                                         // ensure that last-child is set in case the comment that had it just got wiped.
1929                                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1930                                                                 dbesc(datetime_convert()),
1931                                                                 dbesc($item['parent-uri']),
1932                                                                 intval($item['uid'])
1933                                                         );
1934                                                         // who is the last child now? 
1935                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
1936                                                                 ORDER BY `created` DESC LIMIT 1",
1937                                                                         dbesc($item['parent-uri']),
1938                                                                         intval($importer['importer_uid'])
1939                                                         );
1940                                                         if(count($r)) {
1941                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1942                                                                         intval($r[0]['id'])
1943                                                                 );
1944                                                         }       
1945                                                 }
1946                                         }       
1947                                 }
1948                         }
1949                 }
1950         }
1951
1952
1953         foreach($feed->get_items() as $item) {
1954
1955                 $is_reply = false;              
1956                 $item_id = $item->get_id();
1957                 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
1958                 if(isset($rawthread[0]['attribs']['']['ref'])) {
1959                         $is_reply = true;
1960                         $parent_uri = $rawthread[0]['attribs']['']['ref'];
1961                 }
1962
1963                 if($is_reply) {
1964
1965                         // was the top-level post for this reply written by somebody on this site? 
1966                         // Specifically, the recipient? 
1967
1968                         $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, 
1969                                 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item` 
1970                                 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id` 
1971                                 WHERE `contact`.`self` = 1 AND `item`.`wall` = 1 AND `item`.`uri` = '%s' AND `item`.`parent-uri` = '%s'
1972                                 AND `item`.`uid` = %d LIMIT 1",
1973                                 dbesc($parent_uri),
1974                                 dbesc($parent_uri),
1975                                 intval($importer['importer_uid'])
1976                         );
1977                         if($r && count($r)) {   
1978
1979                                 logger('local_delivery: received remote comment');
1980                                 $is_like = false;
1981                                 // remote reply to our post. Import and then notify everybody else.
1982                                 $datarray = get_atom_elements($feed,$item);
1983
1984                                 if(! link_compare($datarray['author-link'],$importer['url'])) {
1985                                         logger('local_delivery: received relay claiming to be from ' . $importer['url'] . ' however comment author url is ' . $datarray['author-link'] ); 
1986                                         // they won't know what to do so don't report an error. Just quietly die.
1987                                         return 0;
1988                                 }                                       
1989
1990                                 $datarray['type'] = 'remote-comment';
1991                                 $datarray['wall'] = 1;
1992                                 $datarray['parent-uri'] = $parent_uri;
1993                                 $datarray['uid'] = $importer['importer_uid'];
1994                                 $datarray['owner-name'] = $r[0]['name'];
1995                                 $datarray['owner-link'] = $r[0]['url'];
1996                                 $datarray['owner-avatar'] = $r[0]['thumb'];
1997                                 $datarray['contact-id'] = $importer['id'];
1998                                 if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
1999                                         $is_like = true;
2000                                         $datarray['type'] = 'activity';
2001                                         $datarray['gravity'] = GRAVITY_LIKE;
2002                                         $datarray['last-child'] = 0;
2003                                 }
2004
2005                                 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2006
2007
2008                                         $xo = parse_xml_string($datarray['object'],false);
2009                                         $xt = parse_xml_string($datarray['target'],false);
2010
2011                                         if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id == $r[0]['uri'])) {
2012
2013                                                 // extract tag, if not duplicate, and this user allows tags, add to parent item                                         
2014                                                 if($xo->content) {
2015
2016                                                         if(! (stristr($r[0]['tag'],trim($xo->content)))) {
2017                                                                 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
2018                                                                         intval($importer['importer_uid'])
2019                                                                 );
2020                                                                 if(count($i) && ! ($i[0]['blocktags'])) {
2021                                                                         q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2022                                                                                 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2023                                                                                 intval($r[0]['id'])
2024                                                                         );
2025                                                                 }
2026                                                         }
2027                                                 }                                                                                                       
2028                                         }
2029                                 }
2030
2031                                 $posted_id = item_store($datarray);
2032                                 $parent = 0;
2033
2034                                 if($posted_id) {
2035                                         $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2036                                                 intval($posted_id),
2037                                                 intval($importer['importer_uid'])
2038                                         );
2039                                         if(count($r))
2040                                                 $parent = $r[0]['parent'];
2041                         
2042                                         if(! $is_like) {
2043                                                 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2044                                                         dbesc(datetime_convert()),
2045                                                         intval($importer['importer_uid']),
2046                                                         intval($r[0]['parent'])
2047                                                 );
2048
2049                                                 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2050                                                         dbesc(datetime_convert()),
2051                                                         intval($importer['importer_uid']),
2052                                                         intval($posted_id)
2053                                                 );
2054                                         }
2055
2056                                         if($posted_id && $parent) {
2057                                 
2058                                                 proc_run('php',"include/notifier.php","comment-import","$posted_id");
2059                                         
2060                                                 if((! $is_like) && ($importer['notify-flags'] & NOTIFY_COMMENT) && (! $importer['self'])) {
2061                                                         push_lang($importer['language']);
2062                                                         require_once('bbcode.php');
2063                                                         $from = stripslashes($datarray['author-name']);
2064
2065                                                         // name of the automated email sender
2066                                                         $msg['notificationfromname']    = stripslashes($datarray['author-name']);;
2067                                                         // noreply address to send from
2068                                                         $msg['notificationfromemail']   = t('noreply') . '@' . $a->get_hostname();                              
2069
2070                                                         // text version
2071                                                         // process the message body to display properly in text mode
2072                                                         $msg['textversion']
2073                                                                 = html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8');
2074                                 
2075                                                         // html version
2076                                                         // process the message body to display properly in text mode
2077                                                         $msg['htmlversion']     
2078                                                                 = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r","\\n\\n" ,"\\n"), "<br />\n",$datarray['body']))));
2079
2080                                                         $imgtouse = ((link_compare($datarray['author-link'],$importer['url'])) ? $importer['thumb'] : $datarray['author-avatar']);
2081
2082                                                         // load the template for private message notifications
2083                                                         $tpl = get_intltext_template('cmnt_received_html_body_eml.tpl');
2084                                                         $email_html_body_tpl = replace_macros($tpl,array(
2085                                                                 '$username'     => $importer['username'],
2086                                                                 '$sitename'             => $a->config['sitename'],                      // name of this site
2087                                                                 '$siteurl'              => $a->get_baseurl(),                           // descriptive url of this site
2088                                                                 '$thumb'                => $imgtouse,                                           // thumbnail url for sender icon
2089                                                                 '$email'                => $importer['email'],                          // email address to send to
2090                                                                 '$url'                  => $datarray['author-link'],            // full url for the site
2091                                                                 '$from'                 => $from,                                                       // name of the person sending the message
2092                                                                 '$body'                 => $msg['htmlversion'],                         // html version of the message
2093                                                                 '$display'              => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2094                                                         ));
2095                         
2096                                                         // load the template for private message notifications
2097                                                         $tpl = get_intltext_template('cmnt_received_text_body_eml.tpl');
2098                                                         $email_text_body_tpl = replace_macros($tpl,array(
2099                                                                 '$username'     => $importer['username'],
2100                                                                 '$sitename'             => $a->config['sitename'],                      // name of this site
2101                                                                 '$siteurl'              => $a->get_baseurl(),                           // descriptive url of this site
2102                                                                 '$thumb'                => $imgtouse,                                           // thumbnail url for sender icon
2103                                                                 '$email'                => $importer['email'],                          // email address to send to
2104                                                                 '$url'                  => $datarray['author-link'],            // full url for the site
2105                                                                 '$from'                 => $from,                                                       // name of the person sending the message
2106                                                                 '$body'                 => $msg['textversion'],                         // text version of the message
2107                                                                 '$display'              => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2108                                                         ));
2109
2110                                                         // use the EmailNotification library to send the message
2111                                                         require_once("include/EmailNotification.php");
2112                                                         EmailNotification::sendTextHtmlEmail(
2113                                                                 $msg['notificationfromname'],
2114                                                                 t("Administrator") . '@' . $a->get_hostname(),
2115                                                                 t("noreply") . '@' . $a->get_hostname(),
2116                                                                 $importer['email'],
2117                                                                 sprintf( t('%s commented on an item at %s'), $from , $a->config['sitename']),
2118                                                                 $email_html_body_tpl,
2119                                                                 $email_text_body_tpl
2120                                                         );
2121                                                         pop_lang();
2122                                                 }
2123                                         }
2124                                         return 0;
2125                                         // NOTREACHED
2126                                 }
2127                         }
2128                         else {
2129
2130                                 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
2131
2132                                 $item_id  = $item->get_id();
2133                                 $datarray = get_atom_elements($feed,$item);
2134
2135                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2136                                         dbesc($item_id),
2137                                         intval($importer['importer_uid'])
2138                                 );
2139
2140                                 // Update content if 'updated' changes
2141
2142                                 if(count($r)) {
2143                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
2144                                                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2145                                                         dbesc($datarray['body']),
2146                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2147                                                         dbesc($item_id),
2148                                                         intval($importer['importer_uid'])
2149                                                 );
2150                                         }
2151
2152                                         // update last-child if it changes
2153
2154                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2155                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
2156                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2157                                                         dbesc(datetime_convert()),
2158                                                         dbesc($parent_uri),
2159                                                         intval($importer['importer_uid'])
2160                                                 );
2161                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2162                                                         intval($allow[0]['data']),
2163                                                         dbesc(datetime_convert()),
2164                                                         dbesc($item_id),
2165                                                         intval($importer['importer_uid'])
2166                                                 );
2167                                         }
2168                                         continue;
2169                                 }
2170
2171                                 $datarray['parent-uri'] = $parent_uri;
2172                                 $datarray['uid'] = $importer['importer_uid'];
2173                                 $datarray['contact-id'] = $importer['id'];
2174                                 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
2175                                         $datarray['type'] = 'activity';
2176                                         $datarray['gravity'] = GRAVITY_LIKE;
2177                                 }
2178
2179                                 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2180
2181                                         $xo = parse_xml_string($datarray['object'],false);
2182                                         $xt = parse_xml_string($datarray['target'],false);
2183
2184                                         if($xt->type == ACTIVITY_OBJ_NOTE) {
2185                                                 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2186                                                         dbesc($xt->id),
2187                                                         intval($importer['importer_uid'])
2188                                                 );
2189                                                 if(! count($r))
2190                                                         continue;                               
2191
2192                                                 // extract tag, if not duplicate, add to parent item                                            
2193                                                 if($xo->content) {
2194                                                         if(! (stristr($r[0]['tag'],trim($xo->content)))) {
2195                                                                 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2196                                                                         dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2197                                                                         intval($r[0]['id'])
2198                                                                 );
2199                                                         }
2200                                                 }                                                                                                       
2201                                         }
2202                                 }
2203
2204                                 $posted_id = item_store($datarray);
2205
2206                                 // find out if our user is involved in this conversation and wants to be notified.
2207                         
2208                                 if(($datarray['type'] != 'activity') && ($importer['notify-flags'] & NOTIFY_COMMENT)) {
2209
2210                                         $myconv = q("SELECT `author-link`, `author-avatar` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 ",
2211                                                 dbesc($parent_uri),
2212                                                 intval($importer['importer_uid'])
2213                                         );
2214                                         if(count($myconv)) {
2215                                                 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
2216                                                 foreach($myconv as $conv) {
2217                                                         if(! link_compare($conv['author-link'],$importer_url))
2218                                                                 continue;
2219
2220                                                         push_lang($importer['language']);
2221                                                         require_once('bbcode.php');
2222                                                         $from = stripslashes($datarray['author-name']);
2223                                                         
2224                                                         // name of the automated email sender
2225                                                         $msg['notificationfromname']    = stripslashes($datarray['author-name']);;
2226                                                         // noreply address to send from
2227                                                         $msg['notificationfromemail']   = t('noreply') . '@' . $a->get_hostname();                              
2228
2229                                                         // text version
2230                                                         // process the message body to display properly in text mode
2231                                                         $msg['textversion']
2232                                                                 = html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8');
2233                                 
2234                                                         // html version
2235                                                         // process the message body to display properly in text mode
2236                                                         $msg['htmlversion']     
2237                                                                 = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r","\\n\\n" ,"\\n"), "<br />\n",$datarray['body']))));
2238
2239                                                         $imgtouse = ((link_compare($datarray['author-link'],$importer['url'])) ? $importer['thumb'] : $datarray['author-avatar']);
2240
2241
2242                                                         // load the template for private message notifications
2243                                                         $tpl = get_intltext_template('cmnt_received_html_body_eml.tpl');
2244                                                         $email_html_body_tpl = replace_macros($tpl,array(
2245                                                                 '$username'     => $importer['username'],
2246                                                                 '$sitename'             => $a->config['sitename'],                              // name of this site
2247                                                                 '$siteurl'              => $a->get_baseurl(),                                   // descriptive url of this site
2248                                                                 '$thumb'                => $imgtouse,                                                   // thumbnail url for sender icon
2249                                                                 '$url'                  => $datarray['author-link'],                    // full url for the site
2250                                                                 '$from'                 => $from,                                                               // name of the person sending the message
2251                                                                 '$body'                 => $msg['htmlversion'],                                 // html version of the message
2252                                                                 '$display'              => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2253                                                         ));
2254                         
2255                                                         // load the template for private message notifications
2256                                                         $tpl = get_intltext_template('cmnt_received_text_body_eml.tpl');
2257                                                         $email_text_body_tpl = replace_macros($tpl,array(
2258                                                                 '$username'     => $importer['username'],
2259                                                                 '$sitename'             => $a->config['sitename'],                              // name of this site
2260                                                                 '$siteurl'              => $a->get_baseurl(),                                   // descriptive url of this site
2261                                                                 '$thumb'                => $imgtouse,                                                   // thumbnail url for sender icon
2262                                                                 '$url'                  => $datarray['author-link'],                    // full url for the site
2263                                                                 '$from'                 => $from,                                                               // name of the person sending the message
2264                                                                 '$body'                 => $msg['textversion'],                                 // text version of the message
2265                                                                 '$display'              => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2266                                                         ));
2267
2268                                                         // use the EmailNotification library to send the message
2269                                                         require_once("include/EmailNotification.php");
2270                                                         EmailNotification::sendTextHtmlEmail(
2271                                                                 $msg['notificationfromname'],
2272                                                                 t("Administrator@") . $a->get_hostname(),
2273                                                                 t("noreply") . '@' . $a->get_hostname(),
2274                                                                 $importer['email'],
2275                                                                 sprintf( t('%s commented on an item at %s'), $from , $a->config['sitename']),
2276                                                                 $email_html_body_tpl,
2277                                                                 $email_text_body_tpl
2278                                                         );
2279                                                         pop_lang();
2280                                                         break;
2281                                                 }
2282                                         }
2283                                 }
2284                                 continue;
2285                         }
2286                 }
2287
2288                 else {
2289
2290                         // Head post of a conversation. Have we seen it? If not, import it.
2291
2292
2293                         $item_id  = $item->get_id();
2294                         $datarray = get_atom_elements($feed,$item);
2295
2296                         if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
2297                                 $ev = bbtoevent($datarray['body']);
2298                                 if(x($ev,'desc') && x($ev,'start')) {
2299                                         $ev['cid'] = $importer['id'];
2300                                         $ev['uid'] = $importer['uid'];
2301                                         $ev['uri'] = $item_id;
2302                                         $ev['edited'] = $datarray['edited'];
2303                                         $ev['private'] = $datarray['private'];
2304
2305                                         $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2306                                                 dbesc($item_id),
2307                                                 intval($importer['uid'])
2308                                         );
2309                                         if(count($r))
2310                                                 $ev['id'] = $r[0]['id'];
2311                                         $xyz = event_store($ev);
2312                                         continue;
2313                                 }
2314                         }
2315
2316                         $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2317                                 dbesc($item_id),
2318                                 intval($importer['importer_uid'])
2319                         );
2320
2321                         // Update content if 'updated' changes
2322
2323                         if(count($r)) {
2324                                 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
2325                                         $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2326                                                 dbesc($datarray['body']),
2327                                                 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2328                                                 dbesc($item_id),
2329                                                 intval($importer['importer_uid'])
2330                                         );
2331                                 }
2332
2333                                 // update last-child if it changes
2334
2335                                 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2336                                 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2337                                         $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2338                                                 intval($allow[0]['data']),
2339                                                 dbesc(datetime_convert()),
2340                                                 dbesc($item_id),
2341                                                 intval($importer['importer_uid'])
2342                                         );
2343                                 }
2344                                 continue;
2345                         }
2346
2347                         // This is my contact on another system, but it's really me.
2348                         // Turn this into a wall post.
2349
2350                         if($contact['remote_self'])
2351                                 $datarray['wall'] = 1;
2352
2353                         $datarray['parent-uri'] = $item_id;
2354                         $datarray['uid'] = $importer['importer_uid'];
2355                         $datarray['contact-id'] = $importer['id'];
2356                         $r = item_store($datarray);
2357                         continue;
2358                 }
2359         }
2360
2361         return 0;
2362         // NOTREACHED
2363
2364 }
2365
2366
2367 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
2368         $url = notags(trim($datarray['author-link']));
2369         $name = notags(trim($datarray['author-name']));
2370         $photo = notags(trim($datarray['author-avatar']));
2371
2372         $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
2373         if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
2374                 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
2375
2376         if(is_array($contact)) {
2377                 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
2378                         || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
2379                         $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
2380                                 intval(CONTACT_IS_FRIEND),
2381                                 intval($contact['id']),
2382                                 intval($importer['uid'])
2383                         );
2384                 }
2385                 // send email notification to owner?
2386         }
2387         else {
2388         
2389                 // create contact record
2390
2391                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`, 
2392                         `blocked`, `readonly`, `pending`, `writable` )
2393                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
2394                         intval($importer['uid']),
2395                         dbesc(datetime_convert()),
2396                         dbesc($url),
2397                         dbesc(normalise_link($url)),
2398                         dbesc($name),
2399                         dbesc($nick),
2400                         dbesc($photo),
2401                         dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
2402                         intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
2403                 );
2404                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
2405                                 intval($importer['uid']),
2406                                 dbesc($url)
2407                 );
2408                 if(count($r))
2409                                 $contact_record = $r[0];
2410
2411                 // create notification  
2412                 $hash = random_string();
2413
2414                 if(is_array($contact_record)) {
2415                         $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
2416                                 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
2417                                 intval($importer['uid']),
2418                                 intval($contact_record['id']),
2419                                 dbesc($hash),
2420                                 dbesc(datetime_convert())
2421                         );
2422                 }
2423                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
2424                         intval($importer['uid'])
2425                 );
2426                 $a = get_app();
2427                 if(count($r)) {
2428                         if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
2429                                 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
2430                                 $email = replace_macros($email_tpl, array(
2431                                         '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
2432                                         '$url' => $url,
2433                                         '$myname' => $r[0]['username'],
2434                                         '$siteurl' => $a->get_baseurl(),
2435                                         '$sitename' => $a->config['sitename']
2436                                 ));
2437                                 $res = mail($r[0]['email'], 
2438                                         (($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],
2439                                         $email,
2440                                         'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
2441                                         . 'Content-type: text/plain; charset=UTF-8' . "\n"
2442                                         . 'Content-transfer-encoding: 8bit' );
2443                         
2444                         }
2445                 }
2446         }
2447 }
2448
2449 function lose_follower($importer,$contact,$datarray,$item) {
2450
2451         if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
2452                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2453                         intval(CONTACT_IS_SHARING),
2454                         intval($contact['id'])
2455                 );
2456         }
2457         else {
2458                 contact_remove($contact['id']);
2459         }
2460 }
2461
2462 function lose_sharer($importer,$contact,$datarray,$item) {
2463
2464         if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
2465                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2466                         intval(CONTACT_IS_FOLLOWER),
2467                         intval($contact['id'])
2468                 );
2469         }
2470         else {
2471                 contact_remove($contact['id']);
2472         }
2473 }
2474
2475
2476 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
2477
2478         if(is_array($importer)) {
2479                 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
2480                         intval($importer['uid'])
2481                 );
2482         }
2483
2484         // Diaspora has different message-ids in feeds than they do 
2485         // through the direct Diaspora protocol. If we try and use
2486         // the feed, we'll get duplicates. So don't.
2487
2488         if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
2489                 return;
2490
2491         $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
2492
2493         // Use a single verify token, even if multiple hubs
2494
2495         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
2496
2497         $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
2498
2499         logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: '  . $push_url . ' with verifier ' . $verify_token);
2500
2501         if(! strlen($contact['hub-verify'])) {
2502                 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
2503                         dbesc($verify_token),
2504                         intval($contact['id'])
2505                 );
2506         }
2507
2508         post_url($url,$params);                 
2509         return;
2510
2511 }
2512
2513
2514 function atom_author($tag,$name,$uri,$h,$w,$photo) {
2515         $o = '';
2516         if(! $tag)
2517                 return $o;
2518         $name = xmlify($name);
2519         $uri = xmlify($uri);
2520         $h = intval($h);
2521         $w = intval($w);
2522         $photo = xmlify($photo);
2523
2524
2525         $o .= "<$tag>\r\n";
2526         $o .= "<name>$name</name>\r\n";
2527         $o .= "<uri>$uri</uri>\r\n";
2528         $o .= '<link rel="photo"  type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2529         $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2530
2531         call_hooks('atom_author', $o);
2532
2533         $o .= "</$tag>\r\n";
2534         return $o;
2535 }
2536
2537 function atom_entry($item,$type,$author,$owner,$comment = false) {
2538
2539         $a = get_app();
2540
2541         if(! $item['parent'])
2542                 return;
2543
2544         if($item['deleted'])
2545                 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
2546
2547
2548         if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
2549                 $body = fix_private_photos($item['body'],$owner['uid']);
2550         else
2551                 $body = $item['body'];
2552
2553
2554         $o = "\r\n\r\n<entry>\r\n";
2555
2556         if(is_array($author))
2557                 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
2558         else
2559                 $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']));
2560         if(strlen($item['owner-name']))
2561                 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
2562
2563         if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']))
2564                 $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";
2565
2566         $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
2567         $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
2568         $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
2569         $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
2570         $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
2571         $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
2572         $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
2573         if($comment)
2574                 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
2575
2576         if($item['location']) {
2577                 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
2578                 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
2579         }
2580
2581         if($item['coord'])
2582                 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
2583
2584         if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
2585                 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
2586
2587         if($item['extid'])
2588                 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
2589         if($item['bookmark'])
2590                 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
2591
2592         if($item['app'])
2593                 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
2594
2595         if($item['guid'])
2596                 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
2597
2598         if($item['signed_text']) {
2599                 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
2600                 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
2601         }
2602
2603         $verb = construct_verb($item);
2604         $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
2605         $actobj = construct_activity_object($item);
2606         if(strlen($actobj))
2607                 $o .= $actobj;
2608         $actarg = construct_activity_target($item);
2609         if(strlen($actarg))
2610                 $o .= $actarg;
2611
2612         $tags = item_getfeedtags($item);
2613         if(count($tags)) {
2614                 foreach($tags as $t) {
2615                         $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
2616                 }
2617         }
2618
2619         $o .= item_getfeedattach($item);
2620
2621         $mentioned = get_mentions($item);
2622         if($mentioned)
2623                 $o .= $mentioned;
2624         
2625         call_hooks('atom_entry', $o);
2626
2627         $o .= '</entry>' . "\r\n";
2628         
2629         return $o;
2630 }
2631
2632 function fix_private_photos($s,$uid) {
2633         $a = get_app();
2634         logger('fix_private_photos');
2635
2636         if(preg_match("/\[img\](.*?)\[\/img\]/is",$s,$matches)) {
2637                 $image = $matches[1];
2638                 logger('fix_private_photos: found photo ' . $image);
2639                 if(stristr($image ,$a->get_baseurl() . '/photo/')) {
2640                         $i = basename($image);
2641                         $i = str_replace('.jpg','',$i);
2642                         $x = strpos($i,'-');
2643                         if($x) {
2644                                 $res = substr($i,$x+1);
2645                                 $i = substr($i,0,$x);
2646                                 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
2647                                         dbesc($i),
2648                                         intval($res),
2649                                         intval($uid)
2650                                 );
2651                                 if(count($r)) {
2652                                         logger('replacing photo');
2653                                         $s = str_replace($image, 'data:image/jpg;base64,' . base64_encode($r[0]['data']), $s);
2654                                 }
2655                         }
2656                         logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
2657                 }       
2658         }
2659         return($s);
2660 }
2661
2662
2663
2664 function item_getfeedtags($item) {
2665         $ret = array();
2666         $matches = false;
2667         $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
2668         if($cnt) {
2669                 for($x = 0; $x < count($matches); $x ++) {
2670                         if($matches[1][$x])
2671                                 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
2672                 }
2673         }
2674         $matches = false; 
2675         $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
2676         if($cnt) {
2677                 for($x = 0; $x < count($matches); $x ++) {
2678                         if($matches[1][$x])
2679                                 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
2680                 }
2681         } 
2682         return $ret;
2683 }
2684
2685 function item_getfeedattach($item) {
2686         $ret = '';
2687         $arr = explode(',',$item['attach']);
2688         if(count($arr)) {
2689                 foreach($arr as $r) {
2690                         $matches = false;
2691                         $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
2692                         if($cnt) {
2693                                 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
2694                                 if(intval($matches[2]))
2695                                         $ret .= 'length="' . intval($matches[2]) . '" ';
2696                                 if($matches[4] !== ' ')
2697                                         $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
2698                                 $ret .= ' />' . "\r\n";
2699                         }
2700                 }
2701         }
2702         return $ret;
2703 }
2704
2705
2706         
2707 function item_expire($uid,$days) {
2708
2709         if((! $uid) || (! $days))
2710                 return;
2711
2712         $r = q("SELECT * FROM `item` 
2713                 WHERE `uid` = %d 
2714                 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY 
2715                 AND `id` = `parent` 
2716                 AND `deleted` = 0",
2717                 intval($uid),
2718                 intval($days)
2719         );
2720
2721         if(! count($r))
2722                 return;
2723  
2724         logger('expire: # items=' . count($r) );
2725
2726         foreach($r as $item) {
2727
2728                 // Only expire posts, not photos and photo comments
2729
2730                 if(strlen($item['resource-id']))
2731                         continue;
2732
2733                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
2734                         dbesc(datetime_convert()),
2735                         dbesc(datetime_convert()),
2736                         intval($item['id'])
2737                 );
2738
2739                 // kill the kids
2740
2741                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2742                         dbesc(datetime_convert()),
2743                         dbesc(datetime_convert()),
2744                         dbesc($item['parent-uri']),
2745                         intval($item['uid'])
2746                 );
2747
2748         }
2749
2750         proc_run('php',"include/notifier.php","expire","$uid");
2751
2752 }
2753
2754
2755 function drop_items($items) {
2756         $uid = 0;
2757
2758         if(count($items)) {
2759                 foreach($items as $item) {
2760                         $owner = drop_item($item,false);
2761                         if($owner && ! $uid)
2762                                 $uid = $owner;
2763                 }
2764         }
2765
2766         // multiple threads may have been deleted, send an expire notification
2767
2768         if($uid)
2769                 proc_run('php',"include/notifier.php","expire","$uid");
2770 }
2771
2772
2773 function drop_item($id,$interactive = true) {
2774
2775         $a = get_app();
2776
2777         // locate item to be deleted
2778
2779         $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
2780                 intval($id)
2781         );
2782
2783         if(! count($r)) {
2784                 if(! $interactive)
2785                         return 0;
2786                 notice( t('Item not found.') . EOL);
2787                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
2788         }
2789
2790         $item = $r[0];
2791
2792         $owner = $item['uid'];
2793
2794         // check if logged in user is either the author or owner of this item
2795
2796         if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
2797
2798                 // delete the item
2799
2800                 $r = q("UPDATE `item` SET `deleted` = 1, `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
2801                         dbesc(datetime_convert()),
2802                         dbesc(datetime_convert()),
2803                         intval($item['id'])
2804                 );
2805
2806                 // If item is a link to a photo resource, nuke all the associated photos 
2807                 // (visitors will not have photo resources)
2808                 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
2809                 // generate a resource-id and therefore aren't intimately linked to the item. 
2810
2811                 if(strlen($item['resource-id'])) {
2812                         q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
2813                                 dbesc($item['resource-id']),
2814                                 intval($item['uid'])
2815                         );
2816                         // ignore the result
2817                 }
2818
2819                 // If item is a link to an event, nuke the event record.
2820
2821                 if(intval($item['event-id'])) {
2822                         q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2823                                 intval($item['event-id']),
2824                                 intval($item['uid'])
2825                         );
2826                         // ignore the result
2827                 }
2828
2829
2830                 // If it's the parent of a comment thread, kill all the kids
2831
2832                 if($item['uri'] == $item['parent-uri']) {
2833                         $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' 
2834                                 WHERE `parent-uri` = '%s' AND `uid` = %d ",
2835                                 dbesc(datetime_convert()),
2836                                 dbesc(datetime_convert()),
2837                                 dbesc($item['parent-uri']),
2838                                 intval($item['uid'])
2839                         );
2840                         // ignore the result
2841                 }
2842                 else {
2843                         // ensure that last-child is set in case the comment that had it just got wiped.
2844                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2845                                 dbesc(datetime_convert()),
2846                                 dbesc($item['parent-uri']),
2847                                 intval($item['uid'])
2848                         );
2849                         // who is the last child now? 
2850                         $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",
2851                                 dbesc($item['parent-uri']),
2852                                 intval($item['uid'])
2853                         );
2854                         if(count($r)) {
2855                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2856                                         intval($r[0]['id'])
2857                                 );
2858                         }       
2859                 }
2860                 $drop_id = intval($item['id']);
2861                         
2862                 // send the notification upstream/downstream as the case may be
2863
2864                 if(! $interactive)
2865                         return $owner;
2866
2867                 proc_run('php',"include/notifier.php","drop","$drop_id");
2868                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
2869                 //NOTREACHED
2870         }
2871         else {
2872                 if(! $interactive)
2873                         return 0;
2874                 notice( t('Permission denied.') . EOL);
2875                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
2876                 //NOTREACHED
2877         }
2878         
2879 }