]> git.mxchange.org Git - friendica.git/blob - mod/item.php
98425d70e0fb747eff4c6bd78108b9e125b3821f
[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
20 function item_post(&$a) {
21
22         if((! local_user()) && (! remote_user()))
23                 return;
24
25         require_once('include/security.php');
26
27         $uid = local_user();
28
29         if(x($_POST,'dropitems')) {
30                 require_once('include/items.php');
31                 $arr_drop = explode(',',$_POST['dropitems']);
32                 drop_items($arr_drop);
33                 $json = array('success' => 1);
34                 echo json_encode($json);
35                 killme();
36         }
37
38         call_hooks('post_local_start', $_POST);
39
40         $api_source = ((x($_POST,'api_source') && $_POST['api_source']) ? true : false);
41         $return_path = ((x($_POST,'return')) ? $_POST['return'] : '');
42
43         /**
44          * Is this a reply to something?
45          */
46
47         $parent = ((x($_POST,'parent')) ? intval($_POST['parent']) : 0);
48         $parent_uri = ((x($_POST,'parent_uri')) ? trim($_POST['parent_uri']) : '');
49
50         $parent_item = null;
51         $parent_contact = null;
52         $thr_parent = '';
53         $parid = 0;
54         $r = false;
55
56         if($parent || $parent_uri) {
57
58                 if(! x($_POST,'type'))
59                         $_POST['type'] = 'net-comment';
60
61                 if($parent) {
62                         $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
63                                 intval($parent)
64                         );
65                 }
66                 elseif($parent_uri && local_user()) {
67                         // This is coming from an API source, and we are logged in
68                         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
69                                 dbesc($parent_uri),
70                                 intval(local_user())
71                         );
72                 }
73                 // if this isn't the real parent of the conversation, find it
74                 if($r !== false && count($r)) {
75                         $parid = $r[0]['parent'];
76                         if($r[0]['id'] != $r[0]['parent']) {
77                                 $r = q("SELECT * FROM `item` WHERE `id` = `parent` AND `parent` = %d LIMIT 1",
78                                         intval($parid)
79                                 );
80                         }
81                 }
82
83                 if(($r === false) || (! count($r))) {
84                         notice( t('Unable to locate original post.') . EOL);
85                         if(x($_POST,'return')) 
86                                 goaway($a->get_baseurl() . "/" . $return_path );
87                         killme();
88                 }
89                 $parent_item = $r[0];
90                 $parent = $r[0]['id'];
91
92                 // multi-level threading - preserve the info but re-parent to our single level threading
93                 if(($parid) && ($parid != $parent))
94                         $thr_parent = $parent_uri;
95
96                 if($parent_item['contact-id'] && $uid) {
97                         $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
98                                 intval($parent_item['contact-id']),
99                                 intval($uid)
100                         );
101                         if(count($r))
102                                 $parent_contact = $r[0];
103                 }
104         }
105
106         if($parent) logger('mod_post: parent=' . $parent);
107
108         $profile_uid = ((x($_POST,'profile_uid')) ? intval($_POST['profile_uid']) : 0);
109         $post_id     = ((x($_POST['post_id']))    ? intval($_POST['post_id'])     : 0);
110         $app         = ((x($_POST['source']))     ? strip_tags($_POST['source'])  : '');
111
112         if(! can_write_wall($a,$profile_uid)) {
113                 notice( t('Permission denied.') . EOL) ;
114                 if(x($_POST,'return')) 
115                         goaway($a->get_baseurl() . "/" . $return_path );
116                 killme();
117         }
118
119
120         // is this an edited post?
121
122         $orig_post = null;
123
124         if($post_id) {
125                 $i = q("SELECT * FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
126                         intval($profile_uid),
127                         intval($post_id)
128                 );
129                 if(! count($i))
130                         killme();
131                 $orig_post = $i[0];
132         }
133
134         $user = null;
135
136         $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
137                 intval($profile_uid)
138         );
139         if(count($r))
140                 $user = $r[0];
141         
142         if(($api_source) 
143                 && (! array_key_exists('allow_cid',$_REQUEST))
144                 && (! array_key_exists('allow_gid',$_REQUEST))
145                 && (! array_key_exists('deny_cid',$_REQUEST))
146                 && (! array_key_exists('deny_gid',$_REQUEST))) {
147                 $str_group_allow   = $user['allow_gid'];
148                 $str_contact_allow = $user['allow_cid'];
149                 $str_group_deny    = $user['deny_gid'];
150                 $str_contact_deny  = $user['deny_cid'];
151         }
152
153         if($orig_post) {
154                 $str_group_allow   = $orig_post['allow_gid'];
155                 $str_contact_allow = $orig_post['allow_cid'];
156                 $str_group_deny    = $orig_post['deny_gid'];
157                 $str_contact_deny  = $orig_post['deny_cid'];
158                 $title             = $orig_post['title'];
159                 $location          = $orig_post['location'];
160                 $coord             = $orig_post['coord'];
161                 $verb              = $orig_post['verb'];
162                 $emailcc           = $orig_post['emailcc'];
163                 $app                       = $orig_post['app'];
164
165                 $body              = escape_tags(trim($_POST['body']));
166                 $private           = $orig_post['private'];
167                 $pubmail_enable    = $orig_post['pubmail'];
168         }
169         else {
170                 $str_group_allow   = perms2str($_POST['group_allow']);
171                 $str_contact_allow = perms2str($_POST['contact_allow']);
172                 $str_group_deny    = perms2str($_POST['group_deny']);
173                 $str_contact_deny  = perms2str($_POST['contact_deny']);
174                 $title             = notags(trim($_POST['title']));
175                 $location          = notags(trim($_POST['location']));
176                 $coord             = notags(trim($_POST['coord']));
177                 $verb              = notags(trim($_POST['verb']));
178                 $emailcc           = notags(trim($_POST['emailcc']));
179
180                 $body              = escape_tags(trim($_POST['body']));
181                 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
182
183                 if(($parent_item) && 
184                         (($parent_item['private']) 
185                                 || strlen($parent_item['allow_cid']) 
186                                 || strlen($parent_item['allow_gid']) 
187                                 || strlen($parent_item['deny_cid']) 
188                                 || strlen($parent_item['deny_gid'])
189                         )) {
190                         $private = 1;
191                 }
192         
193                 $pubmail_enable    = ((x($_POST,'pubmail_enable') && intval($_POST['pubmail_enable']) && (! $private)) ? 1 : 0);
194
195                 // if using the API, we won't see pubmail_enable - figure out if it should be set
196
197                 if($api_source && $profile_uid && $profile_uid == local_user() && (! $private)) {
198                         $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
199                         if(! $mail_disabled) {
200                                 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
201                                         intval(local_user())
202                                 );
203                                 if(count($r) && intval($r[0]['pubmail']))
204                                         $pubmail_enabled = true;
205                         }
206                 }
207
208
209                 if(! strlen($body)) {
210                         info( t('Empty post discarded.') . EOL );
211                         if(x($_POST,'return')) 
212                                 goaway($a->get_baseurl() . "/" . $return_path );
213                         killme();
214                 }
215         }
216
217         // get contact info for poster
218
219         $author = null;
220         $self   = false;
221
222         if(($_SESSION['uid']) && ($_SESSION['uid'] == $profile_uid)) {
223                 $self = true;
224                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
225                         intval($_SESSION['uid'])
226                 );
227         }
228         else {
229                 if((x($_SESSION,'visitor_id')) && (intval($_SESSION['visitor_id']))) {
230                         $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
231                                 intval($_SESSION['visitor_id'])
232                         );
233                 }
234         }
235
236         if(count($r)) {
237                 $author = $r[0];
238                 $contact_id = $author['id'];
239         }
240
241         // get contact info for owner
242         
243         if($profile_uid == $_SESSION['uid']) {
244                 $contact_record = $author;
245         }
246         else {
247                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
248                         intval($profile_uid)
249                 );
250                 if(count($r))
251                         $contact_record = $r[0];
252         }
253
254
255
256         $post_type = notags(trim($_POST['type']));
257
258         if($post_type === 'net-comment') {
259                 if($parent_item !== null) {
260                         if($parent_item['wall'] == 1)
261                                 $post_type = 'wall-comment';
262                         else
263                                 $post_type = 'remote-comment';
264                 }
265         }
266
267         /**
268          *
269          * When a photo was uploaded into the message using the (profile wall) ajax 
270          * uploader, The permissions are initially set to disallow anybody but the
271          * owner from seeing it. This is because the permissions may not yet have been
272          * set for the post. If it's private, the photo permissions should be set
273          * appropriately. But we didn't know the final permissions on the post until
274          * now. So now we'll look for links of uploaded messages that are in the
275          * post and set them to the same permissions as the post itself.
276          *
277          */
278
279         $match = null;
280
281         if(preg_match_all("/\[img\](.*?)\[\/img\]/",$body,$match)) {
282                 $images = $match[1];
283                 if(count($images)) {
284                         foreach($images as $image) {
285                                 if(! stristr($image,$a->get_baseurl() . '/photo/'))
286                                         continue;
287                                 $image_uri = substr($image,strrpos($image,'/') + 1);
288                                 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
289                                 if(! strlen($image_uri))
290                                         continue;
291                                 $srch = '<' . intval($profile_uid) . '>';
292                                 $r = q("SELECT `id` FROM `photo` WHERE `allow_cid` = '%s' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = ''
293                                         AND `resource-id` = '%s' AND `uid` = %d LIMIT 1",
294                                         dbesc($srch),
295                                         dbesc($image_uri),
296                                         intval($profile_uid)
297                                 );
298                                 if(! count($r))
299                                         continue;
300  
301
302                                 $r = q("UPDATE `photo` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
303                                         WHERE `resource-id` = '%s' AND `uid` = %d AND `album` = '%s' ",
304                                         dbesc($str_contact_allow),
305                                         dbesc($str_group_allow),
306                                         dbesc($str_contact_deny),
307                                         dbesc($str_group_deny),
308                                         dbesc($image_uri),
309                                         intval($profile_uid),
310                                         dbesc( t('Wall Photos'))
311                                 );
312  
313                         }
314                 }
315         }
316
317
318         /**
319          * Next link in any attachment references we find in the post.
320          */
321
322         $match = false;
323
324         if(preg_match_all("/\[attachment\](.*?)\[\/attachment\]/",$body,$match)) {
325                 $attaches = $match[1];
326                 if(count($attaches)) {
327                         foreach($attaches as $attach) {
328                                 $r = q("SELECT * FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
329                                         intval($profile_uid),
330                                         intval($attach)
331                                 );                              
332                                 if(count($r)) {
333                                         $r = q("UPDATE `attach` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
334                                                 WHERE `uid` = %d AND `id` = %d LIMIT 1",
335                                                 dbesc($str_contact_allow),
336                                                 dbesc($str_group_allow),
337                                                 dbesc($str_contact_deny),
338                                                 dbesc($str_group_deny),
339                                                 intval($profile_uid),
340                                                 intval($attach)
341                                         );
342                                 }
343                         }
344                 }
345         }
346
347         // embedded bookmark in post? set bookmark flag
348
349         $bookmark = 0;
350         if(preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$body,$match,PREG_SET_ORDER)) {
351                 $bookmark = 1;
352 //              foreach($match as $mtch) {
353 //                      $body = str_replace(
354 //                              '[bookmark=' . $mtch[1] . ']' . $mtch[2] . '[/bookmark]',
355 //                              '[url=' . $mtch[1] . ']' . $mtch[2] . '[/url]',
356 //                              $body
357 //                      );
358 //              }
359         }
360
361         $body = bb_translate_video($body);
362
363         /**
364          * Fold multi-line [code] sequences
365          */
366
367         $body = preg_replace('/\[\/code\]\s*\[code\]/ism',"\n",$body); 
368
369         /**
370          * Look for any tags and linkify them
371          */
372
373         $str_tags = '';
374         $inform   = '';
375
376
377         $tags = get_tags($body);
378
379         /**
380          * add a statusnet style reply tag if the original post was from there
381          * and we are replying, and there isn't one already
382          */
383
384         if(($parent_contact) && ($parent_contact['network'] === NETWORK_OSTATUS) 
385                 && ($parent_contact['nick']) && (! in_array('@' . $parent_contact['nick'],$tags))) {
386                 $body = '@' . $parent_contact['nick'] . ' ' . $body;
387                 $tags[] = '@' . $parent_contact['nick'];
388         }               
389
390         if(count($tags)) {
391                 foreach($tags as $tag) {
392                         
393                         if(isset($profile))
394                                 unset($profile);
395                         if(strpos($tag,'#') === 0) {
396                                 if(strpos($tag,'[url='))
397                                         continue;
398                                 $basetag = str_replace('_',' ',substr($tag,1));
399                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
400                                 if(strlen($str_tags))
401                                         $str_tags .= ',';
402                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
403                                 continue;
404                         }
405                         if(strpos($tag,'@') === 0) {
406                                 if(strpos($tag,'[url='))
407                                         continue;
408                                 $stat = false;
409                                 $name = substr($tag,1);
410                                 if((strpos($name,'@')) || (strpos($name,'http://'))) {
411                                         $newname = $name;
412                                         $links = @lrdd($name);
413                                         if(count($links)) {
414                                                 foreach($links as $link) {
415                                                         if($link['@attributes']['rel'] === 'http://webfinger.net/rel/profile-page')
416                                         $profile = $link['@attributes']['href'];
417                                                         if($link['@attributes']['rel'] === 'salmon') {
418                                                                 if(strlen($inform))
419                                                                         $inform .= ',';
420                                         $inform .= 'url:' . str_replace(',','%2c',$link['@attributes']['href']);
421                                                         }
422                                                 }
423                                         }
424                                 }
425                                 else {
426                                         $newname = $name;
427                                         $alias = '';
428                                         $tagcid = 0;
429                                         if(strrpos($newname,'+')) {
430                                                 $tagcid = intval(substr($newname,strrpos($newname,'+') + 1));
431                                                 if(strpos($name,' '))
432                                                         $name = substr($name,0,strpos($name,' '));
433                                         }       
434                                         if($tagcid) {
435                                                 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
436                                                         intval($tagcid),
437                                                         intval($profile_uid)
438                                                 );
439                                         }
440                                         elseif(strstr($name,'_') || strstr($name,' ')) {
441                                                 $newname = str_replace('_',' ',$name);
442                                                 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
443                                                         dbesc($newname),
444                                                         intval($profile_uid)
445                                                 );
446                                         }
447                                         else {
448                                                 $r = q("SELECT * FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
449                                                         dbesc($name),
450                                                         dbesc($name),
451                                                         intval($profile_uid)
452                                                 );
453                                         }
454                                         if(count($r)) {
455                                                 $profile = $r[0]['url'];
456                                                 if($r[0]['network'] === 'stat') {
457                                                         $newname = $r[0]['nick'];
458                                                         $stat = true;
459                                                         if($r[0]['alias'])
460                                                                 $alias = $r[0]['alias'];
461                                                 }
462                                                 else
463                                                         $newname = $r[0]['name'];
464                                                 if(strlen($inform))
465                                                         $inform .= ',';
466                                                 $inform .= 'cid:' . $r[0]['id'];
467                                         }
468                                 }
469                                 if($profile) {
470                                         $body = str_replace('@' . $name, '@' . '[url=' . $profile . ']' . $newname      . '[/url]', $body);
471                                         $profile = str_replace(',','%2c',$profile);
472                                         $newtag = '@[url=' . $profile . ']' . $newname  . '[/url]';
473                                         if(! stristr($str_tags,$newtag)) {
474                                                 if(strlen($str_tags))
475                                                         $str_tags .= ',';
476                                                 $str_tags .= $newtag;
477                                         }
478
479                                         // Status.Net seems to require the numeric ID URL in a mention if the person isn't 
480                                         // subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both. 
481
482                                         if(strlen($alias)) {
483                                                 $newtag = '@[url=' . $alias . ']' . $newname    . '[/url]';
484                                                 if(! stristr($str_tags,$newtag)) {
485                                                         if(strlen($str_tags))
486                                                                 $str_tags .= ',';
487                                                         $str_tags .= $newtag;
488                                                 }
489                                         }
490                                 }
491                         }
492                 }
493         }
494
495         $attachments = '';
496         $match = false;
497
498         if(preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
499                 foreach($match[2] as $mtch) {
500                         $r = q("SELECT `id`,`filename`,`filesize`,`filetype` FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
501                                 intval($profile_uid),
502                                 intval($mtch)
503                         );
504                         if(count($r)) {
505                                 if(strlen($attachments))
506                                         $attachments .= ',';
507                                 $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]'; 
508                         }
509                         $body = str_replace($match[1],'',$body);
510                 }
511         }
512
513         $wall = 0;
514
515         if($post_type === 'wall' || $post_type === 'wall-comment')
516                 $wall = 1;
517
518         if(! strlen($verb))
519                 $verb = ACTIVITY_POST ;
520
521         $gravity = (($parent) ? 6 : 0 );
522
523         // even if the post arrived via API we are considering that it 
524         // originated on this site by default for determining relayability.
525
526         $origin = ((x($_REQUEST,'origin')) ? intval($_REQUEST['origin']) : 1);
527         
528         $notify_type = (($parent) ? 'comment-new' : 'wall-new' );
529
530         $uri = item_new_uri($a->get_hostname(),$profile_uid);
531
532         $datarray = array();
533         $datarray['uid']           = $profile_uid;
534         $datarray['type']          = $post_type;
535         $datarray['wall']          = $wall;
536         $datarray['gravity']       = $gravity;
537         $datarray['contact-id']    = $contact_id;
538         $datarray['owner-name']    = $contact_record['name'];
539         $datarray['owner-link']    = $contact_record['url'];
540         $datarray['owner-avatar']  = $contact_record['thumb'];
541         $datarray['author-name']   = $author['name'];
542         $datarray['author-link']   = $author['url'];
543         $datarray['author-avatar'] = $author['thumb'];
544         $datarray['created']       = datetime_convert();
545         $datarray['edited']        = datetime_convert();
546         $datarray['commented']     = datetime_convert();
547         $datarray['received']      = datetime_convert();
548         $datarray['changed']       = datetime_convert();
549         $datarray['uri']           = $uri;
550         $datarray['title']         = $title;
551         $datarray['body']          = $body;
552         $datarray['app']           = $app;
553         $datarray['location']      = $location;
554         $datarray['coord']         = $coord;
555         $datarray['tag']           = $str_tags;
556         $datarray['inform']        = $inform;
557         $datarray['verb']          = $verb;
558         $datarray['allow_cid']     = $str_contact_allow;
559         $datarray['allow_gid']     = $str_group_allow;
560         $datarray['deny_cid']      = $str_contact_deny;
561         $datarray['deny_gid']      = $str_group_deny;
562         $datarray['private']       = $private;
563         $datarray['pubmail']       = $pubmail_enable;
564         $datarray['attach']        = $attachments;
565         $datarray['bookmark']      = intval($bookmark);
566         $datarray['thr-parent']    = $thr_parent;
567         $datarray['postopts']      = '';
568         $datarray['origin']        = $origin;
569
570         /**
571          * These fields are for the convenience of plugins...
572          * 'self' if true indicates the owner is posting on their own wall
573          * If parent is 0 it is a top-level post.
574          */
575
576         $datarray['parent']        = $parent;
577         $datarray['self']          = $self;
578 //      $datarray['prvnets']       = $user['prvnets'];
579
580         if($orig_post)
581                 $datarray['edit']      = true;
582         else
583                 $datarray['guid']      = get_guid();
584
585
586         call_hooks('post_local',$datarray);
587
588
589         if($orig_post) {
590                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
591                         dbesc($body),
592                         dbesc(datetime_convert()),
593                         intval($post_id),
594                         intval($profile_uid)
595                 );
596
597                 proc_run('php', "include/notifier.php", 'edit_post', "$post_id");
598                 if((x($_POST,'return')) && strlen($return_path)) {
599                         logger('return: ' . $return_path);
600                         goaway($a->get_baseurl() . "/" . $return_path );
601                 }
602                 killme();
603         }
604         else
605                 $post_id = 0;
606
607
608         $r = q("INSERT INTO `item` (`guid`, `uid`,`type`,`wall`,`gravity`,`contact-id`,`owner-name`,`owner-link`,`owner-avatar`, 
609                 `author-name`, `author-link`, `author-avatar`, `created`, `edited`, `commented`, `received`, `changed`, `uri`, `thr-parent`, `title`, `body`, `app`, `location`, `coord`, 
610                 `tag`, `inform`, `verb`, `postopts`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid`, `private`, `pubmail`, `attach`, `bookmark`,`origin` )
611                 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 )",
612                 dbesc($datarray['guid']),
613                 intval($datarray['uid']),
614                 dbesc($datarray['type']),
615                 intval($datarray['wall']),
616                 intval($datarray['gravity']),
617                 intval($datarray['contact-id']),
618                 dbesc($datarray['owner-name']),
619                 dbesc($datarray['owner-link']),
620                 dbesc($datarray['owner-avatar']),
621                 dbesc($datarray['author-name']),
622                 dbesc($datarray['author-link']),
623                 dbesc($datarray['author-avatar']),
624                 dbesc($datarray['created']),
625                 dbesc($datarray['edited']),
626                 dbesc($datarray['commented']),
627                 dbesc($datarray['received']),
628                 dbesc($datarray['changed']),
629                 dbesc($datarray['uri']),
630                 dbesc($datarray['thr-parent']),
631                 dbesc($datarray['title']),
632                 dbesc($datarray['body']),
633                 dbesc($datarray['app']),
634                 dbesc($datarray['location']),
635                 dbesc($datarray['coord']),
636                 dbesc($datarray['tag']),
637                 dbesc($datarray['inform']),
638                 dbesc($datarray['verb']),
639                 dbesc($datarray['postopts']),
640                 dbesc($datarray['allow_cid']),
641                 dbesc($datarray['allow_gid']),
642                 dbesc($datarray['deny_cid']),
643                 dbesc($datarray['deny_gid']),
644                 intval($datarray['private']),
645                 intval($datarray['pubmail']),
646                 dbesc($datarray['attach']),
647                 intval($datarray['bookmark']),
648                 intval($datarray['origin'])
649         );
650
651         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
652                 dbesc($datarray['uri']));
653         if(count($r)) {
654                 $post_id = $r[0]['id'];
655                 logger('mod_item: saved item ' . $post_id);
656
657                 if($parent) {
658
659                         // This item is the last leaf and gets the comment box, clear any ancestors
660                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent` = %d ",
661                                 dbesc(datetime_convert()),
662                                 intval($parent)
663                         );
664
665                         // Inherit ACL's from the parent item.
666
667                         $r = q("UPDATE `item` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d
668                                 WHERE `id` = %d LIMIT 1",
669                                 dbesc($parent_item['allow_cid']),
670                                 dbesc($parent_item['allow_gid']),
671                                 dbesc($parent_item['deny_cid']),
672                                 dbesc($parent_item['deny_gid']),
673                                 intval($parent_item['private']),
674                                 intval($post_id)
675                         );
676
677                         // Send a notification email to the conversation owner, unless the owner is me and I wrote this item
678                         if(($user['notify-flags'] & NOTIFY_COMMENT) && ($contact_record != $author)) {
679                                 push_lang($user['language']);
680                                 require_once('bbcode.php');
681                                 $from = $author['name'];
682
683                                 // name of the automated email sender
684                                 $msg['notificationfromname']    = stripslashes($datarray['author-name']);;
685                                 // noreply address to send from
686                                 $msg['notificationfromemail']   = t('noreply') . '@' . $a->get_hostname();                              
687
688                                 // text version
689                                 // process the message body to display properly in text mode
690                                 $msg['textversion']
691                                         = html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8');
692                                 
693                                 // html version
694                                 // process the message body to display properly in text mode
695                                 $msg['htmlversion']     
696                                         = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r","\\n\\n" ,"\\n"), "<br />\n",$datarray['body']))));
697
698                                 // load the template for private message notifications
699                                 $tpl = get_intltext_template('cmnt_received_html_body_eml.tpl');
700                                 $email_html_body_tpl = replace_macros($tpl,array(
701                                         '$username'     => $user['username'],
702                                         '$sitename'             => $a->config['sitename'],                              // name of this site
703                                         '$siteurl'              => $a->get_baseurl(),                                   // descriptive url of this site
704                                         '$thumb'                => $author['thumb'],                                    // thumbnail url for sender icon
705                                         '$email'                => $importer['email'],                                  // email address to send to
706                                         '$url'                  => $author['url'],                                              // full url for the site
707                                         '$from'                 => $from,                                                               // name of the person sending the message
708                                         '$body'                 => $msg['htmlversion'],                                 // html version of the message
709                                         '$display'              => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id,
710                                 ));
711                         
712                                 // load the template for private message notifications
713                                 $tpl = get_intltext_template('cmnt_received_text_body_eml.tpl');
714                                 $email_text_body_tpl = replace_macros($tpl,array(
715                                         '$username'     => $user['username'],
716                                         '$sitename'             => $a->config['sitename'],                              // name of this site
717                                         '$siteurl'              => $a->get_baseurl(),                                   // descriptive url of this site
718                                         '$thumb'                => $author['thumb'],                                    // thumbnail url for sender icon
719                                         '$email'                => $importer['email'],                                  // email address to send to
720                                         '$url'                  => $author['url'],                                              // profile url for the author
721                                         '$from'                 => $from,                                                               // name of the person sending the message
722                                         '$body'                 => $msg['textversion'],                                 // text version of the message
723                                         '$display'              => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id,
724                                 ));
725
726                                 // use the EmailNotification library to send the message
727                                 require_once("include/EmailNotification.php");
728                                 EmailNotification::sendTextHtmlEmail(
729                                         $msg['notificationfromname'],
730                                         t("Administrator@") . $a->get_hostname(),
731                                         t("noreply") . '@' . $a->get_hostname(),
732                                         $user['email'],
733                                         sprintf( t('%s commented on an item at %s'), $from , $a->config['sitename']),
734                                         $email_html_body_tpl,
735                                         $email_text_body_tpl
736                                 );
737
738                                 pop_lang();
739                         }
740
741                         // We won't be able to sign Diaspora comments for authenticated visitors - we don't have their private key
742
743                         if($self) {
744                                 require_once('include/bb2diaspora.php');
745                                 $signed_body = html_entity_decode(bb2diaspora($datarray['body']));
746                                 $myaddr = $a->user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
747                                 if($datarray['verb'] === ACTIVITY_LIKE) 
748                                         $signed_text = $datarray['guid'] . ';' . 'Post' . ';' . $parent_item['guid'] . ';' . 'true' . ';' . $myaddr;
749                                 else
750                                 $signed_text = $datarray['guid'] . ';' . $parent_item['guid'] . ';' . $signed_body . ';' . $myaddr;
751
752                                 $authorsig = base64_encode(rsa_sign($signed_text,$a->user['prvkey'],'sha256'));
753
754                                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
755                                         intval($post_id),
756                         dbesc($signed_text),
757                         dbesc(base64_encode($authorsig)),
758                         dbesc($myaddr)
759                         );
760                         }
761                 }
762                 else {
763                         $parent = $post_id;
764
765                         // let me know if somebody did a wall-to-wall post on my profile
766
767                         if(($user['notify-flags'] & NOTIFY_WALL) && ($contact_record != $author)) {
768                                 push_lang($user['language']);
769                                 require_once('bbcode.php');
770                                 $from = $author['name'];
771                                                         
772                                 // name of the automated email sender
773                                 $msg['notificationfromname']    = $from;
774                                 // noreply address to send from
775                                 $msg['notificationfromemail']   = t('noreply') . '@' . $a->get_hostname();                              
776
777                                 // text version
778                                 // process the message body to display properly in text mode
779                                 $msg['textversion']
780                                         = html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8');
781                                 
782                                 // html version
783                                 // process the message body to display properly in text mode
784                                 $msg['htmlversion']     
785                                         = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r","\\n\\n" ,"\\n"), "<br />\n",$datarray['body']))));
786
787                                 // load the template for private message notifications
788                                 $tpl = load_view_file('view/wall_received_html_body_eml.tpl');
789                                 $email_html_body_tpl = replace_macros($tpl,array(
790                                         '$username'     => $user['username'],
791                                         '$sitename'             => $a->config['sitename'],                              // name of this site
792                                         '$siteurl'              => $a->get_baseurl(),                                   // descriptive url of this site
793                                         '$thumb'                => $author['thumb'],                                    // thumbnail url for sender icon
794                                         '$url'                  => $author['url'],                                              // full url for the site
795                                         '$from'                 => $from,                                                               // name of the person sending the message
796                                         '$body'                 => $msg['htmlversion'],                                 // html version of the message
797                                         '$display'              => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id,
798                                 ));
799                         
800                                 // load the template for private message notifications
801                                 $tpl = load_view_file('view/wall_received_text_body_eml.tpl');
802                                 $email_text_body_tpl = replace_macros($tpl,array(
803                                         '$username'     => $user['username'],
804                                         '$sitename'             => $a->config['sitename'],                              // name of this site
805                                         '$siteurl'              => $a->get_baseurl(),                                   // descriptive url of this site
806                                         '$thumb'                => $author['thumb'],                                    // thumbnail url for sender icon
807                                         '$url'                  => $author['url'],                                              // full url for the site
808                                         '$from'                 => $from,                                                               // name of the person sending the message
809                                         '$body'                 => $msg['textversion'],                                 // text version of the message
810                                         '$display'              => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id,
811                                 ));
812
813                                 // use the EmailNotification library to send the message
814                                 require_once("include/EmailNotification.php");
815                                 EmailNotification::sendTextHtmlEmail(
816                                         $msg['notificationfromname'],
817                                         t("Administrator@") . $a->get_hostname(),
818                                         t("noreply") . '@' . $a->get_hostname(),
819                                         $user['email'],
820                                         sprintf( t('%s posted to your profile wall at %s') , $from , $a->config['sitename']),
821                                         $email_html_body_tpl,
822                                         $email_text_body_tpl
823                                 );
824                                 pop_lang();
825                         }
826                 }
827
828                 // fallback so that parent always gets set to non-zero.
829
830                 if(! $parent)
831                         $parent = $post_id;
832
833                 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s', `plink` = '%s', `changed` = '%s', `last-child` = 1, `visible` = 1
834                         WHERE `id` = %d LIMIT 1",
835                         intval($parent),
836                         dbesc(($parent == $post_id) ? $uri : $parent_item['uri']),
837                         dbesc($a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id),
838                         dbesc(datetime_convert()),
839                         intval($post_id)
840                 );
841
842                 // photo comments turn the corresponding item visible to the profile wall
843                 // This way we don't see every picture in your new photo album posted to your wall at once.
844                 // They will show up as people comment on them.
845
846                 if(! $parent_item['visible']) {
847                         $r = q("UPDATE `item` SET `visible` = 1 WHERE `id` = %d LIMIT 1",
848                                 intval($parent_item['id'])
849                         );
850                 }
851         }
852         else {
853                 logger('mod_item: unable to retrieve post that was just stored.');
854                 notify( t('System error. Post not saved.'));
855                 goaway($a->get_baseurl() . "/" . $return_path );
856                 // NOTREACHED
857         }
858
859         // update the commented timestamp on the parent
860
861         q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
862                 dbesc(datetime_convert()),
863                 dbesc(datetime_convert()),
864                 intval($parent)
865         );
866
867         $datarray['id']    = $post_id;
868         $datarray['plink'] = $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id;
869
870         call_hooks('post_local_end', $datarray);
871
872         if(strlen($emailcc) && $profile_uid == local_user()) {
873                 $erecips = explode(',', $emailcc);
874                 if(count($erecips)) {
875                         foreach($erecips as $recip) {
876                                 $addr = trim($recip);
877                                 if(! strlen($addr))
878                                         continue;
879                                 $disclaimer = '<hr />' . sprintf( t('This message was sent to you by %s, a member of the Friendica social network.'),$a->user['username']) 
880                                         . '<br />';
881                                 $disclaimer .= sprintf( t('You may visit them online at %s'), $a->get_baseurl() . '/profile/' . $a->user['nickname']) . EOL;
882                                 $disclaimer .= t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL; 
883
884                                 $subject  = '[Friendica]' . ' ' . sprintf( t('%s posted an update.'),$a->user['username']);
885                                 $headers  = 'From: ' . $a->user['username'] . ' <' . $a->user['email'] . '>' . "\n";
886                                 $headers .= 'MIME-Version: 1.0' . "\n";
887                                 $headers .= 'Content-Type: text/html; charset=UTF-8' . "\n";
888                                 $headers .= 'Content-Transfer-Encoding: 8bit' . "\n\n";
889                                 $link = '<a href="' . $a->get_baseurl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
890                                 $html    = prepare_body($datarray);
891                                 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
892                                 @mail($addr, $subject, $message, $headers);
893                         }
894                 }
895         }
896
897         // This is a real juggling act on shared hosting services which kill your processes
898         // e.g. dreamhost. We used to start delivery to our native delivery agents in the background
899         // and then run our plugin delivery from the foreground. We're now doing plugin delivery first,
900         // because as soon as you start loading up a bunch of remote delivey processes, *this* page is
901         // likely to get killed off. If you end up looking at an /item URL and a blank page,
902         // it's very likely the delivery got killed before all your friends could be notified.
903         // Currently the only realistic fixes are to use a reliable server - which precludes shared hosting,
904         // or cut back on plugins which do remote deliveries.  
905
906         proc_run('php', "include/notifier.php", $notify_type, "$post_id");
907
908         logger('post_complete');
909
910         // figure out how to return, depending on from whence we came
911
912         if($api_source)
913                 return;
914
915         if($return_path) {
916                 goaway($a->get_baseurl() . "/" . $return_path);
917         }
918
919         $json = array('success' => 1);
920         if(x($_POST,'jsreload') && strlen($_POST['jsreload']))
921                 $json['reload'] = $a->get_baseurl() . '/' . $_POST['jsreload'];
922
923         logger('post_json: ' . print_r($json,true), LOGGER_DEBUG);
924
925         echo json_encode($json);
926         killme();
927         // NOTREACHED
928 }
929
930
931
932
933
934 function item_content(&$a) {
935
936         if((! local_user()) && (! remote_user()))
937                 return;
938
939         require_once('include/security.php');
940
941         if(($a->argc == 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
942                 require_once('include/items.php');
943                 drop_item($a->argv[2]);
944         }
945 }