<?PHP
#
#   FILE:  ExportUsersExecute.php
#
#   FUNCTIONS PROVIDED:
#       ExportComplete()
#       PrintResourceCount()
#       PrintExportLink()
#
#   FUNCTIONS EXPECTED:
#       None
#
#   Part of the Collection Workflow Integration System (CWIS)
#   Copyright 2011 Internet Scout Project
#   http://scout.wisc.edu/
#

# ----- EXPORTED FUNCTIONS ---------------------------------------------------

# see if export is complete
function ExportComplete()
{
    global $Session;

    $ExportComplete = $Session->Get("ExportComplete");

    return ($ExportComplete == 1) ? true : false;
}

# print Resource Count
function PrintUserCount()
{
    global $Session;

    print $Session->Get("UserCount");
}

# print link to downloadable exported file
function PrintExportLink()
{
    global $Session;

    print "<a href=\"".$Session->Get("FileName")."\">";
}

# ----- LOCAL FUNCTIONS ------------------------------------------------------

# init variables -- first time thru they will be null
function InitExportVars()
{
    global $DB, $ExportComplete, $UserCount;

    if (is_null($ExportComplete))
        $ExportComplete = 0;
    if (is_null($UserCount))
        $UserCount = 0;

    $DB->Query("Select * from APUsers Limit $UserCount, 50");
    if ($DB->NumRowsSelected() == 0)
        $ExportComplete = 1;
}

# do/while loop, this is the main event
function DoWhileLoop()
{
    global $DB, $DB1, $FP, $Session, $ExportComplete;
    global $UserCount, $FSeek, $TotalLineCount;
    global $PrivDescriptions;

    $Schema = new MetadataSchema();

    while ($Entry = $DB->FetchRow())
    {
        if ($Entry["BrowsingFieldId"] > 0)
        {
            $Field = $Schema->GetField($Entry["BrowsingFieldId"]);
            if (is_object($Field))
                $BrowsingField = $Field->Name();
            else
                $BrowsingField = NULL;
        }
        else
            $BrowsingField = NULL;

        $Output = $Entry["UserName"]."\t".
                  $Entry["UserPassword"]."\t".
                  $Entry["EMail"]."\t".
                  $Entry["WebSite"]."\t".
                  $Entry["RealName"]."\t".
                  $Entry["AddressLineOne"]."\t".
                  $Entry["AddressLineTwo"]."\t".
                  $Entry["City"]."\t".
                  $Entry["State"]."\t".
                  $Entry["Country"]."\t".
                  $Entry["ZipCode"]."\t".
                  $Entry["ActiveUI"]."\t".
                  $BrowsingField."\t\n";

        fwrite($FP, $Output);
        $UserCount++;

        # now export privileges for this user
        $UserName = $Entry["UserName"];
        $NewUser = new User($DB1, $UserName);
        $PrivList = $NewUser->GetPrivList();

        foreach ($PrivList as $Privilege)
        {
            if (is_numeric($Privilege))
            {
                $Privilege = $PrivDescriptions[$Privilege];
                $Output = $UserName."\t\t\t\t\t\t\t\t\t\t\t\t\t".
                            $Privilege."\n";
                fwrite($FP, $Output);
            }
        }
    }
    if ($UserCount % 50 != 0)
        $ExportComplete = 1;
}

# function to get list of matching files
function ListDir($DirPath, $Pattern)
{
    static $ResultArray = array();

    $Handle = opendir($DirPath);
    while ($File = readdir($Handle))
    {
        if ($File == '.' || $File == '..')
            continue;
        if (is_dir($DirPath.$File))
            continue;
        else if (preg_match($Pattern, $File))
            $ResultArray[]=$DirPath.$File;
    }
    closedir($Handle);
    return $ResultArray;
}

# ----- MAIN -----------------------------------------------------------------

# non-standard global variables
global $DB1;
global $ExportComplete;
global $FP;
global $FSeek;
global $PrivDescriptions;
global $TotalLineCount;
global $UserCount;

# check if current user is authorized
if (!CheckAuthorization(PRIV_SYSADMIN, PRIV_USERADMIN)) {  return;  }

$DB = new Database();
$DB1 = new Database();

if (isset($_POST["Submit"]) && $_POST["Submit"] == "Cancel")
{
    $AF->SetJumpToPage("SysAdmin");
    return;
}

InitExportVars();

# open export path
$ExportPath = $Session->Get("ExportPath");
if (is_null($ExportPath))
{
    $ScriptFileName = GetFullScriptFileName();
    $FileName = "tmp/Users_".date("YmdHis").".txt";
    $ExportPath = dirname($ScriptFileName)."/".$FileName;

    # remove any old exported files
    $OldExportFiles = ListDir(dirname($ScriptFileName)."/".
        "tmp/", "/^Users_.*\.txt$/");

    if (is_array($OldExportFiles))
    {
        foreach ($OldExportFiles as $OldFile)
        {
            unlink($OldFile);
        }
    }
}

$FP = fopen($ExportPath, "a");
if ($FP == FALSE)
{
    $ErrorMessage = "Cannot open Export Filename: $ExportPath<br>";
    $Session->PassVariable("ErrorMessage", $ErrorMessage);
    $AF->SetJumpToPage("DisplayError");
    return;
}

# the main work happenes here
DoWhileLoop();

$Session->PassVariable("ExportComplete", $ExportComplete);
$Session->PassVariable("UserCount", $UserCount);
$Session->PassVariable("FileName", $FileName);
$Session->PassVariable("TotalLineCount", $TotalLineCount);
$Session->PassVariable("ExportPath", $ExportPath);

#  Time to auto-refresh?
if ($ExportComplete == 0)
{
    $AutoRefreshToPage = "index.php?P=ExportUsersExecute";
}

PageTitle("Export Users");

# register post-processing function with the application framework
$AF->AddPostProcessingCall("PostProcessingFn", $FP, $ExportComplete);

# post-processing call
function PostProcessingFn($FP, $ExportComplete)
{
    if ($ExportComplete == 1)
    {
        fclose($FP);
    }
}
