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