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