Extension talk:ImportUsers

From MediaWiki.org

Jump to: navigation, search

Contents

[edit] History

[edit] Version 0.0.3

  • Blank line handling corrected (used to produce error message)
  • Added "UTF-8" to upload control label to suggest that import file should be UTF-8 encoded

[edit] Version 0.0.2

  • Initial public release

[edit] Compatible with Version 1.8.2

Hi, I wanted to know if this Extension is also working with MediaWiki 1.8.2.

Please contact me: claudia.oswald@gmail.com

THX

[edit] Tested with 1.10 - OK!

  • a single test on a siteground hosted site. - works fine -
  • needed to make the minor fix to the message that displays the data format (see below).

[edit] Added features to code - only tested with 1.9.3

I added some functionality to this version - and don't know whether I should post as new or just let the original authors decide. These features allow users to be imported, notified, and automatically assigned to groups as they are loaded. --Jpond 22:16, 27 March 2007 (UTC)

The additional features are:

  1. Gives option to send email notifying added users as they are imported (if notification is enabled on wiki)
  2. Add user to specified group when adding if box is checked

For imported user to be added to a group the following must be true:

  1. Logged on user importing must have 'userrights'
  2. The user must have checked the "Add users to groups" box
  3. The CSV line must have a group to add to(e.g. approved)
  4. The permission requested must be one of the available groups - does not create a new group
  5. The user has not already been assigned to that group

If you wanted to add the user(s) to more than one group, you could rerun the import after changing the group in the CSV file, then use the 'Update existing users' checkbox.


The CSV now has up to five columns (first 2 required):

  1. username
  2. password
  3. email
  4. real name
  5. add to this group [must be existing group]

Delimited with commas. For an example:


user1,pass1,user1@gmail.com,User One, Group 1
user2,pass2,user2@gmail.com,User Two, Group 2
user3,pass3,user3@gmail.com,User Three, Group 3
user4,pass4,user4@gmail.com,User Four, Group 4
user5,pass5,user5@gmail.com,User Five, Group 5
user6,pass6,user6@gmail.com,User Six, Group 6
.
.
.
userN,passN,userN@gmail.com,User Nnn, Group nnn

[edit] New, Modified Code - Tested on MediaWiki V 1.9.3

--Jpond 23:11, 27 March 2007 (UTC)

<?php

if (!defined('MEDIAWIKI')) die();
require_once "$IP/includes/SpecialPage.php";

$wgExtensionFunctions[] = 'wfSpecialImportUsers';
$wgExtensionCredits['specialpage'][] = array(
  'name' => 'Import Users',
  'author' =>'Yuriy Ilkiv, Rouslan Zenetl',
  'description' => 'Imports users in bulk from CSV-file; encoding: UTF-8',
);

$wgAvailableRights[] = 'import_users';
$wgGroupPermissions['bureaucrat']['import_users'] = true;

function wfSpecialImportUsers() {
  global $IP, $wgMessageCache;

  $wgMessageCache->addMessages(
    array(
      'importusers' => 'Import Users' ,
      'importusers_form_caption' => 'Input CSV-file (UTF-8)' ,
      'importusers_form_replace_present' => 'Update existing users ' ,
 # Added by Jack D. pond
      'importusers_form_send_email' => 'Send Email to Users' ,
      'importusers_form_add_to_group' => 'Add users to groups (must have userrights)' ,
 # End Add
     'importusers_form_button' => 'Import' ,
      'importusers_user_added' => 'User <b>%s</b> has been added.' ,
      'importusers_user_present_update' => 'User <b>%s</b> already exists. Updated.' ,
      'importusers_user_present_not_update' => 'User <b>%s</b> already exists. Did not update.' ,
      'importusers_user_invalid_format' => 'User data in the line #%s has invalid format or is blank. Skipped.' ,
# Jack D. Pond added next line for invalid email notification
      'importusers_user_invalid_email' => 'User data in the line #%s has invalid email or is blank. Skipped.' ,
      'importusers_log' => 'Import log' ,
      'importusers_log_summary' => 'Summary' ,
      'importusers_log_summary_all' => 'All' ,
      'importusers_log_summary_added' => 'Added' ,
      'importusers_log_summary_updated' => 'Updated', 
# Jack D. Pond added next 2 lines for email notification counts
      'importusers_log_summary_email_sent' => 'Email Notifications Sent' ,
      'importusers_log_summary_email_failed' => 'Email Notifications Failed' ));     

  class SpecialImportUsers extends SpecialPage {

    function SpecialImportUsers() {
      SpecialPage::SpecialPage('ImportUsers' , 'import_users' );
    }
                
    function execute( $par ) {
      global $wgOut, $wgUser;
      $wgOut->setArticleRelated( false );
      if( !$wgUser->isAllowed( 'import_users' ) ) {
        $wgOut->permissionRequired( 'import_users' );
        return;
      }
      $wgOut->setPagetitle( wfMsg( 'importusers' ) );
      if (IsSet($_FILES['users_file'])) {
        $wgOut->addHTML( $this->AnalizeUsers($_FILES['users_file'],IsSet($_POST['replace_present']),IsSet($_POST['send_email']),IsSet($_POST['add_to_group'])) );
      } else {
        $wgOut->addHTML( $this->MakeForm() );
      }
    }

    function MakeForm() {
      $titleObj = Title::makeTitle( NS_SPECIAL, 'ImportUsers' );
      $action = $titleObj->escapeLocalURL();
      $output ='<form enctype="multipart/form-data" method="post"  action="'.$action.'">';
      $output.='<dl><dt>User file format (csv): </dt><dd><login-name>,<password>,<email>,<real-name></dd></dl>';
      $output.='<fieldset><legend>Upload file</legend>';
      $output.='<table border=0 a-valign=center width=100%>';
      $output.='<tr><td align=right width=160>'.wfMsg( 'importusers_form_caption' ).': </td><td><input name="users_file" type="file" size=40 /></td></tr>';
# Jack D. Pond changed line to add send email and ask if add user to groups (if in file)
      $output.='<tr><td align=right></td><td><input name="replace_present" type="checkbox" />'.wfMsg( 'importusers_form_replace_present' ).'<input name="send_email" type="checkbox" />'.wfMsg( 'importusers_form_send_email' ).'</td></tr>';
      $output.='<tr><td align=right></td><td><input name="add_to_group" type="checkbox" />'.wfMsg( 'importusers_form_add_to_group' ).'</td></tr>';
# End change
      $output.='<tr><td align=right></td><td><input type="submit" value="'.wfMsg( 'importusers_form_button' ).'" /></td></tr>';
      $output.='</table>';
      $output.='</fieldset>';
      $output.='</form>';
      return $output;
    }

    function AnalizeUsers($fileinfo,$replace_present,$importusers_send_email,$importusers_add_to_group) {
      global $IP, $wgOut, $wgEmailAuthentication ;
# Jack D. Pond added global $wgEmailAuthentication

      require_once "$IP/includes/User.php";
# Jack D. Pond added email_sent and email_failed counters to array
      $summary=array('all'=>0,'added'=>0,'updated'=>0,'email_sent'=>0,'email_failed'=>0);

      $filedata=explode("\n",rtrim(file_get_contents($fileinfo['tmp_name'])));
      $output='<h2>'.wfMsg( 'importusers_log' ).'</h2>';
      foreach ($filedata as $line=>$newuserstr) {
        $newuserarray=explode(',', trim( $newuserstr ) );
        if (count($newuserarray)<2) {
          $output.=sprintf(wfMsg( 'importusers_user_invalid_format' ) ,$line+1 ).'<br />';
          continue;
        }
        if (!IsSet($newuserarray[2])) $newuserarray[2]='';
        if (!IsSet($newuserarray[3])) $newuserarray[3]='';        
        $NextUser=User::newFromName( $newuserarray[0] );
        $NextUser->setEmail( $newuserarray[2] );
        $NextUser->setRealName( $newuserarray[3] );
        $uid=$NextUser->idForName();
        if ($uid===0) {
                        $NextUser->addToDatabase();
                        $NextUser->setPassword( $newuserarray[1] );
                        $NextUser->saveSettings();
# Added line to import user group assignment too
                        $this->AddToGroup($NextUser,$newuserarray,$importusers_add_to_group);
          
# Extended by Jack D. Pond to send email notifications to users (if enabled)
         
                        if( $wgEmailAuthentication && $importusers_send_email && User::isValidEmailAddr( $NextUser->getEmail() ) ) 
                        {
                                global $wgOut;
                                $error = $NextUser->sendConfirmationMail();
# May want to delete here to end of extend if not using email addresses in import
                                if( WikiError::isError( $error ) )
                                {
                                        $output.=sprintf(wfMsg( 'importusers_user_invalid_email' ) ,$line+1 ).'<br />';
                                        $summary['email_failed']++;
                                } else 
                                {
                                        $summary['email_sent']++;
                                }
                        }
# End Extend
          
          
          
          $output.=sprintf(wfMsg( 'importusers_user_added' ) ,$newuserarray[0] ).'<br />';
          $summary['added']++;
        }
        else {
          if ($replace_present) {
            $NextUser->setPassword( $newuserarray[1] );
            $NextUser->saveSettings();
# Added line to import user group assignment too
                        $this->AddToGroup($NextUser,$newuserarray,$importusers_add_to_group);
                        
            $output.=sprintf( wfMsg( 'importusers_user_present_update' ) ,$newuserarray[0] ).'<br />';
            $summary['updated']++;
          }
          else $output.=sprintf(wfMsg( 'importusers_user_present_not_update' ) ,$newuserarray[0] ).'<br />';
        }
        $summary['all']++;
      }
      $output.='<b>'.wfMsg( 'importusers_log_summary' ).'</b><br />';
      $output.=wfMsg( 'importusers_log_summary_all' ).': '.$summary['all'].'<br />';
      $output.=wfMsg( 'importusers_log_summary_added' ).': '.$summary['added'].'<br />';
      $output.=wfMsg( 'importusers_log_summary_updated' ).': '.$summary['updated'].'<br />';
# Extended by Jack D. Pond to inform importer if any email addresses didn't check out
      $output.=wfMsg( 'importusers_log_summary_email_sent' ).': '.$summary['email_sent'].'<br />';
      $output.=wfMsg( 'importusers_log_summary_email_failed' ).': '.$summary['email_failed'];
# Extension end
      return $output;
    }

# Extension by Jack D. Pond that adds imported user to the group in the last parameter in the line (4)
# under the following conditions:
#
# Logged on user importing must have 'userrights'
# The user must have checked the "Add users to groups" box
# The CSV line must have a group to add to(e.g. approved)
# The permission requested must be one of the available groups - does not create a new group
# The user has not already been assigned to that group
#
        function AddToGroup($u,$user_array,$add_to_group_checked){
                global $wgOut, $wgUser;
                if( $wgUser->isAllowed( 'userrights' ) && $add_to_group_checked && IsSet($user_array[4])) {
                        if ( in_array($user_array[4],User::getAllGroups())){
                                if ( !in_array($user_array[4],$u->getGroups())){
                                        $u->addGroup( $user_array[4] );
                                }
                        }
                }
        }
  }

  SpecialPage::addPage (new SpecialImportUsers());
}

?>

[edit] Added Bonus - MS Excel Template for creating CSV with password generator

This password generator might be of use to others.

The second tab is a template for creating csv file using MS Excel. You would use this template and use the file->save as->type=(.csv). Gives a couple of funky messages - but you'll be able to figure those out.

The first tab will actually generate random (or at least as random as MS Excel will allow) passwords. Code is signed.

Hope this helps someone else out. --Jpond 01:29, 29 March 2007 (UTC)


[edit] Minor Code Edit

The line:

$output.='<dl><dt>User file format (csv): </dt><dd>&lt;login-name&gt;,&lt;password&gt;,&lt;email&gt;,&lt;real-name&gt;</dd></dl>';

was being rendered as:

$output.='<dl><dt>User file format (csv): </dt><dd><login-name>,<password>,<email>,<real-name></dd></dl>';

which, when copy-pasted out, was causing the user file format to appear as ",,," on the Special:ImportUsers page. I edited it to read:

$output.='<dl><dt>User file format (csv): </dt><dd>&amp;lt;login-name&amp;gt;,&amp;lt;password&amp;gt;,&aamp;mp;lt;email&amp;gt;,&amp;lt;real-name&amp;gt;</dd></dl>';

so it would render correctly when copy-pasted.

--Swalsh 23:31, 15 May 2007 (UTC)

[edit] Header information already sent bug. (WM 1.11) Solved

My mediawiki 1.11 gives errors:

Warning: Cannot modify header information - headers already sent by (output started at 
*/wiki/extensions/ImportUser/SpecialImportUser.php:1) in 
*/wiki/includes/WebResponse.php on line 10

Could not find anything relating to this warning... I know production servers have warnings mostly disabled, but imho good script should never yeld warnings.

Anybody suggestions?

Kaspera 12:10, 22 October 2007 (UTC)

Solved after reading this article about a byte-order mark issue. This solved many other issues with headers already sent. Hope this helps other a lot of headache! Kaspera 09:25, 27 November 2007 (UTC)

[edit] Problem running with MW 1.11.0

I copied the code from the extension page, and followed the installation instructions. I run and get the error below.

The website cannot display the page

  HTTP 500  

Most likely causes:

* The website is under maintenance. 
* The website has a programming error.  

I checked the logs, but there are no details there. Any suggestions on how to fix this?

TIA Alex Abramov (alexa at avid-tech dot com)

Version Info: MediaWiki: 1.11.0 PHP: 5.2.3 (cgi-fcgi) MySQL: 5.0.24-community-nt

[edit] Problems with 1.12 final

I have an incompatibility with my MW 1.12 final version. When I require the ImportUsers extension, my MediaWiki crashes every time, showing only a blank page. I verified the path... I don't think the problem is on my side.--Rmatt 17:14, 21 March 2008 (UTC)

Same here, it looks for ExtensionFunctions.php, does not find it and aborts. fix it by putting http://svn.wikimedia.org/svnroot/mediawiki/trunk/extensions/ExtensionFunctions.php into your Extensions folder. 193.175.73.201 14:28, 28 March 2008 (UTC)

Thanks, it solved the problem for me too !
Personal tools