bulk user import for joomla 2.5

2019-08-08 22:58发布

问题:

can someone help me with this php-script, this script is for Joomla 1.5 and I am using 2.5. This is not compatible and I am confused of the tables used because 1.5 and 2.5 has different table names. some tables in 1.5 are not also in 2.5

btw, this script is a bulk user import using csv file to sql/database.

<?php

// Hande form upload
if(isset($_POST['import'])) {

    $mysql_host             = trim($_POST['mysql_host']);
    $mysql_user             = trim($_POST['mysql_username']);
    $mysql_password         = trim($_POST['mysql_password']);
    $mysql_schema           = trim($_POST['mysql_schema']);

    $table_prefix           = trim($_POST['table_prefix']);

    if(!mysql_connect($mysql_host, $mysql_user, $mysql_password) || !mysql_select_db($mysql_schema)) {
        echo 'Supplied MySQL details were incorrect - aborting';
        return;
    }


    // Get the joomla groups
    $sql = sprintf('
            SELECT  `id`, `value`
            FROM    `%score_acl_aro_groups`
        ', 
        $table_prefix
    );
    $rs = mysql_query($sql);
    $groups = array();
    while($group = mysql_fetch_object($rs)) {
        $groups[$group->value] = $group->id;
    }


    $fp = fopen($_FILES['csv']['tmp_name'], 'r');
    while($user = fgetcsv($fp)) {

        printf('Importing "%s" ... ', $user[0]);

        // Lookup and verify user group
        if(!isset($groups[$user[4]])) {
            printf('error: Invalid group (%s) for %s. Defaulting to <code>Registered</code><br />%s', $user[4], $user[0], PHP_EOL);
            $user[4] = 'Registered';
        }

        // Insert record into wsers
        $sql = sprintf('
            INSERT INTO `%susers` 
            SET
                `name`            = "%s",
                `username`        = "%s",
                `email`           = "%s",
                `password`        = "%s",
                `usertype`        = "%s",
                `block`           = "%s",
                `sendEmail`       = "%s",
                `gid`             = "%s",
                `registerDate`    = NOW(),
                `lastvisitDate`   = "0000-00-00 00:00:00",
                `activation`      = "",
                `params`          = ""
            ',
            $table_prefix,
            sql_prep($user[0]),
            sql_prep($user[1]),
            sql_prep($user[2]),
            isset($_POST['md5_passwords']) ? md5($user[3]) : sql_prep($user[3]),
            sql_prep($user[4]),
            sql_prep($user[5]),
            sql_prep($user[6]),
            $groups[$user[4]]
        );
        mysql_query($sql);
        // Get back ther user's ID
        list($user_id) = mysql_fetch_row(mysql_query('SELECT LAST_INSERT_ID()'));

        // Insert record into core_acl_aro
        $sql = sprintf('
                INSERT INTO `%score_acl_aro`
                SET
                    `section_value`   = "users",
                    `value`           = %d,
                    `name`            = "%s"
            ',
            $table_prefix,
            $user_id,
            sql_prep($user[0])
        );
        mysql_query($sql);

        // Insert record into core_acl_groups_aro_map
        $sql = sprintf('
                INSERT INTO `%score_acl_groups_aro_map`
                SET
                    `group_id`        = %d,
                    `aro_id`          = LAST_INSERT_ID()
            ',
            $table_prefix,
            $groups[$user[4]]
        );
        mysql_query($sql);

        echo 'done.';
        flush();
    }

    echo '<br /><br /><strong>Done</strong>';


} else {
    // show upload form
    ?>
    <html><head><title>Bulk import users into Joomla 1.5</title></head><body>
    <h1>Import Users to Joomla</h1>
    <p>
        Use this script to do a bulk import of users into Joomla 1.5.<br />
        Upload a CSV file with the following format:<br />
        <code>
            name, username, email, password, usertype, block, send_email
        </code><br />
        Wrap details with commas in them in quotes.
    </p>
    <hr />
    <form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post" enctype="multipart/form-data"> 
        <input type="hidden" name="import" value="1" />
        <table cellpadding="4px">
            <tr>
                <td>CSV File: </td>
                <td><input type="file" name="csv" /></td>
            </tr>
            <tr>
                <td>MD5 Hash Passwords: </td>
                <td><input type="checkbox" name="md5_passwords" /><br /><small>*Check this option if the passwords in your CSV are in plain text</small></td>
            </tr>
            <tr>
                <td>Joomla Table Prefix: </td>
                <td><input type="text" name="table_prefix" value="jos_" /></td>
            </tr>
            <tr>
                <td>Joomla Database Name: </td>
                <td><input type="text" name="mysql_schema" value="joomla" /></td>
            </tr>
            <tr>
                <td>MySQL Host: </td>
                <td><input type="text" name="mysql_host" value="localhost" /></td>
            </tr>
            <tr>
                <td>MySQL Username: </td>
                <td><input type="text" name="mysql_username" value="" /></td>
            </tr>
            <tr>
                <td>MySQL Password: </td>
                <td><input type="text" name="mysql_password" value="" /></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" name="submit" value=" Import Users! " /></td>
            </tr>
        </table>
    </form>
    </body></html>
    <?php
}

function sql_prep($var) {
    return mysql_real_escape_string($var);
}

回答1:

I wrote this CLI application for bulk import from a table in the same database, you could adapt it to import from your CSV or you could import the CSV file into a database table. Anyway it will get you started, the whole thing is really different than 1.5.



回答2:

I could not find the right code for bulk user upload in Joomla 3. So I reworked the code to work with the new database structure.

It works starting with a simple CSV file:

    <?php

// Hande form upload
if(isset($_POST['import'])) 
    {

    $mysql_host             = trim($_POST['mysql_host']);
    $mysql_user             = trim($_POST['mysql_username']);
    $mysql_password         = trim($_POST['mysql_password']);
    $mysql_schema           = trim($_POST['mysql_schema']);
    $table_prefix           = trim($_POST['table_prefix']);


    if(!mysql_connect($mysql_host, $mysql_user, $mysql_password) || !mysql_select_db($mysql_schema)) {
        echo 'Supplied MySQL details were incorrect - aborting';
        return;
        }

        // set tablenames
        $tb_users = $table_prefix . 'users';
        $tb_usergroups = $table_prefix . 'usergroups';
        $tb_user_usergroup_map = $table_prefix . 'user_usergroup_map';

        // open cvs file
        $fp = fopen($_FILES['csv']['tmp_name'], 'r');

        // validate data
        $valid_data = true;
        while($user = fgetcsv($fp)) {

            // Verify name
            if(!isset($user[0])) {
                display_user('<br /><strong>ERROR!!! Invalid Name </strong><br />', $user);
                $valid_data = false;
            } elseif($user[0] == '') {
                display_user('<br /><strong>ERROR!!! Invalid Name </strong><br />', $user);
                $valid_data = false;
            }

            // Verify username
            if(!isset($user[1])) {
                display_user('<br /><strong>ERROR!!! Invalid username </strong><br />', $user);
                $valid_data = false;
            } elseif($user[1] == '') {
                display_user('<br /><strong>ERROR!!! Invalid username </strong><br />', $user);
                $valid_data = false;
            }

            // Verify email
            if(!isset($user[2])) {
                display_user('<br /><strong>ERROR!!! Invalid email </strong><br />', $user);
                $valid_data = false;
            } elseif($user[2] == '') {
                display_user('<br /><strong>ERROR!!! Invalid email </strong><br />', $user);
                $valid_data = false;
            }

            // Verify Password
            if(!isset($user[3])) {
                display_user('<br /><strong>ERROR!!! Invalid password </strong><br />', $user);
                $valid_data = false;
            } elseif($user[3] == '') {
                display_user('<br /><strong>ERROR!!! Invalid password </strong><br />', $user);
                $valid_data = false;
            }

            // Verify usergroup
            if(!isset($user[4])) {
                display_user('<br /><strong>ERROR!!! Invalid usergroup </strong><br />', $user);
                $valid_data = false;
            } elseif($user[4] == '') {
                display_user('<br /><strong>ERROR!!! Invalid usergroup </strong><br />', $user);
                $valid_data = false;
            }

            // Check duplicate username
            $sql = '
                    SELECT COUNT(*) AS duplicate_username
                    FROM    '.$tb_users.'
                    WHERE   username = "'.$user[1].'"'; 

            $result = mysql_query($sql);
            if (!$result) {
                die('Invalid query: ' . mysql_error());
            }

            while ($row = mysql_fetch_assoc($result)) {
                $duplicate_users = $row['duplicate_username'];
            }

            if ($duplicate_users > 0) {
                display_user('<br /><strong>ERROR!!! Duplicate username </strong><br />', $user);
                    $valid_data = false;
            }

            // Check duplicate email
            $sql = '
                    SELECT COUNT(*) AS duplicate_email
                    FROM    '.$tb_users.'
                    WHERE   email = "'.$user[2].'"'; 

            $result = mysql_query($sql);
            if (!$result) {
                die('Invalid query: ' . mysql_error());
            }

            while ($row = mysql_fetch_assoc($result)) {
                $duplicate_users = $row['duplicate_email'];
            }

            if ($duplicate_users > 0) {
                display_user('<br /><strong>ERROR!!! Duplicate email </strong><br />', $user);
                    $valid_data = false;
            }

    }


    if(!$valid_data) {
        die('<strong>CSV file contains errors. Upload Aborted!</strong>');
    } else {
        printf('<strong>Data is valid. Uploading users...</strong><br />');
    }


    // Count initial users
    $sql = '
            SELECT COUNT(*) AS initial_users
            FROM    '.$tb_users.'
           '
        ; 

    $result = mysql_query($sql);
    if (!$result) {
        die('Invalid query: ' . mysql_error());
    }

    while ($row = mysql_fetch_assoc($result)) {
        $initial_users = $row['initial_users'];
    }



    // Load users

    // open cvs file
    $fp = fopen($_FILES['csv']['tmp_name'], 'r');

    $counter = 0;
    while($user = fgetcsv($fp)) {


        // Check duplicate username
        $valid_username = true;
        $sql = '
                SELECT COUNT(*) AS duplicate_username
                FROM    '.$tb_users.'
                WHERE   username = "'.$user[1].'"'; 

        $result = mysql_query($sql);
        if (!$result) {
            die('Invalid query: ' . mysql_error());
        }

            while ($row = mysql_fetch_assoc($result)) {
            $duplicate_username = $row['duplicate_username'];
        }

        if ($duplicate_users > 0) {
            display_user('<br /><strong>ERROR!!! Duplicate username found in database</strong><br />', $user);
                $valid_username = false;
        }

        // Check duplicate email
        $valid_mail = true;
        $sql = '
                SELECT COUNT(*) AS duplicate_email
                FROM    '.$tb_users.'
                WHERE   email = "'.$user[2].'"'; 

        $result = mysql_query($sql);
        if (!$result) {
            die('Invalid query: ' . mysql_error());
        }

        while ($row = mysql_fetch_assoc($result)) {
            $duplicate_users = $row['duplicate_email'];
        }

        if ($duplicate_users > 0) {
            display_user('<br /><strong>ERROR!!! Duplicate email found in database</strong><br />', $user);
                $valid_mail = false;
        }

        if(!$valid_username or !$valid_mail) {
            printf('<strong>WARNING!!! User not uploaded</strong><br /><br />');
        } else {

            // Upload user
            display_user('<br />', $user);


            // Encypt password if required      
            $user_password = isset($_POST['md5_passwords']) ? md5($user[3]) : sql_prep($user[3]);

            // Insert record into users
            $sql = "
                INSERT INTO ".$tb_users." 
                SET
                    name            = '".sql_prep($user[0])."',
                    username        = '".sql_prep($user[1])."',
                    email           = '".sql_prep($user[2])."',
                    password        = '".$user_password."',
                    registerDate    = NOW(),
                    activation      = '',
                    params          = '{\"admin_style\":\"\",\"admin_language\":\"\",\"language\":\"\",\"editor\":\"\",\"helpsite\":\"\",\"timezone\":\"\"}',
                    otpKey          = '',
                    otep            = ''                
            ";

            $result = mysql_query($sql);
            if (!$result) {
                die('Invalid query: ' . mysql_error());
                }

           // Retrieve last uploaded user's ID
            list($user_id) = mysql_fetch_row(mysql_query('SELECT LAST_INSERT_ID()'));

            printf('Assigned user ID: '.$user_id.'<br />');


            // Insert record user_group_map
            $sql = '
                    INSERT INTO '.$tb_user_usergroup_map.'
                    SET
                        user_id   = '.$user_id.',
                        group_id  = '.$user[4].'
                   ';

            $result = mysql_query($sql);
            if (!$result) {
                die('Invalid query: ' . mysql_error());
                }

            echo 'done.<br />';
            flush();

        }

        // Update counter
        $counter++;

    }

    // Count final users
    $sql = '
            SELECT COUNT(*) AS final_users
            FROM    '.$tb_users.'
           '
        ; 

    $result = mysql_query($sql);
    if (!$result) {
        die('Invalid query: ' . mysql_error());
    }

    while ($row = mysql_fetch_assoc($result)) {
        $final_users = $row['final_users'];
    }


    if(($final_users - $initial_users) == $counter) {
        echo '<br /><br /><strong>Done. <br />
              Uploaded '.$counter.' users </strong>';
    } else {
        echo '<br /><br /><strong>ERROR!!! <br />
              Uploaded only some users</strong><br />
              Users submitted: '.$counter.'<br />
              Users uploaded : '.($final_users - $initial_users);
    }


} else {

    // show upload form
    ?>
    <html><head><title>Bulk import users into Joomla 3</title></head><body>
    <h1>Import Users to Joomla</h1>
    <p>
        Use this script to do a bulk import of users into Joomla 1.5.<br />
        Upload a CSV file with the following format:<br />
        <code>
            name, username, email, password, group_number
        </code><br />
        Wrap details with commas in them in quotes.
    </p>
    <hr />
    <form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post" enctype="multipart/form-data"> 
        <input type="hidden" name="import" value="1" />
        <table cellpadding="4px">
            <tr>
                <td>CSV File: </td>
                <td><input type="file" name="csv" /></td>
            </tr>
            <tr>
                <td>MD5 Hash Passwords: </td>
                <td><input type="checkbox" name="md5_passwords" /><br /><small>*Check this option if the passwords in your CSV are in plain text</small></td>
            </tr>
            <tr>
                <td>Joomla Table Prefix: </td>
                <td><input type="text" name="table_prefix" value="jos_" /></td>
            </tr>
            <tr>
                <td>Joomla Database Name: </td>
                <td><input type="text" name="mysql_schema" value="joomla" /></td>
            </tr>
            <tr>
                <td>MySQL Host: </td>
                <td><input type="text" name="mysql_host" value="localhost" /></td>
            </tr>
            <tr>
                <td>MySQL Username: </td>
                <td><input type="text" name="mysql_username" value="" /></td>
            </tr>
            <tr>
                <td>MySQL Password: </td>
                <td><input type="text" name="mysql_password" value="" /></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" name="submit" value=" Import Users! " /></td>
            </tr>
        </table>
    </form>
    </body></html>

    <?php

}

 function addJoomlaUser($name, $username, $password, $email, $defgroup) {




      jimport('joomla.user.helper');

      $data = array(
          "name"=>$name,
          "username"=>$username,
          "password"=>$password,
          "password2"=>$password,
          "email"=>$email,
          "block"=>0,
          "groups"=>array("1","2")
      );

      $user = new JUser;
      //Write to database
      if(!$user->bind($data)) {
          throw new Exception("Could not bind data. Error: " . $user->getError());
      }
      if (!$user->save()) {
          throw new Exception("Could not save user. Error: " . $user->getError());
      }

  return $user->id;
}

function sql_prep($var) {
    return mysql_real_escape_string($var);
}

function display_user($message, $user) {

//  printf('<p>'.$message.'</p>');
    printf($message);
    printf('Name: "%s" ... ', sql_prep($user[0]));
    printf('  Username: "%s" ... ', sql_prep($user[1]));
    printf('  Password: "%s" ... ', sql_prep($user[3]));
    printf('  Mail: "%s" ... ', sql_prep($user[2]));
    printf('  Group: "%s" ', sql_prep($user[4]));
    printf('<br />');

    return;

}

?>