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
13 * Posts that originate externally or do not fall into the above
14 * posting categories go through item_store() instead of this function.
18 require_once('include/crypto.php');
19 require_once('include/enotify.php');
20 require_once('include/email.php');
21 require_once('include/tags.php');
22 require_once('include/files.php');
23 require_once('include/threads.php');
24 require_once('include/text.php');
25 require_once('include/items.php');
26 require_once('include/Scrape.php');
27 require_once('include/diaspora.php');
28 require_once('include/Contact.php');
30 function item_post(&$a) {
32 $perfdb = $a->performance["database"];
33 $perfdbw = $a->performance["database_write"];
34 $perfnet = $a->performance["network"];
35 $perffile = $a->performance["file"];
37 logger("Performance: Start", LOGGER_DEBUG);
39 if((! local_user()) && (! remote_user()) && (! x($_REQUEST,'commenter')))
42 require_once('include/security.php');
46 if(x($_REQUEST,'dropitems')) {
47 $arr_drop = explode(',',$_REQUEST['dropitems']);
48 drop_items($arr_drop);
49 $json = array('success' => 1);
50 echo json_encode($json);
54 call_hooks('post_local_start', $_REQUEST);
55 // logger('postinput ' . file_get_contents('php://input'));
56 logger('postvars ' . print_r($_REQUEST,true), LOGGER_DATA);
58 $api_source = ((x($_REQUEST,'api_source') && $_REQUEST['api_source']) ? true : false);
60 $message_id = ((x($_REQUEST,'message_id') && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
62 $return_path = ((x($_REQUEST,'return')) ? $_REQUEST['return'] : '');
63 $preview = ((x($_REQUEST,'preview')) ? intval($_REQUEST['preview']) : 0);
66 // Check for doubly-submitted posts, and reject duplicates
67 // Note that we have to ignore previews, otherwise nothing will post
68 // after it's been previewed
69 if(!$preview && x($_REQUEST['post_id_random'])) {
70 if(x($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
71 logger("item post: duplicate post", LOGGER_DEBUG);
72 item_post_return($a->get_baseurl(), $api_source, $return_path);
75 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
79 * Is this a reply to something?
82 $parent = ((x($_REQUEST,'parent')) ? intval($_REQUEST['parent']) : 0);
83 $parent_uri = ((x($_REQUEST,'parent_uri')) ? trim($_REQUEST['parent_uri']) : '');
86 $parent_contact = null;
92 if($parent || $parent_uri) {
94 $objecttype = ACTIVITY_OBJ_COMMENT;
96 if(! x($_REQUEST,'type'))
97 $_REQUEST['type'] = 'net-comment';
100 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
103 } elseif($parent_uri && local_user()) {
104 // This is coming from an API source, and we are logged in
105 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
111 // if this isn't the real parent of the conversation, find it
112 if($r !== false && count($r)) {
113 $parid = $r[0]['parent'];
114 $parent_uri = $r[0]['uri'];
115 if($r[0]['id'] != $r[0]['parent']) {
116 $r = q("SELECT * FROM `item` WHERE `id` = `parent` AND `parent` = %d LIMIT 1",
122 if(($r === false) || (! count($r))) {
123 notice( t('Unable to locate original post.') . EOL);
124 if(x($_REQUEST,'return'))
125 goaway($a->get_baseurl() . "/" . $return_path );
128 $parent_item = $r[0];
129 $parent = $r[0]['id'];
131 // multi-level threading - preserve the info but re-parent to our single level threading
132 //if(($parid) && ($parid != $parent))
133 $thr_parent = $parent_uri;
135 if($parent_item['contact-id'] && $uid) {
136 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
137 intval($parent_item['contact-id']),
141 $parent_contact = $r[0];
143 // If the contact id doesn't fit with the contact, then set the contact to null
144 $thrparent = q("SELECT `author-link`, `network` FROM `item` WHERE `uri` = '%s' LIMIT 1", dbesc($thr_parent));
145 if (count($thrparent) AND ($thrparent[0]["network"] === NETWORK_OSTATUS)
146 AND (normalise_link($parent_contact["url"]) != normalise_link($thrparent[0]["author-link"]))) {
147 $parent_contact = null;
149 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
150 dbesc(normalise_link($thrparent[0]["author-link"])));
152 $parent_contact = $r[0];
153 $parent_contact["thumb"] = $parent_contact["photo"];
154 $parent_contact["micro"] = $parent_contact["photo"];
155 unset($parent_contact["id"]);
158 if (!isset($parent_contact["nick"])) {
159 require_once("include/Scrape.php");
160 $probed_contact = probe_url($thrparent[0]["author-link"]);
161 if ($probed_contact["network"] != NETWORK_FEED) {
162 $parent_contact = $probed_contact;
163 $parent_contact["nurl"] = normalise_link($probed_contact["url"]);
164 $parent_contact["thumb"] = $probed_contact["photo"];
165 $parent_contact["micro"] = $probed_contact["photo"];
166 $parent_contact["addr"] = $probed_contact["addr"];
169 logger('no contact found: '.print_r($thrparent, true), LOGGER_DEBUG);
171 logger('parent contact: '.print_r($parent_contact, true), LOGGER_DEBUG);
173 if ($parent_contact["nick"] == "")
174 $parent_contact["nick"] = $parent_contact["name"];
178 if($parent) logger('mod_item: item_post parent=' . $parent);
180 $profile_uid = ((x($_REQUEST,'profile_uid')) ? intval($_REQUEST['profile_uid']) : 0);
181 $post_id = ((x($_REQUEST,'post_id')) ? intval($_REQUEST['post_id']) : 0);
182 $app = ((x($_REQUEST,'source')) ? strip_tags($_REQUEST['source']) : '');
183 $extid = ((x($_REQUEST,'extid')) ? strip_tags($_REQUEST['extid']) : '');
185 $allow_moderated = false;
187 // here is where we are going to check for permission to post a moderated comment.
189 // First check that the parent exists and it is a wall item.
191 if((x($_REQUEST,'commenter')) && ((! $parent) || (! $parent_item['wall']))) {
192 notice( t('Permission denied.') . EOL) ;
193 if(x($_REQUEST,'return'))
194 goaway($a->get_baseurl() . "/" . $return_path );
198 // Now check that it is a page_type of PAGE_BLOG, and that valid personal details
199 // have been provided, and run any anti-spam plugins
203 if((! can_write_wall($a,$profile_uid)) && (! $allow_moderated)) {
204 notice( t('Permission denied.') . EOL) ;
205 if(x($_REQUEST,'return'))
206 goaway($a->get_baseurl() . "/" . $return_path );
211 // is this an edited post?
216 $i = q("SELECT * FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
217 intval($profile_uid),
227 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
234 $str_group_allow = $orig_post['allow_gid'];
235 $str_contact_allow = $orig_post['allow_cid'];
236 $str_group_deny = $orig_post['deny_gid'];
237 $str_contact_deny = $orig_post['deny_cid'];
238 $location = $orig_post['location'];
239 $coord = $orig_post['coord'];
240 $verb = $orig_post['verb'];
241 $objecttype = $orig_post['object-type'];
242 $emailcc = $orig_post['emailcc'];
243 $app = $orig_post['app'];
244 $categories = $orig_post['file'];
245 $title = notags(trim($_REQUEST['title']));
246 $body = escape_tags(trim($_REQUEST['body']));
247 $private = $orig_post['private'];
248 $pubmail_enable = $orig_post['pubmail'];
249 $network = $orig_post['network'];
250 $guid = $orig_post['guid'];
251 $extid = $orig_post['extid'];
255 // if coming from the API and no privacy settings are set,
256 // use the user default permissions - as they won't have
257 // been supplied via a form.
260 && (! array_key_exists('contact_allow',$_REQUEST))
261 && (! array_key_exists('group_allow',$_REQUEST))
262 && (! array_key_exists('contact_deny',$_REQUEST))
263 && (! array_key_exists('group_deny',$_REQUEST))) {
264 $str_group_allow = $user['allow_gid'];
265 $str_contact_allow = $user['allow_cid'];
266 $str_group_deny = $user['deny_gid'];
267 $str_contact_deny = $user['deny_cid'];
271 // use the posted permissions
273 $str_group_allow = perms2str($_REQUEST['group_allow']);
274 $str_contact_allow = perms2str($_REQUEST['contact_allow']);
275 $str_group_deny = perms2str($_REQUEST['group_deny']);
276 $str_contact_deny = perms2str($_REQUEST['contact_deny']);
279 $title = notags(trim($_REQUEST['title']));
280 $location = notags(trim($_REQUEST['location']));
281 $coord = notags(trim($_REQUEST['coord']));
282 $verb = notags(trim($_REQUEST['verb']));
283 $emailcc = notags(trim($_REQUEST['emailcc']));
284 $body = escape_tags(trim($_REQUEST['body']));
285 $network = notags(trim($_REQUEST['network']));
286 $guid = get_guid(32);
289 item_add_language_opt($_REQUEST);
290 $postopts = $_REQUEST['postopts'] ? $_REQUEST['postopts'] : "";
293 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
296 if($user['hidewall'])
299 // If this is a comment, set the permissions from the parent.
304 // for non native networks use the network of the original post as network of the item
305 if (($parent_item['network'] != NETWORK_DIASPORA)
306 AND ($parent_item['network'] != NETWORK_OSTATUS)
307 AND ($network == ""))
308 $network = $parent_item['network'];
310 if(($parent_item['private'])
311 || strlen($parent_item['allow_cid'])
312 || strlen($parent_item['allow_gid'])
313 || strlen($parent_item['deny_cid'])
314 || strlen($parent_item['deny_gid'])) {
315 $private = (($parent_item['private']) ? $parent_item['private'] : 1);
318 $str_contact_allow = $parent_item['allow_cid'];
319 $str_group_allow = $parent_item['allow_gid'];
320 $str_contact_deny = $parent_item['deny_cid'];
321 $str_group_deny = $parent_item['deny_gid'];
323 $pubmail_enable = ((x($_REQUEST,'pubmail_enable') && intval($_REQUEST['pubmail_enable']) && (! $private)) ? 1 : 0);
325 // if using the API, we won't see pubmail_enable - figure out if it should be set
327 if($api_source && $profile_uid && $profile_uid == local_user() && (! $private)) {
328 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
329 if(! $mail_disabled) {
330 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
333 if(count($r) && intval($r[0]['pubmail']))
334 $pubmail_enabled = true;
338 if(! strlen($body)) {
341 info( t('Empty post discarded.') . EOL );
342 if(x($_REQUEST,'return'))
343 goaway($a->get_baseurl() . "/" . $return_path );
348 if(strlen($categories)) {
349 // get the "fileas" tags for this post
350 $filedas = file_tag_file_to_list($categories, 'file');
352 // save old and new categories, so we can determine what needs to be deleted from pconfig
353 $categories_old = $categories;
354 $categories = file_tag_list_to_file(trim($_REQUEST['category']), 'category');
355 $categories_new = $categories;
356 if(strlen($filedas)) {
357 // append the fileas stuff to the new categories list
358 $categories .= file_tag_list_to_file($filedas, 'file');
361 // Work around doubled linefeeds in Tinymce 3.5b2
362 // First figure out if it's a status post that would've been
363 // created using tinymce. Otherwise leave it alone.
365 /* $plaintext = (local_user() ? intval(get_pconfig(local_user(),'system','plaintext')) || !feature_enabled($profile_uid,'richtext') : 0);
366 if((! $parent) && (! $api_source) && (! $plaintext)) {
367 $body = fix_mce_lf($body);
369 $plaintext = (local_user() ? !feature_enabled($profile_uid,'richtext') : 0);
370 if((! $parent) && (! $api_source) && (! $plaintext)) {
371 $body = fix_mce_lf($body);
375 // get contact info for poster
381 if((local_user()) && (local_user() == $profile_uid)) {
383 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
384 intval($_SESSION['uid']));
386 elseif(remote_user()) {
387 if(is_array($_SESSION['remote'])) {
388 foreach($_SESSION['remote'] as $v) {
389 if($v['uid'] == $profile_uid) {
390 $contact_id = $v['cid'];
396 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
404 $contact_id = $author['id'];
407 // get contact info for owner
409 if($profile_uid == local_user()) {
410 $contact_record = $author;
413 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
417 $contact_record = $r[0];
420 $post_type = notags(trim($_REQUEST['type']));
422 if($post_type === 'net-comment') {
423 if($parent_item !== null) {
424 if($parent_item['wall'] == 1)
425 $post_type = 'wall-comment';
427 $post_type = 'remote-comment';
433 * When a photo was uploaded into the message using the (profile wall) ajax
434 * uploader, The permissions are initially set to disallow anybody but the
435 * owner from seeing it. This is because the permissions may not yet have been
436 * set for the post. If it's private, the photo permissions should be set
437 * appropriately. But we didn't know the final permissions on the post until
438 * now. So now we'll look for links of uploaded messages that are in the
439 * post and set them to the same permissions as the post itself.
445 if((! $preview) && preg_match_all("/\[img([\=0-9x]*?)\](.*?)\[\/img\]/",$body,$match)) {
449 $objecttype = ACTIVITY_OBJ_IMAGE;
451 foreach($images as $image) {
452 if(! stristr($image,$a->get_baseurl() . '/photo/'))
454 $image_uri = substr($image,strrpos($image,'/') + 1);
455 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
456 if(! strlen($image_uri))
458 $srch = '<' . intval($contact_id) . '>';
460 $r = q("SELECT `id` FROM `photo` WHERE `allow_cid` = '%s' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = ''
461 AND `resource-id` = '%s' AND `uid` = %d LIMIT 1",
470 logger("Pre Photo", LOGGER_DEBUG);
471 $r = q("UPDATE `photo` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
472 WHERE `resource-id` = '%s' AND `uid` = %d AND `album` = '%s' ",
473 dbesc($str_contact_allow),
474 dbesc($str_group_allow),
475 dbesc($str_contact_deny),
476 dbesc($str_group_deny),
478 intval($profile_uid),
479 dbesc( t('Wall Photos'))
481 logger("Post Photo", LOGGER_DEBUG);
489 * Next link in any attachment references we find in the post.
494 if((! $preview) && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/",$body,$match)) {
495 $attaches = $match[1];
496 if(count($attaches)) {
497 foreach($attaches as $attach) {
498 $r = q("SELECT * FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
499 intval($profile_uid),
503 logger("Pre Attach", LOGGER_DEBUG);
504 $r = q("UPDATE `attach` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
505 WHERE `uid` = %d AND `id` = %d",
506 dbesc($str_contact_allow),
507 dbesc($str_group_allow),
508 dbesc($str_contact_deny),
509 dbesc($str_group_deny),
510 intval($profile_uid),
513 logger("Post Attach", LOGGER_DEBUG);
519 // embedded bookmark or attachment in post? set bookmark flag
522 $data = get_attachment_data($body);
523 if (preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) OR isset($data["type"])) {
524 $objecttype = ACTIVITY_OBJ_BOOKMARK;
528 $body = bb_translate_video($body);
532 * Fold multi-line [code] sequences
535 $body = preg_replace('/\[\/code\]\s*\[code\]/ism',"\n",$body);
537 $body = scale_external_images($body,false);
540 // Setting the object type if not defined before
542 $objecttype = ACTIVITY_OBJ_NOTE; // Default value
543 require_once("include/plaintext.php");
544 $objectdata = get_attached_data($body);
546 if ($post["type"] == "link")
547 $objecttype = ACTIVITY_OBJ_BOOKMARK;
548 elseif ($post["type"] == "video")
549 $objecttype = ACTIVITY_OBJ_VIDEO;
550 elseif ($post["type"] == "photo")
551 $objecttype = ACTIVITY_OBJ_IMAGE;
556 * Look for any tags and linkify them
563 $tags = get_tags($body);
566 * add a statusnet style reply tag if the original post was from there
567 * and we are replying, and there isn't one already
570 if($parent AND ($parent_contact['network'] === NETWORK_OSTATUS)) {
571 if ($parent_contact['id'] != "")
572 $contact = '@'.$parent_contact['nick'].'+'.$parent_contact['id'];
574 $contact = '@[url='.$parent_contact['url'].']'.$parent_contact['nick'].'[/url]';
576 if (!in_array($contact,$tags)) {
577 $body = $contact.' '.$body;
581 $toplevel_contact = "";
582 $toplevel_parent = q("SELECT `contact`.* FROM `contact`
583 INNER JOIN `item` ON `item`.`contact-id` = `contact`.`id` AND `contact`.`url` = `item`.`author-link`
584 WHERE `item`.`id` = `item`.`parent` AND `item`.`parent` = %d", intval($parent));
585 if ($toplevel_parent)
586 $toplevel_contact = '@'.$toplevel_parent[0]['nick'].'+'.$toplevel_parent[0]['id'];
588 $toplevel_parent = q("SELECT `author-link`, `author-name` FROM `item` WHERE `id` = `parent` AND `parent` = %d", intval($parent));
589 $toplevel_contact = '@[url='.$toplevel_parent[0]['author-link'].']'.$toplevel_parent[0]['author-name'].'[/url]';
592 if (!in_array($toplevel_contact,$tags))
593 $tags[] = $toplevel_contact;
598 $private_forum = false;
601 foreach($tags as $tag) {
603 if(strpos($tag,'#') === 0)
606 // If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
607 // Robert Johnson should be first in the $tags array
609 $fullnametagged = false;
610 for($x = 0; $x < count($tagged); $x ++) {
611 if(stristr($tagged[$x],$tag . ' ')) {
612 $fullnametagged = true;
619 $success = handle_tag($a, $body, $inform, $str_tags, (local_user()) ? local_user() : $profile_uid , $tag, $network);
620 if($success['replaced'])
622 if(is_array($success['contact']) && intval($success['contact']['prv'])) {
623 $private_forum = true;
624 $private_id = $success['contact']['id'];
629 if(($private_forum) && (! $parent) && (! $private)) {
630 // we tagged a private forum in a top level post and the message was public.
633 $str_contact_allow = '<' . $private_id . '>';
639 if(preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
640 foreach($match[2] as $mtch) {
641 $r = q("SELECT `id`,`filename`,`filesize`,`filetype` FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
642 intval($profile_uid),
646 if(strlen($attachments))
648 $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]';
650 $body = str_replace($match[1],'',$body);
656 if($post_type === 'wall' || $post_type === 'wall-comment')
660 $verb = ACTIVITY_POST ;
663 $network = NETWORK_DFRN;
665 $gravity = (($parent) ? 6 : 0 );
667 // even if the post arrived via API we are considering that it
668 // originated on this site by default for determining relayability.
670 $origin = ((x($_REQUEST,'origin')) ? intval($_REQUEST['origin']) : 1);
672 $notify_type = (($parent) ? 'comment-new' : 'wall-new' );
674 $uri = (($message_id) ? $message_id : item_new_uri($a->get_hostname(),$profile_uid, $guid));
676 // Fallback so that we alway have a thr-parent
681 $datarray['uid'] = $profile_uid;
682 $datarray['type'] = $post_type;
683 $datarray['wall'] = $wall;
684 $datarray['gravity'] = $gravity;
685 $datarray['network'] = $network;
686 $datarray['contact-id'] = $contact_id;
687 $datarray['owner-name'] = $contact_record['name'];
688 $datarray['owner-link'] = $contact_record['url'];
689 $datarray['owner-avatar'] = $contact_record['thumb'];
690 $datarray["owner-id"] = get_contact($datarray["owner-link"], 0);
691 $datarray['author-name'] = $author['name'];
692 $datarray['author-link'] = $author['url'];
693 $datarray['author-avatar'] = $author['thumb'];
694 $datarray["author-id"] = get_contact($datarray["author-link"], 0);
695 $datarray['created'] = datetime_convert();
696 $datarray['edited'] = datetime_convert();
697 $datarray['commented'] = datetime_convert();
698 $datarray['received'] = datetime_convert();
699 $datarray['changed'] = datetime_convert();
700 $datarray['extid'] = $extid;
701 $datarray['guid'] = $guid;
702 $datarray['uri'] = $uri;
703 $datarray['title'] = $title;
704 $datarray['body'] = $body;
705 $datarray['app'] = $app;
706 $datarray['location'] = $location;
707 $datarray['coord'] = $coord;
708 $datarray['tag'] = $str_tags;
709 $datarray['file'] = $categories;
710 $datarray['inform'] = $inform;
711 $datarray['verb'] = $verb;
712 $datarray['object-type'] = $objecttype;
713 $datarray['allow_cid'] = $str_contact_allow;
714 $datarray['allow_gid'] = $str_group_allow;
715 $datarray['deny_cid'] = $str_contact_deny;
716 $datarray['deny_gid'] = $str_group_deny;
717 $datarray['private'] = $private;
718 $datarray['pubmail'] = $pubmail_enable;
719 $datarray['attach'] = $attachments;
720 $datarray['bookmark'] = intval($bookmark);
721 $datarray['thr-parent'] = $thr_parent;
722 $datarray['postopts'] = $postopts;
723 $datarray['origin'] = $origin;
724 $datarray['moderated'] = $allow_moderated;
725 $datarray['gcontact-id'] = get_gcontact_id(array("url" => $datarray['author-link'], "network" => $datarray['network'],
726 "photo" => $datarray['author-avatar'], "name" => $datarray['author-name']));
729 * These fields are for the convenience of plugins...
730 * 'self' if true indicates the owner is posting on their own wall
731 * If parent is 0 it is a top-level post.
734 $datarray['parent'] = $parent;
735 $datarray['self'] = $self;
736 // $datarray['prvnets'] = $user['prvnets'];
739 $datarray['edit'] = true;
741 // Search for hashtags
742 item_body_set_hashtags($datarray);
744 // preview mode - prepare the body for display and send it via json
747 require_once('include/conversation.php');
748 $o = conversation($a,array(array_merge($contact_record,$datarray)),'search', false, true);
749 logger('preview: ' . $o);
750 echo json_encode(array('preview' => $o));
755 call_hooks('post_local',$datarray);
757 if(x($datarray,'cancel')) {
758 logger('mod_item: post cancelled by plugin.');
760 goaway($a->get_baseurl() . "/" . $return_path);
763 $json = array('cancel' => 1);
764 if(x($_REQUEST,'jsreload') && strlen($_REQUEST['jsreload']))
765 $json['reload'] = $a->get_baseurl() . '/' . $_REQUEST['jsreload'];
767 echo json_encode($json);
771 // Fill the cache field
772 put_item_in_cache($datarray);
775 logger("Pre Update", LOGGER_DEBUG);
776 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `attach` = '%s', `file` = '%s', `rendered-html` = '%s', `rendered-hash` = '%s', `edited` = '%s', `changed` = '%s' WHERE `id` = %d AND `uid` = %d",
777 dbesc($datarray['title']),
778 dbesc($datarray['body']),
779 dbesc($datarray['tag']),
780 dbesc($datarray['attach']),
781 dbesc($datarray['file']),
782 dbesc($datarray['rendered-html']),
783 dbesc($datarray['rendered-hash']),
784 dbesc(datetime_convert()),
785 dbesc(datetime_convert()),
789 logger("Post Update", LOGGER_DEBUG);
791 create_tags_from_item($post_id);
792 create_files_from_item($post_id);
793 update_thread($post_id);
795 // update filetags in pconfig
796 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
798 proc_run(PRIORITY_HIGH, "include/notifier.php", 'edit_post', $post_id);
799 if((x($_REQUEST,'return')) && strlen($return_path)) {
800 logger('return: ' . $return_path);
801 goaway($a->get_baseurl() . "/" . $return_path );
809 // Inherit ACLs from the parent item.
810 /// @todo Check if really needed
811 $datarray['allow_cid'] = $parent_item['allow_cid'];
812 $datarray['allow_gid'] = $parent_item['allow_gid'];
813 $datarray['deny_cid'] = $parent_item['deny_cid'];
814 $datarray['deny_gid'] = $parent_item['deny_gid'];
815 $datarray['private'] = $parent_item['private'];
818 logger("Pre Insert", LOGGER_DEBUG);
819 $r = q("INSERT INTO `item` (`guid`, `extid`, `uid`,`type`,`wall`,`gravity`, `network`, `contact-id`,
820 `owner-name`,`owner-link`,`owner-avatar`, `owner-id`,
821 `author-name`, `author-link`, `author-avatar`, `author-id`,
822 `created`, `edited`, `commented`, `received`, `changed`,
823 `uri`, `thr-parent`, `title`, `body`, `app`, `location`, `coord`,
824 `tag`, `inform`, `verb`, `object-type`, `postopts`,
825 `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid`, `private`,
826 `pubmail`, `attach`, `bookmark`,`origin`, `moderated`, `file`,
827 `rendered-html`, `rendered-hash`)
828 VALUES('%s', '%s', %d, '%s', %d, %d, '%s', %d,
829 '%s', '%s', '%s', %d,
830 '%s', '%s', '%s', %d,
831 '%s', '%s', '%s', '%s', '%s',
832 '%s', '%s', '%s', '%s', '%s', '%s', '%s',
833 '%s', '%s', '%s', '%s', '%s',
834 '%s', '%s', '%s', '%s', %d,
835 %d, '%s', %d, %d, %d, '%s',
837 dbesc($datarray['guid']),
838 dbesc($datarray['extid']),
839 intval($datarray['uid']),
840 dbesc($datarray['type']),
841 intval($datarray['wall']),
842 intval($datarray['gravity']),
843 dbesc($datarray['network']),
844 intval($datarray['contact-id']),
845 dbesc($datarray['owner-name']),
846 dbesc($datarray['owner-link']),
847 dbesc($datarray['owner-avatar']),
848 intval($datarray['owner-id']),
849 dbesc($datarray['author-name']),
850 dbesc($datarray['author-link']),
851 dbesc($datarray['author-avatar']),
852 intval($datarray['author-id']),
853 dbesc($datarray['created']),
854 dbesc($datarray['edited']),
855 dbesc($datarray['commented']),
856 dbesc($datarray['received']),
857 dbesc($datarray['changed']),
858 dbesc($datarray['uri']),
859 dbesc($datarray['thr-parent']),
860 dbesc($datarray['title']),
861 dbesc($datarray['body']),
862 dbesc($datarray['app']),
863 dbesc($datarray['location']),
864 dbesc($datarray['coord']),
865 dbesc($datarray['tag']),
866 dbesc($datarray['inform']),
867 dbesc($datarray['verb']),
868 dbesc($datarray['object-type']),
869 dbesc($datarray['postopts']),
870 dbesc($datarray['allow_cid']),
871 dbesc($datarray['allow_gid']),
872 dbesc($datarray['deny_cid']),
873 dbesc($datarray['deny_gid']),
874 intval($datarray['private']),
875 intval($datarray['pubmail']),
876 dbesc($datarray['attach']),
877 intval($datarray['bookmark']),
878 intval($datarray['origin']),
879 intval($datarray['moderated']),
880 dbesc($datarray['file']),
881 dbesc($datarray['rendered-html']),
882 dbesc($datarray['rendered-hash'])
885 logger("Post Insert", LOGGER_DEBUG);
887 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
888 dbesc($datarray['uri']));
890 logger('mod_item: unable to retrieve post that was just stored.');
891 notice( t('System error. Post not saved.') . EOL);
892 goaway($a->get_baseurl() . "/" . $return_path );
896 $post_id = $r[0]['id'];
897 logger('mod_item: saved item ' . $post_id);
899 $datarray["id"] = $post_id;
900 $datarray["plink"] = $a->get_baseurl().'/display/'.urlencode($datarray["guid"]);
902 // update filetags in pconfig
903 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
907 logger("Pre Update last-child", LOGGER_DEBUG);
908 // This item is the last leaf and gets the comment box, clear any ancestors
909 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent` = %d AND `last-child`",
910 dbesc(datetime_convert()),
913 logger("Post Update last-child", LOGGER_DEBUG);
914 //Test: update_thread($parent, true);
916 // Inherit ACLs from the parent item.
918 logger("Pre Update ACL", LOGGER_DEBUG);
919 $r = q("UPDATE `item` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d
921 dbesc($parent_item['allow_cid']),
922 dbesc($parent_item['allow_gid']),
923 dbesc($parent_item['deny_cid']),
924 dbesc($parent_item['deny_gid']),
925 intval($parent_item['private']),
928 logger("Post Update ACL", LOGGER_DEBUG);
930 if($contact_record != $author) {
932 'type' => NOTIFY_COMMENT,
933 'notify_flags' => $user['notify-flags'],
934 'language' => $user['language'],
935 'to_name' => $user['username'],
936 'to_email' => $user['email'],
937 'uid' => $user['uid'],
939 'link' => $a->get_baseurl().'/display/'.urlencode($datarray['guid']),
940 'source_name' => $datarray['author-name'],
941 'source_link' => $datarray['author-link'],
942 'source_photo' => $datarray['author-avatar'],
943 'verb' => ACTIVITY_POST,
946 'parent_uri' => $parent_item['uri']
952 // Store the comment signature information in case we need to relay to Diaspora
953 diaspora::store_comment_signature($datarray, $author, ($self ? $user['prvkey'] : false), $post_id);
958 if($contact_record != $author) {
960 'type' => NOTIFY_WALL,
961 'notify_flags' => $user['notify-flags'],
962 'language' => $user['language'],
963 'to_name' => $user['username'],
964 'to_email' => $user['email'],
965 'uid' => $user['uid'],
967 'link' => $a->get_baseurl().'/display/'.urlencode($datarray['guid']),
968 'source_name' => $datarray['author-name'],
969 'source_link' => $datarray['author-link'],
970 'source_photo' => $datarray['author-avatar'],
971 'verb' => ACTIVITY_POST,
977 // fallback so that parent always gets set to non-zero.
982 logger("Pre Update Parent", LOGGER_DEBUG);
983 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s', `plink` = '%s', `changed` = '%s', `last-child` = 1, `visible` = 1
986 dbesc(($parent == $post_id) ? $uri : $parent_item['uri']),
987 dbesc($a->get_baseurl().'/display/'.urlencode($datarray['guid'])),
988 dbesc(datetime_convert()),
991 logger("Pre Update Parent", LOGGER_DEBUG);
993 // photo comments turn the corresponding item visible to the profile wall
994 // This way we don't see every picture in your new photo album posted to your wall at once.
995 // They will show up as people comment on them.
997 //if(! $parent_item['visible']) {
998 // logger("Pre Update Visible", LOGGER_DEBUG);
999 // $r = q("UPDATE `item` SET `visible` = 1 WHERE `id` = %d",
1000 // intval($parent_item['id'])
1002 // logger("Post Update Visible", LOGGER_DEBUG);
1003 //update_thread($parent_item['id']);
1006 // update the commented timestamp on the parent
1008 logger("Pre Update Commented", LOGGER_DEBUG);
1009 q("UPDATE `item` SET `visible` = 1, `commented` = '%s', `changed` = '%s' WHERE `id` = %d",
1010 dbesc(datetime_convert()),
1011 dbesc(datetime_convert()),
1014 logger("Post Update Commented", LOGGER_DEBUG);
1015 if ($post_id != $parent)
1016 update_thread($parent, true);
1018 call_hooks('post_local_end', $datarray);
1020 if(strlen($emailcc) && $profile_uid == local_user()) {
1021 $erecips = explode(',', $emailcc);
1022 if(count($erecips)) {
1023 foreach($erecips as $recip) {
1024 $addr = trim($recip);
1027 $disclaimer = '<hr />' . sprintf( t('This message was sent to you by %s, a member of the Friendica social network.'),$a->user['username'])
1029 $disclaimer .= sprintf( t('You may visit them online at %s'), $a->get_baseurl() . '/profile/' . $a->user['nickname']) . EOL;
1030 $disclaimer .= t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
1031 if (!$datarray['title']=='') {
1032 $subject = email_header_encode($datarray['title'],'UTF-8');
1034 $subject = email_header_encode('[Friendica]' . ' ' . sprintf( t('%s posted an update.'),$a->user['username']),'UTF-8');
1036 $link = '<a href="' . $a->get_baseurl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
1037 $html = prepare_body($datarray);
1038 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
1039 include_once('include/html2plain.php');
1041 'fromName' => $a->user['username'],
1042 'fromEmail' => $a->user['email'],
1044 'replyTo' => $a->user['email'],
1045 'messageSubject' => $subject,
1046 'htmlVersion' => $message,
1047 'textVersion' => html2plain($html.$disclaimer),
1049 Emailer::send($params);
1054 create_tags_from_item($post_id);
1055 create_files_from_item($post_id);
1057 if ($post_id == $parent)
1058 add_thread($post_id);
1060 // This is a real juggling act on shared hosting services which kill your processes
1061 // e.g. dreamhost. We used to start delivery to our native delivery agents in the background
1062 // and then run our plugin delivery from the foreground. We're now doing plugin delivery first,
1063 // because as soon as you start loading up a bunch of remote delivey processes, *this* page is
1064 // likely to get killed off. If you end up looking at an /item URL and a blank page,
1065 // it's very likely the delivery got killed before all your friends could be notified.
1066 // Currently the only realistic fixes are to use a reliable server - which precludes shared hosting,
1067 // or cut back on plugins which do remote deliveries.
1069 proc_run(PRIORITY_HIGH, "include/notifier.php", $notify_type, $post_id);
1071 logger('post_complete');
1073 $perfdb = $a->performance["database"] - $perfdb;
1074 $perfdbw = $a->performance["database_write"] - $perfdbw;
1075 $perfnet = $a->performance["network"] - $perfnet;
1076 $perffile = $a->performance["file"] - $perffile;
1078 logger("Performance: DB-R: ".round($perfdb - $perfdbw, 2)." - DB-W: ".round($perfdbw, 2)." - Net: ".round($perfnet, 2)." - File: ".round($perffile, 2), LOGGER_DEBUG);
1079 //logger("Performance: DB-R: ".round($perfdb - $perfdbw, 2)." - DB-W: ".round($perfdbw, 2)." - Net: ".round($perfnet, 2), LOGGER_DEBUG);
1081 item_post_return($a->get_baseurl(), $api_source, $return_path);
1085 function item_post_return($baseurl, $api_source, $return_path) {
1086 // figure out how to return, depending on from whence we came
1092 goaway($baseurl . "/" . $return_path);
1095 $json = array('success' => 1);
1096 if(x($_REQUEST,'jsreload') && strlen($_REQUEST['jsreload']))
1097 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
1099 logger('post_json: ' . print_r($json,true), LOGGER_DEBUG);
1101 echo json_encode($json);
1107 function item_content(&$a) {
1109 if((! local_user()) && (! remote_user()))
1112 require_once('include/security.php');
1115 if(($a->argc == 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
1116 $o = drop_item($a->argv[2], !is_ajax());
1118 // ajax return: [<item id>, 0 (no perm) | <owner id>]
1119 echo json_encode(array(intval($a->argv[2]), intval($o)));
1127 * This function removes the tag $tag from the text $body and replaces it with
1128 * the appropiate link.
1130 * @param unknown_type $body the text to replace the tag in
1131 * @param string $inform a comma-seperated string containing everybody to inform
1132 * @param string $str_tags string to add the tag to
1133 * @param integer $profile_uid
1134 * @param string $tag the tag to replace
1135 * @param string $network The network of the post
1137 * @return boolean true if replaced, false if not replaced
1139 function handle_tag($a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "") {
1140 require_once("include/Scrape.php");
1141 require_once("include/socgraph.php");
1146 //is it a person tag?
1147 if(strpos($tag,'@') === 0) {
1148 //is it already replaced?
1149 if(strpos($tag,'[url=')) {
1150 //append tag to str_tags
1151 if(!stristr($str_tags,$tag)) {
1152 if(strlen($str_tags))
1157 // Checking for the alias that is used for OStatus
1158 $pattern = "/@\[url\=(.*?)\](.*?)\[\/url\]/ism";
1159 if (preg_match($pattern, $tag, $matches)) {
1161 $r = q("SELECT `alias`, `name` FROM `contact` WHERE `nurl` = '%s' AND `alias` != '' AND `uid` = 0",
1162 normalise_link($matches[1]));
1164 $r = q("SELECT `alias`, `name` FROM `gcontact` WHERE `nurl` = '%s' AND `alias` != ''",
1165 normalise_link($matches[1]));
1169 $data = probe_url($matches[1]);
1171 if ($data["alias"] != "") {
1172 $newtag = '@[url='.$data["alias"].']'.$data["name"].'[/url]';
1173 if(!stristr($str_tags,$newtag)) {
1174 if(strlen($str_tags))
1176 $str_tags .= $newtag;
1184 //get the person's name
1185 $name = substr($tag,1);
1187 // Sometimes the tag detection doesn't seem to work right
1188 // This is some workaround
1189 $nameparts = explode(" ", $name);
1190 $name = $nameparts[0];
1192 // Try to detect the contact in various ways
1193 if ((strpos($name,'@')) || (strpos($name,'http://'))) {
1194 // Is it in format @user@domain.tld or @http://domain.tld/...?
1196 // First check the contact table for the address
1197 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `contact`
1198 WHERE `addr` = '%s' AND `uid` = %d AND
1199 (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1202 intval($profile_uid),
1203 dbesc(NETWORK_OSTATUS)
1206 // Then check in the contact table for the url
1208 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `contact`
1209 WHERE `nurl` = '%s' AND `uid` = %d AND
1210 (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1212 dbesc(normalise_link($name)),
1213 intval($profile_uid),
1214 dbesc(NETWORK_OSTATUS)
1217 // Then check in the global contacts for the address
1219 $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
1220 WHERE `addr` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1223 dbesc(NETWORK_OSTATUS)
1226 // Then check in the global contacts for the url
1228 $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
1229 WHERE `nurl` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1231 dbesc(normalise_link($name)),
1232 dbesc(NETWORK_OSTATUS)
1236 $probed = probe_url($name);
1237 if ($result['network'] != NETWORK_PHANTOM) {
1238 update_gcontact($probed);
1239 $r = q("SELECT `url`, `name`, `nick`, `network`, `alias`, `notify` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1240 dbesc(normalise_link($probed["url"])));
1245 if (strrpos($name,'+')) {
1246 // Is it in format @nick+number?
1247 $tagcid = intval(substr($name,strrpos($name,'+') + 1));
1249 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1251 intval($profile_uid)
1255 //select someone by attag or nick and the name passed in the current network
1256 if(!$r AND ($network != ""))
1257 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `network` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
1261 intval($profile_uid)
1264 //select someone from this user's contacts by name in the current network
1265 if (!$r AND ($network != ""))
1266 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `network` = '%s' AND `uid` = %d LIMIT 1",
1269 intval($profile_uid)
1272 //select someone by attag or nick and the name passed in
1274 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
1277 intval($profile_uid)
1281 //select someone from this user's contacts by name
1283 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
1285 intval($profile_uid)
1290 if(strlen($inform) AND (isset($r[0]["notify"]) OR isset($r[0]["id"])))
1293 if (isset($r[0]["id"]))
1294 $inform .= 'cid:' . $r[0]["id"];
1295 elseif (isset($r[0]["notify"]))
1296 $inform .= $r[0]["notify"];
1298 $profile = $r[0]["url"];
1299 $alias = $r[0]["alias"];
1300 $newname = $r[0]["nick"];
1301 if (($newname == "") OR (($r[0]["network"] != NETWORK_OSTATUS) AND ($r[0]["network"] != NETWORK_TWITTER)
1302 AND ($r[0]["network"] != NETWORK_STATUSNET) AND ($r[0]["network"] != NETWORK_APPNET)))
1303 $newname = $r[0]["name"];
1306 //if there is an url for this persons profile
1307 if (isset($profile) AND ($newname != "")) {
1310 //create profile link
1311 $profile = str_replace(',','%2c',$profile);
1312 $newtag = '@[url='.$profile.']'.$newname.'[/url]';
1313 $body = str_replace('@'.$name, $newtag, $body);
1314 //append tag to str_tags
1315 if(! stristr($str_tags,$newtag)) {
1316 if(strlen($str_tags))
1318 $str_tags .= $newtag;
1321 // Status.Net seems to require the numeric ID URL in a mention if the person isn't
1322 // subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1324 if(strlen($alias)) {
1325 $newtag = '@[url='.$alias.']'.$newname.'[/url]';
1326 if(! stristr($str_tags,$newtag)) {
1327 if(strlen($str_tags))
1329 $str_tags .= $newtag;
1335 return array('replaced' => $replaced, 'contact' => $r[0]);