]> git.mxchange.org Git - friendica.git/blob - mod/item.php
82f33eaebd0772405945c5f2d5e6bf236a24a4c2
[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  * All of these become an "item" which is our basic unit of 
10  * information.
11  * Posts that originate externally or do not fall into the above 
12  * posting categories go through item_store() instead of this function. 
13  *
14  */  
15
16 function item_post(&$a) {
17
18         if((! local_user()) && (! remote_user()))
19                 return;
20
21         require_once('include/security.php');
22
23         $uid = local_user();
24
25         call_hooks('post_local_start', $_POST);
26
27         $parent = ((x($_POST,'parent')) ? intval($_POST['parent']) : 0);
28
29         $parent_item = null;
30         $parent_contact = null;
31
32         if($parent) {
33                 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
34                         intval($parent)
35                 );
36                 if(! count($r)) {
37                         notice( t('Unable to locate original post.') . EOL);
38                         if(x($_POST,'return')) 
39                                 goaway($a->get_baseurl() . "/" . $_POST['return'] );
40                         killme();
41                 }
42                 $parent_item = $r[0];
43                 if($parent_item['contact-id'] && $uid) {
44                         $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
45                                 intval($parent_item['contact-id']),
46                                 intval($uid)
47                         );
48                         if(count($r))
49                                 $parent_contact = $r[0];
50                 }
51         }
52
53         $profile_uid = ((x($_POST,'profile_uid')) ? intval($_POST['profile_uid']) : 0);
54         $post_id     = ((x($_POST['post_id']))    ? intval($_POST['post_id'])     : 0);
55
56         if(! can_write_wall($a,$profile_uid)) {
57                 notice( t('Permission denied.') . EOL) ;
58                 if(x($_POST,'return')) 
59                         goaway($a->get_baseurl() . "/" . $_POST['return'] );
60                 killme();
61         }
62
63
64         // is this an edited post?
65
66         $orig_post = null;
67
68         if($post_id) {
69                 $i = q("SELECT * FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
70                         intval($profile_uid),
71                         intval($post_id)
72                 );
73                 if(! count($i))
74                         killme();
75                 $orig_post = $i[0];
76         }
77
78         $user = null;
79
80         $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
81                 intval($profile_uid)
82         );
83         if(count($r))
84                 $user = $r[0];
85         
86         if($orig_post) {
87                 $str_group_allow   = $orig_post['allow_gid'];
88                 $str_contact_allow = $orig_post['allow_cid'];
89                 $str_group_deny    = $orig_post['deny_gid'];
90                 $str_contact_deny  = $orig_post['deny_cid'];
91                 $title             = $orig_post['title'];
92                 $location          = $orig_post['location'];
93                 $coord             = $orig_post['coord'];
94                 $verb              = $orig_post['verb'];
95                 $emailcc           = $orig_post['emailcc'];
96
97                 $body              = escape_tags(trim($_POST['body']));
98                 $private           = $orig_post['private'];
99                 $pubmail_enable    = $orig_post['pubmail'];
100         }
101         else {
102                 $str_group_allow   = perms2str($_POST['group_allow']);
103                 $str_contact_allow = perms2str($_POST['contact_allow']);
104                 $str_group_deny    = perms2str($_POST['group_deny']);
105                 $str_contact_deny  = perms2str($_POST['contact_deny']);
106                 $title             = notags(trim($_POST['title']));
107                 $location          = notags(trim($_POST['location']));
108                 $coord             = notags(trim($_POST['coord']));
109                 $verb              = notags(trim($_POST['verb']));
110                 $emailcc           = notags(trim($_POST['emailcc']));
111
112                 $body              = escape_tags(trim($_POST['body']));
113                 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
114
115                 if(($parent_item) && 
116                         (($parent_item['private']) 
117                                 || strlen($parent_item['allow_cid']) 
118                                 || strlen($parent_item['allow_gid']) 
119                                 || strlen($parent_item['deny_cid']) 
120                                 || strlen($parent_item['deny_gid'])
121                         )) {
122                         $private = 1;
123                 }
124         
125                 $pubmail_enable    = ((x($_POST,'pubmail_enable') && intval($_POST['pubmail_enable']) && (! $private)) ? 1 : 0);
126
127                 if(! strlen($body)) {
128                         info( t('Empty post discarded.') . EOL );
129                         if(x($_POST,'return')) 
130                                 goaway($a->get_baseurl() . "/" . $_POST['return'] );
131                         killme();
132                 }
133         }
134
135         // get contact info for poster
136
137         $author = null;
138         $self   = false;
139
140         if(($_SESSION['uid']) && ($_SESSION['uid'] == $profile_uid)) {
141                 $self = true;
142                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
143                         intval($_SESSION['uid'])
144                 );
145         }
146         else {
147                 if((x($_SESSION,'visitor_id')) && (intval($_SESSION['visitor_id']))) {
148                         $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
149                                 intval($_SESSION['visitor_id'])
150                         );
151                 }
152         }
153
154         if(count($r)) {
155                 $author = $r[0];
156                 $contact_id = $author['id'];
157         }
158
159         // get contact info for owner
160         
161         if($profile_uid == $_SESSION['uid']) {
162                 $contact_record = $author;
163         }
164         else {
165                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
166                         intval($profile_uid)
167                 );
168                 if(count($r))
169                         $contact_record = $r[0];
170         }
171
172         $post_type = notags(trim($_POST['type']));
173
174         if($post_type === 'net-comment') {
175                 if($parent_item !== null) {
176                         if($parent_item['type'] === 'remote') {
177                                 $post_type = 'remote-comment';
178                         } 
179                         else {          
180                                 $post_type = 'wall-comment';
181                         }
182                 }
183         }
184
185         /**
186          *
187          * When a photo was uploaded into the message using the (profile wall) ajax 
188          * uploader, The permissions are initially set to disallow anybody but the
189          * owner from seeing it. This is because the permissions may not yet have been
190          * set for the post. If it's private, the photo permissions should be set
191          * appropriately. But we didn't know the final permissions on the post until
192          * now. So now we'll look for links of uploaded messages that are in the
193          * post and set them to the same permissions as the post itself.
194          *
195          */
196
197         $match = null;
198
199         if(preg_match_all("/\[img\](.+?)\[\/img\]/",$body,$match)) {
200                 $images = $match[1];
201                 if(count($images)) {
202                         foreach($images as $image) {
203                                 if(! stristr($image,$a->get_baseurl() . '/photo/'))
204                                         continue;
205                                 $image_uri = substr($image,strrpos($image,'/') + 1);
206                                 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
207                                 $r = q("UPDATE `photo` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
208                                         WHERE `resource-id` = '%s' AND `album` = '%s' ",
209                                         dbesc($str_contact_allow),
210                                         dbesc($str_group_allow),
211                                         dbesc($str_contact_deny),
212                                         dbesc($str_group_deny),
213                                         dbesc($image_uri),
214                                         dbesc( t('Wall Photos'))
215                                 );
216  
217                         }
218                 }
219         }
220
221
222         $match = null;
223
224         if(preg_match_all("/\[attachment\](.+?)\[\/attachment\]/",$body,$match)) {
225                 $attaches = $match[1];
226                 if(count($attaches)) {
227                         foreach($attaches as $attach) {
228                                 $r = q("SELECT * FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
229                                         intval($profile_uid),
230                                         intval($attaches)
231                                 );                              
232                                 if(count($r)) {
233                                         $r = q("UPDATE `attach` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
234                                                 WHERE `uid` = %d AND `id` = %d LIMIT 1",
235                                                 intval($profile_uid),
236                                                 intval($attaches)
237                                         );
238                                 }
239                         }
240                 }
241         }
242
243
244
245
246
247         /**
248          * Fold multi-line [code] sequences
249          */
250
251         $body = preg_replace('/\[\/code\]\s*\[code\]/m',"\n",$body); 
252
253         /**
254          * Look for any tags and linkify them
255          */
256
257         $str_tags = '';
258         $inform   = '';
259
260
261         $tags = get_tags($body);
262
263         if(($parent_contact) && ($parent_contact['network'] === 'stat') && ($parent_contact['nick']) && (! in_array('@' . $parent_contact['nick'],$tags))) {
264                 $body = '@' . $parent_contact['nick'] . ' ' . $body;
265                 $tags[] = '@' . $parent_contact['nick'];
266         }               
267
268         if(count($tags)) {
269                 foreach($tags as $tag) {
270                         if(strpos($tag,'#') === 0) {
271                                 if(strpos($tag,'[url='))
272                                         continue;
273                                 $basetag = str_replace('_',' ',substr($tag,1));
274                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
275                                 if(strlen($str_tags))
276                                         $str_tags .= ',';
277                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
278                                 continue;
279                         }
280                         if(strpos($tag,'@') === 0) {
281                                 if(strpos($tag,'[url='))
282                                         continue;
283                                 $stat = false;
284                                 $name = substr($tag,1);
285                                 if((strpos($name,'@')) || (strpos($name,'http://'))) {
286                                         $newname = $name;
287                                         $links = @lrdd($name);
288                                         if(count($links)) {
289                                                 foreach($links as $link) {
290                                                         if($link['@attributes']['rel'] === 'http://webfinger.net/rel/profile-page')
291                                         $profile = $link['@attributes']['href'];
292                                                         if($link['@attributes']['rel'] === 'salmon') {
293                                                                 if(strlen($inform))
294                                                                         $inform .= ',';
295                                         $inform .= 'url:' . str_replace(',','%2c',$link['@attributes']['href']);
296                                                         }
297                                                 }
298                                         }
299                                 }
300                                 else {
301                                         $newname = $name;
302                                         $alias = '';
303                                         if(strstr($name,'_')) {
304                                                 $newname = str_replace('_',' ',$name);
305                                                 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
306                                                         dbesc($newname),
307                                                         intval($profile_uid)
308                                                 );
309                                         }
310                                         else {
311                                                 $r = q("SELECT * FROM `contact` WHERE `nick` = '%s' AND `uid` = %d LIMIT 1",
312                                                         dbesc($name),
313                                                         intval($profile_uid)
314                                                 );
315                                         }
316                                         if(count($r)) {
317                                                 $profile = $r[0]['url'];
318                                                 if($r[0]['network'] === 'stat') {
319                                                         $newname = $r[0]['nick'];
320                                                         $stat = true;
321                                                         if($r[0]['alias'])
322                                                                 $alias = $r[0]['alias'];
323                                                 }
324                                                 else
325                                                         $newname = $r[0]['name'];
326                                                 if(strlen($inform))
327                                                         $inform .= ',';
328                                                 $inform .= 'cid:' . $r[0]['id'];
329                                         }
330                                 }
331                                 if($profile) {
332                                         $body = str_replace('@' . $name, '@' . '[url=' . $profile . ']' . $newname      . '[/url]', $body);
333                                         $profile = str_replace(',','%2c',$profile);
334                                         if(strlen($str_tags))
335                                                 $str_tags .= ',';
336                                         $str_tags .= '@[url=' . $profile . ']' . $newname       . '[/url]';
337
338                                         // Status.Net seems to require the numeric ID URL in a mention if the person isn't 
339                                         // subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both. 
340
341                                         if(strlen($alias)) {
342                                                 if(strlen($str_tags))
343                                                         $str_tags .= ',';
344                                                 $str_tags .= '@[url=' . $alias . ']' . $newname . '[/url]';
345                                         }
346                                 }
347                         }
348                 }
349         }
350
351         $attachments = '';
352
353         if(preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
354                 foreach($match[2] as $mtch) {
355                         $r = q("SELECT `id`,`filename`,`filesize`,`filetype` FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
356                                 intval($profile_uid),
357                                 intval($mtch)
358                         );
359                         if(count($r)) {
360                                 if(strlen($attachments))
361                                         $attachments .= ',';
362                                 $attachments .= '[attach]href="' . $a->get_baseurl() . '/attach/' . $r[0]['id'] . '" size="' . $r[0]['filesize'] . '" type="' . $r[0]['filetype'] . '" title="' . $r[0]['filename'] . '"[/attach]'; 
363                         }
364                         $body = str_replace($match[1],'',$body);
365                 }
366         }
367
368         $wall = 0;
369
370         if($post_type === 'wall' || $post_type === 'wall-comment')
371                 $wall = 1;
372
373         if(! strlen($verb))
374                 $verb = ACTIVITY_POST ;
375
376         $gravity = (($parent) ? 6 : 0 );
377  
378         $notify_type = (($parent) ? 'comment-new' : 'wall-new' );
379
380         $uri = item_new_uri($a->get_hostname(),$profile_uid);
381
382         $datarray = array();
383         $datarray['uid']           = $profile_uid;
384         $datarray['type']          = $post_type;
385         $datarray['wall']          = $wall;
386         $datarray['gravity']       = $gravity;
387         $datarray['contact-id']    = $contact_id;
388         $datarray['owner-name']    = $contact_record['name'];
389         $datarray['owner-link']    = $contact_record['url'];
390         $datarray['owner-avatar']  = $contact_record['thumb'];
391         $datarray['author-name']   = $author['name'];
392         $datarray['author-link']   = $author['url'];
393         $datarray['author-avatar'] = $author['thumb'];
394         $datarray['created']       = datetime_convert();
395         $datarray['edited']        = datetime_convert();
396         $datarray['changed']       = datetime_convert();
397         $datarray['uri']           = $uri;
398         $datarray['title']         = $title;
399         $datarray['body']          = $body;
400         $datarray['location']      = $location;
401         $datarray['coord']         = $coord;
402         $datarray['tag']           = $str_tags;
403         $datarray['inform']        = $inform;
404         $datarray['verb']          = $verb;
405         $datarray['allow_cid']     = $str_contact_allow;
406         $datarray['allow_gid']     = $str_group_allow;
407         $datarray['deny_cid']      = $str_contact_deny;
408         $datarray['deny_gid']      = $str_group_deny;
409         $datarray['private']       = $private;
410         $datarray['pubmail']       = $pubmail_enable;
411         $datarray['attach']        = $attachments;
412
413         /**
414          * These fields are for the convenience of plugins...
415          * 'self' if true indicates the owner is posting on their own wall
416          * If parent is 0 it is a top-level post.
417          */
418
419         $datarray['parent']        = $parent;
420         $datarray['self']          = $self;
421
422         if($orig_post)
423                 $datarray['edit']      = true;
424
425         call_hooks('post_local',$datarray);
426
427
428         if($orig_post) {
429                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
430                         dbesc($body),
431                         dbesc(datetime_convert()),
432                         intval($post_id),
433                         intval($profile_uid)
434                 );
435
436                 proc_run('php', "include/notifier.php", 'edit_post', "$post_id");
437                 if((x($_POST,'return')) && strlen($_POST['return'])) {
438                         logger('return: ' . $_POST['return']);
439                         goaway($a->get_baseurl() . "/" . $_POST['return'] );
440                 }
441                 killme();
442         }
443         else
444                 $post_id = 0;
445
446
447         $r = q("INSERT INTO `item` (`uid`,`type`,`wall`,`gravity`,`contact-id`,`owner-name`,`owner-link`,`owner-avatar`, 
448                 `author-name`, `author-link`, `author-avatar`, `created`, `edited`, `changed`, `uri`, `title`, `body`, `location`, `coord`, 
449                 `tag`, `inform`, `verb`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid`, `private`, `pubmail`, `attach` )
450                 VALUES( %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', %d, %d, '%s' )",
451                 intval($datarray['uid']),
452                 dbesc($datarray['type']),
453                 intval($datarray['wall']),
454                 intval($datarray['gravity']),
455                 intval($datarray['contact-id']),
456                 dbesc($datarray['owner-name']),
457                 dbesc($datarray['owner-link']),
458                 dbesc($datarray['owner-avatar']),
459                 dbesc($datarray['author-name']),
460                 dbesc($datarray['author-link']),
461                 dbesc($datarray['author-avatar']),
462                 dbesc($datarray['created']),
463                 dbesc($datarray['edited']),
464                 dbesc($datarray['changed']),
465                 dbesc($datarray['uri']),
466                 dbesc($datarray['title']),
467                 dbesc($datarray['body']),
468                 dbesc($datarray['location']),
469                 dbesc($datarray['coord']),
470                 dbesc($datarray['tag']),
471                 dbesc($datarray['inform']),
472                 dbesc($datarray['verb']),
473                 dbesc($datarray['allow_cid']),
474                 dbesc($datarray['allow_gid']),
475                 dbesc($datarray['deny_cid']),
476                 dbesc($datarray['deny_gid']),
477                 intval($datarray['private']),
478                 intval($datarray['pubmail']),
479                 dbesc($datarray['attach'])
480         );
481
482         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
483                 dbesc($datarray['uri']));
484         if(count($r)) {
485                 $post_id = $r[0]['id'];
486                 logger('mod_item: saved item ' . $post_id);
487
488                 if($parent) {
489
490                         // This item is the last leaf and gets the comment box, clear any ancestors
491                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent` = %d ",
492                                 dbesc(datetime_convert()),
493                                 intval($parent)
494                         );
495
496                         // Inherit ACL's from the parent item.
497
498                         $r = q("UPDATE `item` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d
499                                 WHERE `id` = %d LIMIT 1",
500                                 dbesc($parent_item['allow_cid']),
501                                 dbesc($parent_item['allow_gid']),
502                                 dbesc($parent_item['deny_cid']),
503                                 dbesc($parent_item['deny_gid']),
504                                 intval($parent_item['private']),
505                                 intval($post_id)
506                         );
507
508                         // Send a notification email to the conversation owner, unless the owner is me and I wrote this item
509                         if(($user['notify-flags'] & NOTIFY_COMMENT) && ($contact_record != $author)) {
510                                 push_lang($user['language']);
511                                 require_once('bbcode.php');
512                                 $from = $author['name'];
513
514                                 // name of the automated email sender
515                                 $msg['notificationfromname']    = stripslashes($datarray['author-name']);;
516                                 // noreply address to send from
517                                 $msg['notificationfromemail']   = t('noreply') . '@' . $a->get_hostname();                              
518
519                                 // text version
520                                 // process the message body to display properly in text mode
521                                 $msg['textversion']
522                                         = html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8');
523                                 
524                                 // html version
525                                 // process the message body to display properly in text mode
526                                 $msg['htmlversion']     
527                                         = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r","\\n\\n" ,"\\n"), "<br />\n",$datarray['body']))));
528
529                                 // load the template for private message notifications
530                                 $tpl = get_intltext_template('cmnt_received_html_body_eml.tpl');
531                                 $email_html_body_tpl = replace_macros($tpl,array(
532                                         '$sitename'             => $a->config['sitename'],                              // name of this site
533                                         '$siteurl'              => $a->get_baseurl(),                                   // descriptive url of this site
534                                         '$thumb'                => $author['thumb'],                                    // thumbnail url for sender icon
535                                         '$email'                => $importer['email'],                                  // email address to send to
536                                         '$url'                  => $author['url'],                                              // full url for the site
537                                         '$from'                 => $from,                                                               // name of the person sending the message
538                                         '$body'                 => $msg['htmlversion'],                                 // html version of the message
539                                         '$display'              => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id,
540                                 ));
541                         
542                                 // load the template for private message notifications
543                                 $tpl = get_intltext_template('cmnt_received_text_body_eml.tpl');
544                                 $email_text_body_tpl = replace_macros($tpl,array(
545                                         '$sitename'             => $a->config['sitename'],                              // name of this site
546                                         '$siteurl'              => $a->get_baseurl(),                                   // descriptive url of this site
547                                         '$thumb'                => $author['thumb'],                                    // thumbnail url for sender icon
548                                         '$email'                => $importer['email'],                                  // email address to send to
549                                         '$url'                  => $author['url'],                                              // profile url for the author
550                                         '$from'                 => $from,                                                               // name of the person sending the message
551                                         '$body'                 => $msg['textversion'],                                 // text version of the message
552                                         '$display'              => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id,
553                                 ));
554
555                                 // use the EmailNotification library to send the message
556                                 require_once("include/EmailNotification.php");
557                                 EmailNotification::sendTextHtmlEmail(
558                                         $msg['notificationfromname'],
559                                         t("Administrator@") . $a->get_hostname(),
560                                         t("noreply") . '@' . $a->get_hostname(),
561                                         $user['email'],
562                                         sprintf( t('%s commented on an item at %s'), $from , $a->config['sitename']),
563                                         $email_html_body_tpl,
564                                         $email_text_body_tpl
565                                 );
566
567                                 pop_lang();
568                         }
569                 }
570                 else {
571                         $parent = $post_id;
572
573                         // let me know if somebody did a wall-to-wall post on my profile
574
575                         if(($user['notify-flags'] & NOTIFY_WALL) && ($contact_record != $author)) {
576                                 push_lang($user['language']);
577                                 require_once('bbcode.php');
578                                 $from = $author['name'];
579                                                         
580                                 // name of the automated email sender
581                                 $msg['notificationfromname']    = $from;
582                                 // noreply address to send from
583                                 $msg['notificationfromemail']   = t('noreply') . '@' . $a->get_hostname();                              
584
585                                 // text version
586                                 // process the message body to display properly in text mode
587                                 $msg['textversion']
588                                         = html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8');
589                                 
590                                 // html version
591                                 // process the message body to display properly in text mode
592                                 $msg['htmlversion']     
593                                         = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r","\\n\\n" ,"\\n"), "<br />\n",$datarray['body']))));
594
595                                 // load the template for private message notifications
596                                 $tpl = load_view_file('view/wall_received_html_body_eml.tpl');
597                                 $email_html_body_tpl = replace_macros($tpl,array(
598                                         '$sitename'             => $a->config['sitename'],                              // name of this site
599                                         '$siteurl'              => $a->get_baseurl(),                                   // descriptive url of this site
600                                         '$thumb'                => $author['thumb'],                                    // thumbnail url for sender icon
601                                         '$url'                  => $author['url'],                                              // full url for the site
602                                         '$from'                 => $from,                                                               // name of the person sending the message
603                                         '$body'                 => $msg['htmlversion'],                                 // html version of the message
604                                         '$display'              => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id,
605                                 ));
606                         
607                                 // load the template for private message notifications
608                                 $tpl = load_view_file('view/wall_received_text_body_eml.tpl');
609                                 $email_text_body_tpl = replace_macros($tpl,array(
610                                         '$sitename'             => $a->config['sitename'],                              // name of this site
611                                         '$siteurl'              => $a->get_baseurl(),                                   // descriptive url of this site
612                                         '$thumb'                => $author['thumb'],                                    // thumbnail url for sender icon
613                                         '$url'                  => $author['url'],                                              // full url for the site
614                                         '$from'                 => $from,                                                               // name of the person sending the message
615                                         '$body'                 => $msg['textversion'],                                 // text version of the message
616                                         '$display'              => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id,
617                                 ));
618
619                                 // use the EmailNotification library to send the message
620                                 require_once("include/EmailNotification.php");
621                                 EmailNotification::sendTextHtmlEmail(
622                                         $msg['notificationfromname'],
623                                         t("Administrator@") . $a->get_hostname(),
624                                         t("noreply") . '@' . $a->get_hostname(),
625                                         $user['email'],
626                                         sprintf( t('%s posted to your profile wall at %s') , $from , $a->config['sitename']),
627                                         $email_html_body_tpl,
628                                         $email_text_body_tpl
629                                 );
630                                 pop_lang();
631                         }
632                 }
633
634                 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s', `plink` = '%s', `changed` = '%s', `last-child` = 1, `visible` = 1
635                         WHERE `id` = %d LIMIT 1",
636                         intval($parent),
637                         dbesc(($parent == $post_id) ? $uri : $parent_item['uri']),
638                         dbesc($a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id),
639                         dbesc(datetime_convert()),
640                         intval($post_id)
641                 );
642
643                 // photo comments turn the corresponding item visible to the profile wall
644                 // This way we don't see every picture in your new photo album posted to your wall at once.
645                 // They will show up as people comment on them.
646
647                 if(! $parent_item['visible']) {
648                         $r = q("UPDATE `item` SET `visible` = 1 WHERE `id` = %d LIMIT 1",
649                                 intval($parent_item['id'])
650                         );
651                 }
652         }
653         else {
654                 logger('mod_item: unable to retrieve post that was just stored.');
655                 notify( t('System error. Post not saved.'));
656                 goaway($a->get_baseurl() . "/" . $_POST['return'] );
657                 // NOTREACHED
658         }
659
660         proc_run('php', "include/notifier.php", $notify_type, "$post_id");
661
662         $datarray['id']    = $post_id;
663         $datarray['plink'] = $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id;
664
665         call_hooks('post_local_end', $datarray);
666
667         if(strlen($emailcc) && $profile_uid == local_user()) {
668                 $erecips = explode(',', $emailcc);
669                 if(count($erecips)) {
670                         foreach($erecips as $recip) {
671                                 $addr = trim($recip);
672                                 if(! strlen($addr))
673                                         continue;
674                                 $disclaimer = '<hr />' . sprintf( t('This message was sent to you by %s, a member of the Friendika social network.'),$a->user['username']) 
675                                         . '<br />';
676                                 $disclaimer .= sprintf( t('You may visit them online at %s'), $a->get_baseurl() . '/profile/' . $a->user['nickname']) . EOL;
677                                 $disclaimer .= t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL; 
678
679                                 $subject  = '[Friendika]' . ' ' . sprintf( t('%s posted an update.'),$a->user['username']);
680                                 $headers  = 'From: ' . $a->user['username'] . ' <' . $a->user['email'] . '>' . "\n";
681                                 $headers .= 'MIME-Version: 1.0' . "\n";
682                                 $headers .= 'Content-Type: text/html; charset=UTF-8' . "\n";
683                                 $headers .= 'Content-Transfer-Encoding: 8bit' . "\n\n";
684                                 $link = '<a href="' . $a->get_baseurl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
685                                 $html    = prepare_body($datarray);
686                                 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
687                                 @mail($addr, $subject, $message, $headers);
688                         }
689                 }
690         }
691
692         logger('post_complete');
693         if((x($_POST,'return')) && strlen($_POST['return'])) {
694                 logger('return: ' . $_POST['return']);
695                 goaway($a->get_baseurl() . "/" . $_POST['return'] );
696         }
697         $json = array('success' => 1);
698         if(x($_POST,'jsreload') && strlen($_POST['jsreload']))
699                 $json['reload'] = $a->get_baseurl() . '/' . $_POST['jsreload'];
700
701         logger('post_json: ' . print_r($json,true), LOGGER_DEBUG);
702
703         echo json_encode($json);
704         killme();
705         // NOTREACHED
706 }
707
708
709
710
711
712 function item_content(&$a) {
713
714         if((! local_user()) && (! remote_user()))
715                 return;
716
717         require_once('include/security.php');
718
719         $uid = local_user();
720
721         if(($a->argc == 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
722
723                 // locate item to be deleted
724
725                 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
726                         intval($a->argv[2])
727                 );
728
729                 if(! count($r)) {
730                         notice( t('Item not found.') . EOL);
731                         goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
732                 }
733                 $item = $r[0];
734
735                 // check if logged in user is either the author or owner of this item
736
737                 if(($_SESSION['visitor_id'] == $item['contact-id']) || ($_SESSION['uid'] == $item['uid'])) {
738
739                         // delete the item
740
741                         $r = q("UPDATE `item` SET `deleted` = 1, `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
742                                 dbesc(datetime_convert()),
743                                 dbesc(datetime_convert()),
744                                 intval($item['id'])
745                         );
746
747                         // If item is a link to a photo resource, nuke all the associated photos 
748                         // (visitors will not have photo resources)
749                         // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
750                         // generate a resource-id and therefore aren't intimately linked to the item. 
751
752                         if(strlen($item['resource-id'])) {
753                                 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
754                                         dbesc($item['resource-id']),
755                                         intval($item['uid'])
756                                 );
757                                 // ignore the result
758                         }
759
760                         // If it's the parent of a comment thread, kill all the kids
761
762                         if($item['uri'] == $item['parent-uri']) {
763                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' 
764                                         WHERE `parent-uri` = '%s' AND `uid` = %d ",
765                                         dbesc(datetime_convert()),
766                                         dbesc(datetime_convert()),
767                                         dbesc($item['parent-uri']),
768                                         intval($item['uid'])
769                                 );
770                                 // ignore the result
771                         }
772                         else {
773                                 // ensure that last-child is set in case the comment that had it just got wiped.
774                                 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
775                                         dbesc(datetime_convert()),
776                                         dbesc($item['parent-uri']),
777                                         intval($item['uid'])
778                                 );
779                                 // who is the last child now? 
780                                 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d ORDER BY `edited` DESC LIMIT 1",
781                                         dbesc($item['parent-uri']),
782                                         intval($item['uid'])
783                                 );
784                                 if(count($r)) {
785                                         q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
786                                                 intval($r[0]['id'])
787                                         );
788                                 }       
789                         }
790                         $drop_id = intval($item['id']);
791                         
792                         // send the notification upstream/downstream as the case may be
793
794                         proc_run('php',"include/notifier.php","drop","$drop_id");
795 // We seem to lose the return url occasionally. Have not been able to reliably duplicate
796 //                      logger('drop_return_url: ' . $_SESSION['return_url']);
797                         goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
798                         //NOTREACHED
799                 }
800                 else {
801                         notice( t('Permission denied.') . EOL);
802                         goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
803                         //NOTREACHED
804                 }
805         }
806 }