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