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