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