function BackupToNas($directory) { if (!is_dir($directory)) { return; } $syslog = new mysql_storelogs(); $sock = new sockets(); $users = new usersMenus(); $unix = new unix(); $myHostname = $unix->hostname_g(); $DirSuffix = basename($directory); $mount = new mount("/var/log/artica-postfix/logrotate.debug"); $BackupSquidLogsNASIpaddr = $sock->GET_INFO("BackupSquidLogsNASIpaddr"); $BackupSquidLogsNASFolder = $sock->GET_INFO("BackupSquidLogsNASFolder"); $BackupSquidLogsNASUser = $sock->GET_INFO("BackupSquidLogsNASUser"); $BackupSquidLogsNASPassword = $sock->GET_INFO("BackupSquidLogsNASPassword"); $BackupSquidLogsNASRetry = $sock->GET_INFO("BackupSquidLogsNASRetry"); if (!is_numeric($BackupSquidLogsNASRetry)) { $BackupSquidLogsNASRetry = 0; } $mount = new mount("/var/log/artica-postfix/logrotate.debug"); $BackupSquidLogsNASIpaddr = $sock->GET_INFO("BackupSquidLogsNASIpaddr"); $BackupSquidLogsNASFolder = $sock->GET_INFO("BackupSquidLogsNASFolder"); $BackupSquidLogsNASUser = $sock->GET_INFO("BackupSquidLogsNASUser"); $BackupSquidLogsNASPassword = $sock->GET_INFO("BackupSquidLogsNASPassword"); $BackupSquidLogsNASRetry = $sock->GET_INFO("BackupSquidLogsNASRetry"); if (!is_numeric($BackupSquidLogsNASRetry)) { $BackupSquidLogsNASRetry = 0; } $mv = $unix->find_program("mv"); if ($BackupSquidLogsNASIpaddr == null) { $this->events("Backup via NAS is disabled, skip", __FUNCTION__, __FILE__, __LINE__, "logrotate"); return false; } $mountPoint = "/mnt/BackupSquidLogsUseNas"; if (!$mount->smb_mount($mountPoint, $BackupSquidLogsNASIpaddr, $BackupSquidLogsNASUser, $BackupSquidLogsNASPassword, $BackupSquidLogsNASFolder)) { $syslog->events("Unable to connect to NAS storage system (1): {$BackupSquidLogsNASUser}@{$BackupSquidLogsNASIpaddr}", __FUNCTION__, __FILE__, __LINE__, "logrotate"); if ($BackupSquidLogsNASRetry == 0) { return; } sleep(3); $mount = new mount("/var/log/artica-postfix/logrotate.debug"); if (!$mount->smb_mount($mountPoint, $BackupSquidLogsNASIpaddr, $BackupSquidLogsNASUser, $BackupSquidLogsNASPassword, $BackupSquidLogsNASFolder)) { $syslog->events("Unable to connect to NAS storage system (1): {$BackupSquidLogsNASUser}@{$BackupSquidLogsNASIpaddr}", __FUNCTION__, __FILE__, __LINE__, "logrotate"); return; } } $syslog->events("Hostname={$myHostname} Suffix = {$DirSuffix} {$BackupSquidLogsNASIpaddr}/{$BackupSquidLogsNASFolder}", __FUNCTION__, __LINE__); $BackupMaxDaysDir = "{$mountPoint}/artica-backup-syslog"; @mkdir("{$BackupMaxDaysDir}", 0755, true); if (!is_dir($BackupMaxDaysDir)) { $syslog->events("Fatal {$BackupMaxDaysDir} permission denied", __FUNCTION__, __LINE__); if ($GLOBALS["VERBOSE"]) { echo "Fatal {$BackupMaxDaysDir} permission denied\n"; } squid_admin_mysql(0, "SYSLOG: FATAL {$BackupMaxDaysDir} permission denied", null, __FILE__, __LINE__); $mount->umount($mountPoint); return false; } $t = time(); @file_put_contents("{$BackupMaxDaysDir}/{$t}", time()); if (!is_file("{$BackupMaxDaysDir}/{$t}")) { $syslog->events("Fatal {$BackupMaxDaysDir} permission denied ({$BackupMaxDaysDir}/{$t}) test failed", __FUNCTION__, __LINE__); squid_admin_mysql(0, "SYSLOG: FATAL {$BackupMaxDaysDir} permission denied", null, __FILE__, __LINE__); $mount->umount($mountPoint); return false; } @unlink("{$BackupMaxDaysDir}/{$t}"); exec("{$mv} --force {$directory} --target-directory={$BackupMaxDaysDir}/ 2>&1", $results); while (list($index, $line) = each($results)) { $syslog->events("{$line}", __FUNCTION__, __LINE__); } analyze_destination_directory($BackupMaxDaysDir . "/proxy"); $mount->umount($mountPoint); return true; }
function smbmount($host,$username,$password,$cmdline){ if($username==null){ events("smbmount(): using no user and password for remote connection is not supported"); return false; } @mkdir("/opt/artica/mount/$host"); $mount_point="/opt/artica/mount/$host"; $f=new mount("/var/log/artica-postfix/computer-scan.debug"); if(!$f->ismounted($mount_point)){ events("smbmount(): not mounted..."); $password_hidden=preg_replace("#.*#","*",$password); events("smbmount(): using $username $password_hidden\n"); if($username<>null){$options=" -o username=$username,password=$password";} $cmd="mount -t smbfs$options //$host/c$ /opt/artica/mount/$host"; events("smbmount(): $cmd"); exec($cmd); } if($f->ismounted($mount_point)){ events("smbmount(): $cmdline $mount_point"); system("$cmdline $mount_point &"); return true; } }
function shared() { $FOLDERS = array(); $unix = new unix(); $sock = new sockets(); $GLOBALS["omindex"] = $unix->find_program("omindex"); $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid"; $pid = $unix->get_pid_from_file($pidfile); if ($unix->process_exists($pid)) { system_admin_events("Already instance executed pid:{$olpid}", __FUNCTION__, __FILE__, __LINE__, "xapian"); die; } @file_put_contents($pidfile, getmypid()); $EnableSambaXapian = $sock->GET_INFO("EnableSambaXapian"); if (!is_numeric($EnableSambaXapian)) { $EnableSambaXapian = 0; } if ($EnableSambaXapian == 0) { system_admin_events("Parsing shared folder is disabled in this configuration, aborting", __FUNCTION__, __FILE__, __LINE__, "xapian"); return; } $SambaXapianAuth = unserialize(base64_decode($sock->GET_INFO("SambaXapianAuth"))); if (!is_file($GLOBALS["omindex"])) { system_admin_events("omindex no such binary, aborting", __FUNCTION__, __FILE__, __LINE__, "xapian"); return; } $smbclient = $unix->find_program("smbclient"); $umount = $unix->find_program("umount"); if (!is_file($smbclient)) { system_admin_events("smbclient, no such binary, aborting...", __FUNCTION__, __FILE__, __LINE__, "xapian"); return; } $username = $SambaXapianAuth["username"]; $password = $SambaXapianAuth["password"]; $domain = $SambaXapianAuth["domain"]; $comp = $SambaXapianAuth["ip"]; if (!isset($SambaXapianAuth["lang"])) { $SambaXapianAuth["lang"] == "none"; } $lang = $SambaXapianAuth["lang"]; if ($lang == null) { $lang = "none"; } $localdatabase = "/usr/share/artica-postfix/LocalDatabases"; $database = "{$localdatabase}/samba.default.db"; $nice = EXEC_NICE(); if ($comp == null) { system_admin_events("smbclient, no computer set, aborting...", __FUNCTION__, __FILE__, __LINE__, "xapian"); return; } if ($username != null) { $creds = "-U {$username}"; if ($password != null) { $creds = $creds . "%{$password}"; } } $t1 = time(); $cmd = "{$smbclient} -N {$creds} -L //{$comp} -g 2>&1"; if ($GLOBALS["VERBOSE"]) { echo $cmd . "\n"; } exec($cmd, $results); if (is_array($results)) { while (list($num, $ligne) = each($results)) { if (preg_match("#Disk\\|(.+?)\\|#", $ligne, $re)) { $folder = $re[1]; if ($folder == "{$username}") { continue; } $FOLDERS[$folder] = true; } } } if (count($FOLDERS) == 0) { system_admin_events("No shared folder can be browsed with {$username}@{$comp}", __FUNCTION__, __FILE__, __LINE__, "xapian"); return; } $tmpM = "/artica-mount-xapian"; $count = 0; @mkdir($tmp, 0755, true); while (list($directory, $none) = each($FOLDERS)) { $mount = new mount(); if (!$mount->smb_mount($tmpM, $comp, $username, $password, $directory)) { system_admin_events("Folder:{$directory}, permission denied\n" . @implode("\n", $GLOBALS["MOUNT_EVENTS"]), __FUNCTION__, __FILE__, __LINE__, "xapian"); return; } $BaseUrl = "file://///{$comp}/{$directory}"; $cmd = "{$nice}{$GLOBALS["omindex"]} -l 0 -s {$lang} -E 512 -m 60M --follow -D \"{$database}\" -U \"{$BaseUrl}\" \"{$tmpM}\" 2>&1"; if ($GLOBALS["VERBOSE"]) { echo "{$cmd}\n"; } $results_scan = array(); exec($cmd, $results_scan); shell_exec("{$umount} -l {$tmpM}"); $dirRes = ParseLogs($results_scan); $took = $unix->distanceOfTimeInWords($t, time(), true); $count++; system_admin_events("scanned smb://{$comp}/{$directory} took {$took} indexed:{$dirRes[0]} skipped:{$dirRes[1]}", __FUNCTION__, __FILE__, __LINE__, "xapian"); } @rmdir($tmpM); $took = $unix->distanceOfTimeInWords($t1, time(), true); system_admin_events("scanned {$count} directorie(s) took {$took}", __FUNCTION__, __FILE__, __LINE__, "xapian"); }
function usb_umount($uuid,$user){ $usb=new usb($uuid); $unix=new unix(); writelogs("Umount $uuid ($usb->TYPE) from $user",__FUNCTION__,__FILE__,__LINE__); $path="/media/$uuid"; $mount=new mount(); if(!$mount->ismounted($path)){exit(0);} $umount_bin=$unix->find_program("umount"); exec("$umount_bin -l $path 2>&1",$results); while (list ($key, $line) = each ($results)){writelogs("$line",__FUNCTION__,__FILE__,__LINE__);} if(!$mount->ismounted($path)){exit(0);} exit(1); }
function mount_smb($pattern, $ID, $testwrite = true) { $backup = new backup_protocols(); $unix = new unix(); $rsync = $unix->find_program("rsync"); if ($GLOBALS["VERBOSE"]) { backup_events($ID, "initialization", "INFO, Extract protocol: `{$pattern}`", __LINE__); } $array = $backup->extract_smb_protocol($pattern); if (!is_array($array)) { writelogs(date('m-d H:i:s') . " " . "[TASK {$ID}]: smb protocol error", __FUNCTION__, __FILE__, __LINE__); return false; } $mount_path = "/opt/artica/mounts/backup/{$ID}"; backup_events($ID, "initialization", "INFO, local mount point {$mount_path} (mount_smb())", __LINE__); include_once dirname(__FILE__) . "/ressources/class.mount.inc"; backup_events($ID, "initialization", "INFO, mount({$GLOBALS["ADDLOG"]})", __LINE__); $mount = new mount($GLOBALS["ADDLOG"]); if (!$mount->ismounted($mount_path)) { backup_events($ID, "initialization", "INFO, local mount point {$mount_path} not mounted creating mount point `{$mount_path}`", __LINE__); @mkdir($mount_path, null, true); } if (!$mount->smb_mount($mount_path, $array["SERVER"], $array["USER"], $array["PASSWORD"], $array["FOLDER"])) { backup_events($ID, "initialization", "ERROR, unable to mount target server (mount_smb({$mount_path},{$array["SERVER"]}))\n" . @implode("\n", $GLOBALS["MOUNT_EVENTS"]), __LINE__); return false; } if (!$testwrite) { return true; } $md5 = md5(date('Y-m-d H:i:s')); exec("/bin/touch {$mount_path}/{$md5} 2>&1", $results_touch); if (is_file("{$mount_path}/{$md5}")) { @unlink("{$mount_path}/{$md5}"); backup_events($ID, "initialization", "INFO, writing test successfully passed OK !", __LINE__); if ($GLOBALS["ONLY_TESTS"]) { writelogs(date('m-d H:i:s') . " " . "<H2>{success}</H2>", __FUNCTION__, __FILE__, __LINE__); } if (is_file($rsync)) { $GLOBALS["COMMANDLINECOPY"] = "{$rsync} -ar --no-p --no-g --no-o --chmod=ug=rwX,o=rwX {SRC_PATH} {NEXT} --stats -v"; } else { $GLOBALS["COMMANDLINECOPY"] = "/bin/cp -ru {SRC_PATH} {NEXT}"; } $GLOBALS["COMMANDLINE_MOUNTED_PATH"] = $mount_path; return true; } else { $logs_touch = implode("<br>", $results_touch); backup_events($ID, "initialization", "ERROR, writing test failed"); writelogs(date('m-d H:i:s') . " " . "[TASK {$ID}]: {$logs_touch}", __FUNCTION__, __FILE__, __LINE__); exec("umount -l {$mount_path}"); } }
function connect($ligne) { $unix = new unix(); $Tmpdir = $unix->TEMP_DIR(); $connection = $ligne["connection"]; $server = $ligne["hostname"]; $username = $ligne["username"]; $password = $ligne["password"]; $folder = $ligne["folder"]; $folder = str_replace("\\", "/", $folder); if (strpos($folder, "/") > 0) { $FF = explode("/", $folder); $SharedDir = $FF[0]; unset($FF[0]); $folder = @implode("/", $FF); } $mountpoint = "{$Tmpdir}/{$ligne["ID"]}"; $mount = new mount(); @mkdir($mountpoint, 0755, true); if (!$mount->smb_mount($mountpoint, $server, $username, $password, $SharedDir)) { system_admin_events("{$connection}: Unable to connect to smb://{$server}/{$folder}", __FUNCTION__, __FILE__, __LINE__, "import", $GLOBALS["SCHEDULE_ID"]); return false; } return true; }
function tests_nas() { $sock = new sockets(); $BackupSquidStatsUseNas = $sock->GET_INFO("BackupSquidStatsUseNas"); $MySQLSyslogType = $sock->GET_INFO("MySQLSyslogType"); $EnableSyslogDB = $sock->GET_INFO("EnableSyslogDB"); if (!is_numeric($EnableSyslogDB)) { $EnableSyslogDB = 0; } if (!is_numeric($MySQLSyslogType)) { $MySQLSyslogType = 1; } if (!is_numeric($BackupSquidStatsUseNas)) { $BackupSquidStatsUseNas = 0; } $users = new usersMenus(); $mount = new mount("/var/log/artica-postfix/logrotate.debug"); if ($BackupSquidStatsUseNas == 0) { echo "Backup using NAS is not enabled\n"; return; } $BackupSquidStatsNASIpaddr = $sock->GET_INFO("BackupSquidStatsNASIpaddr"); $BackupSquidStatsNASFolder = $sock->GET_INFO("BackupSquidStatsNASFolder"); $BackupSquidStatsNASUser = $sock->GET_INFO("BackupSquidStatsNASUser"); $BackupSquidStatsNASPassword = $sock->GET_INFO("BackupSquidStatsNASPassword"); $BackupSquidStatsNASRetry = $sock->GET_INFO("BackupSquidStatsNASRetry"); if (!is_numeric($BackupSquidStatsNASRetry)) { $BackupSquidStatsNASRetry = 0; } $failed = "***********************\n** FAILED **\n***********************\n"; $success = "***********************\n******* SUCCESS *******\n***********************\n"; $mountPoint = "/mnt/BackupSquidStatsUseNas"; if (!$mount->smb_mount($mountPoint, $BackupSquidStatsNASIpaddr, $BackupSquidStatsNASUser, $BackupSquidStatsNASPassword, $BackupSquidStatsNASFolder)) { if ($BackupSquidStatsNASRetry == 1) { sleep(3); $mount = new mount("/var/log/artica-postfix/logrotate.debug"); if (!$mount->smb_mount($mountPoint, $BackupSquidStatsNASIpaddr, $BackupSquidStatsNASUser, $BackupSquidStatsNASPassword, $BackupSquidStatsNASFolder)) { echo "{$failed}\nUnable to connect to NAS storage system: {$BackupSquidStatsNASUser}@{$BackupSquidStatsNASIpaddr}\n"; echo @implode("\n", $GLOBALS["MOUNT_EVENTS"]); return; } } else { echo "{$failed}\nUnable to connect to NAS storage system: {$BackupSquidStatsNASUser}@{$BackupSquidStatsNASIpaddr}\n"; echo @implode("\n", $GLOBALS["MOUNT_EVENTS"]); return; } } $BackupMaxDaysDir = "{$mountPoint}/backup-statistics/{$users->hostname}"; @mkdir($BackupMaxDaysDir, 0755, true); if (!is_dir($BackupMaxDaysDir)) { echo "{$failed}{$BackupSquidStatsNASUser}@{$BackupSquidStatsNASIpaddr}/{$BackupSquidStatsNASFolder}/backup-statistics/{$users->hostname} permission denied.\n"; $mount->umount($mountPoint); return; } $t = time(); @file_put_contents("{$BackupMaxDaysDir}/{$t}", "#"); if (!is_file("{$BackupMaxDaysDir}/{$t}")) { echo "{$failed}{$BackupSquidStatsNASUser}@{$BackupSquidStatsNASIpaddr}/{$BackupSquidStatsNASFolder}/backup-statistics/{$users->hostname}/* permission denied.\n"; $mount->umount($mountPoint); return; } @unlink("{$BackupMaxDaysDir}/{$t}"); $mount->umount($mountPoint); echo "{$success}"; }
function updatev2_NAS() { $sock = new sockets(); $unix = new unix(); $t = time(); $GLOBALS["TEMP_PATH"] = $unix->TEMP_DIR(); $mount_point = "{$GLOBALS["TEMP_PATH"]}/{$t}"; $ArticaDBPath = $sock->GET_INFO("ArticaDBPath"); if ($ArticaDBPath == null) { $ArticaDBPath = "/opt/articatech"; } $ArticaDBNasUpdt = unserialize(base64_decode($sock->GET_INFO("ArticaDBNasUpdt"))); include_once dirname(__FILE__) . "/ressources/class.mount.inc"; $mount = new mount(); updatev2_progress(30, "{mouting} {$ArticaDBNasUpdt["hostname"]}..."); $umount = $unix->find_program("umount"); if (!$mount->smb_mount($mount_point, $ArticaDBNasUpdt["hostname"], $ArticaDBNasUpdt["username"], $ArticaDBNasUpdt["password"], $ArticaDBNasUpdt["folder"])) { updatev2_progress(100, "{failed} to update Artica categories database trough NAS"); squid_admin_mysql(1, "Unable to mount on {$ArticaDBNasUpdt["hostname"]}", @implode("\n", $GLOBALS["MOUNT_EVENTS"])); return false; } $filename = $ArticaDBNasUpdt["filename"]; if (!is_file("{$mount_point}/{$filename}")) { updatev2_progress(100, "{failed} {$ArticaDBNasUpdt["hostname"]}/{$ArticaDBNasUpdt["folder"]}/{$filename} no such file"); squid_admin_mysql(1, "{failed} to update Artica categories database trough NAS", "{$ArticaDBNasUpdt["hostname"]}/{$ArticaDBNasUpdt["folder"]}/{$filename} no such file"); shell_exec("{$umount} -l {$mount_point}"); return false; } $tar = $unix->find_program("tar"); updatev2_progress(40, "{installing}..."); if ($GLOBALS["VERBOSE"]) { echo "uncompressing {$mount_point}/{$filename}\n"; } @mkdir($ArticaDBPath, 0755, true); updatev2_progress(50, "{stopping_service}..."); shell_exec("/etc/init.d/artica-postfix stop articadb"); updatev2_progress(60, "{extracting_package}..."); shell_exec("{$tar} -xf {$mount_point}/{$filename} -C {$ArticaDBPath}/"); updatev2_progress(70, "{cleaning}..."); $sock->SET_INFO("ManualArticaDBPathNAS", "0"); shell_exec("{$umount} -l {$mount_point}"); updatev2_progress(75, "{starting_service}..."); if ($GLOBALS["VERBOSE"]) { echo "starting Articadb\n"; } shell_exec("/etc/init.d/artica-postfix start articadb"); updatev2_progress(80, "{checking}"); $q = new mysql(); if (!$q->DATABASE_EXISTS("catz")) { updatev2_progress(85, "Removing old database catz"); $q->DELETE_DATABASE("catz"); } updatev2_progress(90, "{finish}"); $took = $unix->distanceOfTimeInWords($t, time()); $LOCAL_VERSION = @file_get_contents("{$ArticaDBPath}/VERSION"); squid_admin_mysql(2, "New Artica Database statistics {$LOCAL_VERSION} updated took:{$took}", ""); artica_update_event(2, "New Artica Database statistics {$LOCAL_VERSION} updated took:{$took}", null, __FILE__, __LINE__, "ufbd-artica"); updatev2_progress(100, "{done}"); $q->QUERY_SQL("TRUNCATE TABLE `catztemp`"); $nohup = $unix->find_program("nohup"); $php5 = $unix->LOCATE_PHP5_BIN(); $cmd = trim("{$nohup} {$php5} /usr/share/artica-postfix/exec.squid.visited.sites.php --schedule-id={$GLOBALS["SCHEDULE_ID"]} >/dev/null 2>&1 &"); shell_exec($cmd); return true; }
function winexe_umount($workingDirectory) { events("unmounting and cleaning...."); shell_exec("/bin/rm -rf {$workingDirectory}"); events(@file_get_contents($logfile)); @unlink($logfile); exec("umount -l /opt/artica/mounts/remote-install"); $mount = new mount(); if (!$mount->ismounted("/opt/artica/mounts/remote-install")) { events("unmounted ...."); } }
function ftp_backup($WordpressBackupParams) { $sock = new sockets(); $mount = new mount(); $unix = new unix(); $rm = $unix->find_program("rm"); $FTP_ENABLE = intval($WordpressBackupParams["FTP_ENABLE"]); if ($FTP_ENABLE == 0) { echo "FTP disbabled\n"; return; } $FTP_SERVER = $WordpressBackupParams["FTP_ENABLE"]; $FTP_USER = $WordpressBackupParams["FTP_USER"]; $FTP_PASS = $WordpressBackupParams["FTP_PASS"]; $FTP_SERVER = $WordpressBackupParams["FTP_SERVER"]; $mntDir = "/home/artica/mnt-wordpress-" . time(); @mkdir($mntDir, 0755, true); if (!$mount->ftp_mount($mntDir, $FTP_SERVER, $FTP_USER, $FTP_PASS)) { apache_admin_mysql(0, "Unable to mount FTP {$FTP_USER}@{$FTP_SERVER}", null, __FILE__, __LINE__); return; } $FTPDir = "{$mntDir}/" . $unix->hostname_g() . "/wordpress-backup"; echo "Starting copy... in {$FTPDir}\n"; if ($GLOBALS["VERBOSE"]) { echo "Checks {$FTPDir}\n"; } if (!is_dir($FTPDir)) { if ($GLOBALS["VERBOSE"]) { echo "{$FTPDir} no such directory\n"; } @mkdir($FTPDir, 0755, true); } if (!is_dir($FTPDir)) { apache_admin_mysql(0, "Fatal FTP {$FTP_USER}@{$FTP_SERVER} {$FTPDir} permission denied", null, __FILE__, __LINE__); $mount->umount($mntDir); @rmdir($mntDir); return; } $directories_servernames = $unix->dirdir($WordpressBackupParams["DEST"]); $cp = $unix->find_program("cp"); while (list($directory, $ext) = each($directories_servernames)) { $dirRoot = basename($directory); $TargetDirectory = "{$FTPDir}/{$dirRoot}"; if (!is_dir($TargetDirectory)) { if ($GLOBALS["VERBOSE"]) { echo "Create directory {$TargetDirectory}\n"; } @mkdir($TargetDirectory, 0755, true); } if (!is_dir($TargetDirectory)) { apache_admin_mysql(0, "Fatal FTP {$FTP_USER}@{$FTP_SERVER} {$TargetDirectory} permission denied", __FILE__, __LINE__); continue; } if ($GLOBALS["VERBOSE"]) { echo "Scaning {$directory}\n"; } $directories_conteners = $unix->dirdir($directory); while (list($directoryTime, $ext) = each($directories_conteners)) { $dirRootTime = basename($directoryTime); $TargetDirectory = "{$FTPDir}/{$dirRoot}/{$dirRootTime}"; @mkdir($TargetDirectory, 0755, true); if (!is_dir($TargetDirectory)) { apache_admin_mysql(0, "Fatal FTP {$FTP_USER}@{$FTP_SERVER} {$TargetDirectory} permission denied", __FILE__, __LINE__); continue; } if (!is_file("{$directoryTime}/database.gz")) { apache_admin_mysql(0, "Fatal {$directoryTime}/database.gz no such file, skip", null, __FILE__, __LINE__); continue; } $t = time(); $results = array(); if ($GLOBALS["VERBOSE"]) { echo "Copy {$directoryTime}/* -> {$TargetDirectory}\n"; } exec("{$cp} -rf {$directoryTime}/* {$TargetDirectory}/ 2>&1", $results); while (list($a, $b) = each($results)) { if (preg_match("#cannot#i", $b)) { apache_admin_mysql(0, "Fatal Copy error {$b}, skip", $b, __FILE__, __LINE__); } } $took = $unix->distanceOfTimeInWords($t, time()); if (!is_file("{$TargetDirectory}/database.gz")) { apache_admin_mysql(0, "Fatal {$TargetDirectory}/database.gz permission denied, skip", null, __FILE__, __LINE__); continue; } shell_exec("{$rm} -rf {$directoryTime}"); } } $mount->umount($mntDir); @rmdir($mntDir); return; }
function CleanMysqlDatabase($PURGE_ALL = false) { $filter = null; $users = new usersMenus(); $unix = new unix(); $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid"; $timefile = "/etc/artica-postfix/pids/logrotate." . __FUNCTION__ . ".time"; $pid = @file_get_contents("{$pidfile}"); if ($unix->process_exists($pid, basename(__FILE__))) { system_admin_events("Already executed PID {$pid}", __FUNCTION__, __FILE__, __LINE__, "logrotate"); die; } @file_put_contents($pidfile, getmypid()); $time = $unix->file_time_min($timefile); if (!$PURGE_ALL) { if (!$GLOBALS["FORCE"]) { if ($time < 15) { events("No less than 15mn or delete {$timefile} file to force..."); system_admin_events("No less than 15mn or delete {$timefile} file", __FUNCTION__, __FILE__, __LINE__, "logrotate"); return; } } } @unlink($timefile); @file_put_contents($timefile, time()); $sock = new sockets(); $MySQLSyslogType = $sock->GET_INFO("MySQLSyslogType"); $EnableSyslogDB = $sock->GET_INFO("EnableSyslogDB"); if (!is_numeric($EnableSyslogDB)) { $EnableSyslogDB = 0; } if (!is_numeric($MySQLSyslogType)) { $MySQLSyslogType = 1; } if ($MySQLSyslogType == 0) { $MySQLSyslogType = 4; } $LogRotatePath = $sock->GET_INFO("LogRotatePath"); if ($LogRotatePath == null) { $LogRotatePath = "/home/logrotate"; } $TuningParameters = unserialize(base64_decode($sock->GET_INFO("MySQLSyslogParams"))); if ($EnableSyslogDB == 1) { if ($MySQLSyslogType == 2) { events("Is a client of remote MySQL server , aborting"); if ($GLOBALS["VERBOSE"]) { echo "Is a client of remote MySQL server , aborting\n"; } return; } } $LogRotateCompress = 1; $LogRotatePath = $sock->GET_INFO("LogRotatePath"); $SystemLogsPath = $sock->GET_INFO("SystemLogsPath"); $BackupMaxDays = $sock->GET_INFO("BackupMaxDays"); $BackupMaxDaysDir = $sock->GET_INFO("BackupMaxDaysDir"); $BackupSquidLogsUseNas = $sock->GET_INFO("BackupSquidLogsUseNas"); if ($SystemLogsPath == null) { $SystemLogsPath = "/var/log"; } $MySQLSyslogType = $sock->GET_INFO("MySQLSyslogType"); $EnableSyslogDB = $sock->GET_INFO("EnableSyslogDB"); if (!is_numeric($EnableSyslogDB)) { $EnableSyslogDB = 0; } if (!is_numeric($MySQLSyslogType)) { $MySQLSyslogType = 1; } if (!is_numeric($BackupSquidLogsUseNas)) { $BackupSquidLogsUseNas = 0; } if ($EnableSyslogDB == 1) { if ($MySQLSyslogType != 1) { return; } } if (!is_numeric($BackupMaxDays)) { $BackupMaxDays = 30; } if ($LogRotatePath == null) { $LogRotatePath = "/home/logrotate"; } if ($BackupMaxDaysDir == null) { $BackupMaxDaysDir = "/home/logrotate_backup"; } $mount = new mount("/var/log/artica-postfix/logrotate.debug"); if ($BackupSquidLogsUseNas == 1) { $BackupSquidLogsNASIpaddr = $sock->GET_INFO("BackupSquidLogsNASIpaddr"); $BackupSquidLogsNASFolder = $sock->GET_INFO("BackupSquidLogsNASFolder"); $BackupSquidLogsNASUser = $sock->GET_INFO("BackupSquidLogsNASUser"); $BackupSquidLogsNASPassword = $sock->GET_INFO("BackupSquidLogsNASPassword"); $BackupSquidLogsNASRetry = $sock->GET_INFO("BackupSquidLogsNASRetry"); if (!is_numeric($BackupSquidLogsNASRetry)) { $BackupSquidLogsNASRetry = 0; } $mountPoint = "/mnt/BackupSquidLogsUseNas"; if (!$mount->smb_mount($mountPoint, $BackupSquidLogsNASIpaddr, $BackupSquidLogsNASUser, $BackupSquidLogsNASPassword, $BackupSquidLogsNASFolder)) { events("Unable to connect to NAS storage system (1): {$BackupSquidLogsNASUser}@{$BackupSquidLogsNASIpaddr}"); if ($BackupSquidLogsNASRetry == 0) { return; } sleep(3); $mount = new mount("/var/log/artica-postfix/logrotate.debug"); if (!$mount->smb_mount($mountPoint, $BackupSquidLogsNASIpaddr, $BackupSquidLogsNASUser, $BackupSquidLogsNASPassword, $BackupSquidLogsNASFolder)) { events("Unable to connect to NAS storage system (2): {$BackupSquidLogsNASUser}@{$BackupSquidLogsNASIpaddr}"); return; } } $BackupMaxDaysDir = "{$mountPoint}/artica-backup-syslog/{$users->hostname}"; } @mkdir("{$BackupMaxDaysDir}", 0755, true); if (!is_dir($BackupMaxDaysDir)) { if ($GLOBALS["VERBOSE"]) { echo "Fatal {$BackupMaxDaysDir} permission denied\n"; } events("Fatal {$BackupMaxDaysDir} permission denied"); squid_admin_notifs("SYSLOG: FATAL {$BackupMaxDaysDir} permission denied", __FUNCTION__, __FILE__, __LINE__); system_admin_events($q->mysql_error, __FUNCTION__, __FILE__, __LINE__, "logrotate"); if ($BackupSquidLogsUseNas == 1) { $mount->umount($mountPoint); } return false; } $t = time(); @file_put_contents("{$BackupMaxDaysDir}/{$t}", time()); if (!is_file("{$BackupMaxDaysDir}/{$t}")) { events("Fatal {$BackupMaxDaysDir} permission denied"); if ($GLOBALS["VERBOSE"]) { echo "Fatal {$BackupMaxDaysDir} permission denied\n"; } squid_admin_notifs("SYSLOG: FATAL {$BackupMaxDaysDir} permission denied", __FUNCTION__, __FILE__, __LINE__); system_admin_events($q->mysql_error, __FUNCTION__, __FILE__, __LINE__, "logrotate"); if ($BackupSquidLogsUseNas == 1) { $mount->umount($mountPoint); } return false; } @unlink("{$BackupMaxDaysDir}/{$t}"); if ($BackupSquidLogsUseNas == 1) { if (is_dir("/home/logrotate_backup")) { $files = $unix->DirFiles("/home/logrotate_backup"); events("Scanning the old storage systems.. " . count($files) . " file(s)"); while (list($basename, $none) = each($files)) { $filepath = "/home/logrotate_backup/{$basename}"; if ($GLOBALS["VERBOSE"]) { echo "Checking \"{$filepath}\"\n"; } $size = @filesize($filepath); if ($size < 20) { events("Removing {$filepath}"); @unlink($filepath); continue; } if (!@copy($filepath, "{$BackupMaxDaysDir}/{$basename}")) { events("copy Failed {$filepath} to \"{$BackupMaxDaysDir}/{$basename}\" permission denied..."); continue; } events("Move {$filepath} to {$BackupSquidLogsNASIpaddr} success..."); @unlink($filepath); } } } if ($PURGE_ALL == false) { $filter = "WHERE filetime<DATE_SUB(NOW(),INTERVAL {$BackupMaxDays} DAY)"; } if ($EnableSyslogDB == 1) { $q = new mysql_storelogs(); $sql = "SELECT `filename`,`hostname`,`storeid` FROM `files_info` {$filter}"; if ($GLOBALS["VERBOSE"]) { echo "{$sql}\n"; } $results = $q->QUERY_SQL($sql); if (!$q->ok) { system_admin_events($q->mysql_error, __FUNCTION__, __FILE__, __LINE__); return; } $Count = mysql_num_rows($results); $c = 0; while ($ligne = mysql_fetch_assoc($results)) { $c++; if ($GLOBALS["VERBOSE"]) { echo "{$c}/{$Count} ******** {$ligne["filename"]} {$ligne["storeid"]} *********\n"; } if (!$q->ExtractFile("{$BackupMaxDaysDir}/{$ligne["hostname"]}.{$ligne["filename"]}", $ligne["storeid"])) { if ($GLOBALS["VERBOSE"]) { echo "{$c}/{$Count} ******** {$ligne["filename"]} ExtractFile() = FALSE !!! *********\n"; } continue; } if ($GLOBALS["VERBOSE"]) { echo "{$c}/{$Count} DelteItem({$ligne["storeid"]}) *********\n"; } $q->DelteItem($ligne["storeid"]); if ($GLOBALS["VERBOSE"]) { echo "********* EVENTS NOW --->\n"; } $q->events("{$ligne["filename"]} saved into {$BackupMaxDaysDir}"); if ($GLOBALS["VERBOSE"]) { echo "\n\n###### {$c}/{$Count} Continue to Next ##########\n"; } } $sql = "SELECT `filename`,`hostname`,`storeid` FROM `accesslogs` {$filter}"; if ($GLOBALS["VERBOSE"]) { echo "{$sql}\n"; } $results = $q->QUERY_SQL($sql); if (!$q->ok) { system_admin_events($q->mysql_error, __FUNCTION__, __FILE__, __LINE__); return; } $Count = mysql_num_rows($results); $c = 0; while ($ligne = mysql_fetch_assoc($results)) { $c++; if (!$q->ExtractAccessFile("{$BackupMaxDaysDir}/{$ligne["hostname"]}.{$ligne["filename"]}", $ligne["storeid"])) { continue; } $q->DelteAccessItem($ligne["storeid"]); $q->events("{$ligne["filename"]} saved into {$BackupMaxDaysDir}"); } if ($BackupSquidLogsUseNas == 1) { $mount->umount($mountPoint); } return; } $q = new mysql_syslog(); $sql = "SELECT `filename`,`taskid`,`filesize`,`filetime` FROM `store` {$filter}"; $results = $q->QUERY_SQL($sql); if ($GLOBALS["VERBOSE"]) { echo "{$sql} ({$q->mysql_error}) " . mysql_num_rows($results) . " file(s)\n"; } if (!$q->ok) { system_admin_events($q->mysql_error, __FUNCTION__, __FILE__, __LINE__); return; } while ($ligne = mysql_fetch_assoc($results)) { if ($GLOBALS["VERBOSE"]) { echo "Processing {$ligne["filename"]}\n"; } if (!ExtractFileFromDatabase($ligne["filename"], $BackupMaxDaysDir)) { events("Unable to extract {$ligne["filename"]} to {$BackupMaxDaysDir}"); squid_admin_notifs("SYSLOG: Unable to extract {$ligne["filename"]} to {$BackupMaxDaysDir}", __FUNCTION__, __FILE__, __LINE__); if ($BackupSquidLogsUseNas == 1) { $mount->umount($mountPoint); } return false; } else { events("Success extracting {$ligne["filename"]} to {$BackupMaxDaysDir}"); } } if ($BackupSquidLogsUseNas == 1) { $mount->umount($mountPoint); } }
function killNas() { $sock = new sockets(); $mount = new mount($GLOBALS["LOGFILE"]); $mountPoint = "/mnt/SquidImportLogs"; if ($mount->ismounted($mountPoint)) { $mount->umount($mountPoint); } }
function ftp_backup() { $sock = new sockets(); $mount = new mount(); $unix = new unix(); $ZarafaBackupParams = unserialize(base64_decode($sock->GET_INFO("ZarafaBackupParams"))); $FTP_ENABLE = intval($ZarafaBackupParams["FTP_ENABLE"]); if ($FTP_ENABLE == 0) { echo "FTP disbabled\n"; return; } @mkdir("/home/artica/mnt-zarafa-ftp"); $FTP_SERVER = $ZarafaBackupParams["FTP_ENABLE"]; $FTP_USER = $ZarafaBackupParams["FTP_USER"]; $FTP_PASS = $ZarafaBackupParams["FTP_PASS"]; $FTP_SERVER = $ZarafaBackupParams["FTP_SERVER"]; $mntDir = "/home/artica/mnt-zarafa-ftp"; if ($ZarafaBackupParams["DEST"] == null) { $ZarafaBackupParams["DEST"] = "/home/zarafa-backup"; } if (!$mount->ftp_mount($mntDir, $FTP_SERVER, $FTP_USER, $FTP_PASS)) { system_admin_events("Unable to mount FTP {$FTP_USER}@{$FTP_SERVER}", __FUNCTION__, __FILE__, __LINE__, "mailboxes"); return; } $FTPDir = "{$mntDir}/" . $unix->hostname_g() . "/zarafa-backup"; @mkdir($FTPDir, 0755, true); if (!is_dir($FTPDir)) { system_admin_events("Fatal FTP {$FTP_USER}@{$FTP_SERVER} {$FTPDir} permission denied", __FUNCTION__, __FILE__, __LINE__, "mailboxes"); $mount->umount($mntDir); @rmdir($mntDir); return; } echo "Starting copy... in {$FTPDir}\n"; $directories = $unix->dirdir($ZarafaBackupParams["DEST"]); $cp = $unix->find_program("cp"); while (list($directory, $ext) = each($directories)) { if (!is_file("{$directory}/zarafa.gz")) { continue; } $dirRoot = basename($directory); $TargetDirectory = "{$FTPDir}/{$dirRoot}"; if (is_file("{$TargetDirectory}/zarafa.gz")) { continue; } @mkdir($TargetDirectory, 0755, true); if (!is_dir($TargetDirectory)) { system_admin_events("Fatal FTP {$FTP_USER}@{$FTP_SERVER} {$TargetDirectory} permission denied", __FUNCTION__, __FILE__, __LINE__, "mailboxes"); continue; } $results = array(); $t = time(); exec("{$cp} -rfv {$directory}/* {$TargetDirectory}/ 2>&1", $results); $took = $unix->distanceOfTimeInWords($t, time()); system_admin_events("Success backup {$dirRoot} to FTP {$FTP_SERVER} took: {$took}\nTarget:{$TargetDirectory}\n" . @implode("\n", $results), __FUNCTION__, __FILE__, __LINE__, "mailboxes"); } $mount->umount($mntDir); @rmdir($mntDir); return; }
function restore() { $sock = new sockets(); $unix = new unix(); $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid"; if ($GLOBALS["VERBOSE"]) { echo "PID: {$pidfile}\n"; } $pid = $unix->get_pid_from_file($pidfile); if ($unix->process_exists($pid)) { $TTL = $unix->PROCESS_TTL($pid); if ($TTL < 240) { return; } $kill = $unix->find_program("kill"); unix_system_kill_force($pid); } @file_put_contents($pidfile, getmypid()); $hostname = $unix->hostname_g(); progress(10, "{mounting}"); if (!restore_TestNas()) { system_admin_events("Mounting NAS filesystem report false", __FUNCTION__, __FILE__, __LINE__); progress(100, "{failed}"); return; } $BackupArticaRestoreNASIpaddr = $sock->GET_INFO("BackupArticaRestoreNASIpaddr"); $BackupArticaRestoreNASFolder = $sock->GET_INFO("BackupArticaRestoreNASFolder"); $BackupArticaRestoreNASUser = $sock->GET_INFO("BackupArticaRestoreNASUser"); $BackupArticaRestoreNASPassword = $sock->GET_INFO("BackupArticaRestoreNASPassword"); $BackupArticaRestoreNASFolderSource = $sock->GET_INFO("BackupArticaRestoreNASFolderSource"); $BackupArticaRestoreNetwork = $sock->GET_INFO("BackupArticaRestoreNetwork"); $mountPoint = "/mnt/BackupArticaRestoreNAS"; $BackupArticaRestoreNASFolderSource = str_replace("\\", "/", $BackupArticaRestoreNASFolderSource); $sourceDir = "{$mountPoint}/{$BackupArticaRestoreNASFolderSource}"; $sourceDir = str_replace("//", "/", $sourceDir); if (!is_file("{$sourceDir}/BKVERSION.txt")) { progress(100, "{failed} BKVERSION.txt no such file"); $mount = new mount("/var/log/artica-postfix/backup.debug"); if ($mount->ismounted($mountPoint)) { $mount->umount($mountPoint); } return; } $time = trim(@file_get_contents("{$sourceDir}/BKVERSION.txt")); progress(15, "{backup} " . date("Y-m-d H:i:s")); progress(20, "{restoring_ldap_database}, {please_wait}..."); Restore_ldap($sourceDir); progress(40, "{restoring_artica_settings}, {please_wait}..."); restore_artica_settings($sourceDir); progress(50, "{restoring_artica_databases}, {please_wait}..."); restore_artica_backup($sourceDir); progress(60, "{restoring_artica_databases}, {please_wait}..."); restore_ocsweb($sourceDir); progress(80, "{restoring_artica_databases}, {please_wait}..."); restore_squidlogs($sourceDir); progress(82, "{restoring} PowerDNS, {please_wait}..."); restore_powerdns($sourceDir); progress(90, "{reconfigure_server}, {please_wait}..."); $squidbin = $unix->LOCATE_SQUID_BIN(); $php = $unix->LOCATE_PHP5_BIN(); if (is_file($squidbin)) { shell_exec("{$php} /usr/share/artica-postfix/exec.squid.php --build --force"); } progress(100, "{success}"); $mount = new mount("/var/log/artica-postfix/backup.debug"); if ($mount->ismounted($mountPoint)) { $mount->umount($mountPoint); } if ($BackupArticaRestoreNetwork == 1) { $unix->THREAD_COMMAND_SET("{$php} /usr/share/artica-postfix/exec.virtuals-ip.php --build"); } return; }
function ScanComputers_deploy() { $cmp = new computers($GLOBALS[__FILE__]["uid"]); $sock = new sockets(); $unix = new unix(); setComputerProgress(10); $hash = unserialize(base64_decode($sock->GET_INFO("GlobalNetAdmin"))); $global_user = $hash["GLOBAL"]["username"]; $global_password = $hash["GLOBAL"]["password"]; if ($MinutesToWait == 0) { $MinutesToWait = 5; } $sql = "SELECT * FROM computers_storage WHERE ID='{$GLOBALS[__FILE__]["PACKAGEID"]}'"; $q = new mysql(); $ligne = @mysql_fetch_array($q->QUERY_SQL($sql, 'artica_backup')); task_computers_events("Deploy {$ligne["PUBLISHER"]} {$ligne["NAME"]} {$ligne["version"]}"); $source_path = $ligne["local_path"]; $commandline = $ligne["command_line"]; if (!is_file($source_path)) { task_computers_events("Source {$source_path} no such file"); task_events("{$ligne["uid"]} Failed"); setComputerStatus(-1); setComputerProgress(100); return; } if ($global_user != null) { $users[] = array($global_user, $global_password); } $ini = new Bs_IniHandler(); $ini->loadString($cmp->ComputerCryptedInfos); $global_user = $ini->_params["ACCOUNT"]["USERNAME"]; $global_password = $ini->_params["ACCOUNT"]["PASSWORD"]; if ($global_user != null) { $users[] = array($global_user, $global_password); } task_computers_events("using " . count($users) . " potentials users"); if (count($users) == 0) { task_computers_events("no administrator account set for this computer."); task_events("{$ligne["uid"]} Failed"); setComputerStatus(-1); setComputerProgress(100); return; } if (!preg_match("#^[0-9]+\\.[0-9]+\\.[0-9]+#", $cmp->ComputerIP)) { $cmp->ComputerIP = null; } $ip_src = $cmp->ComputerIP; $realname = $cmp->ComputerRealName; $cmp->ComputerIP = $unix->HostToIp($realname); if ($cmp->ComputerIP == null) { $cmp->ComputerIP = $ip_src; } task_computers_events("{$realname} resolved to {$cmp->ComputerIP}"); setComputerProgress(30); $pp = new ping($cmp->ComputerIP); if (!$pp->Isping()) { task_computers_events("Failed to ping {$realname} ({$cmp->ComputerIP}), aborting process."); return false; } setComputerProgress(40); task_computers_events("Mount the admin\$ to targeted {$realname} computer..."); $mount = new mount(); $mounted = false; while (list($index, $hash_credentials) = each($users)) { if ($mount->MountComputerRemote($realname, $cmp->ComputerIP, $hash_credentials[0], $hash_credentials[1])) { task_computers_events("Success connecting to the {$realname} computer"); $mounted = true; $username = $hash_credentials[0]; $password = $hash_credentials[1]; } else { task_computers_events("Failed connecting to the {$realname} computer using {$hash_credentials[0]}"); } } if (!$mounted) { task_events("{$ligne["uid"]} Failed"); setComputerStatus(-1); setComputerProgress(100); return false; } $mounted_path = $mount->mount_point; @mkdir($mounted . "/artica_remote_install", null, true); if (!is_dir($mounted . "/artica_remote_install")) { task_computers_events("{$mounted}/artica_remote_install permission denied"); shell_exec("umount -l {$mounted_path}"); setComputerStatus(-1); setComputerProgress(100); return false; } if (!@copy($source_path, $mounted . "/artica_remote_install/" . basename($source_path))) { task_computers_events("{$mounted}/artica_remote_install permission denied will copy source file"); shell_exec("umount -l {$mounted_path}"); setComputerStatus(-1); setComputerProgress(100); return false; } $execute_path = "C:\\tmp\\artica_remote_install\\" . basename($source_path) . " {$commandline}"; task_computers_events("runtask:: execute {$execute_path} on target computer"); $logfile = "/tmp/" . md5($cmp->ComputerIP); $cmd = "/usr/bin/winexe -d 2 --user={$username} --password={$password} --interactive=1 --runas={$username}%{$password} --uninstall //{$cmp->ComputerIP} \"{$execute_path}\" >{$logfile} &"; exec($cmd); if (!WaitWinexeForSecondes($MinutesToWait, $cmp->ComputerIP)) { events("runtask:: Time-out !!"); winexe_umount($workingDirectory); return false; } if ($ExecuteAfter != null) { events("runtask:: execute {$ExecuteAfter} on target computer"); $cmd = "/usr/bin/winexe -d 2 --user={$username} --password={$password} --interactive=1 --runas={$username}%{$password} --uninstall //{$cmp->ComputerIP} {$ExecuteAfter} >{$logfile} &"; exec($cmd); if (!WaitWinexeForSecondes($MinutesToWait, $cmp->ComputerIP)) { events("runtask:: execute {$ExecuteAfter} time-out on target computer"); } } winexe_umount($workingDirectory); events("runtask:: Done..."); return true; }
function is_media_mounted() { $mount = new mount(); return $mount->ismounted("/media/cdrom0"); }
function smbmount($host, $username, $password, $cmdline) { if ($username == null) { events("smbmount(): using no user and password for remote connection is not supported"); return false; } @mkdir("/opt/artica/mount/{$host}"); $mount_point = "/opt/artica/mount/{$host}"; $f = new mount("/var/log/artica-postfix/computer-scan.debug"); if (!$f->ismounted($mount_point)) { events("smbmount(): not mounted..."); $password_hidden = preg_replace("#.*#", "*", $password); events("smbmount(): using {$username} {$password_hidden}\n"); if ($username != null) { $options = " -o username={$username},password={$password}"; } $cmd = "mount -t smbfs{$options} //{$host}/c\$ /opt/artica/mount/{$host}"; events("smbmount(): {$cmd}"); exec($cmd); } if ($f->ismounted($mount_point)) { events("smbmount(): {$cmdline} {$mount_point}"); system("{$cmdline} {$mount_point} &"); return true; } }
function MountComputerRemote($uid, $ip, $username, $password, $sourcefile) { $uidPoint = str_replace("\$", "", $uid); $sourcefile_base = basename($sourcefile); $GLOBALS["MOUNT_POINT"] = "/opt/artica/mounts/remote-{$uidPoint}"; @mkdir($GLOBALS["MOUNT_POINT"], null, true); $unix = new unix(); $mount_bin = $unix->find_program("mount"); if ($mount_bin == null) { $GLOBALS[$uid]["EVENTS"][] = "[{$username}/{$ip}]:: mount program, no such file"; return false; } $mount = new mount("/var/log/artica-postfix/remote-install-{$uidPoint}.debug"); if (!$mount->ismounted($GLOBALS["MOUNT_POINT"])) { $GLOBALS[$uid]["EVENTS"][] = "[{$username}/{$ip}]:: Mount point is not mounted, mount it"; $GLOBALS[$uid]["EVENTS"][] = "[{$username}/{$ip}]:: Mount c\$ on {$uidPoint} [{$ip}]"; $cmd = "{$mount_bin} -t smbfs -o username={$username},password={$password} //{$ip}/c\$ {$GLOBALS["MOUNT_POINT"]} 2>&1"; exec($cmd, $results); while (list($index, $line) = each($results)) { if (trim($line) == null) { continue; } $GLOBALS[$uid]["EVENTS"][] = $line; } } else { $GLOBALS[$uid]["EVENTS"][] = "[{$username}/{$ip}]:: Mount point is mounted"; } if (!$mount->ismounted($GLOBALS["MOUNT_POINT"])) { return false; } $GLOBALS["MOUNTED_PATH"] = "{$GLOBALS["MOUNT_POINT"]}/tmp/ocs-agent"; if (!is_dir($GLOBALS["MOUNTED_PATH"])) { @mkdir($GLOBALS["MOUNTED_PATH"], null, true); } if (!is_dir($GLOBALS["MOUNTED_PATH"])) { $GLOBALS[$uid]["EVENTS"][] = "[{$username}/{$ip}]:: c:\tmp\\ocs-agent, permission denied"; exec("umount -l {$mountpoint}"); return false; } unset($results); $GLOBALS["WORKING_FILE_PATH"] = "{$GLOBALS["MOUNTED_PATH"]}/{$sourcefile_base}"; writelogs("WORKING_FILE_PATH={$GLOBALS["WORKING_FILE_PATH"]}", __FUNCTION__, __FILE__, __LINE__); $cmd = "/bin/cp -f {$sourcefile} {$GLOBALS["WORKING_FILE_PATH"]} 2>&1"; writelogs("{$cmd}", __FUNCTION__, __FILE__, __LINE__); exec($cmd, $results); while (list($index, $line) = each($results)) { if (trim($line) == null) { continue; } $GLOBALS[$uid]["EVENTS"][] = $line; } if (!is_file("{$workingDirectory}/{$sourcefile_base}")) { $GLOBALS[$uid]["EVENTS"][] = "[{$username}/{$ip}]:: {$GLOBALS["MOUNTED_PATH"]}\".{$sourcefile_base}, permission denied"; exec("umount -l {$GLOBALS["MOUNT_POINT"]}"); return false; } $GLOBALS["LOCAL_FILE_PATH"] = "c:\\tmp\\ocs-agent\\{$sourcefile_base}"; $GLOBALS[$uid]["EVENTS"][] = "[{$username}/{$ip}]:: {$GLOBALS["MOUNTED_PATH"]}\\{{$sourcefile_base}}, success"; return true; }
function exec_webdav() { $mount = new mount(); $unix = new unix(); $mount_point = $GLOBALS["MOUNT_POINT"]; @mkdir($mount_point, 0755, true); $server = $GLOBALS["CyrusBackupNas"]["WEBDAV_SERVER"]; $username = $GLOBALS["CyrusBackupNas"]["WEBDAV_USER"]; $password = $GLOBALS["CyrusBackupNas"]["WEBDAV_PASSWORD"]; $path = $GLOBALS["CyrusBackupNas"]["WEBDAV_DIR"]; if ($mount->ismounted($mount_point)) { $mount->umount($mount_point); } if ($GLOBALS["VERBOSE"]) { echo "davfs:WEBDAV_DIR...: {$path}\n"; } if ($GLOBALS["VERBOSE"]) { echo "davfs:WEBDAV_SERVER: {$server}\n"; } if (!$mount->davfs_mount($mount_point, $server, $username, $password, $path)) { if ($GLOBALS["VERBOSE"]) { echo $mount->events_compile() . "\n"; } cyrus_admin_mysql(0, "Unable to connect to {$server}", $mount->events_compile(), __FILE__, __LINE__); return; } $path = $mount->davfs_path($mount_point, $server, $username, $password, $path); if ($GLOBALS["VERBOSE"]) { echo "davfs_path: {$path}\n"; } $hostname = $unix->hostname_g(); $GLOBALS["DIRBYTES"] = date("YmdH"); $GLOBALS["MOUNTED_PATH__BACKUPDIR"] = "{$GLOBALS["MOUNT_POINT"]}/{$path}/{$hostname}"; $GLOBALS["MOUNTED_PATH_FINAL"] = "{$GLOBALS["MOUNT_POINT"]}/{$path}/{$hostname}/{$GLOBALS["DIRBYTES"]}"; $GLOBALS["MOUNTED_PATH_FINAL"] = str_replace("//", "/", $GLOBALS["MOUNTED_PATH_FINAL"]); if ($GLOBALS["VERBOSE"]) { echo "MOUNTED_PATH_FINAL: {$GLOBALS["MOUNTED_PATH_FINAL"]}\n"; } if (!is_dir($GLOBALS["MOUNTED_PATH_FINAL"])) { if ($GLOBALS["VERBOSE"]) { echo "Create -> {$GLOBALS["MOUNTED_PATH_FINAL"]}\n"; } @mkdir($GLOBALS["MOUNTED_PATH_FINAL"], 0755, true); if (!is_dir($GLOBALS["MOUNTED_PATH_FINAL"])) { cyrus_admin_mysql(0, "Unable to backup: Permission denied on WebDAV resource {$server}", "For creating directory {$GLOBALS["MOUNTED_PATH_FINAL"]}", __FILE__, __LINE__); killNas(); return; } } $t = time(); @touch("{$GLOBALS["MOUNTED_PATH_FINAL"]}/{$t}"); if (!is_file("{$GLOBALS["MOUNTED_PATH_FINAL"]}/{$t}")) { cyrus_admin_mysql(0, "Unable to backup: Permission denied on WebDAV", "resource {{$GLOBALS["MOUNTED_PATH_FINAL"]}/{$t}}", __FILE__, __LINE__); killNas(); return; } @unlink("{$GLOBALS["MOUNTED_PATH_FINAL"]}/{$t}"); if ($GLOBALS["VERBOSE"]) { echo "backup_ldap():\n"; } backup_ldap(); if ($GLOBALS["VERBOSE"]) { echo "backup_cyrus():\n"; } backup_cyrus(); remove_containers(); killNas(); }
function backup() { $sock = new sockets(); $unix = new unix(); $pidTime = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".time"; $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid"; $pid = $unix->get_pid_from_file($pidfile); if ($unix->process_exists($pid, basename(__FILE__))) { $time = $unix->PROCCESS_TIME_MIN($pid); echo "Starting......: " . date("H:i:s") . " [INIT]: nginx Already Artica task running PID {$pid} since {$time}mn\n"; return; } $time = $unix->file_time_min($pidTime); if ($time < 60) { return; } @file_put_contents($pidfile, getmypid()); @unlink($pidTime); @file_put_contents($pidTime, getmypid()); $SargOutputDir = $sock->GET_INFO("SargOutputDir"); if ($SargOutputDir == null) { $SargOutputDir = "/var/www/html/squid-reports"; } $BackupSargUseNas = $sock->GET_INFO("BackupSargUseNas"); if (!is_numeric($BackupSargUseNas)) { $BackupSargUseNas = 0; } $nice = EXEC_NICE(); $mount = new mount("/var/log/sarg-exec.log"); if ($BackupSargUseNas == 0) { return; } $BackupSargNASIpaddr = $sock->GET_INFO("BackupSargNASIpaddr"); $BackupSargNASFolder = $sock->GET_INFO("BackupSargNASFolder"); $BackupSargNASUser = $sock->GET_INFO("BackupSargNASUser"); $BackupSargNASPassword = $sock->GET_INFO("BackupSargNASPassword"); $mountPoint = "/mnt/BackupSargUseNas"; if (!$mount->smb_mount($mountPoint, $BackupSargNASIpaddr, $BackupSargNASUser, $BackupSargNASPassword, $BackupSargNASFolder)) { sarg_admin_events("SARG: Unable to connect to NAS storage system: {$BackupSargNASUser}@{$BackupSargNASIpaddr}", __FUNCTION__, __FILE__, __LINE__, "sarg"); return; } $BackupDir = "{$mountPoint}/sarg"; @mkdir("{$BackupDir}", 0755); if (!is_dir($BackupDir)) { if ($GLOBALS["VERBOSE"]) { echo "Fatal {$BackupDir} permission denied\n"; } sarg_admin_events("Fatal {$BackupDir} permission denied", __FUNCTION__, __FILE__, __LINE__, "sarg"); $mount->umount($mountPoint); return false; } $t = time(); @file_put_contents("{$BackupDir}/{$t}", time()); if (!is_file("{$BackupDir}/{$t}")) { sarg_admin_events("Fatal {$BackupDir} permission denied", __FUNCTION__, __FILE__, __LINE__, "sarg"); $mount->umount($mountPoint); return false; } @unlink("{$BackupDir}/{$t}"); $cp = $unix->find_program("cp"); shell_exec(trim("{$nice} {$cp} -dpR {$SargOutputDir}/* {$BackupDir}/")); $mount->umount($mountPoint); sarg_admin_events("Copy to {$BackupSargNASIpaddr}/{$BackupSargNASFolder} done", __FUNCTION__, __FILE__, __LINE__, "sarg"); }
function CreateHD() { $sock = new sockets(); $unix = new unix(); $Config = unserialize($sock->GET_INFO("NewCacheCenterWizard")); if (!is_array($Config)) { echo "Corrupted configuration...\n"; build_progress("{failed}", 110); return; } if (!isset($Config["dev"])) { echo "Corrupted configuration...\n"; build_progress("{failed}", 110); return; } $dev = $Config["dev"]; if ($dev == null) { echo "Corrupted configuration...\n"; build_progress("{failed}", 110); return; } $size = $Config["size"]; $oct = intval($Config["oct"]); build_progress("{checking} {$dev} {$size}", 20); $php = $unix->LOCATE_PHP5_BIN(); build_progress("{building_partition} {$dev} {$size}", 20); $explodedDev = basename($dev); $Label = "Cache{$explodedDev}"; $mount = $unix->find_program("mount"); $cpu = $Config["CPU"]; $mount = new mount(); $targetMountPoint = $unix->isDirInFsTab("/media/{$Label}"); echo "Target in fstab = {$targetMountPoint}\n"; if ($targetMountPoint == null) { system("{$php} /usr/share/artica-postfix/exec.system.build-partition.php --full \"{$dev}\" \"{$Label}\" \"ext4\" --bywizard"); } else { build_progress("{building_partition} {$targetMountPoint}", 20); } if (!$mount->ismounted("/media/{$Label}")) { echo "/media/{$Label} is not mounted !!! (1/2)...\n"; shell_exec("{$mount} /media/{$Label}"); if (!$mount->ismounted("/media/{$Label}")) { echo "/media/{$Label} is not mounted !!! (2/2)...\n"; build_progress("{failed}", 110); return; } } echo "Testing /media/{$Label}/proxy-caches\n"; if (!is_dir("/media/{$Label}/proxy-caches")) { @mkdir("/media/{$Label}/proxy-caches", 0755, true); } if (!is_dir("/media/{$Label}/proxy-caches")) { echo "/media/{$Label}/proxy-caches permissions denied\n"; build_progress("{failed}", 110); return; } @chown("/media/{$Label}/proxy-caches", "squid"); @chgrp("/media/{$Label}/proxy-caches", "squid"); $q = new mysql(); if (!$q->FIELD_EXISTS("squid_caches_center", "wizard", "artica_backup")) { $sql = "ALTER TABLE `squid_caches_center` ADD `wizard` smallint NOT NULL DEFAULT 0"; $q->QUERY_SQL($sql, "artica_backup"); if (!$q->ok) { echo "{$q->mysql_error}\n{$sql}\n"; build_progress("{failed} MySQL error", 110); return; } } build_progress("{configuring_caches}", 90); echo "Configuring caches\n"; $oct_free = $oct * 0.8; $oct_small = $oct_free * 0.3; $oct_big = $oct_free * 0.7; echo "BIG: {$oct_free}*0.7; = {$oct_big}\n"; $oct_small = $oct_small / 1000; $oct_small = round($oct_small / 1000); $oct_big = $oct_big / 1000; $oct_big = round($oct_big / 1000); if ($oct_big == 0) { echo "{$q->mysql_error}\n{$sql}\n"; build_progress("{failed} Erro => 0 for big cache", 110); return; } echo "Cache1 - Small {$oct_small}MB\n"; echo "Cache2 - Big {$oct_big}MB\n"; $Cache_small_name = "{$explodedDev} - small - CPU#{$cpu}"; $Cache_small_path = "/media/{$Label}/proxy-caches/small-cpu{$cpu}"; $Cache_big_name = "{$explodedDev} - big - CPU#{$cpu}"; $Cache_big_path = "/media/{$Label}/proxy-caches/big-cpu{$cpu}"; @chown($Cache_small_path, "squid"); @chgrp($Cache_small_path, "squid"); @chown($Cache_big_path, "squid"); @chgrp($Cache_big_path, "squid"); $q->QUERY_SQL("INSERT IGNORE INTO squid_caches_center\n\t(cachename,cpu,cache_dir,cache_type,cache_size,cache_dir_level1,cache_dir_level2,enabled,percentcache,usedcache,zOrder,min_size,max_size,wizard)\n\tVALUES('{$Cache_small_name}',{$cpu},'{$Cache_small_path}','aufs','{$oct_small}','16','256',1,0,0,1,0,512,1)", "artica_backup"); if (!$q->ok) { echo "{$q->mysql_error}\n{$sql}\n"; build_progress("{failed} MySQL error", 110); return; } $q->QUERY_SQL("INSERT IGNORE INTO squid_caches_center\n\t(cachename,cpu,cache_dir,cache_type,cache_size,cache_dir_level1,cache_dir_level2,enabled,percentcache,usedcache,zOrder,min_size,max_size,wizard)\n\tVALUES('{$Cache_big_name}',{$cpu},'{$Cache_big_path}','aufs','{$oct_big}','16','256',1,0,0,1,512,3072000,1)", "artica_backup"); if (!$q->ok) { echo "{$q->mysql_error}\n{$sql}\n"; build_progress("{failed} MySQL error", 110); return; } build_progress("{building_caches}", 90); system("{$php} /usr/share/artica-postfix/exec.squid.verify.caches.php --bywizard"); build_progress("{building_caches} {success}", 100); sleep(3); build_progress("{building_caches} {success}", 100); }