<?PHP
#
#   FILE:  ExportUsersExecute.php
#
#   Part of the Collection Workflow Integration System (CWIS)
#   Copyright 2011-2013 Edward Almasy and Internet Scout Research Group
#   http://scout.wisc.edu/cwis/
#

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

/**
* Check if export is complete.
* @return bool TRUE if complete, otherwise FALSE.
*/
function ExportComplete()
{
    global $Session;

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

    return ($ExportComplete == 1) ? TRUE : FALSE;
}

/**
* Print count of users.
*/
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 ------------------------------------------------------

/**
* Initialize 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 CWUser($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;
    }
}

/**
* Get list of matching files.
* @param string $DirPath Directory path.
* @param string $Pattern Regular expression to match.
* @return array Matching file names.
*/
function ListDir($DirPath, $Pattern)
{
    static $ResultArray = array();

    $Handle = opendir($DirPath);
    while ($File = readdir($Handle))
    {
        if ($File == '.' || $File == '..')
        {
            continue;
        }
        if (is_dir($DirPath.$File))
        {
            continue;
        }
        elseif (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)
{
    $AF->SetJumpToPage("index.php?P=ExportUsersExecute", 1);
}

PageTitle("Export Users");

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

/**
* Post-processing call, to close file pointer after export is complete.
* @param mixed $FP File pointer.
* @param book $ExportComplete If 1, export is complete.
*/
function PostProcessingFn($FP, $ExportComplete)
{
    if ($ExportComplete == 1)
    {
        fclose($FP);
    }
}
