Files
resatennis_tyroltenn/IDrive/.scripts/operations.php

1044 lines
33 KiB
PHP
Executable File

<?php
# To include the current file in Trace Log #
require __DIR__ . '/sqliteDB.php';
#Production Server URL's
/*define('VAULTURL', 'https://www.idrive.com/downloads/nas-servers/IDriveVaultCloudBackup.zip');
define('SYNOLOGY_X64URL', 'https://www.idrive.com/downloads/nas-servers/Synology/Synology_x64.zip');
define('SYNOLOGY_ARMURL', 'https://www.idrive.com/downloads/nas-servers/Synology/Synology_arm.zip');
define('SYNOLOGY_ALPINEURL', => "https://www.idrive.com/downloads/nas-servers/Synology/Synology_alpine.zip"; */
#SVN server URL's
define('VAULTURL', '--user=deepak --password=deepak --http-user=deepak --http-password=deepak https://192.168.2.117:8443/svn/Linux_Repository/trunk/PackagesForTesting/IDriveVault/IDriveVaultCloudBackup.zip');
define('SYNOLOGY_X64URL', '--user=deepak --password=deepak --http-user=deepak --http-password=deepak https://192.168.2.117:8443/svn/Linux_Repository/trunk/PackagesForTesting/Synology/Synology_x64.zip');
define('SYNOLOGY_ARMURL', '--user=deepak --password=deepak --http-user=deepak --http-password=deepak https://192.168.2.117:8443/svn/Linux_Repository/trunk/PackagesForTesting/Synology/Synology_arm.zip');
define('SYNOLOGY_ALPINEURL', '--user=deepak --password=deepak --http-user=deepak --http-password=deepak https://192.168.2.117:8443/svn/Linux_Repository/trunk/PackagesForTesting/Synology/Synology_alpine.zip');
$linestemp_file = array();
$linesCrontabConfigFile = array();
$hrSchedule = -1;
$minSchedule = -1;
$scheduled = 0;
$size = 0;
$argument = $argv[2];
$subargument = $argv[1];
define('NOT_EXIST', 0);
define('EXIST', 1);
define('NOT_CHECKED', 2);
# variables used for calculating the total folder sizes
$filesSizeValue = 0;
$output = operations();
exit;
#****************************************************************************************************
# Subroutine Name : operations
# Objective : Makes call to the respective function depending on operation
# Added By : Sabin Cheruvattil | 2018-11-05
#*****************************************************************************************************/
function operations()
{
GLOBAL $userDir, $argument, $subargument, $linestemp_file;
$operationName = "";
$temp_file = $userDir.PATHSEPARATOR.TEMP_OPERATION_FILE;
$contentFile = trim($argument);
if((file_exists($subargument)) || $subargument == ""){
if(!empty($contentFile))
$temp_file = $contentFile;
$linestemp_file = file($temp_file);
if(!$linestemp_file) {
if(preg_match("/temp_\d*\.txt/", $subargument) !== FALSE) {
$linestemp_file = file($subargument);
$temp_file = $subargument;
} else {
traceLog("Unable to open file $temp_file");
exit(1);
}
}
@unlink($temp_file);
$linestemp_file[0] = trim($linestemp_file[0]);
$operationName = $linestemp_file[0];
}
else
$operationName = trim($subargument);
switch($operationName) {
case 'updateCrontabEntry':
updateCrontabEntry();
configureAndCommitCron();
break;
case 'removeCrontabEntry':
removeCrontabEntry();
configureAndCommitCron();
break;
case 'dirRemove':
dirRemove();
break;
case 'addCrontabEntry':
addCrontabEntry();
configureAndCommitCron();
break;
case 'commandExecution':
commandExecution();
break;
case 'update_App':
print update_App(trim($linestemp_file[1]));
break;
case 'validate_filelist':
print isItemExists();
break;
case 'getFileFolderSize':
getItemSize($linestemp_file[1]);
break;
case 'isWritable':
if (is_writable($linestemp_file[1])) {
print 'writable';
}
else {
print 'not writable';
}
break;
case 'isReadable':
if (is_readable($linestemp_file[1])) {
print 'readable';
}
else {
print 'not readable';
}
break;
case 'StopApp':
stopAllAppServices();
break;
default:
traceLog("Invalid operation type.");
break;
}
}
/****************************************************************************************************
* Subroutine Name : extra_backup_restore_entry
* Objective : Updates the crontab file with extra backup entry
* Added By : Pooja Havaldar
* Modified By : Sabin Cheruvattil | 2016-12-01
*****************************************************************************************************/
function extra_backup_restore_entry($entry)
{
GLOBAL $cronSeparator, $linestemp_file, $linesCrontabConfigFile;
$cronData = '';
$tempArr = explode("$cronSeparator", $linestemp_file[$entry]);
$hrSchedule = $tempArr[1];
$minSchedule = $tempArr[0];
if('*' == $tempArr[2] || 28 >= $tempArr[2]) {
return;
}
if('29' == $tempArr[2]) {
$tempArr[2] = '28';
$tempArr[3] = 2;
} elseif('30' == $tempArr[2]) {
$tempArr[2] = '28-29';
$tempArr[3] = 2;
} elseif('31' == $tempArr[2]) {
$tempArr[2] = '28-30';
$tempArr[3] = '2,4,6,9,11';
}
$cronData = implode($cronSeparator, $tempArr);
array_push($linesCrontabConfigFile, $cronData . " lastDay" . LINEFEED);
}
/****************************************************************************************************
* Subroutine Name : extra_jobtermination_entry
* Objective : Updates the crontab file with extra job termination entry
* Added By : Pooja Havaldar
* Modified By : Sabin Cheruvattil | 2016-12-01
*****************************************************************************************************/
function extra_jobtermination_entry($entry)
{
GLOBAL $cronSeparator, $linestemp_file, $hrSchedule, $minSchedule;
GLOBAL $linesCrontabConfigFile;
$cronData = '';
$tempArr = explode("$cronSeparator", $linestemp_file[$entry]);
if('*' == $tempArr[2] || 28 >= $tempArr[2]) {
return;
}
# when cut off hour is more than scheduler hour
if($tempArr[1] > $hrSchedule) {
if('29' == $tempArr[2]) {
$tempArr[2] = '28';
$tempArr[3] = 2;
} elseif('30' == $tempArr[2]){
$tempArr[2] = '28-29';
$tempArr[3] = 2;
} elseif('31' == $tempArr[2]) {
$tempArr[2] = '28-30';
$tempArr[3] = '2,4,6,9,11';
}
} elseif($tempArr[1] < $hrSchedule) {
# when scheduler hour is more than cut off hour
if('29' == $tempArr[2] || '30' == $tempArr[2]) {
$tempArr[2] = '1';
$tempArr[3] = 3;
} elseif('31' == $tempArr[2]) {
$tempArr[2] = '1';
$tempArr[3] = '3,5,7,10,12';
}
} elseif($tempArr[1] == $hrSchedule) {
# when scheduler hour is equal to cut off hour
if($tempArr[0] > $minSchedule) {
# when cut off minutes are more than scheduler minutes
if('29' == $tempArr[2]) {
$tempArr[2] = '28';
$tempArr[3] = 2;
} elseif('30' == $tempArr[2]) {
$tempArr[2] = '28-29';
$tempArr[3] = 2;
} elseif('31' == $tempArr[2]) {
$tempArr[2] = '28-30';
$tempArr[3] = '2,4,6,9,11';
}
} elseif($tempArr[0] <= $minSchedule) {
# when cut off minutes are equal or less than scheduler minutes
if('29' == $tempArr[2] || '30' == $tempArr[2]) {
$tempArr[2] = '1';
$tempArr[3] = 3;
} elseif('31' == $tempArr[2]) {
$tempArr[2] = '1';
$tempArr[3] = '3,5,7,10,12';
}
}
}
$cronData = implode($cronSeparator, $tempArr);
array_push($linesCrontabConfigFile, $cronData . " lastDay" . LINEFEED);
}
/****************************************************************************************************
* Subroutine Name : updateCrontabEntry
* Objective : Updates the crontab file with new entry
* Added By : Pooja Havaldar
* Modified By : Sabin Cheruvattil
*****************************************************************************************************/
function updateCrontabEntry()
{
GLOBAL $cronCat, $linestemp_file, $scheduled, $linesCrontabConfigFile;
if(!fopen($cronCat, 'r+')) {
traceLog("Unable to open file $cronCat");
return;
}
$linesCrontabConfigFile = file($cronCat);
$linestemp_file[1] = trim($linestemp_file[1]);
$linesCrontabExLines = array();
foreach($linesCrontabConfigFile as $cronTabLine) {
$cronTabLine = trim($cronTabLine);
if($cronTabLine == "")
continue;
elseif(strpos($cronTabLine, $linestemp_file[1] . ';') === FALSE) {
$linesCrontabExLines[] = $cronTabLine."\n";
}
}
$linesCrontabConfigFile = $linesCrontabExLines;
$len = count($linestemp_file);
for($i = 2; $i<= $len; $i++) {
$linestemp_file[$i] = trim($linestemp_file[$i]);
if(preg_match('/Backup_Script_IDrive/', $linestemp_file[$i]) || preg_match('/Restore_Script_IDrive/', $linestemp_file[$i])) {
$scheduled = 1;
extra_backup_restore_entry($i);
} else {
# To check for start immediately with cut off and pass parameter to Job Termination script
if($linestemp_file[$i] != '' && preg_match('/Job_Termination_Script/', $linestemp_file[$i])) {
$linestemp_file[$i] = str_replace('Job_Termination_Script.php', "Job_Termination_Script.php $scheduled", $linestemp_file[$i]);
} elseif(preg_match('/Job_Termination_Script/', $linestemp_file[$i])) {
extra_jobtermination_entry($i);
}
}
array_push($linesCrontabConfigFile,$linestemp_file[$i]."\n");
}
file_put_contents($cronCat,$linesCrontabConfigFile);
}
/****************************************************************************************************
* Subroutine Name : removeCrontabEntry
* Objective : Removes the selected job entry from crontab file
* Modified By : Sabin Cheruvattil
*****************************************************************************************************/
function removeCrontabEntry()
{
GLOBAL $cronCat, $linestemp_file;
$linesCrontabConfigFile = array();
if(!is_writable($cronCat)) {
traceLog("Unable to open file $cronCat");
return;
}
$linesCrontabConfigFile = file($cronCat);
$linestemp_file[1] = trim($linestemp_file[1]);
$linesCrontabExLines = array();
foreach($linesCrontabConfigFile as $cronTabLine) {
if(strpos($cronTabLine, $linestemp_file[1] . ';') === FALSE) {
$linesCrontabExLines[] = $cronTabLine;
}
}
$linesCrontabConfigFile = $linesCrontabExLines;
file_put_contents($cronCat,$linesCrontabConfigFile);
$linestemp_file[2] = trim($linestemp_file[2]);
if("Delete" == $linestemp_file[2]) {
removeItems($linestemp_file[1]);
}
}
/*************************************************************************************************************
* Subroutine Name : dirRemove
* Objective : Removes the files/folders under root level along with local and remote search path
* Added By : Sabin Cheruvattil
**************************************************************************************************************/
function dirRemove()
{
GLOBAL $userDir;
$rListPath = "$userDir/.RestoreList/";
$localSearchPath = "$userDir/".BACKUP."/.+searchList/";
$remoteSearchPath = "$userDir/Restore/.+searchList/";
$sizeFilePath = "$userDir/sizeOutput.txt";
$remoteSearchTrashPath = "$userDir/Restore/.+trashList/";
$val = array($localSearchPath, $remoteSearchPath, $remoteSearchTrashPath, $rListPath, $sizeFilePath);
removeItems($val);
print 1;
}
/*************************************************************************************************************
* Subroutine Name : addCrontabEntry
* Objective : To enter the new job details in crontab file
* Added By : Sabin Cheruvattil
**************************************************************************************************************/
function addCrontabEntry()
{
GLOBAL $cronSeparator, $linestemp_file, $cronCat;
$cronData = '';
$tempArr = explode($cronSeparator, $linestemp_file[2]);
file_put_contents($cronCat, $linestemp_file[2] . LINEFEED, FILE_APPEND);
if('*' != $tempArr[2] && 29 <= $tempArr[2]) {
if('29' == $tempArr[2] || '30' == $tempArr[2]) {
$tempArr[2] = '28-29';
$tempArr[3] = 2;
} elseif('31' == $tempArr[2]) {
$tempArr[2] = '28-30';
$tempArr[3] = '2,4,6,9,11';
}
$tempArr[5] .= $cronSeparator . '[ "$(date +%d -d tomorrow)" = "01" ] &&';
$cronData = implode($cronSeparator, $tempArr);
file_put_contents($cronCat, $cronData . LINEFEED, FILE_APPEND);
}
}
/*************************************************************************************************************
* Subroutine Name : commandExecution
* Objective : This is to execute commands
* Added By : Sabin Cheruvattil
**************************************************************************************************************/
function commandExecution()
{
GLOBAL $linestemp_file;
$result = '';
for($i = 1; $i < count($linestemp_file); $i++) {
$result = `$linestemp_file[$i]`;
}
print $result;
}
/*************************************************************************************************************
* Subroutine Name : clearAppUpdateLock
* Objective : This helps to unlock the update lock
* Added By : Sabin Cheruvattil
**************************************************************************************************************/
function clearAppUpdateLock()
{
GLOBAL $webDir;
$lockFile = fopen("$webDir/".SERVICE."/".USER_PROFILE."/Update/lock", 'a');
if($lockFile) {
flock($lockFile, LOCK_EX);
fclose($lockFile);
}
removeItems($lockFile);
}
/*************************************************************************************************************
* Subroutine Name : update_App
* Objective : To upgrade the present package
* Added By : Pooja Havaldar
* Modified By : Sabin Cheruvattil
**************************************************************************************************************/
function update_App($proxyPath = '')
{
GLOBAL $webDir, $machine;
$cur_path = '';
$lockFile = "$webDir/".SERVICE."/Update/lock";
$fp = fopen($lockFile, 'w+');
if(!$fp) {
traceLog("unable to lock $lockFile file for app update, ".customErrorMsg());
}
flock($fp, 2);
$URLname = getDownloadURL();
$status = 'FAILURE';
$proxySetting = '';
$proxy = '';
$cur_path = getAppPath();
$wgetPath = $cur_path . "/../../bin/wget";
if($machine == SYNOLOGY) {
$wgetPath = `which wget`;
}
$wgetPath = trim($wgetPath);
if(is_link($cur_path)){
$cur_path = readlink($cur_path);
$packageName = $cur_path;
$backupPackageName = $cur_path . '_bak';
} else {
$packageName = $cur_path;
$backupPackageName = $cur_path . '_bak';
}
if(!file_exists($wgetPath)) {
traceLog('Failed to update, Reason: Wget is unavailable.');
clearAppUpdateLock();
return $status;
}
if($proxyPath != '') {
$proxy = $proxyPath;
} else {
# @TODO: Pass by reference | make sure functions accepts the same
$key = 'PROXY';
getParameterValueFromAccountSettingsFile($key, $proxySetting);
$proxySetting = trim($proxySetting);
if($proxySetting != '') {
$i = (int)strrpos($proxySetting, '@');
if($i > 0) {
$user_pass = substr($proxySetting, 0, $i);
$ip_port = substr($proxySetting, $i + 1);
}
if($ip_port != '') {
$index = 0;
$index = (int)strrpos($ip_port, ':');
if($index > 0) {
$ip = substr($ip_port, 0, $index);
$port = substr($ip_port, $index + 1);
}
}
if($user_pass != '' && $user_pass != ':') {
$pos = (int)strrpos($user_pass, ':');
if($pos > 0) {
$user = substr($user_pass, 0, $pos);
$pass = substr($user_pass, $pos + 1);
}
}
if($user == '' && $ip != '') {
$proxy = 'http://' . $ip . ':' . $port;
} else {
$proxy = 'http://' . $user . ':' . $pass . '@' . $ip . ':' . $port;
}
}
}
if($proxy != '') {
$wgetCmd = "$wgetPath --no-check-certificate --tries=5 -e http_proxy=$proxy $URLname[0]";
} else {
$wgetCmd = "$wgetPath --no-check-certificate $URLname[0]";
}
if(!file_exists("$URLname[1].zip")) {
removeItems($URLname[1].".zip");
}
$result = system($wgetCmd);
if($result != 0) {
traceLog("Update failed. Reason: Failed to execute command.");
clearAppUpdateLock();
return $status;
}
$unzip = '';
$tmpDir = $cur_path . '_tmp';
mkdir($tmpDir);
`chmod PERMISSIONVAL $tmpDir`;
$unzip = trim(`which unzip`);
if($unzip == '') {
$unzip = trim(`which 7z`);
$cmd = "$unzip x -o$tmpDir -y $URLname[1].zip";
} else {
$cmd = "$unzip $URLname[1].zip -d $tmpDir";
}
`$cmd`;
$tmp = "$tmpDir/$URLname[1]/IDrive";
`chmod -R PERMISSIONVAL $tmp`;
if(!file_exists($tmp)) {
traceLog("Update failed. Reason: File does not exist : $tmp");
removeItems($tmpDir);
removeItems($URLname[1].".zip");
clearAppUpdateLock();
return $status;
}
$tmpInfo = "$tmpDir/$URLname[1]/INFO";
$cmdFile = "$tmpDir/$URLname[1]/cmdFile.txt";
if($machine == SYNOLOGY) {
`chown -R root:root $tmp`;
`chown -R root:root $tmp/.scripts`;
`chown -R root:root $tmp/.config`;
`chmod PERMISSIONVAL $tmp/.config`;
`chmod PERMISSIONVAL $tmp/.scripts`;
`chmod 04755 $tmp/.config/su`;
}
$rencommand = "mv '$packageName/' '$backupPackageName/'";
$res = `$rencommand`;
if($res != '') {
traceLog('Update failed. Reason: Rename failed to create backup package.');
removeItems($tmpDir);
removeItems($URLname[1].".zip");
clearAppUpdateLock();
return $status;
}
if($machine == SYNOLOGY) {
$appPath = '/var/packages/IDrive/target/app';
$infoPath = '/var/packages/IDrive/INFO';
$tmpHidden = $tmp."/.[^.]*";
$res = `cp -rfp $tmpHidden $appPath`;
$res = `mv $tmpInfo $infoPath`;
$status = 'SUCCESS';
}
$rencommand = "mv '$tmp/' '$packageName/'";
$res = `$rencommand`;
if($res == '') {
$status = "SUCCESS";
removeItems($backupPackageName);
$phpPath = `which php`;
if($machine == SYNOLOGY && $phpPath != '') {
system("$phpPath ".PHP_IGNORE_OPENBASEDIR." '$cur_path/.config/IDrive_cron.php' &");
}
updateCmdExecution($cmdFile);
} else {
$rencommand = "mv '$backupPackageName/' '$packageName/'";
$res = `$rencommand`;
if($res != '') {
traceLog("Update failed. Reason: Unable to rename $backupPackageName to $packageName.");
}
}
clearAppUpdateLock();
removeItems($tmpDir);
removeItems($URLname[1].".zip");
return $status;
}
/*************************************************************************************************************
* Subroutine Name : isItemExists.
* Objective : Check existance of all items and return the result.
* Added By : Sabin Cheruvattil
**************************************************************************************************************/
function isItemExists()
{
GLOBAL $linestemp_file;
$idx = 0;
$j = 0;
$response = 'status[]=true';
$jobPath = trim($linestemp_file[1]);
$item = $linestemp_file[2] . '/';
# get contents of display file $jobPath.
if(!fopen($jobPath, 'r')) {
traceLog("Unable to open $jobPath");
return $response;
}
$contentsArr = file($jobPath);
for($idx = 0, $j = 0; $idx < count($contentsArr); $idx += 4, $j++) {
$contentsArr[$idx] = trim($contentsArr[$idx],"\n");
$contentsArr[$idx+1]= trim($contentsArr[$idx + 1]);
$temp = $contentsArr[$idx]."/";
$fileName = str_replace('&', '%26', $contentsArr[$idx]);
$fileName = str_replace('+', '%2B', $fileName);
$response .= '&fileNames[]=' . $fileName;
$response .= '&fileTypes[]=' . $contentsArr[$idx + 1];
if('//' == $item || preg_match("/^$item/", $temp)) {
# initialize $! with null before check of existance
if(('folder' == $contentsArr[$idx + 1] && is_dir($contentsArr[$idx])) || ('file' == $contentsArr[$idx + 1] && is_file($contentsArr[$idx]))) {
$response .= '&fileInfos[]=' . EXIST;
if('file' == $contentsArr[$idx + 1]) {
$stat = stat($fileName);
$date_value = trim($contentsArr[$idx + 3],"\n");
$response .= '&fileSize[]=' . checkFileSizeAccuracy($stat[7],$stat[9],trim($contentsArr[$idx + 2],"\n"),$date_value,$fileName);
$response .= '&fileLMod[]='.$date_value;
} else {
$response .= '&fileSize[]=-1';
$response .= '&fileLMod[]=undefined';
}
} else {
$response .= '&fileInfos[]=' . NOT_EXIST;
if('file' == $contentsArr[$idx + 1]) {
$stat = stat($fileName);
$response .= '&fileSize[]=' . checkFileSizeAccuracy($stat[7],$stat[9],trim($contentsArr[$idx + 2],"\n"),$contentsArr[$idx + 3],$fileName);
$response .= '&fileLMod[]='.$contentsArr[$idx + 3];
} else {
$response .= '&fileSize[]=-1';
$response .= '&fileLMod[]=undefined';
}
}
} else {
$response .= '&fileInfos[]=' . NOT_CHECKED;
if('file' == $contentsArr[$idx + 1]) {
$stat = stat($fileName);
$response .= '&fileSize[]=' . checkFileSizeAccuracy($stat[7],$stat[9],trim($contentsArr[$idx + 2],"\n"),$contentsArr[$idx + 3],$fileName);
$response .= '&fileLMod[]='.$contentsArr[$idx + 3];
} else {
$response .= '&fileSize[]=-1';
$response .= '&fileLMod[]=undefined';
}
}
}
return $response;
}
/*************************************************************************************
* Subroutine Name : checkFileSizeAccuracy
* Objective : To get whether the file size is correct or not based on 32 and 64 bit
* Added By : Pooja Havaldar, Sabin Cheruvattil
**************************************************************************************/
function checkFileSizeAccuracy($calcSizeValue,$lastModTime,$prevSize,$prevModTime,$tempPath)
{
if(PHP_INT_MAX > 2147483647)
return $calcSizeValue;
// from lModStat value != prevModTime
if($lastModTime == strtotime($prevModTime))
return $prevSize;
return customFileSize($tempPath);
}
/*************************************************************************************************************
* Subroutine Name : getDownloadURL
* Objective : To get the required URL for download and AppName
* Added By : Pooja Havaldar, Sabin Cheruvattil
**************************************************************************************************************/
function getDownloadURL()
{
GLOBAL $machine;
$url = '';
$appName = '';
if($machine != SYNOLOGY) {
$url = VAULTURL;
$appName = 'IDriveVaultCloudBackup';
} else {
$system = `uname -a`;
if(preg_match('/arm/', $system)) {
if(preg_match('/alpine/', $system)) {
$url = SYNOLOGY_ALPINEURL;
$appName = "Synology_alpine";
} else {
$url = SYNOLOGY_ARMURL;
$appName = 'Synology_arm';
}
} else {
$url = SYNOLOGY_X64URL;
$appName = 'Synology_x64';
}
}
return array($url, $appName);
}
/*************************************************************************************************************
* Subroutine Name : updateCmdExecution
* Objective : To execute cmds in the file which are required after update.
* Added By : Pooja Havaldar, Sabin Cheruvattil
**************************************************************************************************************/
function updateCmdExecution($cmdFile)
{
if(!file_exists($cmdFile)) {
return 0;
}
if(fopen($cmdFile, 'r')) {
traceLog("Unable to open $cmdFile file to read.");
}
$content = file($cmdFile);
for($i = 0; $i < count($content); $i++) {
if($content[$i] != '') {
$content[$i] = trim($content[$i]);
$result = `$content[$i]`;
}
}
return 1;
}
/*************************************************************************************************************
* Subroutine Name : getProxyParameter
* Objective : To get the parameters to create proxy string.
* Added By : Pooja Havaldar, Sabin Cheruvattil
**************************************************************************************************************/
function getProxyParameter($proxySetting)
{
$i = (int)strrpos($proxySetting, '@');
if($i > 0) {
$user_pass = substr($proxySetting, 0, $i);
$ip_port = substr($proxySetting, $i + 1);
}
if($ip_port != '') {
$index = (int)strrpos($ip_port, ':');
if($index > 0) {
$ip = substr($ip_port, 0, $index);
$port = substr($ip_port, $index + 1);
}
}
if($user_pass != '' && $user_pass != ':') {
$pos = (int)strrpos($user_pass, ":");
if($pos > 0) {
$user = substr($user_pass, 0, $pos);
$pass = substr($user_pass, $pos + 1);
}
}
return array($user, $pass, $ip, $port);
}
/*************************************************************************************************************
* Subroutine Name : setUnset
* Objective : To set/unset the localDb
* Added By : Pooja Havaldar, Sabin Cheruvattil
**************************************************************************************************************/
/*
function setUnset()
{
GLOBAL $linestemp_file;
$res = '';
$linestemp_file[1] = trim($linestemp_file[1]);
if($linestemp_file[1] == 'set') {
$linestemp_file[2] = trim($linestemp_file[2]);
# set function is coming from sqlite.pl
$res = set($linestemp_file[2]);
if($res != 'success' && $res != 'set'){
traceLog('Unable to set the DB.');
}
} elseif($linestemp_file[1] == 'unset') {
$linestemp_file[2] = trim($linestemp_file[2]);
# set function is coming from sqlite.pl
$res = dbUnset($linestemp_file[2]);
if($res != 'success' && $res != 'unset') {
traceLog('Unable to unset the DB.');
return 0;
}
} else {
traceLog("\n Something wrong with local DB ");
return 0;
}
traceLog('Returning setUnset:1=' . $linestemp_file[1]);
return 1;
}
*/
/*************************************************************************************************************
* Subroutine Name : lockSizeFd
* Objective : Lock the file sizepid.txt before checking folder size.
* Added By : Yogesh Kumar, Sabin Cheruvattil
**************************************************************************************************************/
function lockSizeFd()
{
GLOBAL $fsFP;
$fsFP = "";
$fileSizeRequest = "sizepid.txt"; # File size request PID.
$fsFP = fopen($fileSizeRequest, 'w');
if(!$fsFP) {
traceLog("Unable to open file $fileSizeRequest.Reason:".customErrorMsg());
exit();
}
chmod($fileSizeRequest, PERMISSIONVAL);
if(!flock($fsFP, 2)) {
traceLog("Unable to put lock on $fileSizeRequest.Reason:".customErrorMsg());
exit();
}
file_put_contents($fileSizeRequest, getmypid());
@chmod($fileSizeRequest,PERMISSIONVAL);
# select((select(SIZEFD), $| = 1)[0]); || we are not doing auto flush
return;
}
/*************************************************************************************************************
* Subroutine Name : getFileFolderSize
* Objective : To get File/Folder Size
* Added By : Deepak
* Modified By : Senthil Pandian.K | Sabin Cheruvattil
**************************************************************************************************************/
function getFolderSize($item)
{
GLOBAL $size, $userDir;
if(substr($item, -1, 1) != '/') {
$item = trim($item,"\n");
$item .= '/';
}
$dir = NULL;
if(!($dir = opendir($item))) {
traceLog("Could not open Dir $item:Reason:".customErrorMsg());
return 0;
}
$i = 0;
while (false !== ($file = readdir($dir))) {
if(++$i%100 === 0)
usleep(1000);
if($file == '.' || $file == '..')
continue;
$temp = trim($item.$file,"\n");
if(is_link($temp))
continue;
else if(is_dir($temp))
getFolderSize($temp);
else if(is_file($temp))
$size += customFileSize($temp);
}
closedir($dir);
return 1;
}
/*************************************************************************************************************
* Subroutine Name : getItemSize
* Objective : To get item Size
* Added By : Yogesh Kumar
* Modified By : Sabin Cheruvattil
**************************************************************************************************************/
function getItemSize($item)
{
GLOBAL $size;
$size = 0;
lockSizeFd();
getFinalFolderSize($item);
$sizeOutputFile = 'sizeOutput.txt';
if(!fopen($sizeOutputFile, 'w+')) {
traceLog("Unable to open $sizeOutputFile. Reason:".customErrorMsg());
return;
}
file_put_contents($sizeOutputFile, "$size\t$item" . LINEFEED);
chmod($sizeOutputFile, PERMISSIONVAL);
unlink('sizepid.txt');
return;
}
/*************************************************************************************************************
* Subroutine Name : getFinalFolderSize
* Objective : To get total folder size
* Added By : Anil Kumar
**************************************************************************************************************/
function getFinalFolderSize($item)
{
GLOBAL $filesSizeValue, $size;
# [ 2^((4*8 - 1)-1) ==> (2^31)-1 ==> 2147483647.)) ]
if(PHP_INT_MAX <= 2147483647){
$item = str_replace("'","'\''",$item);
getFolderSizeFromLS($item);
$size = $filesSizeValue;
}
else{
getFolderSize($item);
}
}
/*************************************************************************************************************
* Subroutine Name : getFolderSizeFromLS
* Objective : To parse and loop each and every inner folders
* Added By : Anil Kumar
* MOdified By : Sabin Cheruvattil
**************************************************************************************************************/
function getFolderSizeFromLS($item)
{
GLOBAL $filesSizeValue, $machine, $appPath, $userDir;
$lastLine = '';
$resultList = '';
$lsDIR = $userDir . PATHSEPARATOR . 'lsDIR';
if(!is_dir($lsDIR)) {
mkdir($lsDIR, PERMISSIONVAL);
@chmod($lsDIR, PERMISSIONVAL);
}
$toFind = array("/","'"," ");
$toReplace = array("_","_","_");
$cmdOPFile = $lsDIR . PATHSEPARATOR . LS_TMP_OUTPUT . addslashes(str_replace($toFind, $toReplace, $item));
if($machine == NETGEAR) {
$cmd = "$appPath/ls -aln '$item' > '$cmdOPFile'";
} else if($machine == QNAP || $machine == SYNOLOGY || $machine == ASUSTOR) {
$cmd = "ls -aln '$item' > '$cmdOPFile'";
} else if($machine == TWOTIER) {
$cmd = "/bin/ls -aln '$item' > '$cmdOPFile'";
}
shell_exec($cmd);
$handle = fopen($cmdOPFile, 'r');
while(1) {
if(!$handle) {
break;
}
$buffer = fread($handle, 4096);
if(empty($buffer)) {
break;
}
if(!empty($lastLine)) {
$buffer = $lastLine . $buffer;
}
if(!preg_match('/\n$/', $buffer)) {
$lastNewlinePos = strrpos($buffer, "\n");
$resultList = substr($buffer, 0, $lastNewlinePos);
$lastLine = substr($buffer, $lastNewlinePos);
} else {
$resultList = $buffer;
$lastLine = '';
}
unset($buffer);
$commandOutput = explode("\n", $resultList);
foreach($commandOutput as $outputList) {
$parseDetails = preg_split('/\s+/', $outputList, 8);
$fileSize = $parseDetails[4];
$fileType = $parseDetails[0];
$split1 = preg_split('/\s/', $parseDetails[7], 2);
$fileName = $split1[1];
if(empty($fileName) || $fileName == '.' || $fileName == '..') {
continue;
}
if($fileType[0] == 'd') {
$fileName = str_replace("'", "'\''", $fileName);
$folder_path = $item . "/" . $fileName;
getFolderSizeFromLS($folder_path);
} else if($fileType[0] == '-') {
$filesSizeValue += $fileSize;
}
}
}
unlink($cmdOPFile);
}
/*************************************************************************************************************
* Subroutine Name : stopAllAppServices
* Objective : To remove all pid's of the user jobs inorder to kill the runnning jobs when app got stopped.
* Added By : Anil Kumar
**************************************************************************************************************/
function stopAllAppServices() {
GLOBAL $webDir, $machine;
session_start();
//Added to remove the unwanted existing session file
$sesionId = session_id();
$session_path = session_save_path();
if(session_save_path() == '')
$session_path = sys_get_temp_dir();
session_destroy();
@unlink($session_path.'/sess_'.$sesionId); #removing session file
$userDir = $webDir.PATHSEPARATOR.SERVICE.PATHSEPARATOR.USER_PROFILE;
$jobs=array("Backup", "Restore", "LocalBackup", "LocalRestore", "Achive", "DBReindex" );
# get list of NAS users in the app.
$nasUserDirs = glob($userDir . '/*' , GLOB_ONLYDIR);
if(count($nasUserDirs) > 0) {
for($i = 0; $i < count($nasUserDirs); $i++){
#get list of idrive user dir's
$idriveUserList = glob($nasUserDirs[$i] . '/*' , GLOB_ONLYDIR);
if(count($idriveUserList) > 0) {
for($j = 0; $j < count($idriveUserList); $j++){
$idriveUserVal = $idriveUserList[$j];
# loop through different jobs
for($k = 0; $k < count($jobs); $k++){
$jobDir = $idriveUserVal."/".$jobs[$k];
if ((file_exists($jobDir)) && (is_dir($jobDir))) {
//If it is reindex, remove PID and delete directory.
if($jobs[$k] == "DBReindex"){
$pidPath = $jobDir."/pid.txt";
if(file_exists($pidPath)){
@unlink($pidPath);
}
removeItems($jobDir);
}else{
$jobsList = glob($jobDir . '/*' , GLOB_ONLYDIR);
# loop through all the jobs user have.
for($l = 0; $l < count($jobsList); $l++){
#find and delete pid's if exist.
$pidPath = $jobsList[$l]."/pid.txt";
if(file_exists($pidPath)){
$appCenterDetail = loadMachineAppCenterDetails();
file_put_contents($jobsList[$l].'/'.CANCEL_PATH,"Operation could not be completed. Reason: App has been stopped in ".ucfirst($machine)." $appCenterDetail.",FILE_APPEND);
@unlink($pidPath);
}
}
}
}
}
}
}
}
}
}
?>