]> git.mxchange.org Git - friendica.git/blob - mod/item.php
Optimized version of the possibility to reload the content of the network page only...
[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 require_once('library/langdet/Text/LanguageDetect.php');
22 require_once('include/tags.php');
23 require_once('include/files.php');
24 require_once('include/threads.php');
25
26 function item_post(&$a) {
27
28         if((! local_user()) && (! remote_user()) && (! x($_REQUEST,'commenter')))
29                 return;
30
31         require_once('include/security.php');
32
33         $uid = local_user();
34
35         if(x($_REQUEST,'dropitems')) {
36                 require_once('include/items.php');
37                 $arr_drop = explode(',',$_REQUEST['dropitems']);
38                 drop_items($arr_drop);
39                 $json = array('success' => 1);
40                 echo json_encode($json);
41                 killme();
42         }
43
44         call_hooks('post_local_start', $_REQUEST);
45 //      logger('postinput ' . file_get_contents('php://input'));
46         logger('postvars ' . print_r($_REQUEST,true), LOGGER_DATA);
47
48         $api_source = ((x($_REQUEST,'api_source') && $_REQUEST['api_source']) ? true : false);
49
50         $message_id = ((x($_REQUEST,'message_id') && $api_source)  ? strip_tags($_REQUEST['message_id'])       : '');
51
52         $return_path = ((x($_REQUEST,'return')) ? $_REQUEST['return'] : '');
53         $preview = ((x($_REQUEST,'preview')) ? intval($_REQUEST['preview']) : 0);
54
55
56         // Check for doubly-submitted posts, and reject duplicates
57         // Note that we have to ignore previews, otherwise nothing will post
58         // after it's been previewed
59         if(!$preview && x($_REQUEST['post_id_random'])) {
60                 if(x($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
61                         logger("item post: duplicate post", LOGGER_DEBUG);
62                         item_post_return($a->get_baseurl(), $api_source, $return_path);
63                 }
64                 else
65                         $_SESSION['post-random'] = $_REQUEST['post_id_random'];
66         }
67
68         /**
69          * Is this a reply to something?
70          */
71
72         $parent = ((x($_REQUEST,'parent')) ? intval($_REQUEST['parent']) : 0);
73         $parent_uri = ((x($_REQUEST,'parent_uri')) ? trim($_REQUEST['parent_uri']) : '');
74
75         $parent_item = null;
76         $parent_contact = null;
77         $thr_parent = '';
78         $parid = 0;
79         $r = false;
80
81         if($parent || $parent_uri) {
82
83                 if(! x($_REQUEST,'type'))
84                         $_REQUEST['type'] = 'net-comment';
85
86                 if($parent) {
87                         $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
88                                 intval($parent)
89                         );
90                 }
91                 elseif($parent_uri && local_user()) {
92                         // This is coming from an API source, and we are logged in
93                         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
94                                 dbesc($parent_uri),
95                                 intval(local_user())
96                         );
97                 }
98                 // if this isn't the real parent of the conversation, find it
99                 if($r !== false && count($r)) {
100                         $parid = $r[0]['parent'];
101                         $parent_uri = $r[0]['uri'];
102                         if($r[0]['id'] != $r[0]['parent']) {
103                                 $r = q("SELECT * FROM `item` WHERE `id` = `parent` AND `parent` = %d LIMIT 1",
104                                         intval($parid)
105                                 );
106                         }
107                 }
108
109                 if(($r === false) || (! count($r))) {
110                         notice( t('Unable to locate original post.') . EOL);
111                         if(x($_REQUEST,'return'))
112                                 goaway($a->get_baseurl() . "/" . $return_path );
113                         killme();
114                 }
115                 $parent_item = $r[0];
116                 $parent = $r[0]['id'];
117
118                 // multi-level threading - preserve the info but re-parent to our single level threading
119                 //if(($parid) && ($parid != $parent))
120                 $thr_parent = $parent_uri;
121
122                 if($parent_item['contact-id'] && $uid) {
123                         $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
124                                 intval($parent_item['contact-id']),
125                                 intval($uid)
126                         );
127                         if(count($r))
128                                 $parent_contact = $r[0];
129                 }
130         }
131
132         if($parent) logger('mod_item: item_post parent=' . $parent);
133
134         $profile_uid = ((x($_REQUEST,'profile_uid')) ? intval($_REQUEST['profile_uid']) : 0);
135         $post_id     = ((x($_REQUEST,'post_id'))     ? intval($_REQUEST['post_id'])     : 0);
136         $app         = ((x($_REQUEST,'source'))      ? strip_tags($_REQUEST['source'])  : '');
137
138         $allow_moderated = false;
139
140         // here is where we are going to check for permission to post a moderated comment.
141
142         // First check that the parent exists and it is a wall item.
143
144         if((x($_REQUEST,'commenter')) && ((! $parent) || (! $parent_item['wall']))) {
145                 notice( t('Permission denied.') . EOL) ;
146                 if(x($_REQUEST,'return'))
147                         goaway($a->get_baseurl() . "/" . $return_path );
148                 killme();
149         }
150
151         // Now check that it is a page_type of PAGE_BLOG, and that valid personal details
152         // have been provided, and run any anti-spam plugins
153
154
155         // TODO
156
157
158
159
160         if((! can_write_wall($a,$profile_uid)) && (! $allow_moderated)) {
161                 notice( t('Permission denied.') . EOL) ;
162                 if(x($_REQUEST,'return'))
163                         goaway($a->get_baseurl() . "/" . $return_path );
164                 killme();
165         }
166
167
168         // is this an edited post?
169
170         $orig_post = null;
171
172         if($post_id) {
173                 $i = q("SELECT * FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
174                         intval($profile_uid),
175                         intval($post_id)
176                 );
177                 if(! count($i))
178                         killme();
179                 $orig_post = $i[0];
180         }
181
182         $user = null;
183
184         $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
185                 intval($profile_uid)
186         );
187         if(count($r))
188                 $user = $r[0];
189
190         if($orig_post) {
191                 $str_group_allow   = $orig_post['allow_gid'];
192                 $str_contact_allow = $orig_post['allow_cid'];
193                 $str_group_deny    = $orig_post['deny_gid'];
194                 $str_contact_deny  = $orig_post['deny_cid'];
195                 $location          = $orig_post['location'];
196                 $coord             = $orig_post['coord'];
197                 $verb              = $orig_post['verb'];
198                 $emailcc           = $orig_post['emailcc'];
199                 $app                       = $orig_post['app'];
200                 $categories        = $orig_post['file'];
201                 $title             = notags(trim($_REQUEST['title']));
202                 $body              = escape_tags(trim($_REQUEST['body']));
203                 $private           = $orig_post['private'];
204                 $pubmail_enable    = $orig_post['pubmail'];
205                 $network           = $orig_post['network'];
206                 $guid              = $orig_post['guid'];
207
208         } else {
209
210                 // if coming from the API and no privacy settings are set, 
211                 // use the user default permissions - as they won't have
212                 // been supplied via a form.
213
214                 if(($api_source) 
215                         && (! array_key_exists('contact_allow',$_REQUEST))
216                         && (! array_key_exists('group_allow',$_REQUEST))
217                         && (! array_key_exists('contact_deny',$_REQUEST))
218                         && (! array_key_exists('group_deny',$_REQUEST))) {
219                         $str_group_allow   = $user['allow_gid'];
220                         $str_contact_allow = $user['allow_cid'];
221                         $str_group_deny    = $user['deny_gid'];
222                         $str_contact_deny  = $user['deny_cid'];
223                 }
224                 else {
225
226                         // use the posted permissions
227
228                         $str_group_allow   = perms2str($_REQUEST['group_allow']);
229                         $str_contact_allow = perms2str($_REQUEST['contact_allow']);
230                         $str_group_deny    = perms2str($_REQUEST['group_deny']);
231                         $str_contact_deny  = perms2str($_REQUEST['contact_deny']);
232                 }
233
234                 $title             = notags(trim($_REQUEST['title']));
235                 $location          = notags(trim($_REQUEST['location']));
236                 $coord             = notags(trim($_REQUEST['coord']));
237                 $verb              = notags(trim($_REQUEST['verb']));
238                 $emailcc           = notags(trim($_REQUEST['emailcc']));
239                 $body              = escape_tags(trim($_REQUEST['body']));
240                 $network           = notags(trim($_REQUEST['network']));
241                 $guid              = get_guid(32);
242
243
244                 $naked_body = preg_replace('/\[(.+?)\]/','',$body);
245
246                 if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
247                         $l = new Text_LanguageDetect;
248                         //$lng = $l->detectConfidence($naked_body);
249                         //$postopts = (($lng['language']) ? 'lang=' . $lng['language'] . ';' . $lng['confidence'] : '');
250
251                         $lng = $l->detect($naked_body, 3);
252
253                         if (sizeof($lng) > 0) {
254                                 $postopts = "";
255
256                                 foreach ($lng as $language => $score) {
257                                         if ($postopts == "")
258                                                 $postopts = "lang=";
259                                         else
260                                                 $postopts .= ":";
261
262                                         $postopts .= $language.";".$score;
263                                 }
264                         }
265
266                         logger('mod_item: detect language' . print_r($lng,true) . $naked_body, LOGGER_DATA);
267                 }
268                 else
269                         $postopts = '';
270
271
272                 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
273
274
275                 if($user['hidewall'])
276                         $private = 2;
277
278                 // If this is a comment, set the permissions from the parent.
279
280                 if($parent_item) {
281                         $private = 0;
282
283                         // for non native networks use the network of the original post as network of the item
284                         if (($parent_item['network'] != NETWORK_DIASPORA)
285                                 AND ($parent_item['network'] != NETWORK_OSTATUS)
286                                 AND ($network == ""))
287                                 $network = $parent_item['network'];
288
289                         if(($parent_item['private'])
290                                 || strlen($parent_item['allow_cid'])
291                                 || strlen($parent_item['allow_gid'])
292                                 || strlen($parent_item['deny_cid'])
293                                 || strlen($parent_item['deny_gid'])) {
294                                 $private = (($parent_item['private']) ? $parent_item['private'] : 1);
295                         }
296
297                         $str_contact_allow = $parent_item['allow_cid'];
298                         $str_group_allow   = $parent_item['allow_gid'];
299                         $str_contact_deny  = $parent_item['deny_cid'];
300                         $str_group_deny    = $parent_item['deny_gid'];
301                 }
302                 $pubmail_enable    = ((x($_REQUEST,'pubmail_enable') && intval($_REQUEST['pubmail_enable']) && (! $private)) ? 1 : 0);
303
304                 // if using the API, we won't see pubmail_enable - figure out if it should be set
305
306                 if($api_source && $profile_uid && $profile_uid == local_user() && (! $private)) {
307                         $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
308                         if(! $mail_disabled) {
309                                 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
310                                         intval(local_user())
311                                 );
312                                 if(count($r) && intval($r[0]['pubmail']))
313                                         $pubmail_enabled = true;
314                         }
315                 }
316
317                 if(! strlen($body)) {
318                         if($preview)
319                                 killme();
320                         info( t('Empty post discarded.') . EOL );
321                         if(x($_REQUEST,'return'))
322                                 goaway($a->get_baseurl() . "/" . $return_path );
323                         killme();
324                 }
325         }
326
327         if(strlen($categories)) {
328                 // get the "fileas" tags for this post
329                 $filedas = file_tag_file_to_list($categories, 'file');
330         }
331         // save old and new categories, so we can determine what needs to be deleted from pconfig
332         $categories_old = $categories;
333         $categories = file_tag_list_to_file(trim($_REQUEST['category']), 'category');
334         $categories_new = $categories;
335         if(strlen($filedas)) {
336                 // append the fileas stuff to the new categories list
337                 $categories .= file_tag_list_to_file($filedas, 'file');
338         }
339
340         // Work around doubled linefeeds in Tinymce 3.5b2
341         // First figure out if it's a status post that would've been
342         // created using tinymce. Otherwise leave it alone. 
343
344 /*      $plaintext = (local_user() ? intval(get_pconfig(local_user(),'system','plaintext')) || !feature_enabled($profile_uid,'richtext') : 0);
345         if((! $parent) && (! $api_source) && (! $plaintext)) {
346                 $body = fix_mce_lf($body);
347         }*/
348         $plaintext = (local_user() ? !feature_enabled($profile_uid,'richtext') : 0);
349         if((! $parent) && (! $api_source) && (! $plaintext)) {
350                 $body = fix_mce_lf($body);
351         }
352
353
354         // get contact info for poster
355
356         $author = null;
357         $self   = false;
358         $contact_id = 0;
359
360         if((local_user()) && (local_user() == $profile_uid)) {
361                 $self = true;
362                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
363                         intval($_SESSION['uid'])
364                 );
365         }
366         elseif(remote_user()) {
367                 if(is_array($_SESSION['remote'])) {
368                         foreach($_SESSION['remote'] as $v) {
369                                 if($v['uid'] == $profile_uid) {
370                                         $contact_id = $v['cid'];
371                                         break;
372                                 }
373                         }
374                 }
375                 if($contact_id) {
376                         $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
377                                 intval($contact_id)
378                         );
379                 }
380         }
381
382         if(count($r)) {
383                 $author = $r[0];
384                 $contact_id = $author['id'];
385         }
386
387         // get contact info for owner
388
389         if($profile_uid == local_user()) {
390                 $contact_record = $author;
391         }
392         else {
393                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
394                         intval($profile_uid)
395                 );
396                 if(count($r))
397                         $contact_record = $r[0];
398         }
399
400         $post_type = notags(trim($_REQUEST['type']));
401
402         if($post_type === 'net-comment') {
403                 if($parent_item !== null) {
404                         if($parent_item['wall'] == 1)
405                                 $post_type = 'wall-comment';
406                         else
407                                 $post_type = 'remote-comment';
408                 }
409         }
410
411         /**
412          *
413          * When a photo was uploaded into the message using the (profile wall) ajax
414          * uploader, The permissions are initially set to disallow anybody but the
415          * owner from seeing it. This is because the permissions may not yet have been
416          * set for the post. If it's private, the photo permissions should be set
417          * appropriately. But we didn't know the final permissions on the post until
418          * now. So now we'll look for links of uploaded messages that are in the
419          * post and set them to the same permissions as the post itself.
420          *
421          */
422
423         $match = null;
424
425         if((! $preview) && preg_match_all("/\[img([\=0-9x]*?)\](.*?)\[\/img\]/",$body,$match)) {
426                 $images = $match[2];
427                 if(count($images)) {
428                         foreach($images as $image) {
429                                 if(! stristr($image,$a->get_baseurl() . '/photo/'))
430                                         continue;
431                                 $image_uri = substr($image,strrpos($image,'/') + 1);
432                                 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
433                                 if(! strlen($image_uri))
434                                         continue;
435                                 $srch = '<' . intval($contact_id) . '>';
436
437                                 $r = q("SELECT `id` FROM `photo` WHERE `allow_cid` = '%s' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = ''
438                                         AND `resource-id` = '%s' AND `uid` = %d LIMIT 1",
439                                         dbesc($srch),
440                                         dbesc($image_uri),
441                                         intval($profile_uid)
442                                 );
443
444                                 if(! count($r))
445                                         continue;
446
447
448                                 $r = q("UPDATE `photo` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
449                                         WHERE `resource-id` = '%s' AND `uid` = %d AND `album` = '%s' ",
450                                         dbesc($str_contact_allow),
451                                         dbesc($str_group_allow),
452                                         dbesc($str_contact_deny),
453                                         dbesc($str_group_deny),
454                                         dbesc($image_uri),
455                                         intval($profile_uid),
456                                         dbesc( t('Wall Photos'))
457                                 );
458
459                         }
460                 }
461         }
462
463
464         /**
465          * Next link in any attachment references we find in the post.
466          */
467
468         $match = false;
469
470         if((! $preview) && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/",$body,$match)) {
471                 $attaches = $match[1];
472                 if(count($attaches)) {
473                         foreach($attaches as $attach) {
474                                 $r = q("SELECT * FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
475                                         intval($profile_uid),
476                                         intval($attach)
477                                 );
478                                 if(count($r)) {
479                                         $r = q("UPDATE `attach` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
480                                                 WHERE `uid` = %d AND `id` = %d",
481                                                 dbesc($str_contact_allow),
482                                                 dbesc($str_group_allow),
483                                                 dbesc($str_contact_deny),
484                                                 dbesc($str_group_deny),
485                                                 intval($profile_uid),
486                                                 intval($attach)
487                                         );
488                                 }
489                         }
490                 }
491         }
492
493         // embedded bookmark in post? set bookmark flag
494
495         $bookmark = 0;
496         if(preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$body,$match,PREG_SET_ORDER)) {
497                 $bookmark = 1;
498         }
499
500         $body = bb_translate_video($body);
501
502
503         /**
504          * Fold multi-line [code] sequences
505          */
506
507         $body = preg_replace('/\[\/code\]\s*\[code\]/ism',"\n",$body); 
508
509         $body = scale_external_images($body,false);
510
511
512
513         /**
514          * Look for any tags and linkify them
515          */
516
517         $str_tags = '';
518         $inform   = '';
519
520
521         $tags = get_tags($body);
522
523         /**
524          * add a statusnet style reply tag if the original post was from there
525          * and we are replying, and there isn't one already
526          */
527
528         if(($parent_contact) && ($parent_contact['network'] === NETWORK_OSTATUS) 
529                 && ($parent_contact['nick']) && (! in_array('@' . $parent_contact['nick'],$tags))) {
530                 $body = '@' . $parent_contact['nick'] . ' ' . $body;
531                 $tags[] = '@' . $parent_contact['nick'];
532         }
533
534         $tagged = array();
535
536         $private_forum = false;
537
538         if(count($tags)) {
539                 foreach($tags as $tag) {
540
541                         // If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
542                         // Robert Johnson should be first in the $tags array
543
544                         $fullnametagged = false;
545                         for($x = 0; $x < count($tagged); $x ++) {
546                                 if(stristr($tagged[$x],$tag . ' ')) {
547                                         $fullnametagged = true;
548                                         break;
549                                 }
550                         }
551                         if($fullnametagged)
552                                 continue;
553
554                         $success = handle_tag($a, $body, $inform, $str_tags, (local_user()) ? local_user() : $profile_uid , $tag); 
555                         if($success['replaced'])
556                                 $tagged[] = $tag;
557                         if(is_array($success['contact']) && intval($success['contact']['prv'])) {
558                                 $private_forum = true;
559                                 $private_id = $success['contact']['id'];
560                         }
561                 }
562         }
563
564         if(($private_forum) && (! $parent) && (! $private)) {
565                 // we tagged a private forum in a top level post and the message was public.
566                 // Restrict it.
567                 $private = 1;
568                 $str_contact_allow = '<' . $private_id . '>';
569         }
570
571         $attachments = '';
572         $match = false;
573
574         if(preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
575                 foreach($match[2] as $mtch) {
576                         $r = q("SELECT `id`,`filename`,`filesize`,`filetype` FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
577                                 intval($profile_uid),
578                                 intval($mtch)
579                         );
580                         if(count($r)) {
581                                 if(strlen($attachments))
582                                         $attachments .= ',';
583                                 $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]'; 
584                         }
585                         $body = str_replace($match[1],'',$body);
586                 }
587         }
588
589         $wall = 0;
590
591         if($post_type === 'wall' || $post_type === 'wall-comment')
592                 $wall = 1;
593
594         if(! strlen($verb))
595                 $verb = ACTIVITY_POST ;
596
597         if ($network == "")
598                 $network = NETWORK_DFRN;
599
600         $gravity = (($parent) ? 6 : 0 );
601
602         // even if the post arrived via API we are considering that it 
603         // originated on this site by default for determining relayability.
604
605         $origin = ((x($_REQUEST,'origin')) ? intval($_REQUEST['origin']) : 1);
606
607         $notify_type = (($parent) ? 'comment-new' : 'wall-new' );
608
609         $uri = (($message_id) ? $message_id : item_new_uri($a->get_hostname(),$profile_uid));
610
611         // Fallback so that we alway have a thr-parent
612         if(!$thr_parent)
613                 $thr_parent = $uri;
614
615         $datarray = array();
616         $datarray['uid']           = $profile_uid;
617         $datarray['type']          = $post_type;
618         $datarray['wall']          = $wall;
619         $datarray['gravity']       = $gravity;
620         $datarray['network']       = $network;
621         $datarray['contact-id']    = $contact_id;
622         $datarray['owner-name']    = $contact_record['name'];
623         $datarray['owner-link']    = $contact_record['url'];
624         $datarray['owner-avatar']  = $contact_record['thumb'];
625         $datarray['author-name']   = $author['name'];
626         $datarray['author-link']   = $author['url'];
627         $datarray['author-avatar'] = $author['thumb'];
628         $datarray['created']       = datetime_convert();
629         $datarray['edited']        = datetime_convert();
630         $datarray['commented']     = datetime_convert();
631         $datarray['received']      = datetime_convert();
632         $datarray['changed']       = datetime_convert();
633         $datarray['guid']          = $guid;
634         $datarray['uri']           = $uri;
635         $datarray['title']         = $title;
636         $datarray['body']          = $body;
637         $datarray['app']           = $app;
638         $datarray['location']      = $location;
639         $datarray['coord']         = $coord;
640         $datarray['tag']           = $str_tags;
641         $datarray['file']          = $categories;
642         $datarray['inform']        = $inform;
643         $datarray['verb']          = $verb;
644         $datarray['allow_cid']     = $str_contact_allow;
645         $datarray['allow_gid']     = $str_group_allow;
646         $datarray['deny_cid']      = $str_contact_deny;
647         $datarray['deny_gid']      = $str_group_deny;
648         $datarray['private']       = $private;
649         $datarray['pubmail']       = $pubmail_enable;
650         $datarray['attach']        = $attachments;
651         $datarray['bookmark']      = intval($bookmark);
652         $datarray['thr-parent']    = $thr_parent;
653         $datarray['postopts']      = $postopts;
654         $datarray['origin']        = $origin;
655         $datarray['moderated']     = $allow_moderated;
656
657         /**
658          * These fields are for the convenience of plugins...
659          * 'self' if true indicates the owner is posting on their own wall
660          * If parent is 0 it is a top-level post.
661          */
662
663         $datarray['parent']        = $parent;
664         $datarray['self']          = $self;
665 //      $datarray['prvnets']       = $user['prvnets'];
666
667         if($orig_post)
668                 $datarray['edit']      = true;
669
670         // preview mode - prepare the body for display and send it via json
671
672         if($preview) {
673                 require_once('include/conversation.php');
674                 $o = conversation($a,array(array_merge($contact_record,$datarray)),'search', false, true);
675                 logger('preview: ' . $o);
676                 echo json_encode(array('preview' => $o));
677                 killme();
678         }
679
680
681         call_hooks('post_local',$datarray);
682
683         if(x($datarray,'cancel')) {
684                 logger('mod_item: post cancelled by plugin.');
685                 if($return_path) {
686                         goaway($a->get_baseurl() . "/" . $return_path);
687                 }
688
689                 $json = array('cancel' => 1);
690                 if(x($_REQUEST,'jsreload') && strlen($_REQUEST['jsreload']))
691                         $json['reload'] = $a->get_baseurl() . '/' . $_REQUEST['jsreload'];
692
693                 echo json_encode($json);
694                 killme();
695         }
696
697
698         if($orig_post) {
699                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `attach` = '%s', `file` = '%s', `edited` = '%s', `changed` = '%s' WHERE `id` = %d AND `uid` = %d",
700                         dbesc($datarray['title']),
701                         dbesc($datarray['body']),
702                         dbesc($datarray['tag']),
703                         dbesc($datarray['attach']),
704                         dbesc($datarray['file']),
705                         dbesc(datetime_convert()),
706                         dbesc(datetime_convert()),
707                         intval($post_id),
708                         intval($profile_uid)
709                 );
710
711                 create_tags_from_item($post_id);
712                 create_files_from_item($post_id);
713                 update_thread($post_id);
714
715                 // update filetags in pconfig
716                 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
717
718                 proc_run('php', "include/notifier.php", 'edit_post', "$post_id");
719                 if((x($_REQUEST,'return')) && strlen($return_path)) {
720                         logger('return: ' . $return_path);
721                         goaway($a->get_baseurl() . "/" . $return_path );
722                 }
723                 killme();
724         }
725         else
726                 $post_id = 0;
727
728
729         $r = q("INSERT INTO `item` (`guid`, `uid`,`type`,`wall`,`gravity`, `network`, `contact-id`,`owner-name`,`owner-link`,`owner-avatar`, 
730                 `author-name`, `author-link`, `author-avatar`, `created`, `edited`, `commented`, `received`, `changed`, `uri`, `thr-parent`, `title`, `body`, `app`, `location`, `coord`, 
731                 `tag`, `inform`, `verb`, `postopts`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid`, `private`, `pubmail`, `attach`, `bookmark`,`origin`, `moderated`, `file` )
732                 VALUES( '%s', %d, '%s', %d, %d, '%s', %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, '%s' )",
733                 dbesc($datarray['guid']),
734                 intval($datarray['uid']),
735                 dbesc($datarray['type']),
736                 intval($datarray['wall']),
737                 intval($datarray['gravity']),
738                 dbesc($datarray['network']),
739                 intval($datarray['contact-id']),
740                 dbesc($datarray['owner-name']),
741                 dbesc($datarray['owner-link']),
742                 dbesc($datarray['owner-avatar']),
743                 dbesc($datarray['author-name']),
744                 dbesc($datarray['author-link']),
745                 dbesc($datarray['author-avatar']),
746                 dbesc($datarray['created']),
747                 dbesc($datarray['edited']),
748                 dbesc($datarray['commented']),
749                 dbesc($datarray['received']),
750                 dbesc($datarray['changed']),
751                 dbesc($datarray['uri']),
752                 dbesc($datarray['thr-parent']),
753                 dbesc($datarray['title']),
754                 dbesc($datarray['body']),
755                 dbesc($datarray['app']),
756                 dbesc($datarray['location']),
757                 dbesc($datarray['coord']),
758                 dbesc($datarray['tag']),
759                 dbesc($datarray['inform']),
760                 dbesc($datarray['verb']),
761                 dbesc($datarray['postopts']),
762                 dbesc($datarray['allow_cid']),
763                 dbesc($datarray['allow_gid']),
764                 dbesc($datarray['deny_cid']),
765                 dbesc($datarray['deny_gid']),
766                 intval($datarray['private']),
767                 intval($datarray['pubmail']),
768                 dbesc($datarray['attach']),
769                 intval($datarray['bookmark']),
770                 intval($datarray['origin']),
771                 intval($datarray['moderated']),
772                 dbesc($datarray['file'])
773                );
774
775         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
776                 dbesc($datarray['uri']));
777         if(count($r)) {
778                 $post_id = $r[0]['id'];
779                 logger('mod_item: saved item ' . $post_id);
780                 add_thread($post_id);
781
782                 // update filetags in pconfig
783                 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
784
785                 // Store the fresh generated item into the cache
786                 $cachefile = get_cachefile($datarray["guid"]."-".hash("md5", $datarray['body']));
787
788                 if (($cachefile != '') AND !file_exists($cachefile)) {
789                         $s = prepare_text($datarray['body']);
790                         $stamp1 = microtime(true);
791                         file_put_contents($cachefile, $s);
792                         $a->save_timestamp($stamp1, "file");
793                         logger('mod_item: put item '.$r[0]['id'].' into cachefile '.$cachefile);
794                 }
795
796                 if($parent) {
797
798                         // This item is the last leaf and gets the comment box, clear any ancestors
799                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent` = %d ",
800                                 dbesc(datetime_convert()),
801                                 intval($parent)
802                         );
803                         update_thread($parent, true);
804
805                         // Inherit ACLs from the parent item.
806
807                         $r = q("UPDATE `item` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d
808                                 WHERE `id` = %d",
809                                 dbesc($parent_item['allow_cid']),
810                                 dbesc($parent_item['allow_gid']),
811                                 dbesc($parent_item['deny_cid']),
812                                 dbesc($parent_item['deny_gid']),
813                                 intval($parent_item['private']),
814                                 intval($post_id)
815                         );
816
817                         if($contact_record != $author) {
818                                 notification(array(
819                                         'type'         => NOTIFY_COMMENT,
820                                         'notify_flags' => $user['notify-flags'],
821                                         'language'     => $user['language'],
822                                         'to_name'      => $user['username'],
823                                         'to_email'     => $user['email'],
824                                         'uid'          => $user['uid'],
825                                         'item'         => $datarray,
826                                         //'link'                   => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id,
827                                         'link'             => $a->get_baseurl().'/display/'.$datarray['guid'],
828                                         'source_name'  => $datarray['author-name'],
829                                         'source_link'  => $datarray['author-link'],
830                                         'source_photo' => $datarray['author-avatar'],
831                                         'verb'         => ACTIVITY_POST,
832                                         'otype'        => 'item',
833                                         'parent'       => $parent,
834                                         'parent_uri'   => $parent_item['uri']
835                                 ));
836
837                         }
838
839
840                         // Store the comment signature information in case we need to relay to Diaspora
841                         store_diaspora_comment_sig($datarray, $author, ($self ? $a->user['prvkey'] : false), $parent_item, $post_id);
842
843                 } else {
844                         $parent = $post_id;
845
846                         if($contact_record != $author) {
847                                 notification(array(
848                                         'type'         => NOTIFY_WALL,
849                                         'notify_flags' => $user['notify-flags'],
850                                         'language'     => $user['language'],
851                                         'to_name'      => $user['username'],
852                                         'to_email'     => $user['email'],
853                                         'uid'          => $user['uid'],
854                                         'item'         => $datarray,
855                                         //'link'                   => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id,
856                                         'link'             => $a->get_baseurl().'/display/'.$datarray['guid'],
857                                         'source_name'  => $datarray['author-name'],
858                                         'source_link'  => $datarray['author-link'],
859                                         'source_photo' => $datarray['author-avatar'],
860                                         'verb'         => ACTIVITY_POST,
861                                         'otype'        => 'item'
862                                 ));
863                         }
864                 }
865
866                 // fallback so that parent always gets set to non-zero.
867
868                 if(! $parent)
869                         $parent = $post_id;
870
871                 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s', `plink` = '%s', `changed` = '%s', `last-child` = 1, `visible` = 1
872                         WHERE `id` = %d",
873                         intval($parent),
874                         dbesc(($parent == $post_id) ? $uri : $parent_item['uri']),
875                         //dbesc($a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id),
876                         dbesc($a->get_baseurl().'/display/'.$datarray['guid']),
877                         dbesc(datetime_convert()),
878                         intval($post_id)
879                 );
880
881                 // photo comments turn the corresponding item visible to the profile wall
882                 // This way we don't see every picture in your new photo album posted to your wall at once.
883                 // They will show up as people comment on them.
884
885                 if(! $parent_item['visible']) {
886                         $r = q("UPDATE `item` SET `visible` = 1 WHERE `id` = %d",
887                                 intval($parent_item['id'])
888                         );
889                         update_thread($parent_item['id']);
890                 }
891         }
892         else {
893                 logger('mod_item: unable to retrieve post that was just stored.');
894                 notice( t('System error. Post not saved.') . EOL);
895                 goaway($a->get_baseurl() . "/" . $return_path );
896                 // NOTREACHED
897         }
898
899         // update the commented timestamp on the parent
900
901         q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d",
902                 dbesc(datetime_convert()),
903                 dbesc(datetime_convert()),
904                 intval($parent)
905         );
906         update_thread($parent);
907
908         $datarray['id']    = $post_id;
909         //$datarray['plink'] = $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id;
910         $datarray['plink'] = $a->get_baseurl().'/display/'.$datarray['guid'];
911
912         call_hooks('post_local_end', $datarray);
913
914         if(strlen($emailcc) && $profile_uid == local_user()) {
915                 $erecips = explode(',', $emailcc);
916                 if(count($erecips)) {
917                         foreach($erecips as $recip) {
918                                 $addr = trim($recip);
919                                 if(! strlen($addr))
920                                         continue;
921                                 $disclaimer = '<hr />' . sprintf( t('This message was sent to you by %s, a member of the Friendica social network.'),$a->user['username']) 
922                                         . '<br />';
923                                 $disclaimer .= sprintf( t('You may visit them online at %s'), $a->get_baseurl() . '/profile/' . $a->user['nickname']) . EOL;
924                                 $disclaimer .= t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL; 
925                                 if (!$datarray['title']=='') {
926                                     $subject = email_header_encode($datarray['title'],'UTF-8');
927                                 } else {
928                                     $subject = email_header_encode('[Friendica]' . ' ' . sprintf( t('%s posted an update.'),$a->user['username']),'UTF-8');
929                                 }
930                                 $link = '<a href="' . $a->get_baseurl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
931                                 $html    = prepare_body($datarray);
932                                 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
933                                 include_once('include/html2plain.php');
934                                 $params = array (
935                                     'fromName' => $a->user['username'],
936                                     'fromEmail' => $a->user['email'],
937                                     'toEmail' => $addr,
938                                     'replyTo' => $a->user['email'],
939                                     'messageSubject' => $subject,
940                                     'htmlVersion' => $message,
941                                     'textVersion' => html2plain($html.$disclaimer),
942                                 );
943                                 enotify::send($params);
944                         }
945                 }
946         }
947
948         create_tags_from_item($post_id);
949         create_files_from_item($post_id);
950         update_thread($post_id);
951
952         // This is a real juggling act on shared hosting services which kill your processes
953         // e.g. dreamhost. We used to start delivery to our native delivery agents in the background
954         // and then run our plugin delivery from the foreground. We're now doing plugin delivery first,
955         // because as soon as you start loading up a bunch of remote delivey processes, *this* page is
956         // likely to get killed off. If you end up looking at an /item URL and a blank page,
957         // it's very likely the delivery got killed before all your friends could be notified.
958         // Currently the only realistic fixes are to use a reliable server - which precludes shared hosting,
959         // or cut back on plugins which do remote deliveries.
960
961         proc_run('php', "include/notifier.php", $notify_type, "$post_id");
962
963         logger('post_complete');
964
965         item_post_return($a->get_baseurl(), $api_source, $return_path);
966         // NOTREACHED
967 }
968
969 function item_post_return($baseurl, $api_source, $return_path) {
970         // figure out how to return, depending on from whence we came
971
972         if($api_source)
973                 return;
974
975         if($return_path) {
976                 goaway($baseurl . "/" . $return_path);
977         }
978
979         $json = array('success' => 1);
980         if(x($_REQUEST,'jsreload') && strlen($_REQUEST['jsreload']))
981                 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
982
983         logger('post_json: ' . print_r($json,true), LOGGER_DEBUG);
984
985         echo json_encode($json);
986         killme();
987 }
988
989
990
991 function item_content(&$a) {
992
993         if((! local_user()) && (! remote_user()))
994                 return;
995
996         require_once('include/security.php');
997
998         $o = '';
999         if(($a->argc == 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
1000                 require_once('include/items.php'); 
1001                 $o = drop_item($a->argv[2], !is_ajax());
1002                 if (is_ajax()){
1003                         // ajax return: [<item id>, 0 (no perm) | <owner id>] 
1004                         echo json_encode(array(intval($a->argv[2]), intval($o)));
1005                         killme();
1006                 }
1007         }
1008         return $o;
1009 }
1010
1011 /**
1012  * This function removes the tag $tag from the text $body and replaces it with 
1013  * the appropiate link. 
1014  * 
1015  * @param unknown_type $body the text to replace the tag in
1016  * @param unknown_type $inform a comma-seperated string containing everybody to inform
1017  * @param unknown_type $str_tags string to add the tag to
1018  * @param unknown_type $profile_uid
1019  * @param unknown_type $tag the tag to replace
1020  *
1021  * @return boolean true if replaced, false if not replaced
1022  */
1023 function handle_tag($a, &$body, &$inform, &$str_tags, $profile_uid, $tag) {
1024
1025         $replaced = false;
1026         $r = null;
1027
1028         //is it a hash tag? 
1029         if(strpos($tag,'#') === 0) {
1030                 //if the tag is replaced...
1031                 if(strpos($tag,'[url='))
1032                         //...do nothing
1033                         return $replaced;
1034                 //base tag has the tags name only
1035                 $basetag = str_replace('_',' ',substr($tag,1));
1036                 //create text for link
1037                 $newtag = '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1038                 //replace tag by the link
1039                 $body = str_replace($tag, $newtag, $body);
1040                 $replaced = true;
1041
1042                 //is the link already in str_tags?
1043                 if(! stristr($str_tags,$newtag)) {
1044                         //append or set str_tags
1045                         if(strlen($str_tags))
1046                                 $str_tags .= ',';
1047                         $str_tags .= $newtag;
1048                 }
1049                 return $replaced;
1050         }
1051         //is it a person tag? 
1052         if(strpos($tag,'@') === 0) {
1053                 //is it already replaced? 
1054                 if(strpos($tag,'[url='))
1055                         return $replaced;
1056                 $stat = false;
1057                 //get the person's name
1058                 $name = substr($tag,1);
1059                 //is it a link or a full dfrn address? 
1060                 if((strpos($name,'@')) || (strpos($name,'http://'))) {
1061                         $newname = $name;
1062                         //get the profile links
1063                         $links = @lrdd($name);
1064                         if(count($links)) {
1065                                 //for all links, collect how is to inform and how's profile is to link
1066                                 foreach($links as $link) {
1067                                         if($link['@attributes']['rel'] === 'http://webfinger.net/rel/profile-page')
1068                                                 $profile = $link['@attributes']['href'];
1069                                         if($link['@attributes']['rel'] === 'salmon') {
1070                                                 if(strlen($inform))
1071                                                         $inform .= ',';
1072                                                 $inform .= 'url:' . str_replace(',','%2c',$link['@attributes']['href']);
1073                                         }
1074                                 }
1075                         }
1076                 } else { //if it is a name rather than an address
1077                         $newname = $name;
1078                         $alias = '';
1079                         $tagcid = 0;
1080                         //is it some generated name?
1081                         if(strrpos($newname,'+')) {
1082                                 //get the id
1083                                 $tagcid = intval(substr($newname,strrpos($newname,'+') + 1));
1084                                 //remove the next word from tag's name
1085                                 if(strpos($name,' ')) {
1086                                         $name = substr($name,0,strpos($name,' '));
1087                                 }
1088                         }
1089                         if($tagcid) { //if there was an id
1090                                 //select contact with that id from the logged in user's contact list
1091                                 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1092                                                 intval($tagcid),
1093                                                 intval($profile_uid)
1094                                 );
1095                         }
1096                         else {
1097                                 $newname = str_replace('_',' ',$name);
1098
1099                                 //select someone from this user's contacts by name
1100                                 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
1101                                                 dbesc($newname),
1102                                                 intval($profile_uid)
1103                                 );
1104
1105                                 if(! $r) {
1106                                         //select someone by attag or nick and the name passed in
1107                                         $r = q("SELECT * FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
1108                                                         dbesc($name),
1109                                                         dbesc($name),
1110                                                         intval($profile_uid)
1111                                         );
1112                                 }
1113                         }
1114 /*                      } elseif(strstr($name,'_') || strstr($name,' ')) { //no id
1115                                 //get the real name
1116                                 $newname = str_replace('_',' ',$name);
1117                                 //select someone from this user's contacts by name
1118                                 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
1119                                                 dbesc($newname),
1120                                                 intval($profile_uid)
1121                                 );
1122                         } else {
1123                                 //select someone by attag or nick and the name passed in
1124                                 $r = q("SELECT * FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
1125                                                 dbesc($name),
1126                                                 dbesc($name),
1127                                                 intval($profile_uid)
1128                                 );
1129                         }*/
1130                         //$r is set, if someone could be selected
1131                         if(count($r)) {
1132                                 $profile = $r[0]['url'];
1133                                 //set newname to nick, find alias
1134                                 if(($r[0]['network'] === NETWORK_OSTATUS) OR ($r[0]['network'] === NETWORK_TWITTER)
1135                                         OR ($r[0]['network'] === NETWORK_STATUSNET) OR ($r[0]['network'] === NETWORK_APPNET)) {
1136                                         $newname = $r[0]['nick'];
1137                                         $stat = true;
1138                                         if($r[0]['alias'])
1139                                                 $alias = $r[0]['alias'];
1140                                 }
1141                                 else
1142                                         $newname = $r[0]['name'];
1143                                 //add person's id to $inform
1144                                 if(strlen($inform))
1145                                         $inform .= ',';
1146                                 $inform .= 'cid:' . $r[0]['id'];
1147                         }
1148                 }
1149                 //if there is an url for this persons profile
1150                 if(isset($profile)) {
1151                         $replaced = true;
1152                         //create profile link
1153                         $profile = str_replace(',','%2c',$profile);
1154                         $newtag = '@[url=' . $profile . ']' . $newname  . '[/url]';
1155                         $body = str_replace('@' . $name, $newtag, $body);
1156                         //append tag to str_tags
1157                         if(! stristr($str_tags,$newtag)) {
1158                                 if(strlen($str_tags))
1159                                         $str_tags .= ',';
1160                                 $str_tags .= $newtag;
1161                         }
1162         
1163                         // Status.Net seems to require the numeric ID URL in a mention if the person isn't
1164                         // subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1165         
1166                         if(strlen($alias)) {
1167                                 $newtag = '@[url=' . $alias . ']' . $newname    . '[/url]';
1168                                 if(! stristr($str_tags,$newtag)) {
1169                                         if(strlen($str_tags))
1170                                                 $str_tags .= ',';
1171                                         $str_tags .= $newtag;
1172                                 }
1173                         }
1174                 }
1175         }
1176
1177         return array('replaced' => $replaced, 'contact' => $r[0]);      
1178 }
1179
1180
1181 function store_diaspora_comment_sig($datarray, $author, $uprvkey, $parent_item, $post_id) {
1182         // We won't be able to sign Diaspora comments for authenticated visitors - we don't have their private key
1183
1184         $enabled = intval(get_config('system','diaspora_enabled'));
1185         if(! $enabled) {
1186                 logger('mod_item: diaspora support disabled, not storing comment signature', LOGGER_DEBUG);
1187                 return;
1188         }
1189
1190
1191         logger('mod_item: storing diaspora comment signature');
1192
1193         require_once('include/bb2diaspora.php');
1194         $signed_body = html_entity_decode(bb2diaspora($datarray['body']));
1195
1196         // Only works for NETWORK_DFRN
1197         $contact_baseurl_start = strpos($author['url'],'://') + 3;
1198         $contact_baseurl_length = strpos($author['url'],'/profile') - $contact_baseurl_start;
1199         $contact_baseurl = substr($author['url'], $contact_baseurl_start, $contact_baseurl_length);
1200         $diaspora_handle = $author['nick'] . '@' . $contact_baseurl;
1201
1202         $signed_text = $datarray['guid'] . ';' . $parent_item['guid'] . ';' . $signed_body . ';' . $diaspora_handle;
1203
1204         if( $uprvkey !== false )
1205                 $authorsig = base64_encode(rsa_sign($signed_text,$uprvkey,'sha256'));
1206         else
1207                 $authorsig = '';
1208
1209         q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1210                 intval($post_id),
1211                 dbesc($signed_text),
1212                 dbesc(base64_encode($authorsig)),
1213                 dbesc($diaspora_handle)
1214         );
1215
1216         return;
1217 }