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