Example #1
0
/**
 * Log a Ping request
 * 
 * @param string $hostname Host to ping
 * @param string $fileLog  Filename for the output
 * @param string $dirLog   Directory where to create the filelog
 * 
 * @return void
 */
function logPing($hostname, $fileLog, $dirLog)
{
    announce_script("Ping logger");
    // Make the log line
    $dt = date('Y-m-d\\TH:i:s');
    if ($hostname === "") {
        $hostname = "localhost";
    }
    $ping = shell_exec("ping " . $hostname . " -c 4 | tr -s '\n' | tail -n 1");
    if (check_errs($ping, null, "Failed to ping", "Ping successful!")) {
        // Log the line
        if ($dirLog === "") {
            $dirLog = "/var/log/ping";
        }
        if ($fileLog === "") {
            $file = $dirLog . "/" . $hostname . ".log";
        } else {
            $file = $dirLog . "/" . $fileLog;
        }
        force_dir($dirLog);
        $fic = fopen($file, "a+");
        if (check_errs($fic, false, "Failed to open log file", "Log file opened at " . $file . "!")) {
            fwrite($fic, $dt . " " . $ping);
            fclose($fic);
        }
    }
}
Example #2
0
/**
 * The request function
 * 
 * @param string $url  URL to request
 * @param string $log  Log file
 * @param string $file Output file
 * 
 * @return void
 */
function mediboard_request($url, $log, $file)
{
    if ($file === "") {
        exec("wget \"" . $url . "\" --append-output=" . $log . " --force-directories --no-check-certificate", $request, $return_var);
        check_errs($return_var, true, "Failed to request to Mediboard", "Mediboard requested!");
        echo "Requested URL: " . $url . "\n";
    } else {
        exec("wget \"" . $url . "\" --append-output=" . $log . " --force-directories --no-check-certificate -O " . $file, $request, $return_var);
        check_errs($return_var, true, "Failed to request to Mediboard", "Mediboard requested!");
        echo "Requested URL: " . $url . "\n";
    }
}
Example #3
0
/**
 * Rotate MySQL Binlogs
 * 
 * @param string $userAdminDB         MySQL username allowed to connect, ie admin
 * @param string $passAdminDB         Password of the MySQL user
 * @param string $binLogsDir          Directory where binlogs are stored, ie /var/log/mysq
 * @param string $binLogIndexFilename Name of the binlog-index file, ie log-bin.index
 * @param string $backup              Backup directory, ie /mbbackup/binlogs
 * 
 * @return void
 */
function rotateBinlogs($userAdminDB, $passAdminDB, $binLogsDir, $binLogIndexFilename, $backup)
{
    $currentDir = dirname(__FILE__);
    announce_script("Rotate binlogs");
    if ($userAdminDB === "") {
        $userAdminDB = "mbadmin";
    }
    if ($binLogsDir === "") {
        $binLogsDir = "/var/log/mysql";
    }
    if ($binLogIndexFilename === "") {
        $binLogIndexFilename = "log-bin.index";
    }
    if ($backup === "") {
        $backup = "/mbbackup/binlogs";
    }
    // Backup destination dir
    force_dir($backup);
    // Flush logs to start a new one
    if ($passAdminDB === "") {
        echo shell_exec("mysqladmin -u " . $userAdminDB . " flush-logs");
    } else {
        echo shell_exec("mysqladmin -u " . $userAdminDB . " -p" . $passAdminDB . " flush-logs");
    }
    // Move all logs but latest to backup
    $binLogFiles = file($binLogsDir . "/" . $binLogIndexFilename);
    check_errs($binLogFiles, false, "Impossible d'ouvrir le fichier " . $binLogsDir . "/" . $binLogIndexFilename, "Fichier " . $binLogsDir . "/" . $binLogIndexFilename . " ouvert !");
    $lastBinLogFile = trim(end($binLogFiles));
    $binPrefixPOS = strpos(basename($lastBinLogFile), ".");
    $binPrefix = substr(basename($lastBinLogFile), 0, $binPrefixPOS + 1);
    foreach (glob(dirname($lastBinLogFile) . "/" . $binPrefix . "*") as $oneBinLogFile) {
        if ($oneBinLogFile != $lastBinLogFile) {
            rename($oneBinLogFile, $backup . "/" . basename($oneBinLogFile));
        }
    }
    // Move binlog indexes to binlog backup
    copy($binLogsDir . "/" . $binLogIndexFilename, $backup . "/" . $binLogIndexFilename);
    // Archive the binlogs
    exec("tar -cjf " . $backup . "/binlogs_" . date('Y-m-d\\TH:i:s') . ".tar.bz2 -C " . $backup . " " . $binPrefix . "*", $result, $returnVar);
    // Rotate binlogs
    foreach (glob($backup . "/" . $binPrefix . "*") as $aBinLogFile) {
        unlink($aBinLogFile);
    }
    // Rotate binlogs and indeces for a week
    shell_exec("find {$backup} -name \"*bin.*\" -mtime +7 -exec rm -f {} \\;");
    shell_exec("find {$backup} -name \"binlog-*.index\" -mtime +7 -exec rm -f {} \\;");
    shell_exec("find {$backup} -name \"binlogs_*.tar.bz2\" -mtime +7 -exec rm -f {} \\;");
}
Example #4
0
/**
 * Log the Uptime of a server
 * 
 * @param string $file     Target to log
 * @param string $hostname Hostname for uptime
 * 
 * @return void
 */
function logUptime($file, $hostname)
{
    announce_script("Uptime logger");
    // Make the log line
    $dt = date('Y-m-d\\TH:i:s');
    if ($hostname == "localhost" || $hostname == "") {
        $up = shell_exec("uptime | sed 's/\\(.*\\): \\([0-9.]*\\)[,]* \\([0-9.]*\\)[,]* \\([0-9.]*\\)/1mn:\\2\\t5mn:\\3\\t15mn:\\4/'");
    } else {
        $up = shell_exec("ssh " . $hostname . " uptime | sed 's/\\(.*\\): \\([0-9.]*\\)[,]* \\([0-9.]*\\)[,]* \\([0-9.]*\\)/1mn:\\2\\t5mn:\\3\\t15mn:\\4/'");
    }
    if (check_errs($up, null, "Failed to get uptime", "Uptime successful!")) {
        // Log the line
        if ($file === "") {
            $file = "/var/log/uptime.log";
        }
        $fic = fopen($file, "a+");
        if (check_errs($fic, false, "Failed to open log file", "Log file opened at " . $file . "!")) {
            fwrite($fic, $hostname . ": " . $dt . " " . $up);
            fclose($fic);
        }
    }
}
Example #5
0
/**
 * Update Mediboard
 * 
 * @param string $action   action to perform: info|real|noup
 * @param string $revision revision number you want to update to
 * 
 * @return void
 */
function update($action, $revision)
{
    $currentDir = dirname(__FILE__);
    announce_script("Mediboard SVN updater");
    $MB_PATH = $currentDir . "/..";
    $log = $MB_PATH . "/tmp/svnlog.txt";
    $tmp = $MB_PATH . "/tmp/svnlog.tmp";
    $dif = $MB_PATH . "/tmp/svnlog.dif";
    $status = $MB_PATH . "/tmp/svnstatus.txt";
    $event = $MB_PATH . "/tmp/monitevent.txt";
    $prefixes = array("erg", "fnc", "fct", "bug", "war", "edi", "sys", "svn");
    if ($revision === "") {
        $revision = "HEAD";
    }
    // Choose the target revision
    switch ($action) {
        case "info":
            $out = array();
            exec("svn info {$MB_PATH}", $out, $ret);
            if (check_errs($ret, null, "SVN info error", "SVN info successful!")) {
                echo $out[5] . "\n";
            }
            $out = array();
            exec("svn log {$MB_PATH} -r BASE:{$revision}", $out, $ret);
            if (check_errs($ret, null, "SVN log error", "SVN log successful!")) {
                $out = filter_commit_messages($out);
                echo implode("\n", $out) . "\n";
            }
            $out = array();
            exec("svn info {$MB_PATH} -r {$revision}", $out, $ret);
            if (check_errs($ret, null, "SVN info error", "SVN info successful!")) {
                echo $out[5] . "\n";
            }
            break;
        case "real":
            // Concat the source (BASE) revision number : 5th line of SVN info (!)
            $out = array();
            exec("svn info {$MB_PATH}", $out, $ret);
            if (check_errs($ret, null, "Failed to get source revision info", "SVN Revision source info written!")) {
                $fic = fopen($tmp, "w");
                if (check_errs($fic, false, "Failed to open tmp file", "Tmp file opened!")) {
                    fwrite($fic, $out[5] . "\n");
                    fclose($fic);
                }
            }
            // Concat SVN Log from BASE to target revision
            $out = array();
            exec("svn log {$MB_PATH} -r BASE:{$revision}", $out, $ret);
            if (check_errs($ret, null, "Failed to retrieve SVN log", "SVN log retrieved!")) {
                $fic = fopen($dif, "w");
                if (check_errs($fic, false, "Failed to open dif file", "Dif file opened!")) {
                    fwrite($fic, implode("\n", $out) . "\n");
                    fclose($fic);
                    $fic = fopen($dif, "r");
                    $fic2 = fopen($tmp, "a+");
                    // TODO: use filter_commit_messages()
                    while (!feof($fic)) {
                        $buffer = fgets($fic);
                        if (preg_match("/(erg:|fnc:|fct:|bug:|war:|edi:|sys:|svn:)/i", $buffer)) {
                            fwrite($fic2, $buffer);
                        }
                    }
                    fclose($fic);
                    fclose($fic2);
                    echo "SVN log parsed!\n";
                    unlink($dif);
                }
            }
            // Perform actual update
            $out = array();
            exec("svn update {$MB_PATH} --revision {$revision}", $out, $ret);
            echo implode("\n", $out) . "\n";
            check_errs($ret, null, "Failed to perform SVN update", "SVN update performed!");
            // Concat the target revision number
            $fic = fopen($tmp, "a+");
            $out = array();
            exec("svn info {$MB_PATH}", $out, $ret);
            if (check_errs($ret, null, "Failed to get target revision info", "SVN Revision target info written!")) {
                fwrite($fic, "\n" . implode("\n", $out));
                fclose($fic);
            }
            // Contact dating info
            $fic = fopen($tmp, "a+");
            fwrite($fic, "--- Updated Mediboard on " . strftime("%Y-%m-%d %H:%M:%S") . " ---\n");
            fclose($fic);
            // Concat tmp file to log file //
            // Ensure log file exists
            force_file($log);
            // Log file is reversed, make it straight
            shell_exec("tac " . $log . " > " . $log . ".straight");
            // Concat tmp file
            shell_exec("cat " . $tmp . " >> " . $log . ".straight");
            // Reverse the log file for user convenience
            shell_exec("tac " . $log . ".straight > " . $log);
            // Clean files
            unlink($log . ".straight");
            unlink($tmp);
            // Write status file
            $svn = shell_exec("svn info " . $MB_PATH . " | awk 'NR==5'");
            if (check_errs($svn, null, "Failed to write status file", "Status file written!")) {
                $fic = fopen($status, "w");
                fwrite($fic, $svn . "Date: " . strftime("%Y-%m-%d %H:%M:%S") . "\n");
                fclose($fic);
                if (file_exists($event)) {
                    $fic = fopen($event, "a");
                } else {
                    $fic = fopen($event, "w");
                }
                fwrite($fic, "\n#" . date('Y-m-d H:i:s'));
                fwrite($fic, "\nMise a jour. " . $svn);
                fclose($fic);
            }
            break;
    }
}
Example #6
0
/**
 * Not tested
 * 
 * @param string $libName Library name
 * @param string $url     URL where library can be found
 * @param string $version Version to get
 * 
 * @return void
 */
function package_lib($libName, $url, $version)
{
    echo "Retrieve dompdf from " . $url . "\n";
    $svn = shell_exec("svn co " . $url . " tmp/" . $libName);
    if (check_errs($svn, null, "Failed to check out SVN", "SVN check out successful!")) {
        $svn = shell_exec("tar cfz tmp/" . $libName . "-" . $version . ".tar.gz --directory ./tmp/ " . $libName . " --exclude=.svn");
        if (check_errs($svn, 1, "Failed to load package " . $libName, $libName . "packaged!")) {
            echo shell_exec("mv ./tmp/" . $libName . "-" . $version . ".tar.gz libpkg/") . "\n";
        }
    }
}
Example #7
0
/**
 * Update Mediboard with RSYNC
 * 
 * @param string $action   Action to perform: info|real|noup
 * @param string $revision Revision number you want to update to
 * 
 * @return void
 */
function rsyncupdate($action, $revision)
{
    $currentDir = dirname(__FILE__);
    announce_script("Mediboard SVN updater and rsyncer");
    if ($revision === "") {
        $revision = "HEAD";
    }
    // Choose the target revision
    switch ($action) {
        case "info":
            update("info", $revision);
            break;
        case "real":
            update("real", $revision);
            break;
    }
    // File must exists (touch doesn't override)
    touch("rsyncupdate.exclude");
    if ($action != "info") {
        // Rsyncing -- Parsing rsyncupdate.conf
        $lines = file($currentDir . "/rsyncupdate.conf");
        foreach ($lines as $line_num => $line) {
            // Skip comment lines and empty lines
            if (trim(substr($line, 0, 1)) != "#" && trim(substr($line, 0, 1)) != "") {
                $line = trim($line);
                echo "Do you want to update " . $line . " (y or n) [default n] ? ";
                $answer = trim(fgets(STDIN));
                if ($answer === "y") {
                    echo "-- Rsync " . $line . " --\n";
                    $usernamePOS = strpos($line, "@");
                    if ($usernamePOS) {
                        $hostnamePOS = strpos($line, ":", $usernamePOS);
                        if ($hostnamePOS) {
                            $username = substr($line, 0, $usernamePOS);
                            $hostname = substr($line, $usernamePOS + 1, $hostnamePOS - ($usernamePOS + 1));
                        }
                    }
                    if ($usernamePOS == false) {
                        // Local folder
                        $dirName = $line;
                        $rsync = shell_exec("rsync -avpz --stats " . $currentDir . "/.. --delete " . $line . " --exclude-from=" . $currentDir . "/rsyncupdate.exclude" . " --exclude includes/config_overload.php --exclude tmp --exclude lib --exclude files" . " --exclude includes/config.php --exclude images/pictures/logo_custom.png");
                        echo $rsync . "\n";
                        check_errs($rsync, null, "Failed to rsync " . $line, "Successfully rsync-ed " . $line);
                        // Test for same files
                        if (realpath($currentDir . "/../tmp/svnlog.txt") != realpath($dirName . "/tmp/svnlog.txt")) {
                            copy($currentDir . "/../tmp/svnlog.txt", $dirName . "/tmp/svnlog.txt");
                        }
                        // Test for same files
                        if (realpath($currentDir . "/../tmp/svnstatus.txt") != realpath($dirName . "/tmp/svnstatus.txt")) {
                            copy($currentDir . "/../tmp/svnstatus.txt", $dirName . "/tmp/svnstatus.txt");
                        }
                    } else {
                        // Default value
                        $port = 22;
                        $portPOS = strpos($line, " ");
                        if ($portPOS) {
                            $dirName = substr($line, $hostnamePOS + 1, $portPOS - ($hostnamePOS + 1));
                        } else {
                            $dirName = substr($line, $hostnamePOS + 1);
                        }
                        if ($portPOS) {
                            $port = substr($line, $portPOS + 1);
                        }
                        $rsync = shell_exec("rsync -avpz --stats --rsh='ssh -p {$port}' " . $currentDir . "/.. --delete " . substr($line, 0, $portPOS) . " --exclude-from=" . $currentDir . "/rsyncupdate.exclude --exclude includes/config_overload.php --exclude tmp" . " --exclude lib --exclude files --exclude includes/config.php" . " --exclude images/pictures/logo_custom.png");
                        echo $rsync . "\n";
                        check_errs($rsync, null, "Failed to rsync " . substr($line, 0, $portPOS), "Successfully rsync-ed " . substr($line, 0, $portPOS));
                        $scp = shell_exec("scp -P " . $port . " " . $currentDir . "/../tmp/svnlog.txt " . substr($line, 0, $portPOS) . "/tmp/svnlog.txt");
                        $scp = shell_exec("scp -P " . $port . " " . $currentDir . "/../tmp/svnstatus.txt " . substr($line, 0, $portPOS) . "/tmp/svnstatus.txt");
                    }
                }
            }
        }
    }
}
Example #8
0
/**
 * Enable you to create a database backup
 * 
 * @param string $method        Hotcopy or Dump method
 * @param string $username      Access database
 * @param string $password      Authenticate user
 * @param string $hostname      Database server
 * @param string $port          MySQL port
 * @param string $database      Database to backup, ie mediboard
 * @param string $backupPath    Backup path, ie /var/backup
 * @param string $time          Time in days before removal of files
 * @param string $binary        To create mysql binary log index
 * @param string $loginUsername Username used to send a mail when diskfull is detected
 * @param string $loginPassword Password for the username used to send a mail when diskfull is detected
 * 
 * @return void
 */
function baseBackup($method, $username, $password, $hostname, $port, $database, $backupPath, $time, $binary, $loginUsername, $loginPassword, $lockFilePath = null)
{
    $currentDir = dirname(__FILE__);
    $event = $currentDir . "/../tmp/monitevent.txt";
    announce_script("Database daily backup");
    if ($hostname === "") {
        $hostname = "localhost";
    }
    if ($port === "") {
        $port = "3306";
    }
    if ($time === "") {
        $time = "7";
    }
    $binary = false;
    if ($binary === "y") {
        $binary = true;
    }
    if ($loginUsername === "") {
        $loginUsername = "";
        $loginPassword = "";
    }
    info_script("Backuping " . $database . " database");
    // Make complete path //
    // Make shell path
    $SHELL_PATH = $currentDir;
    // Create the lock file
    if ($lockFilePath) {
        if (!check_errs(touch($lockFilePath), false, "Unable to create lock file", "Lock file created")) {
            return;
        }
    }
    // Make backup path
    force_dir($backupPath);
    // Make database path
    $BASE_PATH = $backupPath . "/" . $database . "-db";
    force_dir($BASE_PATH);
    chdir($BASE_PATH);
    // If no enough free disk space (1.5 * size of database), send mail if provided and quit
    $mysql_conf = shell_exec("find /etc -name my.cnf 2>/dev/null|head -n 1");
    $mysql_conf = trim($mysql_conf);
    $mysql_data_root = "";
    $lines = file($mysql_conf);
    foreach ($lines as $line) {
        if (preg_match("/^(datadir)/m", $line)) {
            $datadirPOS = strpos($line, "=");
            $mysql_data_root = trim(substr($line, $datadirPOS + 1));
        }
    }
    $dir = opendir($mysql_data_root);
    check_errs($dir, false, "Unable to determine MySQL data root", "MySQL data root found!");
    closedir($dir);
    $mysql_data_base = $mysql_data_root . "/" . trim($database);
    $database_size = 0;
    $database_files = getFiles($mysql_data_base . "/");
    if ($database_files) {
        foreach ($database_files as $one_database_file) {
            $database_size += filesize($one_database_file);
        }
    }
    // Expanded size (database + tar)
    $needed_size = $database_size * 3 / 2;
    $available_size = disk_free_space($backupPath);
    if ($available_size < $needed_size) {
        if ($loginUsername != "") {
            info_script("Send a mail using " . $loginUsername . " login");
            // Name of the instance of mediboard
            $instance = basename(dirname($currentDir));
            file_get_contents("http://localhost/" . $instance . "/?login="******":" . $loginPassword . "&m=system&a=ajax_send_mail_diskfull");
        }
    }
    check_errs($available_size < $needed_size, 1, "Needed space " . formatSize($needed_size) . " exceeds available space " . formatSize($available_size), "Enough available space!");
    // Male MySQL method //
    // removes previous hotcopy/dump if something went wrong
    rrmdir($database);
    $DATETIME = date('Y-m-d\\TH-i-s');
    switch ($method) {
        case "hotcopy":
            $result = $database . "/";
            $mysqlhotcopy = shell_exec("mysqlhotcopy -h " . $hostname . " -P " . $port . " -u " . $username . " -p " . $password . " " . $database . " " . $BASE_PATH);
            check_errs($mysqlhotcopy, null, "Failed to create MySQL hot copy", "MySQL hot copy done!");
            if ($binary) {
                $link = mysql_connect($hostname . ":" . $port, $username, $password);
                check_errs($link, false, "Could not connect : " . mysql_error(), "Connected!");
                if (!$link) {
                    if ($lockFilePath) {
                        unlink($lockFilePath);
                    }
                    return 0;
                }
                $query = "SHOW MASTER STATUS";
                $res = mysql_query($query);
                mysql_close($link);
                $row = 0;
                if ($res) {
                    $row = mysql_fetch_object($res);
                }
                $a = 0;
                if ($row) {
                    $file = fopen($backupPath . "/binlog-" . $DATETIME . ".index", "w");
                    if ($file) {
                        fwrite($file, "File            Position\tBinlog_Do_DB\tBinlog_Ignore_DB\n  ");
                        fwrite($file, $row->File . "\t" . $row->Position . "\t        " . $row->Binlog_Do_DB . "\t" . $row->Binlog_Ignore_DB . "\n");
                        fclose($file);
                        $a = 1;
                    }
                }
                check_errs($a, 0, "Failed to create MySQL Binary log index", "MySQL Binary log index done!");
            }
            break;
        case "dump":
            $result = $database . ".sql";
            $mysqldump = shell_exec("mysqldump --opt -u " . $username . " -p" . $password . " -h " . $hostname . " -P " . $port . " " . $database);
            check_errs($mysqldump, null, "Failed to create MySQL dump", "MySQL dump done!");
            $file = fopen($result, "w");
            $a = 0;
            if ($file) {
                fwrite($file, $mysqldump);
                fclose($file);
                $a = 1;
            }
            check_errs($a, 0, "Failed to save MySQL dump file", "MySQL dump file saved!");
            break;
        default:
            echo "Choose hotcopy or dump method\n";
            if ($lockFilePath) {
                unlink($lockFilePath);
            }
            return 0;
    }
    // Rotating files older than n days, all files if 0
    if (!$time) {
        exec("find " . $BASE_PATH . " -name '" . $database . "*.tar.gz'", $find, $return_var);
        foreach ($find as $one_file) {
            unlink($one_file);
        }
        check_errs($return_var, true, "Failed to rotate files", "Files rotated");
    } else {
        $filter = "-ctime +" . $time;
        exec("find " . $BASE_PATH . " -name '" . $database . "*.tar.gz' " . $filter, $find, $return_var);
        foreach ($find as $one_file) {
            unlink($one_file);
        }
        check_errs($return_var, true, "Failed to rotate files", "Files rotated");
    }
    // Compress archive and remove file //
    // Make the tarball
    $tarball = $database . "-" . $DATETIME . ".tar.gz";
    exec("tar cfz " . $tarball . " " . $result, $tar, $return_var);
    check_errs($return_var, true, "Failed to create backup tarball", "Tarball packaged!");
    // Create a symlink
    @unlink($database . "-latest.tar.gz");
    $res = symlink($tarball, $database . "-latest.tar.gz");
    check_errs($res, false, "Failed to create symlink", "Symlink created!");
    // Remove temporay files
    $a = 0;
    if (is_dir($result)) {
        if (rrmdir($result)) {
            $a = 1;
        }
    } else {
        if (unlink($result)) {
            $a = 1;
        }
    }
    check_errs($a, false, "Failed to clean MySQL files", "MySQL files cleaning done!");
    if ($lockFilePath) {
        unlink($lockFilePath);
    }
    // Write into event file
    if (file_exists($event)) {
        $fic = fopen($event, "a");
    } else {
        $fic = fopen($event, "w");
    }
    fwrite($fic, "\n#" . date('Y-m-d H:i:s'));
    fwrite($fic, "\n<strong>" . $database . "</strong> base backup: <strong>" . $method . "</strong> method");
    fclose($fic);
}
Example #9
0
/**
 * Execute SQL requests, separated by ;
 * 
 * @param string $hostname DB hostname
 * @param string $username DB username
 * @param string $password DB user password
 * @param string $sql      SQL query
 * 
 * @return void
 */
function executeSQLRequest($hostname, $username, $password, $sql)
{
    $connection = mysql_connect($hostname, $username, $password);
    check_errs($connection, false, "Unable to connect", "Successfully connected!");
    $queries = explode(";", $sql);
    foreach ($queries as $query) {
        if ($query != "") {
            $result = mysql_query(trim($query));
            check_errs($result, false, "Unable to perform the request", "Query OK!");
        }
    }
    mysql_close($connection);
}
Example #10
0
/**
 * Setup Mediboard
 * 
 * @param string $subDir    modules|style
 * @param string $apacheGrp Name of the primary group for apache user
 *
 * @return void
 */
function setup($subDir, $apacheGrp)
{
    $currentDir = dirname(__FILE__);
    announce_script("Mediboard directories groups and mods");
    if (Task::isWindows()) {
        echo shColorText("This script does not work on Windows\n", "red");
        return;
    }
    $darwin_kernel = PHP_OS;
    // To MAC
    if ($darwin_kernel == "Darwin") {
        $APACHE_USER = trim(shell_exec("ps -ef|grep httpd|head -2|tail -1|cut -d' ' -f4"));
        $APACHE_GROUP = trim(shell_exec("groups " . $APACHE_USER . " | cut -d' ' -f1"));
    } else {
        $APACHE_USER = trim(shell_exec("ps -ef|grep apache|grep -v grep|head -2|tail -1|cut -d' ' -f1"));
        $APACHE_GROUP = trim(shell_exec("groups " . $APACHE_USER . " | cut -d' ' -f3"));
    }
    if ($apacheGrp != null) {
        $APACHE_GROUP = $apacheGrp;
    }
    $fic = fopen("/etc/group", "r");
    while (!feof($fic)) {
        $buffer = fgets($fic);
        if (preg_match("/^({$APACHE_GROUP}:)/m", $buffer)) {
            echo $APACHE_GROUP . " group exists!\n";
            // Check optional sub-directory
            switch ($subDir) {
                case "modules":
                    $BASE_PATH = "modules";
                    break;
                case "style":
                    $BASE_PATH = "style";
                    break;
                default:
                    $BASE_PATH = dirname($currentDir);
                    $SUB_PATH = array("lib/", "tmp/", "files/", "includes/", "modules/*/locales/", "modules/hprimxml/xsd/", "locales/*/");
            }
            // Change to Mediboard directory
            $MB_PATH = dirname($currentDir);
            chdir($MB_PATH);
            // Change group to allow Apache to access files as group
            $chgrp = recurse_chgrp($BASE_PATH, $APACHE_GROUP);
            check_errs($chgrp, false, "Failed to change files group to " . $APACHE_GROUP, "Files group changed to " . $APACHE_GROUP . "!");
            // Remove write access to all files for group and other
            $chmod = chmod_R($BASE_PATH, 0755, 0755);
            check_errs($chmod, false, "Failed to protect all files from writing", "Files protected from writing!");
            if ($BASE_PATH == dirname($currentDir)) {
                // Give write access to Apache for some directories
                foreach ($SUB_PATH as $ONE_PATH) {
                    foreach (glob($ONE_PATH) as $myPATH) {
                        $chmod = chmod_R($myPATH, 0765, 0765);
                    }
                }
                check_errs($chmod, false, "Failed to allow Apache writing to mandatory files", "Apache writing allowed for mandatory files!");
            }
            fclose($fic);
            return 1;
        }
    }
    echo "Error: group " . $APACHE_GROUP . " does not exist\n";
    return 0;
}
Example #11
0
/**
 * To replace a database
 * 
 * @param string $srcLocation Remote location, ie user@host. If localhost, symlink instead of scp
 * @param string $srcDir      Remote directory, ie /var/backup
 * @param string $srcDB       Source database name, ie mediboard
 * @param string $tgtDir      Temporary target directory, ie /tmp
 * @param string $tgtDB       Target database name, ie target_mediboard
 * @param string $restart     [optional] To restart the Mysql server (Warning), ie for InnoDB
 * @param string $safeCopy    [optional] To make a safe copy of existing target database first
 * @param string $mysqlDir    [optional] Directory where databases are stored
 * @param string $port        [optional] SSH port of the target remote location
 * @param string $localCopy   To do a local copy
 * 
 * @return void
 */
function replaceBase($srcLocation, $srcDir, $srcDB, $tgtDir, $tgtDB, $restart, $safeCopy, $mysqlDir, $port, $localCopy)
{
    $currentDir = dirname(__FILE__);
    $event = $currentDir . "/../tmp/monitevent.txt";
    announce_script("Mediboard replace base");
    $restart = false;
    if ($restart === "y") {
        $restart = true;
    }
    if ($port === "") {
        $port = "22";
    }
    $safeCopy = false;
    if ($safeCopy === "y") {
        $safeCopy = true;
    }
    $localCopy = true;
    if ($localCopy === "n") {
        $localCopy = false;
    }
    if ($mysqlDir === "") {
        $mysqlDir = "/var/lib/mysql";
    }
    if ($restart) {
        echo "\n";
        cecho("Warning !!!!!!!!!!!! This will restart the MySQL server", "white", "bold", "red");
        echo "\n\n";
    }
    // MySQL Path
    $path = "/etc/init.d/mysql";
    $mysql_path = "/etc/init.d/mysqld";
    if (file_exists($path)) {
        $mysql_path = $path;
    }
    // Retrieve archive
    $archive = "archive.tar.gz";
    @unlink($tgtDir . "/" . $archive);
    if ($localCopy) {
        $scp = shell_exec("scp " . $srcLocation . ":" . $srcDir . "/" . $srcDB . "-db/" . $srcDB . "-latest.tar.gz " . $tgtDir . "/" . $archive);
        echo $scp . "\n";
        if (!check_errs(file_exists($tgtDir . "/" . $archive), false, "Failed to retrieve remote archive", "Succesfully retrieved remote archive!")) {
            exit(0);
        }
    } else {
        unlink($tgtDir . "/" . $archive);
        $res = symlink($srcDir . "/" . $srcDB . "-db/" . $srcDB . "-latest.tar.gz", $tgtDir . "/" . $archive);
        if (!check_errs($res, false, "Failed to symlink local archive", "Successfully symlinked local archive!")) {
            exit(0);
        }
    }
    // Extract base
    chdir($tgtDir);
    exec("tar -xf " . $archive, $tar, $return_var);
    check_errs($return_var, true, "Failed to extract files", "Succesfully extracted files");
    // Stop MySQL
    if ($restart) {
        exec($mysql_path . " stop", $stop, $return_var);
        check_errs($return_var, true, "Failed to stop mysql", "Succesfully stopped mysql");
    }
    $dir_target = $mysqlDir . "/" . $tgtDB;
    if ($safeCopy) {
        // Copy database
        $DATETIME = date("Y_m_d\\TH_i_s");
        $res = rename($dir_target, $dir_target . "_" . $DATETIME);
        check_errs($res, false, "Failed to move MySQL target directory", "Successfully moved MySQL target directory");
        $res = mkdir($dir_target);
        check_errs($res, false, "Failed to create mysql target directory", "Succesfully created mysql target directory");
        $res = chown($dir_target, "mysql");
        check_errs($res, false, "Failed to change owner", "Succesfully changed owner");
        $res = chgrp($dir_target, "mysql");
        check_errs($res, false, "Failed to change group", "Succesfully changed group");
    } else {
        // Delete files in mediboard database
        $i = 0;
        $tab = array();
        $glob = glob($dir_target . "/*");
        if ($glob) {
            foreach ($glob as $one_file) {
                if ($one_file != "." && $one_file != "..") {
                    $tab[$i] = unlink($one_file);
                    $i++;
                }
            }
            $res = true;
        } else {
            $res = false;
        }
        for ($i = 0; $i < count($tab); $i++) {
            $res = $res && $tab[$i];
        }
        check_errs($res, false, "Failed to delete files", "Successfully deleted files");
    }
    // Move table files
    chdir($srcDB);
    $i = 0;
    $tab2 = array();
    $glob = glob("*");
    if ($glob) {
        foreach ($glob as $one_file) {
            if ($one_file != "." && $one_file != "..") {
                $tab2[$i] = rename($one_file, $dir_target . "/" . $one_file);
                $i++;
            }
        }
        $res = true;
    } else {
        $res = false;
    }
    for ($i = 0; $i < count($tab2); $i++) {
        $res = $res && $tab2[$i];
    }
    check_errs($res, false, "Failed to move files", "Successfully moved files");
    // Change owner and group
    chdir($dir_target);
    $i = 0;
    $tab3 = array();
    $tab4 = array();
    $glob = glob("*");
    if ($glob) {
        foreach ($glob as $one_file) {
            if ($one_file != "." && $one_file != "..") {
                $tab3[$i] = chgrp($one_file, "mysql");
                $tab4[$i] = chown($one_file, "mysql");
                $i++;
            }
        }
        $res = true;
    } else {
        $res = false;
    }
    for ($i = 0; $i < count($tab3); $i++) {
        $res = $res && $tab3[$i] && $tab4[$i];
    }
    check_errs($res, false, "Failed to change owner and group", "Succesfully changed owner and group");
    // Start MySQL
    if ($restart) {
        exec($mysql_path . " start", $start, $return_var);
        check_errs($return_var, true, "Failed to start mysql", "Succesfully started mysql");
    }
    // Cleanup temporary archive
    $res = rrmdir($tgtDir . "/" . $srcDB);
    $res2 = unlink($tgtDir . "/" . $archive);
    check_errs($res && $res2, false, "Failed to delete temporary archive", "Succesfully deleted temporary archive");
    // Write into event file
    if (file_exists($event)) {
        $fic = fopen($event, "a");
    } else {
        $fic = fopen($event, "w");
    }
    fwrite($fic, "\n#" . date('Y-m-d H:i:s'));
    fwrite($fic, "\nreplaceBase: <strong>" . $srcDB . "</strong> to <strong>" . $tgtDB . "</strong>");
    fclose($fic);
}