]> git.mxchange.org Git - friendica.git/blob - include/items.php
bug #157 - allow deleted group to be revived, but warn of side effects
[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'] = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
418                         '[youtube]$1[/youtube]', $res['body']);
419
420                 $res['body'] = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
421                         '[youtube]$1[/youtube]', $res['body']);
422
423                 $res['body'] = oembed_html2bbcode($res['body']);
424
425                 $config = HTMLPurifier_Config::createDefault();
426                 $config->set('Cache.DefinitionImpl', null);
427
428                 // we shouldn't need a whitelist, because the bbcode converter
429                 // will strip out any unsupported tags.
430                 // $config->set('HTML.Allowed', 'p,b,a[href],i'); 
431
432                 $purifier = new HTMLPurifier($config);
433                 $res['body'] = $purifier->purify($res['body']);
434
435                 $res['body'] = html2bbcode($res['body']);
436         }
437
438         $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
439         if($allow && $allow[0]['data'] == 1)
440                 $res['last-child'] = 1;
441         else
442                 $res['last-child'] = 0;
443
444         $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
445         if($private && $private[0]['data'] == 1)
446                 $res['private'] = 1;
447         else
448                 $res['private'] = 0;
449
450         $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
451         if($extid && $extid[0]['data'])
452                 $res['extid'] = $extid[0]['data'];
453
454         $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
455         if($rawlocation)
456                 $res['location'] = unxmlify($rawlocation[0]['data']);
457
458
459         $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
460         if($rawcreated)
461                 $res['created'] = unxmlify($rawcreated[0]['data']);
462
463
464         $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
465         if($rawedited)
466                 $res['edited'] = unxmlify($rawedited[0]['data']);
467
468         if((x($res,'edited')) && (! (x($res,'created'))))
469                 $res['created'] = $res['edited']; 
470
471         if(! $res['created'])
472                 $res['created'] = $item->get_date('c');
473
474         if(! $res['edited'])
475                 $res['edited'] = $item->get_date('c');
476
477
478         // Disallow time travelling posts
479
480         $d1 = strtotime($res['created']);
481         $d2 = strtotime($res['edited']);
482         $d3 = strtotime('now');
483
484         if($d1 > $d3)
485                 $res['created'] = datetime_convert();
486         if($d2 > $d3)
487                 $res['edited'] = datetime_convert();
488
489         $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
490         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
491                 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
492         elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
493                 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
494         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
495                 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
496         elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
497                 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
498
499         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
500                 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
501
502                 foreach($base as $link) {
503                         if(! $res['owner-avatar']) {
504                                 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')                 
505                                         $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
506                         }
507                 }
508         }
509
510         $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
511         if($rawgeo)
512                 $res['coord'] = unxmlify($rawgeo[0]['data']);
513
514
515         $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
516
517         // select between supported verbs
518
519         if($rawverb) {
520                 $res['verb'] = unxmlify($rawverb[0]['data']);
521         }
522
523         // translate OStatus unfollow to activity streams if it happened to get selected
524                 
525         if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
526                 $res['verb'] = ACTIVITY_UNFOLLOW;
527
528         $cats = $item->get_categories();
529         if($cats) {
530                 $tag_arr = array();
531                 foreach($cats as $cat) {
532                         $term = $cat->get_term();
533                         if(! $term)
534                                 $term = $cat->get_label();
535                         $scheme = $cat->get_scheme();
536                         if($scheme && $term && stristr($scheme,'X-DFRN:'))
537                                 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
538                         elseif($term)
539                                 $tag_arr[] = notags(trim($term));
540                 }
541                 $res['tag'] =  implode(',', $tag_arr);
542         }
543
544         $attach = $item->get_enclosures();
545         if($attach) {
546                 $att_arr = array();
547                 foreach($attach as $att) {
548                         $len   = intval($att->get_length());
549                         $link  = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
550                         $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
551                         $type  = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
552                         if(strpos($type,';'))
553                                 $type = substr($type,0,strpos($type,';'));
554                         if((! $link) || (strpos($link,'http') !== 0))
555                                 continue;
556
557                         if(! $title)
558                                 $title = ' ';
559                         if(! $type)
560                                 $type = 'application/octet-stream';
561
562                         $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]'; 
563                 }
564                 $res['attach'] = implode(',', $att_arr);
565         }
566
567         $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
568
569         if($rawobj) {
570                 $res['object'] = '<object>' . "\n";
571                 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
572                         $res['object-type'] = $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'];
573                         $res['object'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
574                 }       
575                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
576                         $res['object'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
577                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
578                         $res['object'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
579                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
580                         $res['object'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
581                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
582                         $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
583                         if(! $body)
584                                 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
585                         // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
586                         $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
587                         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
588
589                                 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
590                                         '[youtube]$1[/youtube]', $body);
591
592                 $res['body'] = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
593                         '[youtube]$1[/youtube]', $res['body']);
594
595
596                                 $config = HTMLPurifier_Config::createDefault();
597                                 $config->set('Cache.DefinitionImpl', null);
598
599                                 $purifier = new HTMLPurifier($config);
600                                 $body = $purifier->purify($body);
601                                 $body = html2bbcode($body);
602                         }
603
604                         $res['object'] .= '<content>' . $body . '</content>' . "\n";
605                 }
606
607                 $res['object'] .= '</object>' . "\n";
608         }
609
610         $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
611
612         if($rawobj) {
613                 $res['target'] = '<target>' . "\n";
614                 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
615                         $res['target'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
616                 }       
617                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
618                         $res['target'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
619
620                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
621                         $res['target'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
622                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
623                         $res['target'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
624                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
625                         $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
626                         if(! $body)
627                                 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
628                         // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
629                         $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
630                         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
631
632                                 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
633                                         '[youtube]$1[/youtube]', $body);
634
635                 $res['body'] = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
636                         '[youtube]$1[/youtube]', $res['body']);
637
638                                 $config = HTMLPurifier_Config::createDefault();
639                                 $config->set('Cache.DefinitionImpl', null);
640
641                                 $purifier = new HTMLPurifier($config);
642                                 $body = $purifier->purify($body);
643                                 $body = html2bbcode($body);
644                         }
645
646                         $res['target'] .= '<content>' . $body . '</content>' . "\n";
647                 }
648
649                 $res['target'] .= '</target>' . "\n";
650         }
651
652         $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
653
654         call_hooks('parse_atom', $arr);
655
656         return $res;
657 }
658
659 function encode_rel_links($links) {
660         $o = '';
661         if(! ((is_array($links)) && (count($links))))
662                 return $o;
663         foreach($links as $link) {
664                 $o .= '<link ';
665                 if($link['attribs']['']['rel'])
666                         $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
667                 if($link['attribs']['']['type'])
668                         $o .= 'type="' . $link['attribs']['']['type'] . '" ';
669                 if($link['attribs']['']['href'])
670                         $o .= 'href="' . $link['attribs']['']['href'] . '" ';
671                 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
672                         $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
673                 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
674                         $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
675                 $o .= ' />' . "\n" ;
676         }
677         return xmlify($o);
678 }
679
680 function item_store($arr,$force_parent = false) {
681
682         // If a Diaspora signature structure was passed in, pull it out of the 
683         // item array and set it aside for later storage.
684
685         $dsprsig = null;
686         if(x($arr,'dsprsig')) {
687                 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
688                 unset($arr['dsprsig']);
689         }
690
691         if($arr['gravity'])
692                 $arr['gravity'] = intval($arr['gravity']);
693         elseif($arr['parent-uri'] == $arr['uri'])
694                 $arr['gravity'] = 0;
695         elseif(activity_match($arr['verb'],ACTIVITY_POST))
696                 $arr['gravity'] = 6;
697         else      
698                 $arr['gravity'] = 6;   // extensible catchall
699
700         if(! x($arr,'type'))
701                 $arr['type']      = 'remote';
702
703         // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
704
705         if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false)) 
706                 $arr['body'] = strip_tags($arr['body']);
707
708
709         $arr['wall']          = ((x($arr,'wall'))          ? intval($arr['wall'])                : 0);
710         $arr['uri']           = ((x($arr,'uri'))           ? notags(trim($arr['uri']))           : random_string());
711         $arr['extid']         = ((x($arr,'extid'))         ? notags(trim($arr['extid']))         : '');
712         $arr['author-name']   = ((x($arr,'author-name'))   ? notags(trim($arr['author-name']))   : '');
713         $arr['author-link']   = ((x($arr,'author-link'))   ? notags(trim($arr['author-link']))   : '');
714         $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
715         $arr['owner-name']    = ((x($arr,'owner-name'))    ? notags(trim($arr['owner-name']))    : '');
716         $arr['owner-link']    = ((x($arr,'owner-link'))    ? notags(trim($arr['owner-link']))    : '');
717         $arr['owner-avatar']  = ((x($arr,'owner-avatar'))  ? notags(trim($arr['owner-avatar']))  : '');
718         $arr['created']       = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
719         $arr['edited']        = ((x($arr,'edited')  !== false) ? datetime_convert('UTC','UTC',$arr['edited'])  : datetime_convert());
720         $arr['received']      = datetime_convert();
721         $arr['changed']       = datetime_convert();
722         $arr['title']         = ((x($arr,'title'))         ? notags(trim($arr['title']))         : '');
723         $arr['location']      = ((x($arr,'location'))      ? notags(trim($arr['location']))      : '');
724         $arr['coord']         = ((x($arr,'coord'))         ? notags(trim($arr['coord']))         : '');
725         $arr['last-child']    = ((x($arr,'last-child'))    ? intval($arr['last-child'])          : 0 );
726         $arr['visible']       = ((x($arr,'visible') !== false) ? intval($arr['visible'])         : 1 );
727         $arr['deleted']       = 0;
728         $arr['parent-uri']    = ((x($arr,'parent-uri'))    ? notags(trim($arr['parent-uri']))    : '');
729         $arr['verb']          = ((x($arr,'verb'))          ? notags(trim($arr['verb']))          : '');
730         $arr['object-type']   = ((x($arr,'object-type'))   ? notags(trim($arr['object-type']))   : '');
731         $arr['object']        = ((x($arr,'object'))        ? trim($arr['object'])                : '');
732         $arr['target-type']   = ((x($arr,'target-type'))   ? notags(trim($arr['target-type']))   : '');
733         $arr['target']        = ((x($arr,'target'))        ? trim($arr['target'])                : '');
734         $arr['plink']         = ((x($arr,'plink'))         ? notags(trim($arr['plink']))         : '');
735         $arr['allow_cid']     = ((x($arr,'allow_cid'))     ? trim($arr['allow_cid'])             : '');
736         $arr['allow_gid']     = ((x($arr,'allow_gid'))     ? trim($arr['allow_gid'])             : '');
737         $arr['deny_cid']      = ((x($arr,'deny_cid'))      ? trim($arr['deny_cid'])              : '');
738         $arr['deny_gid']      = ((x($arr,'deny_gid'))      ? trim($arr['deny_gid'])              : '');
739         $arr['private']       = ((x($arr,'private'))       ? intval($arr['private'])             : 0 );
740         $arr['bookmark']      = ((x($arr,'bookmark'))      ? intval($arr['bookmark'])            : 0 );
741         $arr['body']          = ((x($arr,'body'))          ? trim($arr['body'])                  : '');
742         $arr['tag']           = ((x($arr,'tag'))           ? notags(trim($arr['tag']))           : '');
743         $arr['attach']        = ((x($arr,'attach'))        ? notags(trim($arr['attach']))        : '');
744         $arr['app']           = ((x($arr,'app'))           ? notags(trim($arr['app']))           : '');
745         $arr['guid']          = ((x($arr,'guid'))          ? notags(trim($arr['guid']))          : get_guid());
746
747         if($arr['parent-uri'] === $arr['uri']) {
748                 $parent_id = 0;
749                 $allow_cid = $arr['allow_cid'];
750                 $allow_gid = $arr['allow_gid'];
751                 $deny_cid  = $arr['deny_cid'];
752                 $deny_gid  = $arr['deny_gid'];
753         }
754         else { 
755
756                 // find the parent and snarf the item id and ACL's
757                 // and anything else we need to inherit
758
759                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
760                         dbesc($arr['parent-uri']),
761                         intval($arr['uid'])
762                 );
763
764                 if(count($r)) {
765
766                         // is the new message multi-level threaded?
767                         // even though we don't support it now, preserve the info
768                         // and re-attach to the conversation parent.
769
770                         if($r[0]['uri'] != $r[0]['parent-uri']) {
771                                 $arr['thr-parent'] = $arr['parent-uri'];
772                                 $arr['parent-uri'] = $r[0]['parent-uri'];
773                                 $z = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d LIMIT 1",
774                                         dbesc($r[0]['parent-uri']),
775                                         dbesc($r[0]['parent-uri']),
776                                         intval($arr['uid'])
777                                 );
778                                 if($z && count($z))
779                                         $r = $z;
780                         }
781
782                         $parent_id      = $r[0]['id'];
783                         $parent_deleted = $r[0]['deleted'];
784                         $allow_cid      = $r[0]['allow_cid'];
785                         $allow_gid      = $r[0]['allow_gid'];
786                         $deny_cid       = $r[0]['deny_cid'];
787                         $deny_gid       = $r[0]['deny_gid'];
788                         $arr['wall']    = $r[0]['wall'];
789                 }
790                 else {
791
792                         // Allow one to see reply tweets from status.net even when
793                         // we don't have or can't see the original post.
794
795                         if($force_parent) {
796                                 logger('item_store: $force_parent=true, reply converted to top-level post.');
797                                 $parent_id = 0;
798                                 $arr['thr-parent'] = $arr['parent-uri'];
799                                 $arr['parent-uri'] = $arr['uri'];
800                                 $arr['gravity'] = 0;
801                         }
802                         else {
803                                 logger('item_store: item parent was not found - ignoring item');
804                                 return 0;
805                         }
806                 }
807         }
808
809
810         call_hooks('post_remote',$arr);
811
812         dbesc_array($arr);
813
814         logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
815
816         $r = dbq("INSERT INTO `item` (`" 
817                         . implode("`, `", array_keys($arr)) 
818                         . "`) VALUES ('" 
819                         . implode("', '", array_values($arr)) 
820                         . "')" );
821
822         // find the item we just created
823
824         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
825                 $arr['uri'],           // already dbesc'd
826                 intval($arr['uid'])
827         );
828         if(! count($r)) {
829                 // This is not good, but perhaps we encountered a rare race/cache condition, so back off and try again. 
830                 sleep(3);
831                 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
832                         $arr['uri'],           // already dbesc'd
833                         intval($arr['uid'])
834                 );
835         }
836
837         if(count($r)) {
838                 $current_post = $r[0]['id'];
839                 logger('item_store: created item ' . $current_post);
840         }
841         else {
842                 logger('item_store: could not locate created item');
843                 return 0;
844         }
845
846         if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))      
847                 $parent_id = $current_post;
848
849         if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
850                 $private = 1;
851         else
852                 $private = $arr['private']; 
853
854         // Set parent id - and also make sure to inherit the parent's ACL's.
855
856         $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
857                 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
858                 intval($parent_id),
859                 dbesc($allow_cid),
860                 dbesc($allow_gid),
861                 dbesc($deny_cid),
862                 dbesc($deny_gid),
863                 intval($private),
864                 intval($parent_deleted),
865                 intval($current_post)
866         );
867
868         // update the timestamp on the parent
869
870         q("UPDATE `item` set `changed` = '%s' WHERE `id` = %d LIMIT 1",
871                 dbesc(datetime_convert()),
872                 intval($parent_id)
873         );
874
875         if($dsprsig) {
876                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
877                         intval($current_post),
878                         dbesc($dsprsig->signed_text),
879                         dbesc($dsprsig->signature),
880                         dbesc($dsprsig->signer)
881                 );
882         }
883
884
885         /**
886          * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
887          */
888
889         if($arr['last-child']) {
890                 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
891                         dbesc($arr['uri']),
892                         intval($arr['uid']),
893                         intval($current_post)
894                 );
895         }
896
897         return $current_post;
898 }
899
900 function get_item_contact($item,$contacts) {
901         if(! count($contacts) || (! is_array($item)))
902                 return false;
903         foreach($contacts as $contact) {
904                 if($contact['id'] == $item['contact-id']) {
905                         return $contact;
906                         break; // NOTREACHED
907                 }
908         }
909         return false;
910 }
911
912
913 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
914
915         $a = get_app();
916
917         if((! strlen($contact['issued-id'])) && (! $contact['duplex']) && (! ($owner['page-flags'] == PAGE_COMMUNITY)))
918                 return 3;
919
920         $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
921
922         if($contact['duplex'] && $contact['dfrn-id'])
923                 $idtosend = '0:' . $orig_id;
924         if($contact['duplex'] && $contact['issued-id'])
925                 $idtosend = '1:' . $orig_id;            
926
927         $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
928
929         $rino_enable = get_config('system','rino_encrypt');
930
931         if(! $rino_enable)
932                 $rino = 0;
933
934         $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
935
936         logger('dfrn_deliver: ' . $url);
937
938         $xml = fetch_url($url);
939
940         $curl_stat = $a->get_curl_code();
941         if(! $curl_stat)
942                 return(-1); // timed out
943
944         logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
945
946         if(! $xml)
947                 return 3;
948
949         if(strpos($xml,'<?xml') === false) {
950                 logger('dfrn_deliver: no valid XML returned');
951                 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
952                 return 3;
953         }
954
955         $res = parse_xml_string($xml);
956
957         if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
958                 return (($res->status) ? $res->status : 3);
959
960         $postvars     = array();
961         $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
962         $challenge    = hex2bin((string) $res->challenge);
963         $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
964         $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
965
966         $final_dfrn_id = '';
967
968
969         if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
970                 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
971                 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
972         }
973         else {
974                 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
975                 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
976         }
977
978         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
979
980         if(strpos($final_dfrn_id,':') == 1)
981                 $final_dfrn_id = substr($final_dfrn_id,2);
982
983         if($final_dfrn_id != $orig_id) {
984                 logger('dfrn_deliver: wrong dfrn_id.');
985                 // did not decode properly - cannot trust this site 
986                 return 3;
987         }
988
989         $postvars['dfrn_id']      = $idtosend;
990         $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
991         if($dissolve)
992                 $postvars['dissolve'] = '1';
993
994
995         if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
996                 $postvars['data'] = $atom;
997                 $postvars['perm'] = 'rw';
998         }
999         else {
1000                 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1001                 $postvars['perm'] = 'r';
1002         }
1003
1004         if($rino && $rino_allowed && (! $dissolve)) {
1005                 $key = substr(random_string(),0,16);
1006                 $data = bin2hex(aes_encrypt($postvars['data'],$key));
1007                 $postvars['data'] = $data;
1008                 logger('rino: sent key = ' . $key, LOGGER_DEBUG);       
1009
1010
1011                 if($dfrn_version >= 2.1) {      
1012                         if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1013                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1014                         }
1015                         else {
1016                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1017                         }
1018                 }
1019                 else {
1020                         if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1021                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1022                         }
1023                         else {
1024                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1025                         }
1026                 }
1027
1028                 logger('md5 rawkey ' . md5($postvars['key']));
1029
1030                 $postvars['key'] = bin2hex($postvars['key']);
1031         }
1032
1033         logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1034
1035         $xml = post_url($contact['notify'],$postvars);
1036
1037         logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1038
1039         $curl_stat = $a->get_curl_code();
1040         if((! $curl_stat) || (! strlen($xml)))
1041                 return(-1); // timed out
1042
1043         if(strpos($xml,'<?xml') === false) {
1044                 logger('dfrn_deliver: phase 2: no valid XML returned');
1045                 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1046                 return 3;
1047         }
1048
1049         $res = parse_xml_string($xml);
1050
1051         return $res->status; 
1052 }
1053
1054
1055 /**
1056  *
1057  * consume_feed - process atom feed and update anything/everything we might need to update
1058  *
1059  * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1060  *
1061  * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1062  *             It is this person's stuff that is going to be updated.
1063  * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1064  *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST 
1065  *             have a contact record.
1066  * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or 
1067  *        might not) try and subscribe to it.
1068  *
1069  */
1070
1071 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $secure_feed = false) {
1072
1073         require_once('library/simplepie/simplepie.inc');
1074
1075         if(! strlen($xml)) {
1076                 logger('consume_feed: empty input');
1077                 return;
1078         }
1079                 
1080         $feed = new SimplePie();
1081         $feed->set_raw_data($xml);
1082         if($datedir)
1083                 $feed->enable_order_by_date(true);
1084         else
1085                 $feed->enable_order_by_date(false);
1086         $feed->init();
1087
1088         if($feed->error())
1089                 logger('consume_feed: Error parsing XML: ' . $feed->error());
1090
1091         $permalink = $feed->get_permalink();
1092
1093         // Check at the feed level for updated contact name and/or photo
1094
1095         $name_updated  = '';
1096         $new_name = '';
1097         $photo_timestamp = '';
1098         $photo_url = '';
1099         $birthday = '';
1100
1101         $hubs = $feed->get_links('hub');
1102
1103         if(count($hubs))
1104                 $hub = implode(',', $hubs);
1105
1106         $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1107         if(! $rawtags)
1108                 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1109         if($rawtags) {
1110                 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1111                 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1112                         $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1113                         $new_name = $elems['name'][0]['data'];
1114                 } 
1115                 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1116                         $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1117                         $photo_url = $elems['link'][0]['attribs']['']['href'];
1118                 }
1119
1120                 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1121                         $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1122                 }
1123         }
1124
1125         if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1126                 logger('consume_feed: Updating photo for ' . $contact['name']);
1127                 require_once("Photo.php");
1128                 $photo_failure = false;
1129                 $have_photo = false;
1130
1131                 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1132                         intval($contact['id']),
1133                         intval($contact['uid'])
1134                 );
1135                 if(count($r)) {
1136                         $resource_id = $r[0]['resource-id'];
1137                         $have_photo = true;
1138                 }
1139                 else {
1140                         $resource_id = photo_new_resource();
1141                 }
1142                         
1143                 $img_str = fetch_url($photo_url,true);
1144                 $img = new Photo($img_str);
1145                 if($img->is_valid()) {
1146                         if($have_photo) {
1147                                 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1148                                         dbesc($resource_id),
1149                                         intval($contact['id']),
1150                                         intval($contact['uid'])
1151                                 );
1152                         }
1153                                 
1154                         $img->scaleImageSquare(175);
1155                                 
1156                         $hash = $resource_id;
1157                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1158                                 
1159                         $img->scaleImage(80);
1160                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1161
1162                         $img->scaleImage(48);
1163                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1164
1165                         $a = get_app();
1166
1167                         q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'  
1168                                 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1169                                 dbesc(datetime_convert()),
1170                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
1171                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
1172                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
1173                                 intval($contact['uid']),
1174                                 intval($contact['id'])
1175                         );
1176                 }
1177         }
1178
1179         if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1180                 q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1181                         dbesc(notags(trim($new_name))),
1182                         dbesc(datetime_convert()),
1183                         intval($contact['uid']),
1184                         intval($contact['id'])
1185                 );
1186         }
1187
1188         if(strlen($birthday)) {
1189                 if(substr($birthday,0,4) != $contact['bdyear']) {
1190                         logger('consume_feed: updating birthday: ' . $birthday);
1191
1192                         /**
1193                          *
1194                          * Add new birthday event for this person
1195                          *
1196                          * $bdtext is just a readable placeholder in case the event is shared
1197                          * with others. We will replace it during presentation to our $importer
1198                          * to contain a sparkle link and perhaps a photo. 
1199                          *
1200                          */
1201                          
1202                         $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1203
1204
1205                         $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1206                                 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1207                                 intval($contact['uid']),
1208                                 intval($contact['id']),
1209                                 dbesc(datetime_convert()),
1210                                 dbesc(datetime_convert()),
1211                                 dbesc(datetime_convert('UTC','UTC', $birthday)),
1212                                 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1213                                 dbesc($bdtext),
1214                                 dbesc('birthday')
1215                         );
1216                         
1217
1218                         // update bdyear
1219
1220                         q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1221                                 dbesc(substr($birthday,0,4)),
1222                                 intval($contact['uid']),
1223                                 intval($contact['id'])
1224                         );
1225
1226                         // This function is called twice without reloading the contact
1227                         // Make sure we only create one event. This is why &$contact 
1228                         // is a reference var in this function
1229
1230                         $contact['bdyear'] = substr($birthday,0,4);
1231                 }
1232
1233         }
1234
1235
1236         // process any deleted entries
1237
1238         $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1239         if(is_array($del_entries) && count($del_entries)) {
1240                 foreach($del_entries as $dentry) {
1241                         $deleted = false;
1242                         if(isset($dentry['attribs']['']['ref'])) {
1243                                 $uri = $dentry['attribs']['']['ref'];
1244                                 $deleted = true;
1245                                 if(isset($dentry['attribs']['']['when'])) {
1246                                         $when = $dentry['attribs']['']['when'];
1247                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1248                                 }
1249                                 else
1250                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1251                         }
1252                         if($deleted && is_array($contact)) {
1253                                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `contact-id` = %d LIMIT 1",
1254                                         dbesc($uri),
1255                                         intval($importer['uid']),
1256                                         intval($contact['id'])
1257                                 );
1258                                 if(count($r)) {
1259                                         $item = $r[0];
1260
1261                                         if(! $item['deleted'])
1262                                                 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1263
1264                                         if($item['uri'] == $item['parent-uri']) {
1265                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1266                                                         `body` = '', `title` = ''
1267                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
1268                                                         dbesc($when),
1269                                                         dbesc(datetime_convert()),
1270                                                         dbesc($item['uri']),
1271                                                         intval($importer['uid'])
1272                                                 );
1273                                         }
1274                                         else {
1275                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1276                                                         `body` = '', `title` = '' 
1277                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1278                                                         dbesc($when),
1279                                                         dbesc(datetime_convert()),
1280                                                         dbesc($uri),
1281                                                         intval($importer['uid'])
1282                                                 );
1283                                                 if($item['last-child']) {
1284                                                         // ensure that last-child is set in case the comment that had it just got wiped.
1285                                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1286                                                                 dbesc(datetime_convert()),
1287                                                                 dbesc($item['parent-uri']),
1288                                                                 intval($item['uid'])
1289                                                         );
1290                                                         // who is the last child now? 
1291                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d 
1292                                                                 ORDER BY `created` DESC LIMIT 1",
1293                                                                         dbesc($item['parent-uri']),
1294                                                                         intval($importer['uid'])
1295                                                         );
1296                                                         if(count($r)) {
1297                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1298                                                                         intval($r[0]['id'])
1299                                                                 );
1300                                                         }
1301                                                 }       
1302                                         }
1303                                 }       
1304                         }
1305                 }
1306         }
1307
1308         // Now process the feed
1309
1310         if($feed->get_item_quantity()) {                
1311
1312                 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1313
1314         // in inverse date order
1315                 if ($datedir)
1316                         $items = array_reverse($feed->get_items());
1317                 else
1318                         $items = $feed->get_items();
1319
1320
1321                 foreach($items as $item) {
1322
1323                         $is_reply = false;              
1324                         $item_id = $item->get_id();
1325                         $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1326                         if(isset($rawthread[0]['attribs']['']['ref'])) {
1327                                 $is_reply = true;
1328                                 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1329                         }
1330
1331                         if(($is_reply) && is_array($contact)) {
1332
1333                                 // Have we seen it? If not, import it.
1334         
1335                                 $item_id  = $item->get_id();
1336                                 $datarray = get_atom_elements($feed,$item);
1337
1338                                 if(! x($datarray,'author-name'))
1339                                         $datarray['author-name'] = $contact['name'];
1340                                 if(! x($datarray,'author-link'))
1341                                         $datarray['author-link'] = $contact['url'];
1342                                 if(! x($datarray,'author-avatar'))
1343                                         $datarray['author-avatar'] = $contact['thumb'];
1344
1345
1346                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1347                                         dbesc($item_id),
1348                                         intval($importer['uid'])
1349                                 );
1350
1351                                 // Update content if 'updated' changes
1352
1353                                 if(count($r)) {
1354                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1355                                                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1356                                                         dbesc($datarray['body']),
1357                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1358                                                         dbesc($item_id),
1359                                                         intval($importer['uid'])
1360                                                 );
1361                                         }
1362
1363                                         // update last-child if it changes
1364
1365                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1366                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1367                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1368                                                         dbesc(datetime_convert()),
1369                                                         dbesc($parent_uri),
1370                                                         intval($importer['uid'])
1371                                                 );
1372                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1373                                                         intval($allow[0]['data']),
1374                                                         dbesc(datetime_convert()),
1375                                                         dbesc($item_id),
1376                                                         intval($importer['uid'])
1377                                                 );
1378                                         }
1379                                         continue;
1380                                 }
1381
1382                                 $force_parent = false;
1383                                 if($contact['network'] === 'stat') {
1384                                         $force_parent = true;
1385                                         if(strlen($datarray['title']))
1386                                                 unset($datarray['title']);
1387                                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1388                                                 dbesc(datetime_convert()),
1389                                                 dbesc($parent_uri),
1390                                                 intval($importer['uid'])
1391                                         );
1392                                         $datarray['last-child'] = 1;
1393                                 }
1394
1395                                 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1396                                         // one way feed - no remote comment ability
1397                                         $datarray['last-child'] = 0;
1398                                 }
1399                                 $datarray['parent-uri'] = $parent_uri;
1400                                 $datarray['uid'] = $importer['uid'];
1401                                 $datarray['contact-id'] = $contact['id'];
1402                                 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1403                                         $datarray['type'] = 'activity';
1404                                         $datarray['gravity'] = GRAVITY_LIKE;
1405                                 }
1406
1407                                 $r = item_store($datarray,$force_parent);
1408                                 continue;
1409                         }
1410
1411                         else {
1412
1413                                 // Head post of a conversation. Have we seen it? If not, import it.
1414
1415                                 $item_id  = $item->get_id();
1416
1417                                 $datarray = get_atom_elements($feed,$item);
1418
1419                                 if(is_array($contact)) {
1420                                         if(! x($datarray,'author-name'))
1421                                                 $datarray['author-name'] = $contact['name'];
1422                                         if(! x($datarray,'author-link'))
1423                                                 $datarray['author-link'] = $contact['url'];
1424                                         if(! x($datarray,'author-avatar'))
1425                                                 $datarray['author-avatar'] = $contact['thumb'];
1426                                 }
1427
1428                                 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1429                                         $ev = bbtoevent($datarray['body']);
1430                                         if(x($ev,'desc') && x($ev,'start')) {
1431                                                 $ev['uid'] = $importer['uid'];
1432                                                 $ev['uri'] = $item_id;
1433                                                 $ev['edited'] = $datarray['edited'];
1434                                                 $ev['private'] = $datarray['private'];
1435
1436                                                 if(is_array($contact))
1437                                                         $ev['cid'] = $contact['id'];
1438                                                 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1439                                                         dbesc($item_id),
1440                                                         intval($importer['uid'])
1441                                                 );
1442                                                 if(count($r))
1443                                                         $ev['id'] = $r[0]['id'];
1444                                                 $xyz = event_store($ev);
1445                                                 continue;
1446                                         }
1447                                 }
1448
1449                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1450                                         dbesc($item_id),
1451                                         intval($importer['uid'])
1452                                 );
1453
1454                                 // Update content if 'updated' changes
1455
1456                                 if(count($r)) {
1457                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1458                                                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1459                                                         dbesc($datarray['body']),
1460                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1461                                                         dbesc($item_id),
1462                                                         intval($importer['uid'])
1463                                                 );
1464                                         }
1465
1466                                         // update last-child if it changes
1467
1468                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1469                                         if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1470                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1471                                                         intval($allow[0]['data']),
1472                                                         dbesc(datetime_convert()),
1473                                                         dbesc($item_id),
1474                                                         intval($importer['uid'])
1475                                                 );
1476                                         }
1477                                         continue;
1478                                 }
1479
1480                                 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1481                                         logger('consume-feed: New follower');
1482                                         new_follower($importer,$contact,$datarray,$item);
1483                                         return;
1484                                 }
1485                                 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW))  {
1486                                         lose_follower($importer,$contact,$datarray,$item);
1487                                         return;
1488                                 }
1489                                 if(! is_array($contact))
1490                                         return;
1491
1492                                 if($contact['network'] === 'stat' || stristr($permalink,'twitter.com')) {
1493                                         if(strlen($datarray['title']))
1494                                                 unset($datarray['title']);
1495                                         $datarray['last-child'] = 1;
1496                                 }
1497
1498                                 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1499                                         // one way feed - no remote comment ability
1500                                         $datarray['last-child'] = 0;
1501                                 }
1502
1503                                 // This is my contact on another system, but it's really me.
1504                                 // Turn this into a wall post.
1505
1506                                 if($contact['remote_self'])
1507                                         $datarray['wall'] = 1;
1508
1509                                 $datarray['parent-uri'] = $item_id;
1510                                 $datarray['uid'] = $importer['uid'];
1511                                 $datarray['contact-id'] = $contact['id'];
1512                                 $r = item_store($datarray);
1513                                 continue;
1514
1515                         }
1516                 }
1517         }
1518 }
1519
1520 function new_follower($importer,$contact,$datarray,$item) {
1521         $url = notags(trim($datarray['author-link']));
1522         $name = notags(trim($datarray['author-name']));
1523         $photo = notags(trim($datarray['author-avatar']));
1524
1525         $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1526         if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
1527                 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1528
1529         if(is_array($contact)) {
1530                 if($contact['network'] == 'stat' && $contact['rel'] == CONTACT_IS_SHARING) {
1531                         $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
1532                                 intval(CONTACT_IS_FRIEND),
1533                                 intval($contact['id']),
1534                                 intval($importer['uid'])
1535                         );
1536                 }
1537
1538                 // send email notification to owner?
1539         }
1540         else {
1541         
1542                 // create contact record
1543
1544                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `name`, `nick`, `photo`, `network`, `rel`, 
1545                         `blocked`, `readonly`, `pending`, `writable` )
1546                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
1547                         intval($importer['uid']),
1548                         dbesc(datetime_convert()),
1549                         dbesc($url),
1550                         dbesc($name),
1551                         dbesc($nick),
1552                         dbesc($photo),
1553                         dbesc('stat'),
1554                         intval(CONTACT_IS_FOLLOWER)
1555                 );
1556                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 AND `rel` = %d LIMIT 1",
1557                                 intval($importer['uid']),
1558                                 dbesc($url),
1559                                 intval(CONTACT_IS_FOLLOWER)
1560                 );
1561                 if(count($r))
1562                                 $contact_record = $r[0];
1563
1564                 // create notification  
1565                 $hash = random_string();
1566
1567                 if(is_array($contact_record)) {
1568                         $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
1569                                 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
1570                                 intval($importer['uid']),
1571                                 intval($contact_record['id']),
1572                                 dbesc($hash),
1573                                 dbesc(datetime_convert())
1574                         );
1575                 }
1576                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1577                         intval($importer['uid'])
1578                 );
1579                 $a = get_app();
1580                 if(count($r)) {
1581                         if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
1582                                 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
1583                                 $email = replace_macros($email_tpl, array(
1584                                         '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
1585                                         '$url' => $url,
1586                                         '$myname' => $r[0]['username'],
1587                                         '$siteurl' => $a->get_baseurl(),
1588                                         '$sitename' => $a->config['sitename']
1589                                 ));
1590                                 $res = mail($r[0]['email'], 
1591                                         t("You have a new follower at ") . $a->config['sitename'],
1592                                         $email,
1593                                         'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
1594                                         . 'Content-type: text/plain; charset=UTF-8' . "\n"
1595                                         . 'Content-transfer-encoding: 8bit' );
1596                         
1597                         }
1598                 }
1599         }
1600 }
1601
1602 function lose_follower($importer,$contact,$datarray,$item) {
1603
1604         if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
1605                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
1606                         intval(CONTACT_IS_SHARING),
1607                         intval($contact['id'])
1608                 );
1609         }
1610         else {
1611                 contact_remove($contact['id']);
1612         }
1613 }
1614
1615
1616 function subscribe_to_hub($url,$importer,$contact) {
1617
1618         if(is_array($importer)) {
1619                 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
1620                         intval($importer['uid'])
1621                 );
1622         }
1623         if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
1624                 return;
1625
1626         $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
1627
1628         // Use a single verify token, even if multiple hubs
1629
1630         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
1631
1632         $params= 'hub.mode=subscribe&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
1633
1634         logger('subscribe_to_hub: subscribing ' . $contact['name'] . ' to hub ' . $url . ' with verifier ' . $verify_token);
1635
1636         if(! strlen($contact['hub-verify'])) {
1637                 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
1638                         dbesc($verify_token),
1639                         intval($contact['id'])
1640                 );
1641         }
1642
1643         post_url($url,$params);                 
1644         return;
1645
1646 }
1647
1648
1649 function atom_author($tag,$name,$uri,$h,$w,$photo) {
1650         $o = '';
1651         if(! $tag)
1652                 return $o;
1653         $name = xmlify($name);
1654         $uri = xmlify($uri);
1655         $h = intval($h);
1656         $w = intval($w);
1657         $photo = xmlify($photo);
1658
1659
1660         $o .= "<$tag>\r\n";
1661         $o .= "<name>$name</name>\r\n";
1662         $o .= "<uri>$uri</uri>\r\n";
1663         $o .= '<link rel="photo"  type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1664         $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1665
1666         call_hooks('atom_author', $o);
1667
1668         $o .= "</$tag>\r\n";
1669         return $o;
1670 }
1671
1672 function atom_entry($item,$type,$author,$owner,$comment = false) {
1673
1674         $a = get_app();
1675
1676         if($item['deleted'])
1677                 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
1678
1679
1680         if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
1681                 $body = fix_private_photos($item['body'],$owner['uid']);
1682         else
1683                 $body = $item['body'];
1684
1685
1686         $o = "\r\n\r\n<entry>\r\n";
1687
1688         if(is_array($author))
1689                 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
1690         else
1691                 $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']));
1692         if(strlen($item['owner-name']))
1693                 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
1694
1695         if($item['parent'] != $item['id'])
1696                 $o .= '<thr:in-reply-to ref="' . xmlify($item['parent-uri']) . '" type="text/html" href="' .  xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
1697
1698         $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
1699         $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
1700         $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
1701         $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
1702         $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
1703         $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
1704         $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
1705         if($comment)
1706                 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
1707
1708         if($item['location']) {
1709                 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
1710                 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
1711         }
1712
1713         if($item['coord'])
1714                 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
1715
1716         if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
1717                 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
1718
1719         if($item['extid'])
1720                 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
1721         if($item['bookmark'])
1722                 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
1723
1724         if($item['app'])
1725                 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
1726
1727         if($item['guid'])
1728                 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
1729
1730         if($item['signed_text']) {
1731                 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
1732                 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
1733         }
1734
1735         $verb = construct_verb($item);
1736         $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
1737         $actobj = construct_activity_object($item);
1738         if(strlen($actobj))
1739                 $o .= $actobj;
1740         $actarg = construct_activity_target($item);
1741         if(strlen($actarg))
1742                 $o .= $actarg;
1743
1744         $tags = item_getfeedtags($item);
1745         if(count($tags)) {
1746                 foreach($tags as $t) {
1747                         $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
1748                 }
1749         }
1750
1751         $o .= item_getfeedattach($item);
1752
1753         $mentioned = get_mentions($item);
1754         if($mentioned)
1755                 $o .= $mentioned;
1756         
1757         call_hooks('atom_entry', $o);
1758
1759         $o .= '</entry>' . "\r\n";
1760         
1761         return $o;
1762 }
1763
1764 function fix_private_photos($s,$uid) {
1765         $a = get_app();
1766         logger('fix_private_photos');
1767
1768         if(preg_match("/\[img\](.*?)\[\/img\]/is",$s,$matches)) {
1769                 $image = $matches[1];
1770                 logger('fix_private_photos: found photo ' . $image);
1771                 if(stristr($image ,$a->get_baseurl() . '/photo/')) {
1772                         $i = basename($image);
1773                         $i = str_replace('.jpg','',$i);
1774                         $x = strpos($i,'-');
1775                         if($x) {
1776                                 $res = substr($i,$x+1);
1777                                 $i = substr($i,0,$x);
1778                                 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
1779                                         dbesc($i),
1780                                         intval($res),
1781                                         intval($uid)
1782                                 );
1783                                 if(count($r)) {
1784                                         logger('replacing photo');
1785                                         $s = str_replace($image, 'data:image/jpg;base64,' . base64_encode($r[0]['data']), $s);
1786                                 }
1787                         }
1788                         logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
1789                 }       
1790         }
1791         return($s);
1792 }
1793
1794
1795
1796 function item_getfeedtags($item) {
1797         $ret = array();
1798         $matches = false;
1799         $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
1800         if($cnt) {
1801                 for($x = 0; $x < count($matches); $x ++) {
1802                         if($matches[1][$x])
1803                                 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
1804                 }
1805         }
1806         $matches = false; 
1807         $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
1808         if($cnt) {
1809                 for($x = 0; $x < count($matches); $x ++) {
1810                         if($matches[1][$x])
1811                                 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
1812                 }
1813         } 
1814         return $ret;
1815 }
1816
1817 function item_getfeedattach($item) {
1818         $ret = '';
1819         $arr = explode(',',$item['attach']);
1820         if(count($arr)) {
1821                 foreach($arr as $r) {
1822                         $matches = false;
1823                         $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
1824                         if($cnt) {
1825                                 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
1826                                 if(intval($matches[2]))
1827                                         $ret .= 'length="' . intval($matches[2]) . '" ';
1828                                 if($matches[4] !== ' ')
1829                                         $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
1830                                 $ret .= ' />' . "\r\n";
1831                         }
1832                 }
1833         }
1834         return $ret;
1835 }
1836
1837
1838         
1839 function item_expire($uid,$days) {
1840
1841         if((! $uid) || (! $days))
1842                 return;
1843
1844         $r = q("SELECT * FROM `item` 
1845                 WHERE `uid` = %d 
1846                 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY 
1847                 AND `id` = `parent` 
1848                 AND `deleted` = 0",
1849                 intval($uid),
1850                 intval($days)
1851         );
1852
1853         if(! count($r))
1854                 return;
1855  
1856         logger('expire: # items=' . count($r) );
1857
1858         foreach($r as $item) {
1859
1860                 // Only expire posts, not photos and photo comments
1861
1862                 if(strlen($item['resource-id']))
1863                         continue;
1864
1865                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
1866                         dbesc(datetime_convert()),
1867                         dbesc(datetime_convert()),
1868                         intval($item['id'])
1869                 );
1870
1871                 // kill the kids
1872
1873                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1874                         dbesc(datetime_convert()),
1875                         dbesc(datetime_convert()),
1876                         dbesc($item['parent-uri']),
1877                         intval($item['uid'])
1878                 );
1879
1880         }
1881
1882         proc_run('php',"include/notifier.php","expire","$uid");
1883
1884 }
1885
1886
1887 function drop_items($items) {
1888         $uid = 0;
1889
1890         if(count($items)) {
1891                 foreach($items as $item) {
1892                         $owner = drop_item($item,false);
1893                         if($owner && ! $uid)
1894                                 $uid = $owner;
1895                 }
1896         }
1897
1898         // multiple threads may have been deleted, send an expire notification
1899
1900         if($uid)
1901                 proc_run('php',"include/notifier.php","expire","$uid");
1902 }
1903
1904
1905 function drop_item($id,$interactive = true) {
1906
1907         $a = get_app();
1908
1909         // locate item to be deleted
1910
1911         $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
1912                 intval($id)
1913         );
1914
1915         if(! count($r)) {
1916                 if(! $interactive)
1917                         return 0;
1918                 notice( t('Item not found.') . EOL);
1919                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
1920         }
1921
1922         $item = $r[0];
1923
1924         $owner = $item['uid'];
1925
1926         // check if logged in user is either the author or owner of this item
1927
1928         if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
1929
1930                 // delete the item
1931
1932                 $r = q("UPDATE `item` SET `deleted` = 1, `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
1933                         dbesc(datetime_convert()),
1934                         dbesc(datetime_convert()),
1935                         intval($item['id'])
1936                 );
1937
1938                 // If item is a link to a photo resource, nuke all the associated photos 
1939                 // (visitors will not have photo resources)
1940                 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1941                 // generate a resource-id and therefore aren't intimately linked to the item. 
1942
1943                 if(strlen($item['resource-id'])) {
1944                         q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
1945                                 dbesc($item['resource-id']),
1946                                 intval($item['uid'])
1947                         );
1948                         // ignore the result
1949                 }
1950
1951                 // If item is a link to an event, nuke the event record.
1952
1953                 if(intval($item['event-id'])) {
1954                         q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1955                                 intval($item['event-id']),
1956                                 intval($item['uid'])
1957                         );
1958                         // ignore the result
1959                 }
1960
1961
1962                 // If it's the parent of a comment thread, kill all the kids
1963
1964                 if($item['uri'] == $item['parent-uri']) {
1965                         $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' 
1966                                 WHERE `parent-uri` = '%s' AND `uid` = %d ",
1967                                 dbesc(datetime_convert()),
1968                                 dbesc(datetime_convert()),
1969                                 dbesc($item['parent-uri']),
1970                                 intval($item['uid'])
1971                         );
1972                         // ignore the result
1973                 }
1974                 else {
1975                         // ensure that last-child is set in case the comment that had it just got wiped.
1976                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1977                                 dbesc(datetime_convert()),
1978                                 dbesc($item['parent-uri']),
1979                                 intval($item['uid'])
1980                         );
1981                         // who is the last child now? 
1982                         $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",
1983                                 dbesc($item['parent-uri']),
1984                                 intval($item['uid'])
1985                         );
1986                         if(count($r)) {
1987                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1988                                         intval($r[0]['id'])
1989                                 );
1990                         }       
1991                 }
1992                 $drop_id = intval($item['id']);
1993                         
1994                 // send the notification upstream/downstream as the case may be
1995
1996                 if(! $interactive)
1997                         return $owner;
1998
1999                 proc_run('php',"include/notifier.php","drop","$drop_id");
2000                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
2001                 //NOTREACHED
2002         }
2003         else {
2004                 if(! $interactive)
2005                         return 0;
2006                 notice( t('Permission denied.') . EOL);
2007                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
2008                 //NOTREACHED
2009         }
2010         
2011 }