]> git.mxchange.org Git - friendica.git/blob - mod/item.php
ability to change tags in edited posts
[friendica.git] / mod / item.php
1 <?php
2
3 /**
4  *
5  * This is the POST destination for most all locally posted
6  * text stuff. This function handles status, wall-to-wall status, 
7  * local comments, and remote coments that are posted on this site 
8  * (as opposed to being delivered in a feed).
9  * Also processed here are posts and comments coming through the 
10  * statusnet/twitter API. 
11  * All of these become an "item" which is our basic unit of 
12  * information.
13  * Posts that originate externally or do not fall into the above 
14  * posting categories go through item_store() instead of this function. 
15  *
16  */  
17
18 require_once('include/crypto.php');
19 require_once('include/enotify.php');
20 require_once('include/email.php');
21
22 function item_post(&$a) {
23
24         if((! local_user()) && (! remote_user()) && (! x($_REQUEST,'commenter')))
25                 return;
26
27         require_once('include/security.php');
28
29         $uid = local_user();
30
31         if(x($_REQUEST,'dropitems')) {
32                 require_once('include/items.php');
33                 $arr_drop = explode(',',$_REQUEST['dropitems']);
34                 drop_items($arr_drop);
35                 $json = array('success' => 1);
36                 echo json_encode($json);
37                 killme();
38         }
39
40         call_hooks('post_local_start', $_REQUEST);
41 //      logger('postinput ' . file_get_contents('php://input'));
42         logger('postvars ' . print_r($_REQUEST,true), LOGGER_DATA);
43
44         $api_source = ((x($_REQUEST,'api_source') && $_REQUEST['api_source']) ? true : false);
45         $return_path = ((x($_REQUEST,'return')) ? $_REQUEST['return'] : '');
46         $preview = ((x($_REQUEST,'preview')) ? intval($_REQUEST['preview']) : 0);
47
48         /**
49          * Is this a reply to something?
50          */
51
52         $parent = ((x($_REQUEST,'parent')) ? intval($_REQUEST['parent']) : 0);
53         $parent_uri = ((x($_REQUEST,'parent_uri')) ? trim($_REQUEST['parent_uri']) : '');
54
55         $parent_item = null;
56         $parent_contact = null;
57         $thr_parent = '';
58         $parid = 0;
59         $r = false;
60
61         if($parent || $parent_uri) {
62
63                 if(! x($_REQUEST,'type'))
64                         $_REQUEST['type'] = 'net-comment';
65
66                 if($parent) {
67                         $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
68                                 intval($parent)
69                         );
70                 }
71                 elseif($parent_uri && local_user()) {
72                         // This is coming from an API source, and we are logged in
73                         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
74                                 dbesc($parent_uri),
75                                 intval(local_user())
76                         );
77                 }
78                 // if this isn't the real parent of the conversation, find it
79                 if($r !== false && count($r)) {
80                         $parid = $r[0]['parent'];
81                         if($r[0]['id'] != $r[0]['parent']) {
82                                 $r = q("SELECT * FROM `item` WHERE `id` = `parent` AND `parent` = %d LIMIT 1",
83                                         intval($parid)
84                                 );
85                         }
86                 }
87
88                 if(($r === false) || (! count($r))) {
89                         notice( t('Unable to locate original post.') . EOL);
90                         if(x($_REQUEST,'return')) 
91                                 goaway($a->get_baseurl() . "/" . $return_path );
92                         killme();
93                 }
94                 $parent_item = $r[0];
95                 $parent = $r[0]['id'];
96
97                 // multi-level threading - preserve the info but re-parent to our single level threading
98                 if(($parid) && ($parid != $parent))
99                         $thr_parent = $parent_uri;
100
101                 if($parent_item['contact-id'] && $uid) {
102                         $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
103                                 intval($parent_item['contact-id']),
104                                 intval($uid)
105                         );
106                         if(count($r))
107                                 $parent_contact = $r[0];
108                 }
109         }
110
111         if($parent) logger('mod_post: parent=' . $parent);
112
113         $profile_uid = ((x($_REQUEST,'profile_uid')) ? intval($_REQUEST['profile_uid']) : 0);
114         $post_id     = ((x($_REQUEST,'post_id'))     ? intval($_REQUEST['post_id'])     : 0);
115         $app         = ((x($_REQUEST,'source'))      ? strip_tags($_REQUEST['source'])  : '');
116
117         $allow_moderated = false;
118
119         // here is where we are going to check for permission to post a moderated comment.
120
121         // First check that the parent exists and it is a wall item.
122
123         if((x($_REQUEST,'commenter')) && ((! $parent) || (! $parent_item['wall']))) {
124                 notice( t('Permission denied.') . EOL) ;
125                 if(x($_REQUEST,'return')) 
126                         goaway($a->get_baseurl() . "/" . $return_path );
127                 killme();
128         }
129
130         // Now check that it is a page_type of PAGE_BLOG, and that valid personal details
131         // have been provided, and run any anti-spam plugins
132
133
134         // TODO
135
136
137
138
139         if((! can_write_wall($a,$profile_uid)) && (! $allow_moderated)) {
140                 notice( t('Permission denied.') . EOL) ;
141                 if(x($_REQUEST,'return')) 
142                         goaway($a->get_baseurl() . "/" . $return_path );
143                 killme();
144         }
145
146
147         // is this an edited post?
148
149         $orig_post = null;
150
151         if($post_id) {
152                 $i = q("SELECT * FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
153                         intval($profile_uid),
154                         intval($post_id)
155                 );
156                 if(! count($i))
157                         killme();
158                 $orig_post = $i[0];
159         }
160
161         $user = null;
162
163         $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
164                 intval($profile_uid)
165         );
166         if(count($r))
167                 $user = $r[0];
168
169         if($orig_post) {
170                 $str_group_allow   = $orig_post['allow_gid'];
171                 $str_contact_allow = $orig_post['allow_cid'];
172                 $str_group_deny    = $orig_post['deny_gid'];
173                 $str_contact_deny  = $orig_post['deny_cid'];
174                 $title             = $orig_post['title'];
175                 $location          = $orig_post['location'];
176                 $coord             = $orig_post['coord'];
177                 $verb              = $orig_post['verb'];
178                 $emailcc           = $orig_post['emailcc'];
179                 $app                       = $orig_post['app'];
180                 $categories        = $orig_post['file'];
181                 $body              = escape_tags(trim($_REQUEST['body']));
182                 $private           = $orig_post['private'];
183                 $pubmail_enable    = $orig_post['pubmail'];
184
185         }
186         else {
187
188                 // if coming from the API and no privacy settings are set, 
189                 // use the user default permissions - as they won't have
190                 // been supplied via a form.
191
192                 if(($api_source) 
193                         && (! array_key_exists('contact_allow',$_REQUEST))
194                         && (! array_key_exists('group_allow',$_REQUEST))
195                         && (! array_key_exists('contact_deny',$_REQUEST))
196                         && (! array_key_exists('group_deny',$_REQUEST))) {
197                         $str_group_allow   = $user['allow_gid'];
198                         $str_contact_allow = $user['allow_cid'];
199                         $str_group_deny    = $user['deny_gid'];
200                         $str_contact_deny  = $user['deny_cid'];
201                 }
202                 else {
203
204                         // use the posted permissions
205
206                         $str_group_allow   = perms2str($_REQUEST['group_allow']);
207                         $str_contact_allow = perms2str($_REQUEST['contact_allow']);
208                         $str_group_deny    = perms2str($_REQUEST['group_deny']);
209                         $str_contact_deny  = perms2str($_REQUEST['contact_deny']);
210                 }
211
212                 $title             = notags(trim($_REQUEST['title']));
213                 $location          = notags(trim($_REQUEST['location']));
214                 $coord             = notags(trim($_REQUEST['coord']));
215                 $verb              = notags(trim($_REQUEST['verb']));
216                 $emailcc           = notags(trim($_REQUEST['emailcc']));
217                 $body              = escape_tags(trim($_REQUEST['body']));
218
219                 // $categories = TODO
220
221                 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
222
223                 if(($parent_item) && 
224                         (($parent_item['private']) 
225                                 || strlen($parent_item['allow_cid']) 
226                                 || strlen($parent_item['allow_gid']) 
227                                 || strlen($parent_item['deny_cid']) 
228                                 || strlen($parent_item['deny_gid'])
229                         )) {
230                         $private = 1;
231                 }
232         
233                 $pubmail_enable    = ((x($_REQUEST,'pubmail_enable') && intval($_REQUEST['pubmail_enable']) && (! $private)) ? 1 : 0);
234
235                 // if using the API, we won't see pubmail_enable - figure out if it should be set
236
237                 if($api_source && $profile_uid && $profile_uid == local_user() && (! $private)) {
238                         $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
239                         if(! $mail_disabled) {
240                                 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
241                                         intval(local_user())
242                                 );
243                                 if(count($r) && intval($r[0]['pubmail']))
244                                         $pubmail_enabled = true;
245                         }
246                 }
247
248                 if(! strlen($body)) {
249                         if($preview)
250                                 killme();
251                         info( t('Empty post discarded.') . EOL );
252                         if(x($_REQUEST,'return')) 
253                                 goaway($a->get_baseurl() . "/" . $return_path );
254                         killme();
255                 }
256         }
257
258         // Work around doubled linefeeds in Tinymce 3.5b2
259         // First figure out if it's a status post that would've been
260         // created using tinymce. Otherwise leave it alone. 
261
262         $plaintext = (local_user() ? intval(get_pconfig(local_user(),'system','plaintext')) : 0);
263         if((! $parent) && (! $api_source) && (! $plaintext)) {
264                 $body = str_replace("\r\n","\n",$body);
265                 $body = str_replace("\n\n","\n",$body);
266         }
267
268
269         // get contact info for poster
270
271         $author = null;
272         $self   = false;
273
274         if(($_SESSION['uid']) && ($_SESSION['uid'] == $profile_uid)) {
275                 $self = true;
276                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
277                         intval($_SESSION['uid'])
278                 );
279         }
280         else {
281                 if((x($_SESSION,'visitor_id')) && (intval($_SESSION['visitor_id']))) {
282                         $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
283                                 intval($_SESSION['visitor_id'])
284                         );
285                 }
286         }
287
288         if(count($r)) {
289                 $author = $r[0];
290                 $contact_id = $author['id'];
291         }
292
293         // get contact info for owner
294         
295         if($profile_uid == $_SESSION['uid']) {
296                 $contact_record = $author;
297         }
298         else {
299                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
300                         intval($profile_uid)
301                 );
302                 if(count($r))
303                         $contact_record = $r[0];
304         }
305
306
307
308         $post_type = notags(trim($_REQUEST['type']));
309
310         if($post_type === 'net-comment') {
311                 if($parent_item !== null) {
312                         if($parent_item['wall'] == 1)
313                                 $post_type = 'wall-comment';
314                         else
315                                 $post_type = 'remote-comment';
316                 }
317         }
318
319         /**
320          *
321          * When a photo was uploaded into the message using the (profile wall) ajax 
322          * uploader, The permissions are initially set to disallow anybody but the
323          * owner from seeing it. This is because the permissions may not yet have been
324          * set for the post. If it's private, the photo permissions should be set
325          * appropriately. But we didn't know the final permissions on the post until
326          * now. So now we'll look for links of uploaded messages that are in the
327          * post and set them to the same permissions as the post itself.
328          *
329          */
330
331         $match = null;
332
333         if((! $preview) && preg_match_all("/\[img\](.*?)\[\/img\]/",$body,$match)) {
334                 $images = $match[1];
335                 if(count($images)) {
336                         foreach($images as $image) {
337                                 if(! stristr($image,$a->get_baseurl() . '/photo/'))
338                                         continue;
339                                 $image_uri = substr($image,strrpos($image,'/') + 1);
340                                 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
341                                 if(! strlen($image_uri))
342                                         continue;
343                                 $srch = '<' . intval($profile_uid) . '>';
344                                 $r = q("SELECT `id` FROM `photo` WHERE `allow_cid` = '%s' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = ''
345                                         AND `resource-id` = '%s' AND `uid` = %d LIMIT 1",
346                                         dbesc($srch),
347                                         dbesc($image_uri),
348                                         intval($profile_uid)
349                                 );
350                                 if(! count($r))
351                                         continue;
352  
353
354                                 $r = q("UPDATE `photo` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
355                                         WHERE `resource-id` = '%s' AND `uid` = %d AND `album` = '%s' ",
356                                         dbesc($str_contact_allow),
357                                         dbesc($str_group_allow),
358                                         dbesc($str_contact_deny),
359                                         dbesc($str_group_deny),
360                                         dbesc($image_uri),
361                                         intval($profile_uid),
362                                         dbesc( t('Wall Photos'))
363                                 );
364  
365                         }
366                 }
367         }
368
369
370         /**
371          * Next link in any attachment references we find in the post.
372          */
373
374         $match = false;
375
376         if((! $preview) && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/",$body,$match)) {
377                 $attaches = $match[1];
378                 if(count($attaches)) {
379                         foreach($attaches as $attach) {
380                                 $r = q("SELECT * FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
381                                         intval($profile_uid),
382                                         intval($attach)
383                                 );                              
384                                 if(count($r)) {
385                                         $r = q("UPDATE `attach` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
386                                                 WHERE `uid` = %d AND `id` = %d LIMIT 1",
387                                                 dbesc($str_contact_allow),
388                                                 dbesc($str_group_allow),
389                                                 dbesc($str_contact_deny),
390                                                 dbesc($str_group_deny),
391                                                 intval($profile_uid),
392                                                 intval($attach)
393                                         );
394                                 }
395                         }
396                 }
397         }
398
399         // embedded bookmark in post? set bookmark flag
400
401         $bookmark = 0;
402         if(preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$body,$match,PREG_SET_ORDER)) {
403                 $bookmark = 1;
404         }
405
406         $body = bb_translate_video($body);
407
408         /**
409          * Fold multi-line [code] sequences
410          */
411
412         $body = preg_replace('/\[\/code\]\s*\[code\]/ism',"\n",$body); 
413
414         $body = scale_external_images($body,false);
415
416         /**
417          * Look for any tags and linkify them
418          */
419
420         $str_tags = '';
421         $inform   = '';
422
423
424         $tags = get_tags($body);
425
426         /**
427          * add a statusnet style reply tag if the original post was from there
428          * and we are replying, and there isn't one already
429          */
430
431         if(($parent_contact) && ($parent_contact['network'] === NETWORK_OSTATUS) 
432                 && ($parent_contact['nick']) && (! in_array('@' . $parent_contact['nick'],$tags))) {
433                 $body = '@' . $parent_contact['nick'] . ' ' . $body;
434                 $tags[] = '@' . $parent_contact['nick'];
435         }               
436
437         if(count($tags)) {
438                 foreach($tags as $tag) {
439                         handle_tag($a, $body, $inform, $str_tags, $profile_uid, $tag); 
440                 }
441         }
442
443         $attachments = '';
444         $match = false;
445
446         if(preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
447                 foreach($match[2] as $mtch) {
448                         $r = q("SELECT `id`,`filename`,`filesize`,`filetype` FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
449                                 intval($profile_uid),
450                                 intval($mtch)
451                         );
452                         if(count($r)) {
453                                 if(strlen($attachments))
454                                         $attachments .= ',';
455                                 $attachments .= '[attach]href="' . $a->get_baseurl() . '/attach/' . $r[0]['id'] . '" length="' . $r[0]['filesize'] . '" type="' . $r[0]['filetype'] . '" title="' . (($r[0]['filename']) ? $r[0]['filename'] : '') . '"[/attach]'; 
456                         }
457                         $body = str_replace($match[1],'',$body);
458                 }
459         }
460
461         $wall = 0;
462
463         if($post_type === 'wall' || $post_type === 'wall-comment')
464                 $wall = 1;
465
466         if(! strlen($verb))
467                 $verb = ACTIVITY_POST ;
468
469         $gravity = (($parent) ? 6 : 0 );
470
471         // even if the post arrived via API we are considering that it 
472         // originated on this site by default for determining relayability.
473
474         $origin = ((x($_REQUEST,'origin')) ? intval($_REQUEST['origin']) : 1);
475         
476         $notify_type = (($parent) ? 'comment-new' : 'wall-new' );
477
478         $uri = item_new_uri($a->get_hostname(),$profile_uid);
479
480         $datarray = array();
481         $datarray['uid']           = $profile_uid;
482         $datarray['type']          = $post_type;
483         $datarray['wall']          = $wall;
484         $datarray['gravity']       = $gravity;
485         $datarray['contact-id']    = $contact_id;
486         $datarray['owner-name']    = $contact_record['name'];
487         $datarray['owner-link']    = $contact_record['url'];
488         $datarray['owner-avatar']  = $contact_record['thumb'];
489         $datarray['author-name']   = $author['name'];
490         $datarray['author-link']   = $author['url'];
491         $datarray['author-avatar'] = $author['thumb'];
492         $datarray['created']       = datetime_convert();
493         $datarray['edited']        = datetime_convert();
494         $datarray['commented']     = datetime_convert();
495         $datarray['received']      = datetime_convert();
496         $datarray['changed']       = datetime_convert();
497         $datarray['uri']           = $uri;
498         $datarray['title']         = $title;
499         $datarray['body']          = $body;
500         $datarray['app']           = $app;
501         $datarray['location']      = $location;
502         $datarray['coord']         = $coord;
503         $datarray['tag']           = $str_tags;
504         $datarray['file']          = $categories;
505         $datarray['inform']        = $inform;
506         $datarray['verb']          = $verb;
507         $datarray['allow_cid']     = $str_contact_allow;
508         $datarray['allow_gid']     = $str_group_allow;
509         $datarray['deny_cid']      = $str_contact_deny;
510         $datarray['deny_gid']      = $str_group_deny;
511         $datarray['private']       = $private;
512         $datarray['pubmail']       = $pubmail_enable;
513         $datarray['attach']        = $attachments;
514         $datarray['bookmark']      = intval($bookmark);
515         $datarray['thr-parent']    = $thr_parent;
516         $datarray['postopts']      = '';
517         $datarray['origin']        = $origin;
518         $datarray['moderated']     = $allow_moderated;
519
520         /**
521          * These fields are for the convenience of plugins...
522          * 'self' if true indicates the owner is posting on their own wall
523          * If parent is 0 it is a top-level post.
524          */
525
526         $datarray['parent']        = $parent;
527         $datarray['self']          = $self;
528 //      $datarray['prvnets']       = $user['prvnets'];
529
530         if($orig_post)
531                 $datarray['edit']      = true;
532         else
533                 $datarray['guid']      = get_guid();
534
535         // preview mode - prepare the body for display and send it via json
536
537         if($preview) {
538                 require_once('include/conversation.php');
539                 $o = conversation($a,array(array_merge($contact_record,$datarray)),'search',false,true);
540                 logger('preview: ' . $o);
541                 echo json_encode(array('preview' => $o));
542                 killme();
543         }
544
545
546         call_hooks('post_local',$datarray);
547
548         if(x($datarray,'cancel')) {
549                 logger('mod_item: post cancelled by plugin.');
550                 if($return_path) {
551                         goaway($a->get_baseurl() . "/" . $return_path);
552                 }
553
554                 $json = array('cancel' => 1);
555                 if(x($_REQUEST,'jsreload') && strlen($_REQUEST['jsreload']))
556                         $json['reload'] = $a->get_baseurl() . '/' . $_REQUEST['jsreload'];
557
558                 echo json_encode($json);
559                 killme();
560         }
561
562
563         if($orig_post) {
564                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `attach` = '%s', `file` = '%s', `edited` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
565                         dbesc($datarray['title']),
566                         dbesc($datarray['body']),
567                         dbesc($datarray['tag']),
568                         dbesc($datarray['attach']),
569                         dbesc($datarray['file']),
570                         dbesc(datetime_convert()),
571                         intval($post_id),
572                         intval($profile_uid)
573                 );
574
575                 proc_run('php', "include/notifier.php", 'edit_post', "$post_id");
576                 if((x($_REQUEST,'return')) && strlen($return_path)) {
577                         logger('return: ' . $return_path);
578                         goaway($a->get_baseurl() . "/" . $return_path );
579                 }
580                 killme();
581         }
582         else
583                 $post_id = 0;
584
585
586         $r = q("INSERT INTO `item` (`guid`, `uid`,`type`,`wall`,`gravity`,`contact-id`,`owner-name`,`owner-link`,`owner-avatar`, 
587                 `author-name`, `author-link`, `author-avatar`, `created`, `edited`, `commented`, `received`, `changed`, `uri`, `thr-parent`, `title`, `body`, `app`, `location`, `coord`, 
588                 `tag`, `inform`, `verb`, `postopts`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid`, `private`, `pubmail`, `attach`, `bookmark`,`origin`, `moderated` )
589                 VALUES( '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', %d, %d, %d )",
590                 dbesc($datarray['guid']),
591                 intval($datarray['uid']),
592                 dbesc($datarray['type']),
593                 intval($datarray['wall']),
594                 intval($datarray['gravity']),
595                 intval($datarray['contact-id']),
596                 dbesc($datarray['owner-name']),
597                 dbesc($datarray['owner-link']),
598                 dbesc($datarray['owner-avatar']),
599                 dbesc($datarray['author-name']),
600                 dbesc($datarray['author-link']),
601                 dbesc($datarray['author-avatar']),
602                 dbesc($datarray['created']),
603                 dbesc($datarray['edited']),
604                 dbesc($datarray['commented']),
605                 dbesc($datarray['received']),
606                 dbesc($datarray['changed']),
607                 dbesc($datarray['uri']),
608                 dbesc($datarray['thr-parent']),
609                 dbesc($datarray['title']),
610                 dbesc($datarray['body']),
611                 dbesc($datarray['app']),
612                 dbesc($datarray['location']),
613                 dbesc($datarray['coord']),
614                 dbesc($datarray['tag']),
615                 dbesc($datarray['inform']),
616                 dbesc($datarray['verb']),
617                 dbesc($datarray['postopts']),
618                 dbesc($datarray['allow_cid']),
619                 dbesc($datarray['allow_gid']),
620                 dbesc($datarray['deny_cid']),
621                 dbesc($datarray['deny_gid']),
622                 intval($datarray['private']),
623                 intval($datarray['pubmail']),
624                 dbesc($datarray['attach']),
625                 intval($datarray['bookmark']),
626                 intval($datarray['origin']),
627                 intval($datarry['moderated'])
628         );
629
630         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
631                 dbesc($datarray['uri']));
632         if(count($r)) {
633                 $post_id = $r[0]['id'];
634                 logger('mod_item: saved item ' . $post_id);
635
636                 if($parent) {
637
638                         // This item is the last leaf and gets the comment box, clear any ancestors
639                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent` = %d ",
640                                 dbesc(datetime_convert()),
641                                 intval($parent)
642                         );
643
644                         // Inherit ACL's from the parent item.
645
646                         $r = q("UPDATE `item` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d
647                                 WHERE `id` = %d LIMIT 1",
648                                 dbesc($parent_item['allow_cid']),
649                                 dbesc($parent_item['allow_gid']),
650                                 dbesc($parent_item['deny_cid']),
651                                 dbesc($parent_item['deny_gid']),
652                                 intval($parent_item['private']),
653                                 intval($post_id)
654                         );
655
656                         if($contact_record != $author) {
657                                 notification(array(
658                                         'type'         => NOTIFY_COMMENT,
659                                         'notify_flags' => $user['notify-flags'],
660                                         'language'     => $user['language'],
661                                         'to_name'      => $user['username'],
662                                         'to_email'     => $user['email'],
663                                         'uid'          => $user['uid'],
664                                         'item'         => $datarray,
665                                         'link'             => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id,
666                                         'source_name'  => $datarray['author-name'],
667                                         'source_link'  => $datarray['author-link'],
668                                         'source_photo' => $datarray['author-avatar'],
669                                         'verb'         => ACTIVITY_POST,
670                                         'otype'        => 'item',
671                                         'parent'       => $parent,
672                                 ));
673                         
674                         }
675
676                         // We won't be able to sign Diaspora comments for authenticated visitors - we don't have their private key
677
678                         if($self) {
679                                 require_once('include/bb2diaspora.php');
680                                 $signed_body = html_entity_decode(bb2diaspora($datarray['body']));
681                                 $myaddr = $a->user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
682                                 if($datarray['verb'] === ACTIVITY_LIKE) 
683                                         $signed_text = $datarray['guid'] . ';' . 'Post' . ';' . $parent_item['guid'] . ';' . 'true' . ';' . $myaddr;
684                                 else
685                                 $signed_text = $datarray['guid'] . ';' . $parent_item['guid'] . ';' . $signed_body . ';' . $myaddr;
686
687                                 $authorsig = base64_encode(rsa_sign($signed_text,$a->user['prvkey'],'sha256'));
688
689                                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
690                                         intval($post_id),
691                         dbesc($signed_text),
692                         dbesc(base64_encode($authorsig)),
693                         dbesc($myaddr)
694                         );
695                         }
696                 }
697                 else {
698                         $parent = $post_id;
699
700                         if($contact_record != $author) {
701                                 notification(array(
702                                         'type'         => NOTIFY_WALL,
703                                         'notify_flags' => $user['notify-flags'],
704                                         'language'     => $user['language'],
705                                         'to_name'      => $user['username'],
706                                         'to_email'     => $user['email'],
707                                         'uid'          => $user['uid'],
708                                         'item'         => $datarray,
709                                         'link'             => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id,
710                                         'source_name'  => $datarray['author-name'],
711                                         'source_link'  => $datarray['author-link'],
712                                         'source_photo' => $datarray['author-avatar'],
713                                         'verb'         => ACTIVITY_POST,
714                                         'otype'        => 'item'
715                                 ));
716                         }
717                 }
718
719                 // fallback so that parent always gets set to non-zero.
720
721                 if(! $parent)
722                         $parent = $post_id;
723
724                 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s', `plink` = '%s', `changed` = '%s', `last-child` = 1, `visible` = 1
725                         WHERE `id` = %d LIMIT 1",
726                         intval($parent),
727                         dbesc(($parent == $post_id) ? $uri : $parent_item['uri']),
728                         dbesc($a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id),
729                         dbesc(datetime_convert()),
730                         intval($post_id)
731                 );
732
733                 // photo comments turn the corresponding item visible to the profile wall
734                 // This way we don't see every picture in your new photo album posted to your wall at once.
735                 // They will show up as people comment on them.
736
737                 if(! $parent_item['visible']) {
738                         $r = q("UPDATE `item` SET `visible` = 1 WHERE `id` = %d LIMIT 1",
739                                 intval($parent_item['id'])
740                         );
741                 }
742         }
743         else {
744                 logger('mod_item: unable to retrieve post that was just stored.');
745                 notify( t('System error. Post not saved.'));
746                 goaway($a->get_baseurl() . "/" . $return_path );
747                 // NOTREACHED
748         }
749
750         // update the commented timestamp on the parent
751
752         q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
753                 dbesc(datetime_convert()),
754                 dbesc(datetime_convert()),
755                 intval($parent)
756         );
757
758         $datarray['id']    = $post_id;
759         $datarray['plink'] = $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id;
760
761         call_hooks('post_local_end', $datarray);
762
763         if(strlen($emailcc) && $profile_uid == local_user()) {
764                 $erecips = explode(',', $emailcc);
765                 if(count($erecips)) {
766                         foreach($erecips as $recip) {
767                                 $addr = trim($recip);
768                                 if(! strlen($addr))
769                                         continue;
770                                 $disclaimer = '<hr />' . sprintf( t('This message was sent to you by %s, a member of the Friendica social network.'),$a->user['username']) 
771                                         . '<br />';
772                                 $disclaimer .= sprintf( t('You may visit them online at %s'), $a->get_baseurl() . '/profile/' . $a->user['nickname']) . EOL;
773                                 $disclaimer .= t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL; 
774
775                                 $subject  = email_header_encode('[Friendica]' . ' ' . sprintf( t('%s posted an update.'),$a->user['username']),'UTF-8');
776                                 $headers  = 'From: ' . email_header_encode($a->user['username'],'UTF-8') . ' <' . $a->user['email'] . '>' . "\n";
777                                 $headers .= 'MIME-Version: 1.0' . "\n";
778                                 $headers .= 'Content-Type: text/html; charset=UTF-8' . "\n";
779                                 $headers .= 'Content-Transfer-Encoding: 8bit' . "\n\n";
780                                 $link = '<a href="' . $a->get_baseurl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
781                                 $html    = prepare_body($datarray);
782                                 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
783                                 @mail($addr, $subject, $message, $headers);
784                         }
785                 }
786         }
787
788         // This is a real juggling act on shared hosting services which kill your processes
789         // e.g. dreamhost. We used to start delivery to our native delivery agents in the background
790         // and then run our plugin delivery from the foreground. We're now doing plugin delivery first,
791         // because as soon as you start loading up a bunch of remote delivey processes, *this* page is
792         // likely to get killed off. If you end up looking at an /item URL and a blank page,
793         // it's very likely the delivery got killed before all your friends could be notified.
794         // Currently the only realistic fixes are to use a reliable server - which precludes shared hosting,
795         // or cut back on plugins which do remote deliveries.  
796
797         proc_run('php', "include/notifier.php", $notify_type, "$post_id");
798
799         logger('post_complete');
800
801         // figure out how to return, depending on from whence we came
802
803         if($api_source)
804                 return;
805
806         if($return_path) {
807                 goaway($a->get_baseurl() . "/" . $return_path);
808         }
809
810         $json = array('success' => 1);
811         if(x($_REQUEST,'jsreload') && strlen($_REQUEST['jsreload']))
812                 $json['reload'] = $a->get_baseurl() . '/' . $_REQUEST['jsreload'];
813
814         logger('post_json: ' . print_r($json,true), LOGGER_DEBUG);
815
816         echo json_encode($json);
817         killme();
818         // NOTREACHED
819 }
820
821
822
823
824
825 function item_content(&$a) {
826
827         if((! local_user()) && (! remote_user()))
828                 return;
829
830         require_once('include/security.php');
831
832         if(($a->argc == 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
833                 require_once('include/items.php');
834                 drop_item($a->argv[2]);
835         }
836 }
837
838 /**
839  * This function removes the tag $tag from the text $body and replaces it with 
840  * the appropiate link. 
841  * 
842  * @param unknown_type $body the text to replace the tag in
843  * @param unknown_type $inform a comma-seperated string containing everybody to inform
844  * @param unknown_type $str_tags string to add the tag to
845  * @param unknown_type $profile_uid
846  * @param unknown_type $tag the tag to replace
847  */
848 function handle_tag($a, &$body, &$inform, &$str_tags, $profile_uid, $tag) {
849         //is it a hash tag? 
850         if(strpos($tag,'#') === 0) {
851                 //if the tag is replaced...
852                 if(strpos($tag,'[url='))
853                         //...do nothing
854                         return;
855                 //base tag has the tags name only
856                 $basetag = str_replace('_',' ',substr($tag,1));
857                 //create text for link
858                 $newtag = '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
859                 //replace tag by the link
860                 $body = str_replace($tag, $newtag, $body);
861         
862                 //is the link already in str_tags?
863                 if(! stristr($str_tags,$newtag)) {
864                         //append or set str_tags
865                         if(strlen($str_tags))
866                                 $str_tags .= ',';
867                         $str_tags .= $newtag;
868                 }
869                 return;
870         }
871         //is it a person tag? 
872         if(strpos($tag,'@') === 0) {
873                 //is it already replaced? 
874                 if(strpos($tag,'[url='))
875                         return;
876                 $stat = false;
877                 //get the person's name
878                 $name = substr($tag,1);
879                 //is it a link or a full dfrn address? 
880                 if((strpos($name,'@')) || (strpos($name,'http://'))) {
881                         $newname = $name;
882                         //get the profile links
883                         $links = @lrdd($name);
884                         if(count($links)) {
885                                 //for all links, collect how is to inform and how's profile is to link
886                                 foreach($links as $link) {
887                                         if($link['@attributes']['rel'] === 'http://webfinger.net/rel/profile-page')
888                                                 $profile = $link['@attributes']['href'];
889                                         if($link['@attributes']['rel'] === 'salmon') {
890                                                 if(strlen($inform))
891                                                         $inform .= ',';
892                                                 $inform .= 'url:' . str_replace(',','%2c',$link['@attributes']['href']);
893                                         }
894                                 }
895                         }
896                 } else { //if it is a name rather than an address
897                         $newname = $name;
898                         $alias = '';
899                         $tagcid = 0;
900                         //is it some generated name?
901                         if(strrpos($newname,'+')) {
902                                 //get the id
903                                 $tagcid = intval(substr($newname,strrpos($newname,'+') + 1));
904                                 //remove the next word from tag's name
905                                 if(strpos($name,' ')) {
906                                         $name = substr($name,0,strpos($name,' '));
907                                 }
908                         }
909                         if($tagcid) { //if there was an id
910                                 //select contact with that id from the logged in user's contact list
911                                 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
912                                                 intval($tagcid),
913                                                 intval($profile_uid)
914                                 );
915                         } elseif(strstr($name,'_') || strstr($name,' ')) { //no id
916                                 //get the real name
917                                 $newname = str_replace('_',' ',$name);
918                                 //select someone from this user's contacts by name
919                                 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
920                                                 dbesc($newname),
921                                                 intval($profile_uid)
922                                 );
923                         } else {
924                                 //select someone by attag or nick and the name passed in
925                                 $r = q("SELECT * FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
926                                                 dbesc($name),
927                                                 dbesc($name),
928                                                 intval($profile_uid)
929                                 );
930                         }
931                         //$r is set, if someone could be selected
932                         if(count($r)) {
933                                 $profile = $r[0]['url'];
934                                 //set newname to nick, find alias
935                                 if($r[0]['network'] === 'stat') {
936                                         $newname = $r[0]['nick'];
937                                         $stat = true;
938                                         if($r[0]['alias'])
939                                                 $alias = $r[0]['alias'];
940                                 }
941                                 else
942                                         $newname = $r[0]['name'];
943                                 //add person's id to $inform
944                                 if(strlen($inform))
945                                         $inform .= ',';
946                                 $inform .= 'cid:' . $r[0]['id'];
947                         }
948                 }
949                 //if there is an url for this persons profile
950                 if(isset($profile)) {
951                         //create profile link
952                         $profile = str_replace(',','%2c',$profile);
953                         $newtag = '@[url=' . $profile . ']' . $newname  . '[/url]';
954                         $body = str_replace('@' . $name, $newtag, $body);
955                         //append tag to str_tags
956                         if(! stristr($str_tags,$newtag)) {
957                                 if(strlen($str_tags))
958                                         $str_tags .= ',';
959                                 $str_tags .= $newtag;
960                         }
961         
962                         // Status.Net seems to require the numeric ID URL in a mention if the person isn't
963                         // subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
964         
965                         if(strlen($alias)) {
966                                 $newtag = '@[url=' . $alias . ']' . $newname    . '[/url]';
967                                 if(! stristr($str_tags,$newtag)) {
968                                         if(strlen($str_tags))
969                                                 $str_tags .= ',';
970                                         $str_tags .= $newtag;
971                                 }
972                         }
973                 }
974         }
975 }