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