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