Example #1
0
/**
 * InitializeWork
 *
 * Creates a unique work directory for this run.
 *
 * @return 0 on success
 *         1 If base temp path isn't a directory
 *         2 If it was unable to create a temp directory
 *         3 base temp directory could not be created
 */
function InitializeWork()
{
    // Make sure the temp dir exists
    $sTmpPath = Config::GetPath("tmp");
    if (!file_exists($sTmpPath)) {
        if (mkdir($sTmpPath) === FALSE) {
            return 3;
        }
    }
    // Can we use the tmp dir?
    if (!is_dir($sTmpPath)) {
        print "Cannot access " . $sTmpPath;
        return 1;
    }
    // We have to make SURE that we can share this directory with
    // the other parts of the system (such as web and/or script)
    chmod($sTmpPath, 0777);
    // Randomly create a new directory name
    $i = 0;
    $bSuccess = false;
    do {
        $sRandom = "/" . md5(time() . mt_rand() . $i);
        if (!file_exists($sTmpPath . $sRandom)) {
            if (mkdir($sTmpPath . $sRandom) === FALSE) {
                // Hmm, unable to create the dir, someone beat us to it?
                $i++;
            } else {
                $bSuccess = true;
            }
        } else {
            // Already exists, try another one
            $i++;
        }
    } while ($i < 1000 && !$bSuccess);
    if ($bSuccess) {
        // Store the new tmp path
        $sTmpPath .= $sRandom;
    } else {
        // In the unlikely situation that we kept colliding with other
        return 2;
    }
    Config::SetPath("tmp", $sTmpPath);
    return 0;
}