<?page
title=><?_ml .title _ml?>
body<=
<?_code
{
    use strict;
    use vars qw(%GET %POST);

    LJ::set_active_crumb('createcommunity');

    return LJ::server_down_html() if $LJ::SERVER_DOWN;
    return "<?badinput?>" unless LJ::text_in(\%POST);

    my $mode = $POST{mode} || 'getinfo';

    my $remote = LJ::get_remote();
    return "<?needlogin?>" if !$remote;
    return "<?h1 $ML{'Error'} h1?><?p $ML{'.error.notperson'} p?>"
        if $remote->{journaltype} ne 'P';
    return "<?h1 $ML{'Error'} h1?><?p $ML{'.error.notactive'} p?>"
        unless $remote->{statusvis} eq 'V';

    if ($remote->underage) {
        return BML::redirect("$LJ::SITEROOT/agecheck/?s=1");
    }

    # fix up the incoming data (is used in getinfo mode and submit mode so it's here)
    $POST{membership} = 'open'
        unless $POST{membership} =~ m/^(?:open|moderated|closed)$/;
    $POST{postlevel} = 'members'
        unless $POST{postlevel} =~ m/^(?:members|select)$/;
    $POST{nonmember_posting} = '0'
        unless $POST{nonmember_posting} =~ m/^[01]$/;
    $POST{moderated} = '0'
        unless $POST{moderated} =~ m/^[01]$/;

    # MODE: submit - try to create an account.  might change mode
    #       if there are errors, we'll populate $error and
    #       return to "getinfo" mode below
    my $error;
SUBMIT:
    while ($mode eq 'submit')  # using while instead of if so we can 'last' out of it
    {
        return "<b>$ML{'Error'}</b>: $ML{'.error.postrequired'}" unless LJ::did_post();

        my $user = LJ::canonical_username($POST{user});
        my $title = $POST{title} || $user;

        # reject this email?
        return LJ::sysban_block(0, "Create user blocked based on email",
                                { new_user => $user, email => $remote->{email}, name => $user })
        if LJ::sysban_check('email', $remote->{email});

        $error = "$ML{'error.usernamelong'}" if length($user) > 15;
        $error = "$ML{'error.usernameinvalid'}" if $POST{user} && !$user;
        $error = "$ML{'.error.username.mustenter'}" unless $POST{user};

        my $u = LJ::load_user($user);

  if(!LJ::check_priv($remote, 'create_protected_com')){
            foreach my $re ("^system\$", @LJ::PROTECTED_USERNAMES) {
          next unless $user =~ /$re/;
    
          # you can give people sharedjournal priv ahead of time to create
              # reserved communities:
          next if LJ::check_priv($remote, "sharedjournal", $user);

          $error = "$ML{'.error.username.reserved'}";
      }
        }

        my $second_submit = 0;
        if ($u) {
            my $in_use = 1;

            if ($u->{email} eq $remote->{email}) {
                if (LJ::login_ip_banned($u)) {
                    # brute-force possible going on
                } else {
                    if ($u->{password} eq $remote->{password}) {
                        # oh, they double-clicked the submit button
                        $second_submit = 1;

                        # if we found a comm and everything matches, they double hit.  if
                        # we found a person/etc, then they tried to recreate their community,
                        # which isn't allowed anymore
                        $in_use = $u->{journaltype} eq 'C' ? 0 : 1;
                    } else {
                        LJ::handle_bad_login($u);
                    }
                }
            }

            if ($in_use) {
                $error = "$ML{'.error.username.inuse'}";
            }
        }

        last SUBMIT if $error;

        my $qclusterid = LJ::new_account_cluster() + 0;
        die "Cluster 0 not supported" unless $qclusterid;

        my $userid = ref $u ? $u->{userid} : 0;
        unless ($second_submit) {
            my $dbh = LJ::get_db_writer();

            my $errorcounter = 0;
            my $old_print_error = $dbh->{PrintError}; # save PrintError mode
            $dbh->{PrintError} = 0; # will check for errors manually

            while (1) {
              my $ruserid = LJ::get_new_userid("P");

              if (!$ruserid) {
                return "<?h1 $ML{'Error'} h1?><?p $ML{'error.procrequest'} p?>";
              }
              $dbh->do("set insert_id = $ruserid");

              $dbh->do(
                "INSERT INTO user (user, email, status, caps, name, clusterid, dversion, journaltype) ".
                "VALUES (?, ?, ?, ?, ?, ?, $LJ::MAX_DVERSION, 'C')",
                undef, $user, $remote->{email}, $remote->{status}, int($LJ::NEWUSER_CAPS), $title, $qclusterid);

              if ($dbh->err) {
                # who wants to try forever
                if ($errorcounter > 10) {
                  return "<?h1 $ML{'Error'} h1?><?p $ML{'error.procrequest'} <b>" . $dbh->errstr . "</b> p?>";
                }

                $errorcounter++;
                sleep 1; # let it breathe
                next; # try again
              }
              else {
                $userid = $dbh->{'mysql_insertid'}; # smells like success
                $dbh->{PrintError} = $old_print_error; # restore error reporting

                return 0 unless $userid; # but?

                last; # finally
              }
            }

            if ($LJ::LJR_FIF) {
              use LJ::MemCache;
              my $ljr_fif_id = LJ::get_userid($LJ::LJR_FIF);
              if ($ljr_fif_id) {
                $dbh->do("INSERT INTO friends (userid, friendid) VALUES (?, ?)", undef, $ljr_fif_id, $userid);
                # refresh memcache
                #my $memkey = [$ljr_fif_id, "friends:$ljr_fif_id"];
                #LJ::MemCache::delete($memkey);
                LJ::get_friends($ljr_fif_id, undef, undef, 'force', {} );
              }
            }

            $dbh->do("REPLACE INTO useridmap (userid, user) VALUES (?, ?)", undef, $userid, $user);
            $dbh->do("REPLACE INTO userusage (userid, timecreate) VALUES (?, NOW())", undef, $userid);

            # set any properties that get set in new users
            $u = LJ::load_userid($userid);
            while (my ($name, $val) = each %LJ::USERPROP_INIT) {
                LJ::set_userprop($u, $name, $val);
            }

            # since they're a community, let's do more setup
            $dbh->do("REPLACE INTO community (userid, membership, postlevel) VALUES (?, ?, ?)",
                     undef, $userid, $POST{membership}, $POST{postlevel});
            LJ::set_userprop($u, 'nonmember_posting', $POST{nonmember_posting} + 0);
            LJ::set_userprop($u, 'moderated', $POST{moderated} + 0);
            LJ::set_rel($userid, $remote->{userid}, 'M') if $POST{moderated}; # moderator if moderated
            LJ::set_rel($userid, $remote->{userid}, 'A');                     # maintainer
            LJ::join_community($remote, $u, 0, 1); # make them a member of the community

            LJ::run_hooks("post_create", {
                'userid' => $userid,
                'user' => $user,
            });
        }

        my $nu = LJ::load_userid($userid, "force");

        # log creation
        $nu->log_event('account_create', { remote => $remote });

        # local sites may want to override what happens at this point
        my $ret;
        my $redirect;
        my $stop_output;
        LJ::run_hooks("create.bml_postsession", {
            post => \%POST,
            u => $nu,
            type => 'community',
            redirect => \$redirect,
            ret => \$ret,
            stop_output => \$stop_output,
        });
        return BML::redirect($redirect) if $redirect;
        return $ret if $stop_output;

        $ret = "<?h1 $ML{'.success.head'} h1?><?p $ML{'.success.text1'} p?>";
        my $uri = LJ::journal_base($nu);
        $ret .= "<?p $ML{'.success.text2'} p?>\n";
        $ret .= "<?standout <font size='+1' face='arial'><b><a href='$uri'>$uri/</a></b></font> standout?>\n";
        $ret .= "<?p $ML{'.success.text3'} p?>\n";

        $ret .= "<form method='get' action='$LJ::SITEROOT/editinfo.bml?authas=$nu->{user}'>";
        $ret .= "<p align='center'>" . LJ::html_submit(undef, "$ML{'.success.btn.enterinfo'} &rarr;") . "</p>";
        $ret .= "</form>\n";

        return $ret;

    }

    if ($mode eq "getinfo" || $error)
    {
        my $ret;

        if ($error) {
            $ret .= "<?errorbar <strong>$ML{'.errors.label'}</strong><ul>";
            $ret .= "<li>$error</li>";
            $ret .= "</ul> errorbar?>";
        }

        $ret .= "<?p $ML{'.create.text'} p?>" unless $error;
        $ret .= "<form action=\"create.bml\" method=\"post\">\n";
        $ret .= LJ::html_hidden(mode => 'submit', ssl => $FORM{'ssl'});

        $ret .= "<ol>";

        # username
        my $v = LJ::ehtml($FORM{'user'});
        $ret .= "<li><div class='formitem'><div class='formitemName'>$ML{'.username.head'}</div>";
        $ret .= "<p class='formitemFlag'>$error</p>";
        $ret .= "<div class='formitemDesc'>" . BML::ml(".username.text", { sitename => $LJ::SITENAME }) . "</div>";
        $ret .= LJ::html_text({'name' => 'user', 'size' => 15, 'maxlength' => 15, 'value' => $v, raw => 'style="<?commloginboxstyle?>"' });
        $ret .= "<br />" . BML::ml('.person', { aopts => "href='$LJ::SITEROOT/create.bml'" });
        $ret .= "<div class='formitemNote'>$ML{'.username.charsallowed'}</div>" unless $error;
        $ret .= "</div></li>";

        # account title
        $v = LJ::ehtml($FORM{'title'});
        $ret .= "<li><div class='formitem'><div class='formitemName'>$ML{'.name.head'}</div>";
        $ret .= "<div class='formitemDesc'>$ML{'.name.text'}</div>";
        $ret .= LJ::html_text({ name => 'title', style => 'width: 60%;', maxlength => 80, value => $v, });
        $ret .= "</div></li>";

        # membership levels
        $ret .= "<li><div class='formitem'><div class='formitemName'>$ML{'/community/settings.bml.label.membership'}" .
            "</div><div class='formitemDesc'>$ML{'/community/settings.bml.label.whocanjoin'}</div><div><p>";
        $ret .= LJ::html_check({ type => 'radio', name => 'membership', id => 'memopen',
                value => 'open', selected => ($POST{membership} eq 'open' ? 1 : 0)});
        $ret .= "<label for='memopen' $ML{'/community/settings.bml.label.openmemb'}</label><br /></p><p>";
        $ret .= LJ::html_check({ type => 'radio', name => 'membership', id => 'memmoderated',
                value => 'moderated', selected => ($POST{membership} eq 'moderated' ? 1 : 0)});
        $ret .= "<label for='memmoderated' $ML{'/community/settings.bml.label.moderatedmemb'}</label></p><p>";
        $ret .= LJ::html_check({ type => 'radio', name => 'membership', id => 'memclosed',
                value => 'closed', selected => ($POST{membership} eq 'closed' ? 1 : 0)});
        $ret .= "<label for='memclosed' $ML{'/community/settings.bml.label.closedmemb2'}</label></p>";
        $ret .= "</div></div></li>";

        # posting access options
        $ret .= "<li><div class='formitem'><div class='formitemName'>$ML{'/community/settings.bml.label.postaccess'}" .
            "</div><div class='formitemDesc'>$ML{'/community/settings.bml.label.whocanpost'}</div><div><p>";
        $ret .= LJ::html_check({ type => 'radio', name => 'postlevel', id => 'postopen',
                value => 'members', selected => ($POST{postlevel} eq 'members' ? 1 : 0)});
        $ret .= "<label for='postopen'>$ML{'/community/settings.bml.label.anybodycan'}</label></p><p>";
        $ret .= LJ::html_check({ type => 'radio', name => 'postlevel', id => 'postclosed',
                value => 'select', selected => ($POST{postlevel} eq 'select' ? 1 : 0)});
        $ret .= "<label for='postclosed'>$ML{'/community/settings.bml.label.selcan'}</label></p>";
        $ret .= "</div></div></li>";

        # nonmember posting options
        $ret .= "<li><div class='formitem'><div class='formitemName'>$ML{'/community/settings.bml.label.nmheader'}" .
            "</div><div class='formitemDesc'>$ML{'/community/settings.bml.label.nmtext'}</div><div><p>";
        $ret .= LJ::html_check({ type => 'radio', name => 'nonmember_posting', id => 'nonopen',
                value => '0', selected => ($POST{nonmember_posting} eq '0' ? 1 : 0)});
        $ret .= "<label for='nonopen'>$ML{'/community/settings.bml.label.nmcant'}</label></p><p>";
        $ret .= LJ::html_check({ type => 'radio', name => 'nonmember_posting', id => 'nonclosed',
                value => '1', selected => ($POST{nonmember_posting} eq '1' ? 1 : 0)});
        $ret .= "<label for='nonclosed'>$ML{'/community/settings.bml.label.nmcan'}</label></p>";
        $ret .= "</div></div></li>";

        # moderated options
        $ret .= "<li><div class='formitem'><div class='formitemName'>$ML{'/community/settings.bml.label.modheader'}" .
            "</div><div class='formitemDesc'>$ML{'/community/settings.bml.label.modtext'}</div><div><p>";
        $ret .= LJ::html_check({ type => 'radio', name => 'moderated', id => 'radunmod',
                value => '0', selected => ($POST{moderated} eq '0' ? 1 : 0)});
        $ret .= "<label for='radunmod'>$ML{'/community/settings.bml.label.modisnt'}</label></p><p>";
        $ret .= LJ::html_check({ type => 'radio', name => 'moderated', id => 'radmod',
                value => '1', selected => ($POST{moderated} eq '1' ? 1 : 0)});
        $ret .= "<label for='radmod'>$ML{'/community/settings.bml.label.modis'}</label></p>";
        $ret .= "</div></div></li>";

        LJ::run_hooks("create.bml_opts", {
            post => \%POST,
            get => \%GET,
            ret => \$ret,
        });

        $ret .= "</ol>";

        $ret .= "<div style='width:600; text-align: center'>";
        $ret .= "<input type='submit' value=\"$ML{'.btn.create'}\">";
        $ret .= "</div>";
        $ret .= "</form>";

        return $ret;
    }

    return "$ML{'error.unknownmode'}: <b>$mode</b>";
}
_code?>
<=body
page?>
