Unable to load php sessions."; exit; } function my_autoloader($class_name) { if($class_name == 'SQLite3') { return FALSE; } include "c.".$class_name . ".php"; } spl_autoload_register('my_autoloader'); session_start(); if(isset($_SESSION['baseDir'])){ session_destroy(); session_start(); } error_reporting(0); //error_reporting(E_ALL); //ini_set("display_errors", 1); if(!isset($_SESSION['httpuser'])) { $_SESSION['httpuser'] = exec('whoami'); } $permissionVal = 0777; # populate base session if(!isset($_SESSION['machine']) || !isset($_SESSION['webDir']) || !isset($_SESSION['nasUser'])) { loadMachineConfigurations(); } if(!isset($_SESSION['haslsdatetimeformat'])) { $_SESSION['haslsdatetimeformat'] = exec('ls --time-style="+%a %b %e %H:%M:%S %Y" &> /dev/null ; echo $?'); } $webDir = isset($_SESSION['webDir'])? $_SESSION['webDir'] : ''; $user = isset($_SESSION['nasUser'])? $_SESSION['nasUser'] : ''; $machine = isset($_SESSION['machine'])? $_SESSION['machine'] : ''; $perlPath = getPerlPath(); include_once 'common.php'; if(isset($_SESSION['validUser']) && ($_SESSION['validUser'] === true)) { // check for trigger file and logout. $needToLogout = "$appPath/logout.txt"; if(file_exists($needToLogout)) { @unlink($needToLogout); $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}"; $url = ""; if (strpos($actual_link, '.config') !== false) { $url = "logout.php"; }else $url = ".config/logout.php"; exit(header("Location:".$url)); } } // check for trigger file and logout. $needToClose = "$appPath/appWasStopped.txt"; if(file_exists($needToClose)) { exit(header("Location: index.php")); } $twoTierSharePathLength = strlen(TWOTIER_SHARED_PATH)-1; if($machine == NETGEAR_LOCAL){ if(!isset($_SESSION['getNetgearSharedPath'])) $NetgearSharedPath = getNetgearSharedPath(); else $NetgearSharedPath = $_SESSION['getNetgearSharedPath']; } /********************************************************************************************************* * Subroutine Name : getPerlPath * Objective : This function will return full path for perl based on machine type * Added By : Deepak Chaurasia **********************************************************************************************************/ function getPerlPath() { GLOBAL $machine; GLOBAL $appPerlPath; if(!isset($_SESSION['perlPath'])){ machineBasedContent($machine); if("twotier" == $machine){ $perlPath = $appPerlPath; } else { $command = "which perl"; $perlPath=shell_exec($command); $perlPath = trim($perlPath); if($perlPath == ''){ $perlPath = $appPerlPath; } } $_SESSION['perlPath'] = $perlPath; } else { $perlPath = $_SESSION['perlPath']; } return $perlPath; } /********************************************************************************************************* * Subroutine Name : getPhpPath * Objective : This function will return full path for PHP based on machine type * Added By : Senthil Pandian **********************************************************************************************************/ function getPhpPath() { GLOBAL $machine; GLOBAL $appPHPPath; if(!isset($_SESSION['phpPath'])){ machineBasedContent($machine); if ("twotier" == $machine){ $phpPath = $appPHPPath; } else { $command = "which php"; $phpPath=shell_exec($command); $phpPath = trim($phpPath); if($phpPath == ''){ $phpPath = $appPHPPath; } } $_SESSION['phpPath'] = $phpPath; } else { $phpPath = $_SESSION['phpPath']; } return $phpPath.PHP_IGNORE_OPENBASEDIR; } /********************************************************************************************************* * Subroutine Name : appServices * Objective : Build and write perl commands to a file. * Added By : Yogesh Kumar P * Modified By : Avinash Kumar **********************************************************************************************************/ function appServices($script, $currPath) { GLOBAL $machine; GLOBAL $appPath; GLOBAL $phpPath; GLOBAL $webDir; GLOBAL $userName,$permissionVal; if($currPath==""){ $currPath = getcwd(); } $currPath = str_replace("'","'\''",$currPath); $currPath = str_replace('"','\"',$currPath); $currPath = str_replace('$','\$',$currPath); $currPath = "'".$currPath."'"; $tempFile = Scheduler::$nasUser_dir;//"$webDir/".SERVICE."/".USER_PROFILE; $tempFile .= "/$userName/".TEMP_OPERATION_FILE; $contentFile = NULL; if (file_exists($tempFile)) { $contents = file($tempFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); $contentFile = Scheduler::$user_dir; $contentFile .= ('temp_'.time().'.txt'); $firstTime = TRUE; foreach($contents as $content) { if ($firstTime) { file_put_contents((__DIR__ . "/" . SCHEDULERFILE), ('echo ' . escapeshellarg($content) . ' > ' . escapeshellarg($contentFile) . PHP_EOL), FILE_APPEND); $firstTime = FALSE; } else { file_put_contents((__DIR__ . "/" . SCHEDULERFILE), ('echo ' . escapeshellarg($content) . ' >> ' . escapeshellarg($contentFile) . PHP_EOL), FILE_APPEND); } } file_put_contents((__DIR__ . "/" . SCHEDULERFILE), "rm -rf \"$tempFile\"" . PHP_EOL, FILE_APPEND); } $command = "cd $currPath; " . " $phpPath \"$appPath/" . SCRIPT . "/$script\""; if ($contentFile !== NULL) { $command .= (" \"$contentFile\" "); } file_put_contents((__DIR__ . "/" . SCHEDULERFILE), ($command . "\n"), FILE_APPEND); @chmod((__DIR__ . "/" . SCHEDULERFILE), $permissionVal); return ''; } /********************************************************************************************************* * Subroutine Name : isJpbRunning. * Objective : Chaeck job is running or not through lock on StartPid.txt. * Added By : Avinash Kumar. **********************************************************************************************************/ function isJobRunning($startPidPath) { if(isFileLocked($startPidPath)){ Scheduler::Log("Job is running: " . dirname($startPidPath)); return true; } return false; } /********************************************************************************************************* * Subroutine Name : clearAppUpdateLock * Objective : clear app aupdate lock if the lock is removed * Added By : Sabin Cheruvattil | 2016-08-02 **********************************************************************************************************/ function clearAppUpdateLock() { if(file_exists(Scheduler::$appUpdateLockFile)) { $lockFlag = 0; $fp = fopen(Scheduler::$appUpdateLockFile, 'a'); if(!flock($fp, LOCK_EX, $lockFlag)) { Scheduler::Log("App update is running..."); return FALSE; } fclose($fp); unlink(Scheduler::$appUpdateLockFile); rmdir(Scheduler::$appUpdateLockDir); } return TRUE; } /**************************************************************************************************** * Function Name : binaryChk * Objective : Check if EVS binary file is compatible with NAS device * Added By : Vijay Vinoth * Modified By : Sabin Cheruvattil ******************************************************************************************************/ function binaryChk() { GLOBAL $idevsutilBinaryPath, $machine, $appPath; $status = TRUE; $lines = `$idevsutilBinaryPath -h | wc -l`; if($lines < 50) { $status = FALSE; Scheduler::Log('Invalid EVS Utility'); } if($status && ($machine == QNAP || $machine == SYNOLOGY_LOCAL)) { $suPath = $appPath . '/' . CONFIG . '/su'; `$suPath --help 1>./su.res 2>./su.res`; $lines = 0; if(file_exists('./su.res')) { $lines = trim(`cat ./su.res | wc -l`); unlink('./su.res'); } if($lines < 5) { $status = FALSE; Scheduler::Log('Invalid su Utility'); } } return $status; } /********************************************************************************************************* * Subroutine Name : addAppUpdateLockFile * Objective : This creates a lock file for the update process. This file will be locked by perl script * Added By : Sabin Cheruvattil | 2016-08-02 **********************************************************************************************************/ function addAppUpdateLockFile() { GLOBAL $permissionVal; mkdir(Scheduler::$appUpdateLockDir); file_put_contents(Scheduler::$appUpdateLockFile, ''); chmod(Scheduler::$appUpdateLockFile, $permissionVal); } /********************************************************************************************************* * Subroutine Name : cancelJobAfterTerminate. * Objective : Remove userCancel.txt if required. * Added By : Avinash Kumar. **********************************************************************************************************/ function cancelJobAfterTerminate($jobPathArray) { GLOBAL $pidPath; foreach($jobPathArray as $jobPath){ $jobs = glob($jobPath . '*' , GLOB_ONLYDIR); for($k = 0; $k < count($jobs); $k++){ $actualPidPath = $jobs[$k]."/$pidPath"; $actualUserCancelPath = $jobs[$k]."/".CANCEL_PATH; // if pid is not available but user cancel is there sleep for 5 sec and unlink user cancel. if((!file_exists($actualPidPath)) && file_exists($actualUserCancelPath)){ sleep(5); @unlink($actualUserCancelPath); } } } } /********************************************************************************************************* * Subroutine Name : clearPid. * Objective : Remove pid.txt if required. * Added By : Avinash Kumar. * Updated By : Yogesh Kumar **********************************************************************************************************/ function clearPid($jobPathArray) { GLOBAL $pidPath; foreach($jobPathArray as $jobPath){ /* check pid.txt existance */ $jobs = glob($jobPath . '*' , GLOB_ONLYDIR); for($k = 0; $k < count($jobs); $k++){ $actualPidPath = $jobs[$k]."/$pidPath"; if(file_exists($actualPidPath)){ Scheduler::debug_Log("clearPid: " . $actualPidPath); /* check lock on pid.txt */ if(!($handle = fopen($actualPidPath, "w"))){ Scheduler::Log("Failed to open $actualPidPath"); continue; } else{ if(flock($handle, LOCK_EX|LOCK_NB, $lockFlag)) { Scheduler::Log("Trying to remove $actualPidPath"); unlink($actualPidPath); } } } } } } /********************************************************************************************************* * Subroutine Name : clearStartPid. * Objective : Remove StartPid.txt if required. * Added By : Avinash Kumar. **********************************************************************************************************/ function clearStartPid($jobPathArray) { GLOBAL $pidPath,$permissionVal; $logpid = LOG_PID_FILE; foreach($jobPathArray as $jobPath){ /* check StartPid.txt existance in each backup job */ $jobs = glob($jobPath . '*' , GLOB_ONLYDIR); for($k = 0; $k < count($jobs); $k++){ $jobRunningFlag = 0; $startPidPath = $jobs[$k]."/".START_PID; $jobPidPath = $jobs[$k]."/".$pidPath; $userCancelPath = $jobs[$k]."/".CANCEL_PATH; if(!file_exists($startPidPath) && !file_exists($jobPidPath) && !file_exists($userCancelPath)) { # Scheduler::Log("[startPidFile | jobPidFile | userCancelFile] not found, Going back."); continue; } /* job is running or not. */ $jobRunningFlag = isJobRunning($startPidPath); if($jobRunningFlag) continue; @unlink($startPidPath); @unlink($jobPidPath); $cmd = "rm -rf ".$jobPidPath."*"; #`$cmd`; removeItems($jobPidPath."*"); @unlink($userCancelPath); $logpidPath = $jobs[$k]."/".$logpid; if(!file_exists($logpidPath)) continue; $logpidContent = file_get_contents($logpidPath); $logpidContent = trim($logpidContent); if(!file_exists($logpidContent)) @unlink($logpidPath); if(strpos($logpidContent,"_SUCCESS")=== false && strpos($logpidContent,"_ABORTED")=== false && strpos($logpidContent,"_FAILURE")=== false){ $logFileNew = $logpidContent."_FAILURE"; $cmdToMove = "mv '$logpidContent' '$logFileNew'"; systemCmdExecutionViaPhp($cmdToMove); file_put_contents($logpidPath,$logFileNew); @chmod($logpidPath, $permissionVal); } } } } /********************************************************************************************************* * Subroutine Name : perlScriptExecution * Objective : Executes the perl script provided * Added By : Deepak Chaurasia * Modified By : Yogesh Kumar **********************************************************************************************************/ function perlScriptExecution($script, $currPath="", $needExecute=1, $cronUpdate=FALSE, $useHTTP=FALSE) { GLOBAL $machine; GLOBAL $user; GLOBAL $appPath; GLOBAL $appSudoPath; // In case for non admin users, cron updates are not possible. // So executing the commands via Idrive services. if ((QNAP == $machine) && ($_SESSION['nasUserName'] != 'admin') && $cronUpdate) { return appServices($script, $currPath); } else if ((SYNOLOGY_LOCAL == $machine || ASUSTOR==$machine) && ($_SESSION['nasUserName'] != 'root') && isset($_SESSION['encryptedToken']) && !empty($_SESSION['encryptedToken']) && $cronUpdate) { return appServices($script, $currPath); } $command = ""; $scriptPath = "$appPath/".SCRIPT; $configPath = "$appPath/".CONFIG; $suPath = "$configPath/su"; $nasUserName = $_SESSION['nasUserName']; if(SYNOLOGY_LOCAL == $machine || QNAP==$machine || ASUSTOR==$machine){ if($currPath==""){ $currPath = getcwd(); } $currPath = str_replace("'","'\''",$currPath); $currPath = str_replace('"','\"',$currPath); $currPath = str_replace('$','\$',$currPath); $currPath = "'".$currPath."'"; if (((SYNOLOGY_LOCAL==$machine || ASUSTOR==$machine) && empty($_SESSION['encryptedToken'])) || $useHTTP) { $command = "cd $currPath; $perlPath \"$scriptPath/$script\""; } else { $phpPath = getPhpPath(); putenv("TOKEN=$nasUserName"); $TOKEN = 'TOKEN'; $str = $_SESSION['encryptedToken'].$_COOKIE['encryptedToken']; $command = "$phpPath $configPath/token.php $str ".$_SESSION['encryptionFlag']."| $suPath -c \"cd $currPath; $perlPath \"$scriptPath/$script\"\""; $command .= " \"$$TOKEN\""; } } else { if($currPath == "") { $currPath = getcwd(); } $currPath = str_replace("'","'\''",$currPath); $currPath = "'".$currPath."'"; if($currPath != ""){ $command = "cd $currPath;"; } machineBasedContent($machine); $command .= "$appSudoPath -u $user $perlPath $scriptPath/$script"; } if($needExecute){ if((QNAP == $machine) || ASUSTOR==$machine || ((SYNOLOGY_LOCAL == $machine) && (!empty($_SESSION['encryptedToken'])))){ $res=shell_exec($command); $stOutput = preg_replace('/^Password: /', '', $res); } else $stOutput=shell_exec($command); return $stOutput; } else{ return $command; } } /********************************************************************************************************* * Subroutine Name : phpScriptExecution * Objective : Executes the php script provided * Added By : Deepak Chaurasia * Modified By : Yogesh Kumar, Sabin Cheruvattil **********************************************************************************************************/ function phpScriptExecution($script, $currPath="", $needExecute=1, $cronUpdate=FALSE, $useHTTP=FALSE) { GLOBAL $machine; GLOBAL $user; GLOBAL $appPath; GLOBAL $appSudoPath; GLOBAL $phpPath; $phpPath = getPhpPath(); // In case for non admin users, cron updates are not possible. // So executing the commands via Idrive services. if ((QNAP == $machine) && ($_SESSION['nasUserName'] != 'admin') && $cronUpdate) { return appServices($script, $currPath); } else if ((SYNOLOGY_LOCAL == $machine || ASUSTOR==$machine) && ($_SESSION['nasUserName'] != 'root') && isset($_SESSION['encryptedToken']) && !empty($_SESSION['encryptedToken']) && $cronUpdate) { return appServices($script, $currPath); } $command = ""; $scriptPath = "$appPath/".SCRIPT; $configPath = "$appPath/".CONFIG; $suPath = "$configPath/su"; $nasUserName = $_SESSION['nasUserName']; if(SYNOLOGY_LOCAL == $machine || QNAP == $machine || ASUSTOR == $machine) { if($currPath=="") { $currPath = getcwd(); } $currPath = str_replace("'","'\''",$currPath); $currPath = str_replace('"','\"',$currPath); $currPath = str_replace('`','\`',$currPath); //$currPath = str_replace('$','\$',$currPath); $currPath = "'".$currPath."'"; if (((SYNOLOGY_LOCAL ==$machine || ASUSTOR==$machine) && empty($_SESSION['encryptedToken'])) || $useHTTP) { $command = "cd $currPath; $phpPath \"$scriptPath/$script\""; } else { putenv("TOKEN=$nasUserName"); $TOKEN = 'TOKEN'; $str = $_SESSION['encryptedToken'].$_COOKIE['encryptedToken']; $command = "$phpPath $configPath/token.php $str ".$_SESSION['encryptionFlag']." | $suPath -c \"cd $currPath; $phpPath \"$scriptPath/$script\"\""; $command .= " \"$$TOKEN\""; } } else { if($currPath == "") { $currPath = getcwd(); } $currPath = str_replace("'","'\''",$currPath); $currPath = "'".$currPath."'"; if($currPath != ""){ $command = "cd $currPath;"; } machineBasedContent($machine); $command .= "$appSudoPath -u $user $phpPath $scriptPath/$script"; } if($needExecute){ if((QNAP == $machine) || ASUSTOR==$machine || ((SYNOLOGY_LOCAL == $machine) && (!empty($_SESSION['encryptedToken'])))){ $res=shell_exec($command); $stOutput = preg_replace('/^Password: /', '', $res); } else $stOutput=shell_exec($command); return trim($stOutput); } else{ return $command; } } /********************************************************************************************************* * Subroutine Name : systemCmdExecution * Objective : Executes the system commands provided * Added By : Deepak Chaurasia **********************************************************************************************************/ function systemCmdExecution($script, $needExecute=1, $currPath='') { GLOBAL $machine; GLOBAL $user; GLOBAL $appPath; GLOBAL $appSudoPath; $command = ""; $nasUserName = $_SESSION['nasUserName']; if(SYNOLOGY_LOCAL == $machine || QNAP == $machine || ASUSTOR == $machine){ $configPath = "$appPath/".CONFIG; $suPath = "$configPath/su"; if (SYNOLOGY_LOCAL == $machine && empty($_SESSION['encryptedToken'])) { $currPath = empty($currPath)?'':"cd \"$currPath\";"; $command = "$currPath$script"; } else { if ($currPath === '') { $currPath = getcwd(); } putenv("TOKEN=$nasUserName"); $TOKEN = 'TOKEN'; $str = $_SESSION['encryptedToken'].$_COOKIE['encryptedToken']; $phpPath = getPhpPath(); $command = "$phpPath $configPath/token.php $str ".$_SESSION['encryptionFlag']." | $suPath -c \"cd \"$currPath\"; $script\""; $command .= " \"$$TOKEN\""; } } else { machineBasedContent($machine); $currPath = empty($currPath)?'':"cd \"$currPath\";"; $command = "$currPath $appSudoPath -u $user $script"; } if($needExecute){ if(QNAP == $machine || ASUSTOR==$machine || ((SYNOLOGY_LOCAL == $machine) && (!empty($_SESSION['encryptedToken'])))){ $res=shell_exec($command); $stOutput = preg_replace('/^Password: /', '', $res); } else $stOutput=shell_exec($command); return $stOutput; } else{ return $command; } } /**************************************************************************************************** * Subroutine Name : systemCmdExecutionViaPhp. * Objective : To execute system commands via perl * Added By : Pooja Havaldar * Modified By : Avinash Kumar ******************************************************************************************************/ function systemCmdExecutionViaPhp($script, $currPath = '') { GLOBAL $baseDir; GLOBAL $userName; GLOBAL $temp_file,$permissionVal; if(empty($script)) return false; $userType = shell_exec("whoami"); $userType = rtrim($userType); if("root" === $userType) { if(is_array($script)){ for($j = 0; $j < sizeof($script); $j++) shell_exec($script[$j]); } else shell_exec($script); return; } $operation = "commandExecution\n"; file_put_contents($temp_file,$operation); if(is_array($script)){ $script = implode("\n", $script); } file_put_contents($temp_file,$script."\n",FILE_APPEND); @chmod($temp_file, $permissionVal); #$output = phpScriptExecution(OPERATIONSFILE." commandExecution", $currPath); $output = phpScriptExecution(OPERATIONSFILE, $currPath); return $output; } /**************************************************************************************************** * Subroutine Name : setUnset. * Objective : To encrypt/decrypt the SQlite DB. * Added By : Pooja ******************************************************************************************************/ function setUnset($option, $file) { GLOBAL $temp_file, $permissionVal; $output =''; $option = strtolower($option)."\n"; $operation = "setUnset\n"; file_put_contents($temp_file,$operation.$option.$file."\n"); @chmod($temp_file, $permissionVal); Scheduler::Log('',"file ",$file); $output = phpScriptExecution(OPERATIONSFILE, Scheduler::$user_dir); Scheduler::Log("setUnset:" .$output); return $output; } /**************************************************************************************************** * Subroutine Name : createDefaultBackupSet. * Objective : To create befault backupset file. * Added By : Avinash Kumar. * Modified By : Senthil Pandian.K * Modified On : 25-06-2015 ******************************************************************************************************/ function createDefaultBackupSet() { GLOBAL $machine; GLOBAL $appPath; GLOBAL $permissionVal, $NetgearSharedPath; $publicPath = ""; //$sharedPath = ""; $multimediaPath = ""; $downloadPath = ""; $backupSetDisplayFile = Scheduler::$backup_dir.DEFAULT_BACKUPSET."/".BACKUPSETFILEDISPLAY; if(!file_exists($backupSetDisplayFile)){ $backupSetDisplayContent = ''; if(SYNOLOGY_LOCAL == $machine) { $shared = getSynologySharedFolders(SYNOLOGY_AVOID_PROP); foreach($shared as $dir => $property) { if(strtolower($property['realName']) == 'public') { $backupSetDisplayContent .= $dir . "\nfolder\nundefined\nundefined\n"; } if(strtolower($property['realName']) == 'shared') { $backupSetDisplayContent .= $dir . "\nfolder\nundefined\nundefined\n"; } } } else if(QNAP == $machine) { $shared = getQNAPSharedFolders(); foreach($shared as $dirName=>$property){ $publicPathRes = strPos("$dirName/",'/Public/'); if($publicPathRes>0){ $backupSetDisplayContent .= $dirName."\nfolder\n"; } $multimediaPathRes = strPos("$dirName/",'/Multimedia/'); if($multimediaPathRes>0){ $backupSetDisplayContent .= $dirName."\nfolder\n"; } $downloadPathRes = strPos("$dirName/",'/Download/'); if($downloadPathRes>0){ $backupSetDisplayContent .= $dirName."\nfolder\n"; } } } else if(NETGEAR_LOCAL == $machine){ $shared = getNetgearSharedFolders(); foreach($shared as $dirName=>$property){ $picturesPathRes = strPos("$dirName/",'/Pictures/'); if($picturesPathRes>0){ $backupSetDisplayContent .= $dirName."\nfolder\n"; } $documentsPathRes = strPos("$dirName/",'/Documents/'); if($documentsPathRes>0){ $backupSetDisplayContent .= $dirName."\nfolder\n"; } $musicPathRes = strPos("$dirName/",'/Music/'); if($musicPathRes>0){ $backupSetDisplayContent .= $dirName."\nfolder\n"; } $videosPathRes = strPos("$dirName/",'/Videos/'); if($videosPathRes>0){ $backupSetDisplayContent .= $dirName."\nfolder\n"; } } } else if("twotier" == $machine){ $shared = getTwotierSharedFolders(); foreach($shared as $dirName=>$property){ $type = $property['type']=='D'?'folder':'file'; $backupSetDisplayContent .= "$dirName\n$type\n"; } autoUpdateBackupset(); } else if(ASUSTOR == $machine) { $shared = getASUSTORSharedFolders(); foreach($shared as $dir => $property) { if(strtolower($property['filename']) == 'public'){ $backupSetDisplayContent .= $dir . "\nfolder\n"; continue; } if(strtolower($property['filename'])=="music"){ $backupSetDisplayContent .= $dir."\nfolder\n"; continue; } if(strtolower($property['filename'])=="videos"){ $backupSetDisplayContent .= $dir."\nfolder\n"; continue; } if(strtolower($property['filename'])=="photogallery"){ $backupSetDisplayContent .= $dir."\nfolder\n"; continue; } } } file_put_contents($backupSetDisplayFile,$backupSetDisplayContent); @chmod($backupSetDisplayFile, $permissionVal); } else if ("twotier" == $machine) { autoUpdateBackupset(); } } /**************************************************************************************************** * Subroutine Name : getCronEntry. * Objective : To get cron table entries. * Added By : Uttam Tiwari. ******************************************************************************************************/ function getCronEntry($args) { $result=""; $space = " "; $tab = "\t"; $arguments = func_get_args(); GLOBAL $machine; GLOBAL $user; if($machine=== SYNOLOGY_LOCAL) { //in synology we need to add user in crontab entry //so we are adding user at end and swaping with previous value. array_push($arguments,$user); $lastIndex = count($arguments) - 1; $tmp = $arguments[$lastIndex-1]; $arguments[$lastIndex - 1] = $arguments[$lastIndex]; $arguments[$lastIndex] = $tmp; foreach ($arguments as $argument) { $result .= $argument.$tab; } chop($result,$tab); } else { foreach ($arguments as $argument) { $result .= $argument.$space; } chop($result,$space); } return $result; } /**************************************************************************************************** * Subroutine Name : crontabSeperator. * Objective : Separate content depends on machine type. * Added By : Avinash Kumar. ******************************************************************************************************/ function crontabSeperator($scheduleString) { GLOBAL $machine; $scheduleArray = Array(); if(SYNOLOGY_LOCAL == $machine) { $scheduleArray = explode("\t", $scheduleString); } else { $scheduleArray = explode(' ', $scheduleString); } return $scheduleArray; } function dirlist($arg = "/") { GLOBAL $machine; GLOBAL $appPath; $tmpDirArr = array(); $dirDefault = array(); if("twotier" == $machine){ $arg = str_replace("'","'\''",$arg); } else{ $arg = str_replace('\\','\\\\',$arg); $arg = str_replace("'","'\''",$arg); $arg = preg_replace("/\"/","\\\"",$arg); $arg = str_replace('$','\$',$arg); $arg = str_replace('`','\`',$arg); } if(SYNOLOGY_LOCAL == $machine){ if($arg=="/") { $tmpDirArr = getSynologySharedFolders(SYNOLOGY_AVOID_PROP); } else { $dirDefault = systemCmdExecution("ls -aln '$arg' | grep ^d"); } } else if(QNAP == $machine){ if($arg=="/") { $tmpDirArr = getQNAPSharedFolders(); } else { $dirDefault = systemCmdExecution("ls -aln '$arg' | grep ^d"); } } else if(NETGEAR_LOCAL == $machine){ if($arg=="/") { $tmpDirArr = getNetgearSharedFolders(); } else { $dirDefault = systemCmdExecution("$appPath/ls -al '$arg' | grep ^d"); } } else if("twotier" == $machine){ if($arg=='/') $arg = '/'.IDRIVE_VAULT_RESTORELOCATION_ROOT; $dirDefault = systemCmdExecution("/bin/ls -al '$arg' | grep ^d"); } else if(ASUSTOR == $machine){ if($arg=="/") $tmpDirArr = getASUSTORSharedFolders(); else $dirDefault = systemCmdExecution("ls -al '$arg/' | grep ^d "); } if(!empty($tmpDirArr)) ksort($tmpDirArr); else if(!empty($dirDefault)){ $tmpArr = explode("\n",rtrim($dirDefault,"\n")); $tmpDirArr = array(); foreach($tmpArr as $tmpDir){ $trimmedDirname = trim($tmpDir); if($trimmedDirname !='' && $trimmedDirname !='.' && $trimmedDirname !='..'){ $split = preg_split('/\s+/', $tmpDir,9); $tmpDirArr[] = $split[8]; } } sort($tmpDirArr); } return $tmpDirArr; } /**************************************************************************************************** * Function Name : machineBasedContent. * Objective : Getting content based on machine QNAP/Synology * Added By : Senthil Pandian ******************************************************************************************************/ function machineBasedContent($machine){ GLOBAL $appName; GLOBAL $logoClassName; GLOBAL $appVersion; GLOBAL $releaseDate; GLOBAL $appTitle; GLOBAL $appDesc; GLOBAL $appHelpLink; GLOBAL $appMetaTitle; GLOBAL $appUpdateMsg; GLOBAL $appUpdateKey; GLOBAL $appUpdateURL; GLOBAL $appThemeCSS; GLOBAL $appPerlPath; GLOBAL $appPHPPath; GLOBAL $appSudoPath; GLOBAL $appCloudPath; GLOBAL $appFavicon; GLOBAL $appIDriveDesc; GLOBAL $processPath; GLOBAL $diskRootPath; switch($machine){ case 'QNAP': $appName = QNAP; $logoClassName = QNAP_LOGO_CLASSNAME; $appVersion = QNAP_VERSION; $releaseDate = QNAP_RELEASE_DATE; $appTitle = QNAP_TITLE; $appDesc = NAS_DESC; $appIDriveDesc = QNAP_IDRIVE_ACCOUNT_DESC; $appHelpLink = QNAP_HELP; $appMetaTitle = QNAP_META_TITLE; $appUpdateMsg = QNAP_VERSION_MSG; $appUpdateKey = IDRIVE_APP_FOR_QNAP; $appUpdateURL = QNAP_UPDATE_URL; $appThemeCSS = CSS_THEME_FOR_NAS; $appPerlPath = PERL_PATH_FOR_QNAP; $appPHPPath = PHP_PATH_FOR_QNAP; $appCloudPath = IDRIVE_CLOUD_FOR_NAS; $appFavicon = IDRIVE_FAV_FOR_NAS; $processPath = PS_PATH_FOR_QNAP; $diskRootPath = DISK_PATH_FOR_QNAP; break; case 'synology': $appName = SYNOLOGY; $logoClassName = SYNOLOGY_LOGO_CLASSNAME; $appVersion = SYNOLOGY_VERSION; $releaseDate = SYNOLOGY_RELEASE_DATE; $appTitle = SYNOLOGY_TITLE; $appDesc = NAS_DESC; $appIDriveDesc = SYNOLOGY_IDRIVE_ACCOUNT_DESC; $appHelpLink = SYNOLOGY_HELP; $appMetaTitle = SYNOLOGY_META_TITLE; $appUpdateMsg = SYNOLOGY_VERSION_MSG; $appUpdateKey = IDRIVE_APP_FOR_SYNOLOGY; $appUpdateURL = SYNOLOGY_UPDATE_URL; $appThemeCSS = CSS_THEME_FOR_NAS; $appPerlPath = PERL_PATH_FOR_SYNOLOGY; $appPHPPath = PHP_PATH_FOR_SYNOLOGY; $appCloudPath = IDRIVE_CLOUD_FOR_NAS; $appFavicon = IDRIVE_FAV_FOR_NAS; $processPath = PS_PATH_FOR_SYNOLOGY; $diskRootPath = DISK_PATH_FOR_SYNOLOGY; break; case 'netgear': $appName = NETGEAR; $logoClassName = NETGEAR_LOGO_CLASSNAME; $appVersion = NETGEAR_VERSION; $releaseDate = NETGEAR_RELEASE_DATE; $appTitle = NETGEAR_TITLE; $appDesc = NAS_DESC; $appIDriveDesc = NETGEAR_IDRIVE_ACCOUNT_DESC; $appHelpLink = NETGEAR_HELP; $appMetaTitle = NETGEAR_META_TITLE; $appUpdateMsg = NETGEAR_VERSION_MSG; $appUpdateKey = IDRIVE_APP_FOR_NETGEAR; $appUpdateURL = NETGEAR_UPDATE_URL; $appThemeCSS = CSS_THEME_FOR_NAS; $appPerlPath = PERL_PATH_FOR_NETGEAR; $appPHPPath = PHP_PATH_FOR_NETGEAR; $appSudoPath = SUDO_PATH_FOR_NETGEAR; $appCloudPath = IDRIVE_CLOUD_FOR_NAS; $appFavicon = IDRIVE_FAV_FOR_NAS; $processPath = PS_PATH_FOR_NETGEAR; $diskRootPath = DISK_PATH_FOR_NETGEAR; break; case 'twotier': $appName = TWOTIER; $logoClassName = TWOTIER_LOGO_CLASSNAME; $appVersion = TWOTIER_VERSION; $appTitle = TWOTIER_TITLE; $appDesc = TWOTIER_DESC; $appIDriveDesc = TWOTIER_IDRIVE_ACCOUNT_DESC; $appHelpLink = TWOTIER_HELP; $appMetaTitle = TWOTIER_META_TITLE; $appUpdateMsg = TWOTIER_VERSION_MSG; $appUpdateKey = IDRIVE_APP_FOR_TWOTIER; $appUpdateURL = TWOTIER_UPDATE_URL; $appThemeCSS = CSS_THEME_FOR_TWOTIER; $appPerlPath = PERL_PATH_FOR_TWOTIER; $appPHPPath = PHP_PATH_FOR_TWOTIER; $appSudoPath = SUDO_PATH_FOR_TWOTIER; $appCloudPath = IDRIVE_CLOUD_FOR_TWOTIER; $appFavicon = IDRIVE_FAV_FOR_TWOTIER; $processPath = PS_PATH_FOR_TWOTIER; $diskRootPath = DISK_PATH_FOR_TWOTIER; break; case ASUSTOR: $appName = ASUSTOR; $logoClassName = ASUSTOR_LOGO_CLASSNAME; $appVersion = ASUSTOR_VERSION; $releaseDate = ASUSTOR_RELEASE_DATE; $appTitle = ASUSTOR_TITLE; $appDesc = NAS_DESC; $appIDriveDesc = ASUSTOR_IDRIVE_ACCOUNT_DESC; $appHelpLink = ASUSTOR_HELP; $appMetaTitle = ASUSTOR_META_TITLE; $appUpdateMsg = ASUSTOR_VERSION_MSG; $appUpdateKey = IDRIVE_APP_FOR_ASUSTOR; $appUpdateURL = ASUSTOR_UPDATE_URL; $appThemeCSS = CSS_THEME_FOR_NAS; $appPerlPath = PERL_PATH_FOR_ASUSTOR; $appPHPPath = PHP_PATH_FOR_ASUSTOR; $appCloudPath = IDRIVE_CLOUD_FOR_NAS; $appFavicon = IDRIVE_FAV_FOR_NAS; $processPath = PS_PATH_FOR_ASUSTOR; break; } } /**************************************************************************************************** * Function Name : getSynologyNASIP * Objective : Get Synology NAS IP Address * Added By : Sabin Cheruvattil ******************************************************************************************************/ function getSynologyNASIP() { $ipDetails = trim(`ip route | grep default`, "\n"); $ipDetailsArr = explode(" ", $ipDetails); if(count($ipDetailsArr) > 6){ return $ipDetailsArr[7]; } else { $ipDetails = explode("\n", `ip addr show eth0 | grep inet | awk '{ print $2; }' | sed 's/\/.*$//'`); $valid = preg_match('/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/ ', $ipDetails[0]); if(!$valid){ return "127.0.0.1"; } return $ipDetails[0]; } } /**************************************************************************************************** * Function Name : synologyNASlogin * Objective : Verifying synology NAS login detail * Added By : Senthil Pandian ******************************************************************************************************/ function synologyNASlogin($user,$pass,$nasVerification) { $optCode = ''; $version=3; $isNonAdmin=false; if(!empty($nasVerification)){ $optCode = "&otp_code=".$nasVerification; } START: $shareURL = getNasURL(); $shareURL .= "webapi/auth.cgi"; $shareData = ""; if($isNonAdmin==false){ $shareData .= "api=SYNO.API.Auth&version=$version&method=login&account=$user&passwd=$pass".$optCode.'&format=cookie'; } else { $shareData .= "api=SYNO.API.Auth&version=$version&method=login&account=$user&passwd=$pass".$optCode."&session=FileStation&format=cookie"; } console.log($shareURL); $shareOutputArr = getCurlOutput($shareURL, $shareData); if($shareOutputArr['status']===false){ Scheduler::Log("Auth CGI: "." Output: ".$shareOutputArr['output']. " Error: ".$shareOutputArr['error']); } $sharePage = $shareOutputArr['output']; $arr = json_decode($sharePage); $strPos = strpos($sharePage,"data"); if(empty($sharePage)){ if(isset($_SESSION['isProxyEnabled']) && !empty($_SESSION['ipAddress'])) return INVALID_PROXY; else return INVALID_HOST_NAME; } elseif(!empty($strPos) && $strPos>=0){ $sid = $arr->data->sid; $succ = $arr->success; if($sid!='' && $succ==1){ $_SESSION['CGI_SID'] = $sid; return "TRUE"; } else { return $succ; } } else { $sid = $arr->error->code; $succ = $arr->success; if($sid=='104' && $succ==''){ $version--; goto START; } elseif($sid=='402' || ($sid=='400' && $isNonAdmin==false)){ $isNonAdmin=true; goto START; } elseif($sid=='403' && $succ==''){ return TWO_STEP_REQUIRED; } elseif($sid=='404' && $succ==''){ return INVALID_TWO_STEP; }/* elseif($sid=='400' && $succ==''){ return BLOCKED_IP; }*/ elseif($sid!='' && $succ==''){ return INVALID_NAS_LOGIN; } else { return $succ; } } } /**************************************************************************************************** * Function Name : qnapNASlogin * Objective : Verifying QNAP NAS login detail * Added By : Senthil Pandian ******************************************************************************************************/ function qnapNASlogin($user,$pass,$nasVerification) { $pass = base64_encode($pass); $optCode = ''; #If QTS is 4.2 or later if(file_exists(QNAP_LOGIN_CGI_PATH)){ if(!empty($nasVerification)){ $optCode = "&security_code=".$nasVerification; } $shareURL = getNasURL(); $shareURL .= "cgi-bin/authLogin.cgi"; $shareData = "user=$user&pwd=$pass&force_to_check_2sv=1".$optCode; $shareOutputArr = getCurlOutput($shareURL, $shareData); if($shareOutputArr['status']===false){ Scheduler::Log("Qnap Login CGI: "." Output: ".$shareOutputArr['output']. " Error: ".$shareOutputArr['error']); } #$postVars = "user=$user&pwd=$pass&force_to_check_2sv=1".$optCode; #$shareOutputArr = getCurlOutput($shareURL,$postVars); $sharePage = $shareOutputArr['output']; $strPos = strpos($sharePage,"authPassed"); if(empty($sharePage)){ if(isset($_SESSION['isProxyEnabled']) && !empty($_SESSION['ipAddress'])) return INVALID_PROXY; } elseif(!empty($strPos) && $strPos>=0){ $xml = simplexml_load_string($sharePage, 'SimpleXMLElement', LIBXML_NOCDATA); $jsonString = json_encode($xml); $resultArray = json_decode($jsonString, TRUE); $succ = $resultArray['authPassed']; $sid = $resultArray['authSid']; if($sid!='' && $succ==1){ $_SESSION['CGI_SID'] = $sid; return "TRUE"; } else if(isset($resultArray['need_2sv']) && $resultArray['need_2sv']==1){ if($succ==1){ $_SESSION['CGI_SID'] = $sid; return "TRUE"; } else if(!$nasVerification) return TWO_STEP_REQUIRED; else return INVALID_TWO_STEP; } } } #If QTS is less than 4.2 if(!empty($nasVerification)){ $optCode = "&security_code=".$nasVerification; } $shareURL = getNasURL(); $shareURL .= "cgi-bin/filemanager/wfm2Login.cgi"; $shareURLData = "user=$user&pwd=$pass".$optCode; //$sharePage = getCurlOutput($shareURL); $shareOutputArr = getCurlOutput($shareURL, $shareURLData); if($shareOutputArr['status']===false){ Scheduler::Log("Qnap verify code CGI: "." Output: ".$shareOutputArr['output']. " Error: ".$shareOutputArr['error']); } $sharePage = $shareOutputArr['output']; $strPos = strpos($sharePage,"status"); if(empty($sharePage)){ if(isset($_SESSION['isProxyEnabled']) && !empty($_SESSION['ipAddress'])) return INVALID_PROXY; else return INVALID_HOST_NAME; } elseif(!empty($strPos) && $strPos>=0){ //$sharePage = utf8_encode($sharePage); $arr = json_decode($sharePage); $sid = $arr->sid; $succ = $arr->status; if($sid!='' && $succ==1){ $_SESSION['CGI_SID'] = $sid; return "TRUE"; } else if(isset($arr->need_2sv) && $arr->need_2sv==1){ if($arr->authPassed==1){ $_SESSION['CGI_SID'] = $arr->authSid; return "TRUE"; } else if(!$nasVerification) return TWO_STEP_REQUIRED; else return INVALID_TWO_STEP; } else if($succ=='8'){ return FILESTATION_DISABLED; } else { return $succ; } } else { return INVALID_PROXY; } } /**************************************************************************************************** * Function Name : asustorNASlogin * Objective : Verifying ASUSTOR NAS login detail * Added By : Vijay Vinoth ******************************************************************************************************/ function asustorNASlogin($user,$pass,$nasVerification) { $optCode = ''; if(!empty($nasVerification)) $optCode = "&verifycode=".$nasVerification; if($user == 'root') $user = 'admin'; $shareURL = getNasURL().ASUSTOR_LOGIN_CGI_PATH; #$shareURL .= ASUSTOR_LOGIN_CGI_PATH."&account=".$user."&password=".$pass."&two-step-auth=true&stay=yes".$optCode; $shareURLData = "account=".$user."&password=".$pass."&two-step-auth=true&stay=yes".$optCode; $sharePage = getCurlOutput($shareURL,$shareURLData); if($sharePage['status']===false){ Scheduler::Log("Asus Login CGI: "." Output: ".$sharePage['output']. " Error: ".$sharePage['error']); } $arr = json_decode($sharePage['output']); if($arr->success == false){ if($arr->error_code == ASUSTOR_TWO_STEP_REQUIRED_ERROR_CODE) return TWO_STEP_REQUIRED; else if($arr->error_code == ASUSTOR_INVALID_TWO_STEP_ERROR_CODE) return INVALID_TWO_STEP; else if((strpos($sharePage['error'], 'Connection timed out') !== false || strpos($sharePage['error'], 'The requested URL returned error: 407') !== false) && count($arr) == 0) return INVALID_PROXY; else return INVALID_NAS_LOGIN; } else{ $sid = $arr->sid; $succ = $arr->success; if($sid!='' && $succ==1){ $_SESSION['CGI_SID'] = $sid; return "TRUE"; } return $succ; } } /**************************************************************************************************** * Function Name : nasLogin * Objective : Validating the NAS login detail based on NAS machine * Added By : Senthil Pandian ******************************************************************************************************/ function nasLogin($nasUserName,$nasPassword,$nasVerification){ GLOBAL $machine; GLOBAL $appPath,$permissionVal; #if((SYNOLOGY_LOCAL == $machine || ASUSTOR == $machine) && $nasUserName=='admin') { /*if((ASUSTOR == $machine) && $nasUserName=='admin') { $_SESSION['nasUserName'] = 'root'; } else */ $_SESSION['nasUserName'] = $nasUserName; $_SESSION['encryptedToken'] = ''; if(SYNOLOGY_LOCAL == $machine){ if ($_SESSION['httpuser'] != 'root') { encryptAndSaveNasPassword($nasPassword); } $stOutput = synologyNASlogin(rawurlencode($nasUserName),rawurlencode($nasPassword),rawurlencode($nasVerification)); } else if(QNAP == $machine){ encryptAndSaveNasPassword($nasPassword); $stOutput = qnapNASlogin(rawurlencode($nasUserName),$nasPassword,rawurlencode($nasVerification)); } else if(ASUSTOR == $machine){ encryptAndSaveNasPassword($nasPassword); $stOutput = asustorNASlogin(rawurlencode($nasUserName),rawurlencode($nasPassword),rawurlencode($nasVerification)); } else { if ($machine == "twotier") $passwordFile = " /etc/master.passwd"; elseif ($machine == NETGEAR_LOCAL) $passwordFile = " /etc/shadow"; file_put_contents("$appPath/".SESSIONTOK,$nasUserName."\n".encrypt($nasPassword)); @chmod("$appPath/".SESSIONTOK, $permissionVal); $stOutput = phpScriptExecution(NASLOGIN.$passwordFile,$appPath); } return $stOutput; } /**************************************************************************************************** * Function Name : searchKeyword * Objective : constructing search keyword based on NAS machine * Added By : Senthil Pandian ******************************************************************************************************/ function searchKeyword($searchKeyword){ GLOBAL $machine; if($machine == SYNOLOGY_LOCAL){ $searchKeyword = strtolower($searchKeyword); } return $searchKeyword; } /**************************************************************************************************** * Function Name : getLocalServerPort * Objective : Getting the local server port number * Added By : Senthil Pandian ******************************************************************************************************/ function getLocalServerPort(){ GLOBAL $machine; if(!isset($_SESSION['PORT'])){ if($machine==SYNOLOGY_LOCAL){ //Getting DSM port number $synoConfig = SYNOLOGY_INFOCONF; $contents = file($synoConfig); $i=0; foreach ($contents as $line) { if(strpos($line,"admin_port=") !== FALSE){ $isPort1 = explode("=", trim($line)); if($isPort1[0]=="admin_port"){ $port = trim($isPort1[1],'\"'); } if($isPort1[0]=="secure_admin_port") { $securePort = trim($isPort1[1],'\"'); } $i++; } if(strpos($line,"runHTTPS") !== FALSE){ $isPort1 = explode("=", trim($line)); if($isPort1[0]=="runHTTPS"){ $isSSL = trim($isPort1[1],'\"'); } $i++; } if($i==3){ break; } } if(isset($isSSL) && ($isSSL == 'yes')) { $port = $securePort; } } else if($machine==QNAP){ $port = shell_exec('/sbin/getcfg System "Web Access Port"'); $port = trim($port); if(trim($port)==''){ $port = '8080'; } } $_SESSION['PORT'] = $port; } else{ $port = $_SESSION['PORT']; } return $port; } /**************************************************************************************************** * Function Name : getNasURL * Objective : Getting the NAS URL * Added By : Senthil Pandian ******************************************************************************************************/ function getNasURL(){ GLOBAL $machine; if(!isset($_SESSION['nasURL'])){ if($machine=="QNAP"){ /*$FORCE_SSL = parse_ini_string(exec('cat /etc/config/uLinux.conf | grep "Force SSL"')); $FORCE_SSL = ((isset($FORCE_SSL['Force SSL'])) ? $FORCE_SSL['Force SSL'] : '');*/ // modified to handle multiple force ssl when user has two network cables connected. $FORCE_SSL = 0; $FORCE_SSL_Val = `cat /etc/config/uLinux.conf | grep "Force SSL"`; $FORCE_SSL_Val = rtrim($FORCE_SSL_Val,"\n"); $FORCE_SSL_Array = explode("\n", $FORCE_SSL_Val); foreach ($FORCE_SSL_Array as $result) { $result = parse_ini_string($result); $FORCE_SSL += ((isset($result['Force SSL'])) ? $result['Force SSL'] : 0); } if ($FORCE_SSL) { $QNAP_HTTPS_PORT = exec("/sbin/getcfg Stunnel \"Port\" -f /etc/config/uLinux.conf"); if ($QNAP_HTTPS_PORT != 443 && $QNAP_HTTPS_PORT != '') $contact_port = ":".$QNAP_HTTPS_PORT; else $contact_port = ""; $protocol = "https"; } else { $QNAP_HTTPD_PORT = parse_ini_string(exec('cat /etc/config/uLinux.conf | grep "Web Access Port"')); $QNAP_HTTPD_PORT = ((isset($QNAP_HTTPD_PORT['Web Access Port'])) ? $QNAP_HTTPD_PORT['Web Access Port'] : '8080'); $contact_port = ":".$QNAP_HTTPD_PORT; $protocol = "http"; } if(isset($_SESSION['ipAddress'])&&!empty($_SESSION['ipAddress'])){ $ip = $_SERVER['SERVER_ADDR']; $nasURL = $protocol."://$ip".$contact_port."/"; } else { $nasURL = $protocol."://127.0.0.1".$contact_port."/"; } } else if($machine==SYNOLOGY_LOCAL){ //Getting DSM port number $synoConfig = SYNOLOGY_INFOCONF; $contents = file($synoConfig); $i=0; foreach ($contents as $line) { if(strpos($line,"admin_port=") !== FALSE){ $isPort1 = explode("=", trim($line)); if($isPort1[0]=="admin_port"){ $port = trim($isPort1[1],'\"'); } if($isPort1[0]=="secure_admin_port") { $securePort = trim($isPort1[1],'\"'); } $i++; } if(strpos($line,"runHTTPS") !== FALSE){ $isPort1 = explode("=", trim($line)); if($isPort1[0]=="runHTTPS"){ $isSSL = trim($isPort1[1],'\"'); } $i++; } if($i==3){ break; } } // In case on DSM-6 find the admin_port in http.service file. if(!isset($port) && !isset($securePort)) { $httpConfFile = NULL; if (file_exists(SYNOLOGY_HTTP_CONF_1)) { $httpConfFile = SYNOLOGY_HTTP_CONF_1; } else if (file_exists(SYNOLOGY_HTTP_CONF_2)) { $httpConfFile = SYNOLOGY_HTTP_CONF_2; } if ($httpConfFile !== NULL) { $service = file_get_contents($httpConfFile); $xml = new SimpleXMLElement($service); $arr = get_object_vars($xml->service); foreach($arr['txt-record'] as $line) { if( strpos($line,"admin_port=") !== FALSE ) { $isPort1 = explode("=", trim($line)); if( $isPort1[0]=="admin_port" ) { $port = trim($isPort1[1],'\"'); } } } } } if(isset($isSSL) && ($isSSL == 'yes')) { $protocol = "https"; $contact_port = ":".$securePort; } else { $protocol = "http"; $contact_port = ":".$port; } if(isset($_SESSION['ipAddress'])&&!empty($_SESSION['ipAddress'])) { # $ip = $_SERVER['SERVER_ADDR']; $ip = getSynologyNASIP(); $nasURL = $protocol . "://$ip" . $contact_port . "/"; } else { $ip = getSynologyNASIP(); if($ip == '') { $ip = '127.0.0.1'; } $nasURL = $protocol . "://{$ip}" . $contact_port . "/"; } } else if($machine == ASUSTOR){ $asusConfig = ASUSTOR_INFOCONF; $contents = file($asusConfig); $i=0; foreach ($contents as $line) { if(strpos($line,"HttpsOnly =") !== FALSE){ $HttpsOnlyArray = explode("=", trim($line)); $HttpsOnly = trim($HttpsOnlyArray[1]); $i++; continue; } if(strpos($line,"EnableHttps =") !== FALSE){ $EnableHttpsArray = explode("=", trim($line)); $EnableHttps = trim($EnableHttpsArray[1]); $i++; continue; } if(strpos($line,"HttpPort =") !== FALSE){ $HttpPortArray = explode("=", trim($line)); $HttpPort = trim($HttpPortArray[1]); $i++; continue; } if(strpos($line,"HttpsPort =") !== FALSE){ $HttpsPortArray = explode("=", trim($line)); $HttpsPort = trim($HttpsPortArray[1]); $i++; continue; } if($i == 4) break; } if($HttpsOnly == 'Yes' && $EnableHttps == 'Yes') { $protocol = "https"; $contact_port = ":".$HttpsPort; } else { $protocol = "http"; $contact_port = ":".$HttpPort; } if(isset($_SESSION['ipAddress'])&&!empty($_SESSION['ipAddress'])){ $ip = $_SERVER['SERVER_ADDR']; $nasURL = $protocol."://$ip".$contact_port."/"; } else $nasURL = $protocol."://127.0.0.1".$contact_port."/"; } $_SESSION['nasURL'] = $nasURL; return $nasURL; } else { return $_SESSION['nasURL']; } } /**************************************************************************************************** * Function Name : getSynologySharedFolders * Objective : Getting synology shared folders list * Added By : Senthil Pandian * Modified By : Sabin Cheruvattil - 2016-05-20 | shared files are now stored in session ******************************************************************************************************/ function getSynologySharedFolders($flag = 0) { $shareArray = array(); $dir_list = array(); if(isset($_SESSION['sharedDirectoriesRaw']) && !empty($_SESSION['sharedDirectoriesRaw']) && (is_object($_SESSION['sharedDirectoriesRaw']) && count($_SESSION['sharedDirectoriesRaw']) == 1)) { $sharedCheckArr = json_decode($_SESSION['sharedDirectoriesRaw'], TRUE); $sharedFirstDir = current($sharedCheckArr); if(isset($sharedFirstDir['filename']) && $sharedFirstDir['filename'] === 'Home') { unset($_SESSION['sharedDirectoriesRaw']); } } if(@empty($_SESSION['sharedDirectoriesRaw'])){ if(isset($_SESSION['sharedDirectoriesRaw'])) unset($_SESSION['sharedDirectoriesRaw']); saveSynologySharedFolders(); } if(isset($_SESSION['sharedDirectoriesRaw']) && !empty($_SESSION['sharedDirectoriesRaw'])) { $sharedDirList = $_SESSION['sharedDirectoriesRaw']; # check whether we get a valid object or not $arr = json_decode($sharedDirList); if(!$arr){ unset($_SESSION['sharedDirectoriesRaw']); saveSynologySharedFolders(); $sharedDirList = $_SESSION['sharedDirectoriesRaw']; $arr = json_decode($sharedDirList); } if($_SESSION['isSharedListFromCGI']) { $shareArray = $arr->data->shares; $_SESSION['shared_folders'] = array(); foreach($shareArray as $dirList) { $dirname = $dirList->additional->real_path; if($flag == 0) { $type = $dirList->isdir=='1'?"D":"F"; $size = $dirList->isdir=='1'?"":$dirList->size; $dir_list[$dirname]["size"] = trim($size); $dir_list[$dirname]["datetime"] = gmdate("Y/m/d h:i:s A", $dirList->additional->time->mtime); $dir_list[$dirname]["type"] = $type; } # added this new condition for fixing Snigdha_2.04.04_1_16 if($dirList->name == "home"){ if(strpos($dirname,"/volume1/")!==false){ //then it was found $dir_list[$dirname]["realName"] = $_SESSION['nasUserName']; } } else $dir_list[$dirname]["realName"] = $dirList->name; array_push($_SESSION['shared_folders'], ($dirname . '/')); } ksort($dir_list); } else { $dir_list = json_decode($sharedDirList, true); if(count($dir_list) > 0) { // $dir_list = json_decode($sharedDirList, true); foreach($dir_list as $key => &$value) { $value['realName'] = basename($key); array_push($_SESSION['shared_folders'], ($key.'/')); } ksort($dir_list); } } } return $dir_list; } /**************************************************************************************************** * Function Name : saveSynologySharedFolders * Objective : Saving synology shared folders list into text file * Added By : Senthil Pandian * Modified By : Sabin Cheruvattil - 2016-05-20 | shared files are now stored in session ******************************************************************************************************/ function saveSynologySharedFolders() { isRootLevelDisplayEnabled(); $shareArray = array(); $sharedDirList = ''; if(!$_SESSION['displayRoot'] && (file_exists(SYNOLOGY_SHARE_CGI_PATH) || file_exists(SYNOLOGY_SHARE_CGI_PATH_DSM6))) { $_SESSION['isSharedListFromCGI'] = true; $shareURL = getNasURL(); if(!isset($_SESSION['CGI_SID'])) exit(header("Location:logout.php")); else $sid = $_SESSION['CGI_SID']; $cgiPartialURL = ''; if(file_exists(SYNOLOGY_SHARE_CGI_PATH)) { $cgiPartialURL = 'webfm/webUI/file_share.cgi'; } else if(file_exists(SYNOLOGY_SHARE_CGI_PATH_DSM6)) { $cgiPartialURL = 'webapi/entry.cgi'; } $sharedDirURL = $shareURL."{$cgiPartialURL}"; $sharedDirData = "api=SYNO.FileStation.List&version=1&method=list_share&additional=real_path%2Ctime%2Csize&_sid=$sid"; $shareOutputArr = getCurlOutput($sharedDirURL, $sharedDirData); if($shareOutputArr['status']==false){ Scheduler::Log("Get share files List CGI: "." Output: ".$shareOutputArr['output']. " Error: ".$shareOutputArr['error']); exit(header("Location:logout.php")); } $sharedDirList = $shareOutputArr['output']; if(empty($sharedDirList)) exit(header("Location:logout.php")); // If the shared folders are empty, fallback to manual listing. $arr = json_decode($sharedDirList); $shareArray = $arr->data->shares; } if (!(count($shareArray) > 0) || $_SESSION['displayRoot'] === 1) { $_SESSION['isSharedListFromCGI'] = false; $list = array(); $shared = (($_SESSION['displayRoot'] === 1)? systemCmdExecution("ls -d -1 /") : systemCmdExecution("ls -d -1 /volume*")); $sharedList = explode("\n",trim($shared)); $_SESSION['shared_folders'] = array(); foreach($sharedList as $name){ $command = ''; if ($_SESSION['haslsdatetimeformat'] == 0) { $command = ('ls -aln ' . escapeshellarg($name)); $command .= (' --time-style=\"+%a %b %e %H:%M:%S %Y\"'); } else { $command = ('ls -alen ' . escapeshellarg($name)); } $res = systemCmdExecution($command); $res = parseLocalDirList($res,$name,'/'); if($_SESSION['displayRoot'] === 1) { $_SESSION['shared_folders'] = array_keys($res); } else { array_push($_SESSION['shared_folders'], ($name . '/')); } $list = $list+$res; } $sharedDirList = json_encode($list); } $_SESSION['sharedDirectoriesRaw'] = $sharedDirList; } /**************************************************************************************************** * Function Name : getQNAPSharedFolders * Objective : Getting QNAP shared folders list * Added By : Senthil Pandian * Modified By : Sabin Cheruvattil - 2016-05-18 | shared files are now stored in session ******************************************************************************************************/ function getQNAPSharedFolders() { $dir_list = array(); if(@empty($_SESSION['sharedDirectoriesRaw'])){ if(isset($_SESSION['sharedDirectoriesRaw'])) unset($_SESSION['sharedDirectoriesRaw']); saveQNAPSharedFolders(); } if(isset($_SESSION['sharedDirectoriesRaw']) && !empty($_SESSION['sharedDirectoriesRaw'])) { $sharedDirList = $_SESSION['sharedDirectoriesRaw']; # check whether we get a valid object or not $dir_list = json_decode($sharedDirList, true); if(!$dir_list){ unset($_SESSION['sharedDirectoriesRaw']); saveQNAPSharedFolders(); $sharedDirList = $_SESSION['sharedDirectoriesRaw']; $dir_list = json_decode($sharedDirList, true); } ksort($dir_list); } return $dir_list; } /**************************************************************************************************** * Function Name : saveQNAPSharedFolders * Objective : Saving QNAP shared folders list into text file * Added By : Senthil Pandian * Modified By : Sabin Cheruvattil - 2016-05-18 | shared files are now stored in session ******************************************************************************************************/ function saveQNAPSharedFolders() { GLOBAL $appPath; isRootLevelDisplayEnabled(); //$path = QNAP_SHARED_PATH; $path = (($_SESSION['displayRoot'] === 1)? "/" : QNAP_SHARED_PATH ); if($_SESSION['haslsdatetimeformat'] == 0) { $command = ('ls -aln ' . escapeshellarg($path)); //$command .= (' --time-style=\"+%a %b %e %H:%M:%S %Y\" | grep \'^l\''); $command .= (' --time-style=\"+%a %b %e %H:%M:%S %Y\"'); if($_SESSION['displayRoot'] == 0) $command .= (' | grep \'^l\''); else $command .= (' | grep \'^d\|^-\''); } else { $command = ('ls -alen ' . escapeshellarg($path)); //$command .= (' | grep \'^l\''); if($_SESSION['displayRoot'] == 0) $command .= (' | grep \'^l\''); else $command .= (' | grep \'^d\|^-\''); } $res = systemCmdExecution($command); if($_SESSION['displayRoot'] === 1) $res = parseRootLevelFilesForQNAP($res,'/','/'); else $res = parseLocalDirList($res,'/','/'); if($_SESSION['displayRoot'] === 1) { $_SESSION['shared_folders'] = array_keys($res); } $sharedDirList = json_encode($res); $_SESSION['sharedDirectoriesRaw'] = $sharedDirList; } /**************************************************************************************************** * Function Name : getNetgearSharedFolders * Objective : Getting Netgear shared folders list * Added By : Senthil Pandian * Modified By : Sabin Cheruvattil - 2016-05-18 | shared files are now stored in session ******************************************************************************************************/ function getNetgearSharedFolders() { $dir_list = array(); if(@empty($_SESSION['sharedDirectoriesRaw'])){ if(isset($_SESSION['sharedDirectoriesRaw'])) unset($_SESSION['sharedDirectoriesRaw']); saveNetgearSharedFolders(); } if(isset($_SESSION['sharedDirectoriesRaw']) && !empty($_SESSION['sharedDirectoriesRaw'])) { $sharedDirList = $_SESSION['sharedDirectoriesRaw']; $dir_list = json_decode($sharedDirList, true); if(!$dir_list){ unset($_SESSION['sharedDirectoriesRaw']); saveNetgearSharedFolders(); $sharedDirList = $_SESSION['sharedDirectoriesRaw']; $dir_list = json_decode($sharedDirList); } ksort($dir_list); } return $dir_list; } /**************************************************************************************************** * Function Name : saveNetgearSharedFolders * Objective : Saving Netgear shared folders list into text file * Added By : Senthil Pandian * Modified By : Sabin Cheruvattil - 2016-05-19 | shared files are now stored in session ******************************************************************************************************/ function saveNetgearSharedFolders() { GLOBAL $appPath; isRootLevelDisplayEnabled(); $sharedDirList = ''; $list = array(); $sharedList = array(); if($_SESSION['displayRoot'] === 1){ $shared = systemCmdExecution("ls -d -1 /"); $sharedList = explode("\n",trim($shared)); } else { $cmd = "find / -maxdepth 2 -name '._share'"; $output = `$cmd`; $pathArray = explode("\n",trim($output,"\n")); foreach($pathArray as $path){ $getNetgearSharedPath = "/".trim(strtok($path, "//"))."/"; array_push($sharedList, $getNetgearSharedPath); } } $_SESSION['shared_folders'] = array(); foreach($sharedList as $name){ $homePath = $name; $toGrep = 'home'; $path = $name.'._share'; $res = systemCmdExecution("$appPath/ls -aln \"$path\" --time-style=\"+%a %b %e %H:%M:%S %Y\" | grep '^d'"); $res .= systemCmdExecution("$appPath/ls -aln \"$homePath\" --time-style=\"+%a %b %e %H:%M:%S %Y\" | grep '$toGrep'| grep '^d'"); $name = rtrim($name,"/"); $res = parseLocalDirList($res,$name,'/'); /*if($_SESSION['displayRoot'] === 1) { $_SESSION['shared_folders'] = array_keys($res); } else { array_push($_SESSION['shared_folders'], ($name . '/')); }*/ //Commented by Senthil on 24-Oct-2017 $list = $list+$res; } $sharedDirList = json_encode($list); $_SESSION['sharedDirectoriesRaw'] = $sharedDirList; } /**************************************************************************************************** * Function Name : getTwotierSharedFolders * Objective : Getting Netgear shared folders list * Added By : Yogesh Kumar * Modified By : Sabin Cheruvattil - 2016-05-18 | shared files are now stored in session ******************************************************************************************************/ function getTwotierSharedFolders() { $dir_list = array(); if(@empty($_SESSION['sharedDirectoriesRaw'])){ if(isset($_SESSION['sharedDirectoriesRaw'])) unset($_SESSION['sharedDirectoriesRaw']); saveTwotierSharedFolders(); } if(isset($_SESSION['sharedDirectoriesRaw']) && !empty($_SESSION['sharedDirectoriesRaw'])) { $sharedDirList = $_SESSION['sharedDirectoriesRaw']; # check whether we get a valid object or not $dir_list = json_decode($sharedDirList, true); if(!$dir_list){ unset($_SESSION['sharedDirectoriesRaw']); saveTwotierSharedFolders(); $sharedDirList = $_SESSION['sharedDirectoriesRaw']; $dir_list = json_decode($sharedDirList, true); } ksort($dir_list); } return $dir_list; } /**************************************************************************************************** * Function Name : saveTwotierSharedFolders * Objective : Saving Twotier shared folders list into text file * Added By : Yogesh Kumar * Modified By : Sabin Cheruvattil - 2016-05-19 | shared files are now stored in session ******************************************************************************************************/ function saveTwotierSharedFolders() { GLOBAL $appPath; $homePath = TWOTIER_SHARED_PATH; $cmd = "/bin/ls -aln -D \"+%a %b %e %H:%M:%S %Y\" \"$homePath\" | grep '^d' | grep -v '\.zfs$'"; $res = systemCmdExecution($cmd); $res = parseLocalDirList($res,'/'); $sharedDirList = json_encode($res); $_SESSION['sharedDirectoriesRaw'] = $sharedDirList; } /**************************************************************************************************** * Function Name : updateBackupsetFiles * Objective : To remove the file entries which are not exists. * Added By : Yogesh Kumar * Modified By : Senthil Pandian ******************************************************************************************************/ function updateBackupsetFiles($oldDeltaSharedList, $tempListArray, $backupSetDir) { GLOBAL $permissionVal; $backupSetDisplayFile = $backupSetDir . '/' . BACKUPSETFILEDISPLAY; $backupSetDisplayFileList = file_get_contents($backupSetDisplayFile); $backupSetDisplayFileArray = explode("\n", $backupSetDisplayFileList); array_pop($backupSetDisplayFileArray); $deltaFiles = array(); foreach( $oldDeltaSharedList as $file) { $filename = preg_quote($file, '/'); $match = preg_grep('/^' . $filename . '$|^' . $filename . '\//', $backupSetDisplayFileArray); if( count( $match ) > 0 ) { $deltaFiles[] = array_keys($match); } } $udpateBackupSet = false; foreach( $deltaFiles as $deltaArray) { foreach( $deltaArray as $index => $value) { unset($backupSetDisplayFileArray[($value * 2)]); unset($backupSetDisplayFileArray[($value * 2) + 1]); if( ! $udpateBackupSet ) $udpateBackupSet = true; } } if( $udpateBackupSet ) { //Added this condition to avoid keeping only '\n' if(count($backupSetDisplayFileArray)>0){ $newBSDF = implode("\n", $backupSetDisplayFileArray) . "\n"; } else { $newBSF = ''; $newBSDF = ''; } file_put_contents($backupSetDisplayFile, $newBSDF, LOCK_EX); @chmod($backupSetDisplayFile, $permissionVal); return true; } return false; } /**************************************************************************************************** * Function Name : autoUpdateBackupset * Objective : To dynamically add newly added folders to backupset. * Added By : Yogesh Kumar ******************************************************************************************************/ function autoUpdateBackupset($userServicePath = NULL) { $backupSetDir = NULL; GLOBAL $userDirListsFile,$permissionVal; if ($userServicePath === NULL) { $backupSetDir = Scheduler::$backup_dir.DEFAULT_BACKUPSET; } else { $userDirListsFile = ($userServicePath.'/'.USERDIRLISTS) ; $backupSetDir = $userServicePath.'/'.BACKUPDIR.'/'.DEFAULT_BACKUPSET; } // Get all directory (excluding hidden dirs) names. $command = ("find " . TWOTIER_SHARED_PATH . " -not -path '*/\.*' -type d -name '*' -mindepth 1 -maxdepth 1"); $newSharedDirList = shell_exec($command); // Convert string to an array. $tempListArray = explode("\n", $newSharedDirList); // Pop is required to remove last empty element. array_pop($tempListArray); // If userDirListsFile is not set just return void; if (!isset($userDirListsFile)) { return; } // If the userdirlists is empty then init. if(!file_exists($userDirListsFile)) { $newSharedDirList = serialize($tempListArray); file_put_contents($userDirListsFile, $newSharedDirList, LOCK_EX); } else { // Get the old list to compare with the new list. $oldSharedList = file_get_contents($userDirListsFile); $oldSharedList = unserialize($oldSharedList); // Get newly added directories. $newDeltaSharedList = array_diff($tempListArray, $oldSharedList); // Get all deleted directories. $oldDeltaSharedList = array_diff($oldSharedList, $tempListArray); if( (count($oldDeltaSharedList) > 0) && file_exists($backupSetDir) ) { updateBackupsetFiles($oldDeltaSharedList, $tempListArray, $backupSetDir); } // When there're new Dirs added, it requires to udpate 3 files. // 1.userdirlists.txt 2.BackupSetFile.txt 3.BackupSetDisplayFile.txt if( (count($newDeltaSharedList) > 0) && file_exists($backupSetDir) ) { $backupSetDisplayFile = $backupSetDir . '/' . BACKUPSETFILEDISPLAY; // Check for duplicate entries. $newDeltaSharedList = array_diff($newDeltaSharedList, file($backupSetDisplayFile, FILE_IGNORE_NEW_LINES)); if (count($newDeltaSharedList) > 0) { $newBackupDisplaySet = (implode("\nfolder\n", $newDeltaSharedList) . "\nfolder\n"); file_put_contents($backupSetDisplayFile, $newBackupDisplaySet, FILE_APPEND | LOCK_EX); @chmod($backupSetDisplayFile, $permissionVal); } } file_put_contents($userDirListsFile, serialize($tempListArray), LOCK_EX); @chmod($userDirListsFile, $permissionVal); } } /**************************************************************************************************** * Function Name : getFullPathOfSharedFolder * Objective : Getting Netgear shared folders list * Added By : Senthil Pandian ******************************************************************************************************/ function getFullPathOfSharedFolder(){ GLOBAL $machine, $NetgearSharedPath; $path = ''; if(NETGEAR_LOCAL == $machine){ $path = $NetgearSharedPath; } elseif('twotier' == $machine) { $path = TWOTIER_SHARED_PATH; } elseif(ASUSTOR == $machine) { $path = ASUSTOR_SHARED_PATH; } return $path; } /**************************************************************************************************** * Function Name : getTwotierSharedPath * Objective : Getting two tier's mounted shared folder name * Added By : Senthil Pandian ******************************************************************************************************/ function getTwotierSharedPath(){ if(!isset($_SESSION['TWOTIER_SHARED_PATH'])){ $cmd = "ls / | grep '^ID'"; $getMountedPath = systemCmdExecution($cmd); $homePath = '/'.trim($getMountedPath).'/'; $_SESSION['TWOTIER_SHARED_PATH'] = $homePath; } else { $homePath = $_SESSION['TWOTIER_SHARED_PATH']; } return $homePath; } /**************************************************************************************************** * Function Name : parseRootLevelFilesForQNAP * Objective : Parsing the ls command result & returning as array[As we are using links as shared in QNAP, parsing differs] * Added By : Anil Kumar ******************************************************************************************************/ function parseRootLevelFilesForQNAP($res,$path,$actualPath=''){ GLOBAL $machine; GLOBAL $appPath; if($path=='/') { $res1 = explode("\n", $res); $res1 = array_filter($res1); $dir_list = array(); $retry = 0; foreach($res1 as $res2) { $split = preg_split('/\s+/', $res2,5); $split1 = preg_split('/\s+/', $split[4],2); $size = trim($split1[0]); $dirname = substr($split1[1],25); $dirname = strToUtf8($dirname); $dirname = trim($dirname); $dirname = "/".$dirname; if ((($dirname == "/.") || ($dirname == "/..")) || (!file_exists($dirname))) { continue; } $type = substr($split[0],0,1); $type = $type=='d'?"D":"F"; $dir_list[$dirname]["size"] = humanReadableSize(trim($size)); $parts = preg_split('/\s+/', $date); $fullPath = str_replace("'","'\''",$dirname); $fullPath = str_replace('\\','\\\\',$fullPath); $fullPath = preg_replace("/\"/","\\\"",$fullPath); $fullPath = str_replace('$','\$',$fullPath); $fullPath = str_replace('`','\`',$fullPath); $cmd = "date +'%Y/%m/%d %T %p' -r '$fullPath'"; $date = systemCmdExecution($cmd); $dir_list[$dirname]["datetime"] = trim($date,"\n"); $dir_list[$dirname]["type"] = $type; } ksort($dir_list); return $dir_list; } } /**************************************************************************************************** * Function Name : parseLocalDirList * Objective : Parsing the ls command result & returning as array * Added By : Senthil Pandian ******************************************************************************************************/ function parseLocalDirList($res,$path,$actualPath=''){ GLOBAL $machine; GLOBAL $appPath; if(QNAP == $machine && $path=='/') { $res1 = explode("\n", $res); $res1 = array_filter($res1); $dir_list = array(); $retry = 0; while ($retry <= 1) { $retry++; $loggedIn = 'TRUE'; if (!isset($_SESSION['CGI_SID'])) { $nasUserName = rawurlencode($_SESSION['nasUserName']); $nasPwd = rawurlencode(simple_decrypt()); $loggedIn = qnapNASlogin($nasUserName, $nasPwd,""); } if ($loggedIn === 'TRUE') { $url = getNasURL() . "cgi-bin/filemanager/utilRequest.cgi"; $data = "func=get_tree&sid=". $_SESSION['CGI_SID'] . "&node=share_root"; $shareOutputArr = getCurlOutput($url, $data); if($shareOutputArr['status']==false){ Scheduler::Log("Qnap shared folder list CGI: "." Output: ".$shareOutputArr['output']. " Error: ".$shareOutputArr['error']); unset($_SESSION['CGI_SID']); break; } $sharedFoldersJSON = json_decode($shareOutputArr['output']); // Usually status is set on Failure. if (isset($sharedFoldersJSON->status) && ($sharedFoldersJSON->status == 3)) { unset($_SESSION['CGI_SID']); } else if (isset($sharedFoldersJSON->status)) { Scheduler::Log("Failed to get shared folders: " . print_r($sharedFoldersJSON, true)); unset($_SESSION['CGI_SID']); } else { break; } } } $sharedFolders = array(); foreach($sharedFoldersJSON as $foldersInfo) { if (isset($foldersInfo->text)) { $sharedFolders[$foldersInfo->text] = $foldersInfo->text; } else { break; } } $parentLevel = ""; foreach($res1 as $res2) { $split = preg_split('/\s+/', $res2,5); $split1 = preg_split('/\s+/', $split[4],2); $size = trim($split1[0]); $linkName = substr($split1[1],25); $splitLink = preg_split('/->/', $linkName); $dirname = strToUtf8($splitLink[1]); $dirname = trim($dirname); $splitLink[0] = rtrim($splitLink[0]); $dirname = QNAP_SHARED_PATH.$dirname; $parentLevel = str_replace($splitLink[0], "", $dirname); if (!file_exists($dirname) || (isset($_SESSION['CGI_SID']) && !isset($sharedFolders[$splitLink[0]]))) { continue; } $type = substr($split[0],0,1); $type = $type=='l'?"D":"F"; $dir_list[$dirname]["size"] = humanReadableSize(trim($size)); $parts = preg_split('/\s+/', $date); $fullPath = str_replace("'","'\''",$dirname); $fullPath = str_replace('\\','\\\\',$fullPath); $fullPath = preg_replace("/\"/","\\\"",$fullPath); $fullPath = str_replace('$','\$',$fullPath); $fullPath = str_replace('`','\`',$fullPath); $cmd = "date +'%Y/%m/%d %T %p' -r '$fullPath'"; $date = systemCmdExecution($cmd); $dir_list[$dirname]["datetime"] = trim($date,"\n"); $dir_list[$dirname]["type"] = $type; } $homeDir = $parentLevel.HOMES; if($_SESSION['nasUserName'] =='root') $homeDir = $homeDir.'/'.ADMIN; else $homeDir = $homeDir.'/'.$_SESSION['nasUserName']; //need to add home path here. $cmd = "date +'%Y/%m/%d %T %p' -r '$homeDir'"; $date = systemCmdExecution($cmd); $dir_list[$homeDir]["size"] = "21 B"; $dir_list[$homeDir]["datetime"] = trim($date,"\n"); $dir_list[$homeDir]["type"] = "D"; } /*elseif("netgear" == $machine && $path=='/'){ $res1 = explode("\n", $res); $res1 = array_filter($res1); $dir_list = array(); foreach($res1 as $res2) { $split = preg_split('/\s+/', $res2,5); $split1 = preg_split('/\s+/', $split[4],2); $size = trim($split1[0]); $date = trim(substr($split1[1],0,24)); $dirname = substr($split1[1],25); $trimmedDirname = trim($dirname); if($trimmedDirname !='' && $trimmedDirname !='.' && $trimmedDirname !='..'){ $dirname = $NetgearSharedPath.$dirname; if(!file_exists($dirname)) continue; $type = substr($split[0],0,1); $type = $type=='d'?"D":"F"; $dir_list[$dirname]["size"] = humanReadableSize(trim($size)); $parts = preg_split('/\s+/', $date); $dir_list[$dirname]["datetime"] = date("Y/m/d h:i:s A", strtotime($parts[2]." ".$parts[1]." ".$parts[4]." ".$parts[3])); $dir_list[$dirname]["type"] = $type; } } } */ elseif("twotier" == $machine && $path=='/'){ $res1 = explode("\n", $res); $res1 = array_filter($res1); $dir_list = array(); $homePath = TWOTIER_SHARED_PATH; foreach($res1 as $res2) { $split = preg_split('/\s+/', $res2,5); $split1 = preg_split('/\s+/', $split[4],2); $size = trim($split1[0]); $date = trim(substr($split1[1],0,25)); $dirname = substr($split1[1],26); $dirname = strToUtf8($dirname); $trimmedDirname = trim($dirname); if($trimmedDirname !='' && $trimmedDirname !='.' && $trimmedDirname !='..'){ $dirname = $homePath.$dirname; if(!file_exists($dirname) || $dirname=='.zfs') continue; $type = substr($split[0],0,1); $type = $type=='d'?"D":"F"; $dir_list[$dirname]["size"] = humanReadableSize(trim($size)); $parts = preg_split('/\s+/', $date); $dir_list[$dirname]["datetime"] = date("Y/m/d h:i:s A", strtotime($parts[2]." ".$parts[1]." ".$parts[4]." ".$parts[3])); $dir_list[$dirname]["type"] = $type; } } } else if((SYNOLOGY_LOCAL == $machine || NETGEAR_LOCAL == $machine) && $actualPath=='/'){ $res1 = explode("\n", $res); $res1 = array_filter($res1); $dir_list = array(); $splitCount = count(preg_split('/\s+/', $res1[2])); //Added for fallback logic for Synology: by Senthil on Sep 04, 2017 foreach($res1 as $res2) { if ((0 === strpos($res2, 'dr')) || (0 === strpos($res2, '-r'))) { $split = preg_split('/\s+/', $res2,5); $split1 = preg_split('/\s+/', $split[4],2); $size = trim($split1[0]); $date = trim(substr($split1[1],0,24)); $dirname = substr($split1[1],25); $dirname = strToUtf8($dirname); $dirname1 = trim($dirname); if($dirname1!='' && $dirname1!='.' && $dirname1!='..' && substr($dirname1,0,1)!='@'){ $dirname = (($_SESSION['displayRoot'] === 1)? "/$dirname" : "$path/$dirname"); $type = substr($split[0],0,1); $type = $type=='d'?"D":"F"; $dir_list[$dirname]["size"] = $type=='d'?"--":humanReadableSize(trim($size)); $parts = preg_split('/\s+/', $date); $dir_list[$dirname]["datetime"] = date("Y/m/d h:i:s A", strtotime($parts[2]." ".$parts[1]." ".$parts[4]." ".$parts[3])); $dir_list[$dirname]["type"] = $type; $dir_list[$dirname]["orgSize"] = trim($size); $dir_list[$dirname]["orgDate"] = $date; } } } //Added Fallback logic: by Senthil on Sep 04, 2017 if(SYNOLOGY_LOCAL == $machine && $splitCount<11 && count($res1)>2 && !$dir_list){ $_SESSION['haslsdatetimeformat'] = 0; $res1 = explode("\n", $res); $res1 = array_filter($res1); $dir_list = array(); foreach($res1 as $res2) { $split = preg_split('/\s+/', $res2,6); $split1 = preg_split('/\s+/', $split[5],4); $dirname = $split1[3]; $dirname = strToUtf8($dirname); $dirname1 = trim($dirname); if($dirname1!='' && $dirname1!='.' && $dirname1!='..' && substr($dirname1,0,1)!='@'){ if($path=='/') $dirname = (($_SESSION['displayRoot'] === 1)? "/$dirname" : "$path/$dirname"); $type = substr($split[0],0,1); $type = $type=='d'?"D":"F"; $dir_list[$dirname]["size"] = ''; $dir_list[$dirname]["datetime"] = "--"; $dir_list[$dirname]["type"] = $type; } } } } else if("asustor" == $machine && $path=='/'){ $res1 = explode("\n", $res); $res1 = array_filter($res1); $dir_list = array(); foreach($res1 as $res2) { $split = preg_split('/\s+/', $res2,5); $split1 = preg_split('/\s+/', $split[4],2); $size = trim($split1[0]); $date = trim(substr($split1[1],0,24)); $dirname = substr($split1[1],25); $dirname = strToUtf8($dirname); $dirname1 = trim($dirname); if($dirname1!='' && $dirname1!='.' && $dirname1!='..' && substr($dirname1,0,1)!='@'){ $dirname = "$path$dirname"; $type = substr($split[0],0,1); $type = $type=='d'?"D":"F"; $dir_list[$dirname]["size"] = ''; $parts = preg_split('/\s+/', $date); $dir_list[$dirname]["datetime"] = date("Y/m/d h:i:s A", strtotime($parts[2]." ".$parts[1]." ".$parts[4]." ".$parts[3])); $dir_list[$dirname]["type"] = $type; $dir_list[$dirname]["filename"] = $dirname1; } } } else { $res1 = explode("\n", $res); $res1 = array_filter($res1); $dir_list = array(); $splitCount = 0; if(SYNOLOGY_LOCAL == $machine && isset($res1[2])) $splitCount = count(preg_split('/\s+/', $res1[2])); //Added for fallback logic: by Senthil on Sep 04, 2017 foreach($res1 as $res2) { if ((0 === strpos($res2, 'd?')) || (0 === strpos($res2, '-?'))) { continue; } $split = preg_split('/\s+/', $res2,5); $split1 = preg_split('/\s+/', $split[4],2); $size = trim($split1[0]); if ('twotier' == $machine){ $dirname = substr($split1[1],26); $date = trim(substr($split1[1],0,25)); } else { $dirname = substr($split1[1],25); $date = trim(substr($split1[1],0,24)); } # added by anil to handle backup issue when values in ls(size and groupid got merged) got merged with any other values in the list. if(!is_numeric($size)){ $dirname = substr($split1[1],20); $pathForStat = "$path$dirname"; $statVal = stat($pathForStat); $gid = $statVal['gid']; $fileSize = $statVal['size']; $uid = $statVal['uid']; $date = date('D M d H:i:s Y', $statVal['mtime']); $size = validateLSOutput($split); } $dirname = strToUtf8($dirname); $trimmedDirname = trim($dirname,"\n"); //Added "\n" for Junk charactered file display issue - Senthil if($trimmedDirname !='' && $trimmedDirname !='.' && $trimmedDirname !='..'){ $type = substr($split[0],0,1); $type = $type=='d'?"D":"F"; $dir_list[$dirname]["size"] = humanReadableSize(trim($size)); $parts = preg_split('/\s+/', $date); $dir_list[$dirname]["datetime"] = date("Y/m/d h:i:s A", strtotime($parts[2]." ".$parts[1]." ".$parts[4]." ".$parts[3])); $dir_list[$dirname]["type"] = $type; $dir_list[$dirname]["orgSize"] = trim($size); $dir_list[$dirname]["orgDate"] = $date; } } } ksort($dir_list); return $dir_list; } /**************************************************************************************************** * Function Name : getLocalDirListHTML * Objective : Returning the HTML elements for local directory list * Added By : Senthil Pandian ******************************************************************************************************/ function getLocalDirListHTML($dir_list,$fullPath){ GLOBAL $machine; GLOBAL $index; GLOBAL $dirArray; GLOBAL $type; GLOBAL $class; $resHtml = ''; /* Condition added for synology market place */ isRootLevelDisplayEnabled(); if($fullPath=='/'){ $fullPath = ""; if($machine==NETGEAR_LOCAL || $machine==ASUSTOR || 'twotier' == $machine){ $fullPath = getFullPathOfSharedFolder(); $drivePath = str_replace('/','',$fullPath); } foreach($dir_list as $dir=>$property) { if($_SESSION['displayRoot'] === 1){ $fullPath='/'; $dir = ltrim($dir,'/'); $dirName = $dir; $title = htmlentities($dir, ENT_QUOTES); } else { $parts = explode("/", $dir); $dir = array_pop($parts); $fullPath = implode("/", $parts)."/"; $dirName = $dir; if($machine==QNAP){ $drivePath = $parts[1]."/".$parts[2]; $title = htmlentities($dir,ENT_QUOTES)." @ ".htmlentities($drivePath,ENT_QUOTES); } else if($machine==NETGEAR_LOCAL){ $drivePath = $drivePath; $title = htmlentities($dir,ENT_QUOTES)." @ ".htmlentities($drivePath,ENT_QUOTES); } else if('twotier' == $machine){ $drivePath = $drivePath; $title = htmlentities($dir,ENT_QUOTES); } else if(ASUSTOR == $machine){ $dirName = $property['filename']; $drivePath = $drivePath; $title = htmlentities($dir,ENT_QUOTES); } else if('synology' == $machine) { if($property['realName'] != '') { $dirName = $property['realName']; } $drivePath = $parts[1]; $title = htmlentities($dir, ENT_QUOTES)." @ ".htmlentities($drivePath,ENT_QUOTES); } else { $drivePath = $parts[1]; $title = htmlentities($dir, ENT_QUOTES)." @ ".htmlentities($drivePath,ENT_QUOTES); } } if($_SESSION['showHidden']=="Hide" && (strpos($dir, '.') === 0)){ $tr_style='hide'; } else{ $tr_style=''; } if($property['type']=="D") { if($tr_style==''){ $resHtml .= ''; $resHtml .= " "; $resHtml .= ""; $resHtml .= ''; $resHtml .= ""; $resHtml .= str_replace(" "," ",htmlentities($dirName,ENT_QUOTES)); $resHtml .= ''; $resHtml .= ' -- '.$property["datetime"].''; $resHtml .= ''; $resHtml .= ''; $index++; } $type[] = 'folder'; $dirArray[] = $fullPath.$dir; } else { if($tr_style==''){ $resHtml .= ''; $resHtml .= " "; $resHtml .= ""; $resHtml .= str_replace(" "," ",htmlentities($dirName,ENT_QUOTES)); $resHtml .= ''; $resHtml .= ' '.$property["size"].' '.$property["datetime"].' '; $resHtml .= ''; $resHtml .= ''; $index++; } $type[] = 'file'; $dirArray[] = $fullPath.$dir; } } } else { $fullPath = "$fullPath/"; foreach($dir_list as $dir=>$property) { if($_SESSION['showHidden']=="Hide" && (strpos($dir, '.') === 0)){ $tr_style='hide'; } else{ $tr_style=''; } $dirName = $dir; if($property['type']=="D") { if($tr_style==''){ $resHtml .= ''; $resHtml .= ""; $resHtml .= ""; $resHtml .= ''; $resHtml .= ""; $resHtml .= str_replace(" "," ",htmlentities($dirName,ENT_QUOTES)); $resHtml .= ''; $resHtml .= ' -- '.$property["datetime"].''; $resHtml .= ''; $resHtml .= ''; $index++; } $type[] = 'folder'; $dirArray[] = $fullPath.$dir; } else { if($tr_style==''){ $resHtml .= ''; $resHtml .= ""; $resHtml .= ""; $resHtml .= str_replace(" "," ",htmlentities($dir,ENT_QUOTES)); $resHtml .= ''; $resHtml .= ' '.$property["size"].' '.$property["datetime"].' '; $resHtml .= ''; $resHtml .= ''; $index++; } $type[] = 'file'; $dirArray[] = $fullPath.$dir; } } } return $resHtml; } /**************************************************************************************************** * Function Name : getRemoteLocationListHTML * Objective : Returning the HTML elements for Remote Location List * Added By : Senthil Pandian ******************************************************************************************************/ function getRemoteLocationListHTML($dir_list,$fullPath){ GLOBAL $machine; GLOBAL $index; GLOBAL $dirArray; GLOBAL $type; GLOBAL $class; $resHtml = ''; /* Condition added for synology market place */ if($fullPath=='/'){ $fullPath = ""; foreach($dir_list as $dir=>$property) { if($machine=='twotier') { if($property!='.' && $property!='..'){ $dir = $property; } else { continue; } $drivePath = IDRIVE_VAULT_RESTORELOCATION_ROOT; $fullPath = '/'.IDRIVE_VAULT_RESTORELOCATION_ROOT.'/'; } else { $parts = explode("/", $dir); if($machine==ASUSTOR){ $dirName = $property['filename']; } else{ $dir = array_pop($parts); $dirName = $dir; } $fullPath = implode("/", $parts)."/"; if($machine==QNAP){ $drivePath = $parts[1]."/".$parts[2]; } else { $drivePath = $parts[1]; } } if($_SESSION['showHidden']=="Hide" && (strpos($dir, '.') === 0)){ $tr_style='hide'; } else{ $tr_style=''; } if($machine=='twotier') $title = htmlentities($dir,ENT_QUOTES); else $title = htmlentities($dir,ENT_QUOTES)." @ ".htmlentities($drivePath,ENT_QUOTES); if($machine==ASUSTOR) $path = $dir; else $path = $fullPath.$dir; if($tr_style==''){ $resHtml .= ''; $resHtml .= ""; $resHtml .= ""; $resHtml .= htmlentities($dirName,ENT_QUOTES); $resHtml .= ""; $resHtml .= ''; $index++; $type[] = 'folder'; $dirArray[] = $path; } } } else { $fullPath = "$fullPath/"; foreach($dir_list as $dir) { if(trim($dir) !='' && trim($dir)!='.' && trim($dir)!='..'){ if($_SESSION['showHidden']=="Hide" && (strpos($dir, '.') === 0)){ $tr_style='hide'; } else{ $tr_style=''; } if($tr_style==''){ $resHtml .= ''; $resHtml .= ""; $resHtml .= ""; $resHtml .= htmlentities($dir,ENT_QUOTES); $resHtml .= ""; $resHtml .= ''; $index++; $type[] = 'folder'; if($machine==ASUSTOR) $dirArray[] = $fullPath; else $dirArray[] = $fullPath.$dir; } } } } return $resHtml; } /**************************************************************************************************** * Function Name : getCronContent * Objective : This function will return the cron file content based on machine * Added By : Deepak Chaurasia ******************************************************************************************************/ function getCronContent($MIN, $HOUR, $DOM, $MON, $DOW){ GLOBAL $machine; GLOBAL $user; if (QNAP == $machine || ASUSTOR == $machine) { $content = $MIN." ".$HOUR." ".$DOM." ".$MON." ".$DOW." "; } else{ $content = $MIN."\t".$HOUR."\t".$DOM."\t".$MON."\t".$DOW."\t".$user."\t"; } return $content; } /**************************************************************************************************** * Function Name : getListForDirectory * Objective : This function will return the directory list for the path passed as input * Added By : Deepak Chaurasia ******************************************************************************************************/ function getListForDirectory($fullPath){ GLOBAL $machine; GLOBAL $appPath; $full_Path = $fullPath; if ("twotier" == $machine){ $fullPath = str_replace("'","'\''",$fullPath); } else if (SYNOLOGY_LOCAL == $machine) { if(!empty($_SESSION['encryptedToken'])){ $fullPath = preg_replace("/\"/","\\\"",$fullPath); $fullPath = str_replace('$','\$',$fullPath); } } else { if($machine != QNAP) { $fullPath = str_replace("'","'\''",$fullPath); } if($machine == NETGEAR_LOCAL) { $fullPath = preg_replace('/\\\\/', '\\\\', $fullPath); } else { $fullPath = str_replace('\\', '\\\\', $fullPath); } $fullPath = preg_replace("/\"/","\\\"",$fullPath); $fullPath = str_replace('$','\$',$fullPath); $fullPath = str_replace('`','\`',$fullPath); } $page_no = 1; $list_per_page = MAX_NUM_OF_ITEMS; if (isset($_GET['page_no'])) $page_no = $_GET['page_no']; $from = ($list_per_page * ($page_no -1)); $from = ($from === 0 ? 1 : $from+1); $to = (($list_per_page * $page_no) . 'p'); $pagination = ("sed -n $from,$to"); if($machine == NETGEAR_LOCAL){ if($fullPath=='/'){ $res = getNetgearSharedFolders(); } else { $res = systemCmdExecution("$appPath/ls -aln '$fullPath' --time-style=\"+%a %b %e %H:%M:%S %Y\" | grep '^d\|^-' | $pagination"); $res = parseLocalDirList($res,$full_Path); } } else if($machine == QNAP){ if($fullPath=='/'){ $res = getQNAPSharedFolders(); } else { if($_SESSION['haslsdatetimeformat'] == 0) { #$command = ('ls -aln ' . $fullPath); # commented by anil to handle some french characters like Réseau if(strlen(escapeshellarg($fullPath)) > strlen($fullPath) ) $command = ('ls -aln ' . escapeshellarg($fullPath)); else $command = ("ls -aln '$fullPath'"); $command .= (' --time-style=\"+%a %b %e %H:%M:%S %Y\" | grep \'^d\|^-\' | ' . $pagination); } else { #$command = ('ls -alen ' . $fullPath); # commented by anil to handle some french characters like Réseau if(strlen(escapeshellarg($fullPath)) > strlen($fullPath) ) $command = ('ls -alen ' . escapeshellarg($fullPath)); else $command = ("ls -alen '$fullPath'"); $command .= (' | grep \'^d\|^-\' | ' . $pagination); } $res = systemCmdExecution($command); $res = parseLocalDirList($res,$full_Path); } } else if($machine == SYNOLOGY_LOCAL){ if($fullPath=='/') { $res = getSynologySharedFolders(); //Getting shared folders list } else { if (hasReadPermissions($fullPath)) { if ($_SESSION['haslsdatetimeformat'] == 0) { #$command = ('ls -aln ' . $fullPath); if(strlen(escapeshellarg($fullPath)) > strlen($fullPath) ) $command = ('ls -aln ' . escapeshellarg($fullPath)); else $command = ("ls -aln '$fullPath'"); $command .= (' --time-style=\"+%a %b %e %H:%M:%S %Y\" | grep \'^d\|^-\' | ' . $pagination); } else { #$command = ('ls -alen ' . $fullPath); if(strlen(escapeshellarg($fullPath)) > strlen($fullPath) ) $command = ('ls -alen ' . escapeshellarg($fullPath)); else $command = ("ls -alen '$fullPath'"); $command .= (' | grep \'^d\|^-\' | ' . $pagination); } $res = systemCmdExecution($command); $res = parseLocalDirList($res,$full_Path); } else { $res = array(); } } } else if ("twotier" == $machine) { if($fullPath=='/'){ $res = getTwotierSharedFolders(); } else { $res = systemCmdExecution("/bin/ls -aln -D \"+%a %b %e %H:%M:%S %Y\" '$fullPath' | grep '^d\|^-' | $pagination"); $res = parseLocalDirList($res,$full_Path); } } else if($machine == ASUSTOR){ if($fullPath=='/'){ $res = getASUSTORSharedFolders(); } else { $res = systemCmdExecution("ls -alen '$fullPath' | grep '^d\|^-' | $pagination"); $res = parseLocalDirList($res,$full_Path); } } return $res; } /**************************************************************************************************** * Function Name : excludeworkingfolder * Objective : Creating/updating full path exclude file with working folder * Added By : Pooja Havaldar ******************************************************************************************************/ function excludeworkingfolder() { GLOBAL $excludeFullFile,$baseDir,$webDir,$userName,$machine,$permissionVal; $excludeFullFile = Scheduler::$user_dir.FULL_PATH_EXCLUDE_FILE; # as we are handling internally for synology we are removing it here. if($machine==NETGEAR_LOCAL || $machine=="twotier" || $machine == SYNOLOGY_LOCAL ){ return true; } $servicePath = getOriginalServicePath(); # added new service path to exclude from the backup. //$servicePath = "/volume1/@appstore/IDrive/"; $servicePath .= "\n"; if (!file_exists($excludeFullFile)) { file_put_contents($excludeFullFile, ($servicePath ."folder\nundefined\nundefined\n")); unset($_SESSION['fullEntry']); unset($_SESSION['fullEntryImg']); } else { $sessionFullEntry = file_get_contents($excludeFullFile, FILE_IGNORE_NEW_LINES); $ret = strpos($sessionFullEntry,$servicePath); if($ret === FALSE){ $sessionFullEntry = trim($sessionFullEntry, "\s"); file_put_contents($excludeFullFile, $servicePath . "folder\nundefined\nundefined\n" . $sessionFullEntry); unset($_SESSION['fullEntry']); } } @chmod($excludeFullFile, $permissionVal); } /**************************************************************************************************** * Function Name : getOriginalServicePath * Objective : Returns the Working folder path according to machine * Modified By : Senthil Pandian ******************************************************************************************************/ function getOriginalServicePath() { $servicePath = getWebDirPath()."/".SERVICE; return $servicePath; } /**************************************************************************************************** * Function Name : getWebDirPath * Objective : Returns the Web directory path according to machine * Added By : Senthil Pandian ******************************************************************************************************/ function getWebDirPath() { GLOBAL $webDir,$machine; $servicePath = "$webDir"; if(SYNOLOGY_LOCAL == $machine || ASUSTOR == $machine) { $servicePath = readlink("$webDir"); } else if(QNAP == $machine){ $servicePath = readlink("$webDir"); $servicePath = "/share/".rtrim($servicePath,'/'); } return $servicePath; } /**************************************************************************************************** * Function Name : machineBasedError * Objective : Returning machine based error for backup list * Added By : Senthil Pandian ******************************************************************************************************/ /*function machineBasedError(){ GLOBAL $machine; if("synology" == $machine){ if(isset($_SESSION['encryptedToken']) && isset($_SESSION['nasUserName'])){ $resHtml = '
'.str_replace('#USERNAME#',$_SESSION['nasUserName'],NO_SH).'
'; } else { $resHtml = '
'.SESSION_TIMEOUT.'
'; } } else { $resHtml = '
No files
'; } return $resHtml; }*/ /**************************************************************************************************** * Function Name : createLocalSearchTxt * Objective : Creating Local Search Txt file * Added By : Senthil Pandian ******************************************************************************************************/ function createLocalSearchTxt($localPatternPath,$searchKeyword,$searchPath) { GLOBAL $machine,$permissionVal; if($searchPath=='/'){ file_put_contents("$localPatternPath/".SEARCH_FILE,$searchKeyword); if(SYNOLOGY_LOCAL == $machine){ $dir_list = getSynologySharedFolders(SYNOLOGY_AVOID_PROP); foreach($dir_list as $dir=>$property){ file_put_contents("$localPatternPath/".SEARCH_FILE,"\n".$dir,FILE_APPEND); } } else if(QNAP == $machine){ $res = getQNAPSharedFolders(); foreach($res as $dir=>$property){ file_put_contents("$localPatternPath/".SEARCH_FILE,"\n".$dir,FILE_APPEND); } } else if(NETGEAR_LOCAL == $machine){ $res = getNetgearSharedFolders(); $path = getFullPathOfSharedFolder(); foreach($res as $dir=>$property){ //$dir = $path.$dir; file_put_contents("$localPatternPath/".SEARCH_FILE,"\n".$dir,FILE_APPEND); } } else if ("twotier" == $machine) { $res = getTwotierSharedFolders(); $path = getFullPathOfSharedFolder(); foreach($res as $dir=>$property){ file_put_contents("$localPatternPath/".SEARCH_FILE,"\n".$dir,FILE_APPEND); } } else if(ASUSTOR == $machine){ $res = getASUSTORSharedFolders(); $path = getFullPathOfSharedFolder(); foreach($res as $dir=>$property){ file_put_contents("$localPatternPath/".SEARCH_FILE,"\n".$dir,FILE_APPEND); } @chmod("$localPatternPath/".SEARCH_FILE, $permissionVal); } } else { file_put_contents("$localPatternPath/".SEARCH_FILE,$searchKeyword."\n".$searchPath); } @chmod("$localPatternPath/".SEARCH_FILE, $permissionVal); } /**************************************************************************************************** * Function Name : clearSessionProxySettings * Objective : Clear Proxy settings in session * Added By : Sabin Cheruvattil ******************************************************************************************************/ function clearSessionProxySettings() { $proxysettings = array('proxyUserName', 'proxyPassword', 'isProxyEnabled', 'ipAddress', 'port', 'proxy_option'); foreach($proxysettings as $ps) { unset($_SESSION[$ps]); } } /**************************************************************************************************** * Function Name : getProxyDetail * Objective : Reading Proxy details * Added By : Senthil Pandian ******************************************************************************************************/ function getProxyDetail(){ GLOBAL $machine; $output = array(); $httpIPAddr =""; $httpPort =""; if($machine==SYNOLOGY_LOCAL){ $proxyConfFile = SYNOLOGY_PROXYCONF; if(!file_exists($proxyConfFile)){ return $output; } $isProxyEnabled = array(); $contents = file($proxyConfFile); foreach ($contents as $line) { if(strpos($line, "proxy_enabled=") !== FALSE){ $isProxyEnabled = explode("=", $line); $temp = trim($isProxyEnabled[1]); $_SESSION['isProxyEnabled']=true; if($temp == "no"){ $proxy_enabled=0; unsetProxySessions(); $_SESSION['isProxyEnabled']=false; break; } } elseif(strpos($line, "bypass_enabled=") !== FALSE){ $proxyAddrField = explode("=", $line); $output[0] = trim($proxyAddrField[1]); $_SESSION['bypass_enabled'] = $output[0]; } elseif(strpos($line, "https_host=") !== FALSE){ $proxyAddrField = explode("=", $line); $output[0] = trim($proxyAddrField[1]); $_SESSION['ipAddress'] = $output[0]; } elseif(strpos($line, "https_port=") !== FALSE){ $proxyPassField = explode("=", $line); $output[1] = trim($proxyPassField[1]); $_SESSION['port']=$output[1]; } elseif(strpos($line, "http_host=") !== FALSE){ $proxyAddrField = explode("=", $line); $httpIPAddr = trim($proxyAddrField[1]); } elseif(strpos($line, "http_port=") !== FALSE){ $proxyPassField = explode("=", $line); $httpPort = trim($proxyPassField[1]); } elseif(strpos($line, "auth_enabled=") !== FALSE){ $isAuthEnabled = explode("=", $line); $temp = trim($isAuthEnabled[1]); if($temp == "no"){ $auth_enabled=0; } } elseif(strpos($line, "proxy_user=") !== FALSE){ $proxyUser = explode("=", $line); if($proxyUser === ""){ $output[2] = ""; $_SESSION['proxyUserName']=''; } else{ $output[2] = trim($proxyUser[1]); $_SESSION['proxyUserName']=trim($proxyUser[1]); } } elseif(strpos($line, "proxy_pwd=") !== FALSE){ $proxyPass = explode("=", $line); if($proxyPass === ""){ $output[3] = ""; $_SESSION['proxyPassword']=''; } else{ $output[3] = trim($proxyPass[1]); $_SESSION['proxyPassword']=trim($proxyPass[1]); } } } $_SESSION['proxy_option']='autodetect'; if(empty($_SESSION['ipAddress'])){ $_SESSION['ipAddress'] = $httpIPAddr; $_SESSION['port'] = $httpPort; $output[0] = $httpIPAddr; $output[1] = $httpPort; } } else if($machine=="QNAP"){ $proxyDetails = shell_exec("/sbin/getcfg \"System\" \"proxy server\" -d \"\""); $proxyDetails = trim($proxyDetails); if($proxyDetails == ""){ return $output; } $proxyUser = shell_exec("/sbin/getcfg \"System\" \"proxy username\" -d \"\""); $proxyUser = trim($proxyUser); if($proxyUser === ""){ $output[2] = ""; $_SESSION['proxyUserName']=""; } else{ $output[2] = $proxyUser; $_SESSION['proxyUserName']=$proxyUser; } $proxyPass = shell_exec("/sbin/getcfg \"System\" \"proxy password\" -d \"\""); $proxyPass = trim($proxyPass); if($proxyPass === ""){ $output[3] = ""; $_SESSION['proxyPassword']=''; } else{ $output[3] = $proxyPass; $_SESSION['proxyPassword']=$proxyPass; } $proxyFields = explode(":", $proxyDetails); $output[0] = str_replace('/','',$proxyFields[1]); $output[1] =trim($proxyFields[2]); $_SESSION['ipAddress'] = trim($output[0]); $_SESSION['port'] = $output[1]; $_SESSION['proxy_option']='autodetect'; $_SESSION['isProxyEnabled']=true; } else if($machine==ASUSTOR){ $proxy_enabled=1; $auth_enabled=1; $proxyConfFile = ASUSTOR_PROXYCONF; if(file_exists($proxyConfFile) === FALSE) return $output; $contents = file($proxyConfFile); $proxy_data = 0; $i = 0; foreach ($contents as $line) { if(strpos($line, "[Proxy Client]") !== FALSE){ $proxy_data = 1; continue; } if($proxy_data == 1 && $i<6){ if(strpos($line, "IsEnabled =") !== FALSE){ $isProxyEnabled = explode("=", $line); $proxy_enabled_chk = trim($isProxyEnabled[1]); $_SESSION['isProxyEnabled']=true; if($proxy_enabled_chk == 'No'){ $proxy_enabled = 0; unset($_SESSION['ipAddress']); unset($_SESSION['port']); unset($_SESSION['proxyUserName']); unset($_SESSION['proxyPassword']); $_SESSION['isProxyEnabled']=false; break; } $i++; } else if(strpos($line, "ServerAddress =") !== FALSE){ $proxyAddrField = explode("=", $line); $server_ip = preg_replace("(https?://)", "", trim($proxyAddrField[1])); $output[0] = $server_ip; $_SESSION['ipAddress'] = $output[0]; $i++; } else if(strpos($line, "ServerPort =") !== FALSE){ $proxyAddrField = explode("=", $line); $output[1] = trim($proxyAddrField[1]); $_SESSION['port']=$output[1]; $i++; } else if(strpos($line, "AuthEnabled =") !== FALSE){ $proxyAddrField = explode("=", $line); $auth_enabled_chk = trim($proxyAddrField[1]); if($auth_enabled_chk == 'No') $auth_enabled = 0; $i++; } else if(strpos($line, "AuthUsername =") !== FALSE){ $proxyAddrField = explode("=", $line); $output[2] = trim($proxyAddrField[1]); $_SESSION['proxyUserName']=$output[2]; $i++; } else if(strpos($line, "AuthPassword =") !== FALSE){ $proxyAddrField = explode("=", $line); $output[3] = trim($proxyAddrField[1]); $_SESSION['proxyPassword']=$output[3]; $i++; } } } $_SESSION['proxy_option']='autodetect'; } else if($machine == NETGEAR_LOCAL){ $proxyConfFile = NETGEAR_PROXYCONF; $https = 0; if(file_exists($proxyConfFile) === FALSE) return $output; //$cmd = "cat $proxyConfFile"; $cmd = "cat $proxyConfFile"; $outputData = systemCmdExecutionViaPhp($cmd, Scheduler::$user_dir); $contents = explode("\n",$outputData); if(count($contents) > 0 && $contents[0] != ''){ foreach ($contents as $line) { if($https == 1) break; if (strpos($line, 'https_proxy') !== false) { $arrayData = explode('https_proxy',$line); $https = 1; }else{ $arrayData = explode('http_proxy',$line); } $str = ltrim($arrayData[1], '='); $str1 = explode('@',$str); if(count($str1) == 2){ $user_detail = explode(':',$str1[0]); $output[2] = $user_detail[0]; $output[3] = $user_detail[1]; $server_detail = explode(':',$str1[1]); $output[0] = $server_detail[0]; $output[1] = $server_detail[1]; $_SESSION['ipAddress'] = $output[0]; $_SESSION['port'] = $output[1]; $_SESSION['proxyUserName'] = $output[2]; $_SESSION['proxyPassword'] = $output[3]; }else{ $server_detail = explode(':',$str1[0]); $output[0] = $server_detail[0]; $output[1] = $server_detail[1]; $_SESSION['ipAddress'] = $output[0]; $_SESSION['port'] = $output[1]; $output[2] = ""; $output[3] = ""; } } $_SESSION['proxy_option']='autodetect'; }else{ $output = array(); } } return $output; } /**************************************************************************************************** * Function Name : getFullPath * Objective : Reading Proxy details * Added By : Senthil Pandian ******************************************************************************************************/ function createRestoreLocationFile(){ GLOBAL $machine,$drlFile,$userName,$permissionVal,$webDir; if($machine==QNAP || $machine==SYNOLOGY_LOCAL || $machine==ASUSTOR){ $servicePath = getOriginalServicePath(); # anil removed / on 2july2018 $restorePath = Scheduler::$nasUser_dir."$userName/RESTORE_DATA"; file_put_contents($drlFile,$restorePath); } else if($machine==NETGEAR_LOCAL){ $idrivePath = $webDir."/".SERVICE; /* Creating the directory "idrive" if not exist */ if(!is_dir($idrivePath)){ if(!mkdir($idrivePath, $permissionVal)){ Scheduler::Log("Failed to create Directory ".$idrivePath." : ".customErrorMsg()); return; } } $userProfile = Scheduler::$nasUser_dir; //$idrivePath.'/'.USER_PROFILE; if(!is_dir($userProfile)){ if(!mkdir($userProfile, $permissionVal)){ Scheduler::Log("Failed to create Directory ".$userProfile." : ".customErrorMsg()); return; } } $userFolder = $userProfile."/$userName"; if(!is_dir($userFolder)){ if(!mkdir($userFolder, $permissionVal)){ Scheduler::Log("Failed to create Directory ".$userFolder." : ".customErrorMsg()); return; } } $restorePath = $userFolder.'/RESTORE_DATA'; if(!is_dir($restorePath)){ if(!mkdir($restorePath, $permissionVal)){ Scheduler::Log("Failed to create Directory ".$restorePath." : ".customErrorMsg()); return; } } file_put_contents($drlFile,$restorePath); } else if ("twotier" == $machine) { $restorePath = IDRIVE_VAULT_RESTORELOCATION; if(!file_exists($restorePath)){ $restoredData = '/'.IDRIVE_VAULT_RESTORELOCATION_ROOT; if(!is_dir($restoredData)){ systemCmdExecutionViaPhp("mkdir $restoredData", Scheduler::$user_dir); } systemCmdExecutionViaPhp("mkdir $restorePath", Scheduler::$user_dir); } file_put_contents($drlFile,$restorePath); } @chmod($drlFile, $permissionVal); return $restorePath; } /**************************************************************************************************** * Function Name : checkServicePath * Objective : Checking the first element of full path exclude file * Added By : Senthil Pandian ******************************************************************************************************/ function checkServicePath($firstElement,$servicePath){ GLOBAL $machine; if($firstElement==$servicePath || $machine==NETGEAR_LOCAL || $machine=="twotier"){ return false; } return true; } /**************************************************************************************************** * Function Name : getSearchPattern * Objective : Getting the search pattern for Search * Added By : Pooja Havaldar *****************************************************************************************************/ function getSearchPattern($searchKeyword = "") { GLOBAL $machine; if($searchKeyword == ""){ scheduler::Log("No pattern to search : "); return; } if(QNAP == $machine){ $searchKeyword = str_replace('\\','',$searchKeyword); return $searchKeyword; } return $searchKeyword; } /**************************************************************************************************** * Subroutine Name : removeFromCron. * Objective : Remove crontab entries. * Added By : Uttam Tiwari. *not in use ******************************************************************************************************/ function removeFromCron() { GLOBAL $webDir; GLOBAL $userName; $retVal = perlScriptExecution(REMOVECRON); @unlink(Scheduler::$user_dir.REMOVE_FROM_CRON_TAB_FILE); return $retVal; } /**************************************************************************************************** * Function Name : getBackupMode * Objective : Get backup mode to enable/disable Archive cleanup link * Added By : Senthil Pandian ******************************************************************************************************/ function getBackupMode(){ GLOBAL $relativeFile,$backupMode; if(file_exists($relativeFile)) { $readRelativetxt = file_get_contents($relativeFile); if($readRelativetxt == NORELATIVE){ $backupMode='relative'; } else{ $backupMode='mirror'; } } else{ $backupMode='mirror'; } return $backupMode; } /**************************************************************************************************** * Function Name : getCleanupCmd * Objective : Get command for archive cleanup * Added By : Deepak ******************************************************************************************************/ function getCleanupCmd($jobName){ GLOBAL $machine; GLOBAL $appPath; GLOBAL $archive_dir; $phpPath = getphpPath(); $scriptPath = "$appPath/".SCRIPT; $cmd = "$phpPath $scriptPath/".GETCLEANUPLIST; return $cmd; } /**************************************************************************************************** * Function Name : getNAShostname * Objective : Getting host name of NAS * Added By : Senthil Pandian ******************************************************************************************************/ function getNAShostname(){ GLOBAL $machine; $hostName = ''; if($machine=="twotier"){ if(file_exists('/'.MPC_FILE)){ $hostName = file_get_contents('/'.MPC_FILE); $hostName = trim("/$hostName"); } if(empty($hostName)){ $hostName = shell_exec("hostname"); traceLog(MPC_FILE . "#$hostName#"); } } else { $hostName = shell_exec("hostname"); } $hostName = trim("/$hostName"); if($_SESSION['dedup']) $hostName = trim($hostName,'/'); return $hostName; } /**************************************************************************************************** * Function Name : update_mpc * Objective : update the backup location to mpc.txt file * Added By : Deepak Chaurasia ******************************************************************************************************/ function update_mpc($mpcLoc='') { GLOBAL $mpc; GLOBAL $permissionVal; GLOBAL $machine; if(($machine=='twotier' || $machine==SYNOLOGY_LOCAL) && (trim($mpcLoc)=='/' || $mpcLoc=='')){ $mpcName = getNAShostname(); } else if($mpcLoc == "") $mpcName = "/".php_uname('n'); else $mpcName = rtrim(phpRealEscapeString($mpcLoc), '/'); file_put_contents($mpc, $mpcName); @chmod($mpc, $permissionVal); return $mpcName ; } /************************************************************************************************ * Subroutine Name : getMachinePattern * Objective : Find the brand of this NAS machine * Added By : Yogesh Kumar * Modified By : Senthil Pandian, Sabin Cheruvattil * Modified On : 11/23/2016 ************************************************************************************************/ function getMachinePattern() { GLOBAL $machine; $filePatterns = array(); $filePatterns['/var/services/web'] = SYNOLOGY_LOCAL; $filePatterns['/var/services/web_packages'] = SYNOLOGY_LOCAL; $filePatterns['/share/Web'] = QNAP; $filePatterns['/share/Qweb'] = QNAP; $filePatterns['/apps/idrive/web'] = NETGEAR_LOCAL; #$filePatterns['/usr/local/www'] = 'twotier'; $filePatterns['/usr/local/www'] = ASUSTOR; $machinePattern = NULL; foreach($filePatterns as $key => $machine) { if($machine===QNAP || $machine==="twotier"){ if(file_exists($key."/".APPDIR) && dirname(dirname(__FILE__)) == readlink($key."/".APPDIR)) { $machinePattern = array($key, $machine); break; } } if($machine===SYNOLOGY_LOCAL){ $val1 = dirname(dirname(__FILE__)); $val2 = readlink($key)."/".APPDIR; if(file_exists($key."/".APPDIR) && is_link($key."/".APPDIR) && dirname(dirname(__FILE__)) == readlink($key."/".APPDIR)) { // For Production $machinePattern = array($key, $machine); break; } else if(file_exists($key."/".APPDIR) && is_link($key)."/".APPDIR && dirname(dirname(__FILE__)) == readlink($key)."/".APPDIR) { // For APP Path customization $machinePattern = array($key, $machine); break; } } if($machine===NETGEAR_LOCAL){ if (dirname(dirname(dirname(__FILE__))) == $key){ $machinePattern = array($key, $machine); break; } } if($machine===ASUSTOR){ if (dirname(dirname(dirname(__FILE__))) == readlink($key)){ $machinePattern = array($key, $machine); break; } } } if ($machinePattern == NULL) { return FALSE; } return $machinePattern; } /************************************************************************************************ * Subroutine Name : getMachineDetails * Objective : Prepare the NAS machine details * Added By : Yogesh Kumar * Modified By : Senthil Pandian * Modified On : 11/23/2016 ************************************************************************************************/ function getMachineDetails() { if (($machinePattern = getMachinePattern()) !== FALSE) { GLOBAL $machine; $machineDetails = array(); $machineDetails['documentroot'] = $machinePattern[0]; $machine = $machinePattern[1]; switch($machine) { case "synology": $machineDetails['cronCat'] = 'cat /etc/crontab'; $machineDetails['superuser'] = 'root'; break; case "QNAP": $machineDetails['cronCat'] = 'cat /etc/config/crontab'; $machineDetails['superuser'] = 'admin'; break; case "netgear": $machineDetails['cronCat'] = 'cat /etc/crontab'; $machineDetails['superuser'] = 'root'; break; case ASUSTOR: $machineDetails['cronCat'] = 'cat /var/spool/cron/crontabs/root'; $machineDetails['superuser'] = 'root'; break; case "twotier": $machineDetails['cronCat'] = 'cat /etc/crontab'; $machineDetails['superuser'] = 'root'; break; } return $machineDetails; } return FALSE; } /********************************************************************************************************* * Subroutine Name : getSynoDSMVersion * Objective : Finds the Synology DSM version * Added By : Sabin Cheruvattil **********************************************************************************************************/ function getSynoDSMVersion() { $verarr = explode("\n", `cat /etc.defaults/VERSION`); array_walk($verarr, 'trim'); $kvp = preg_split('/=/', $verarr[0]); $ver = (int)trim($kvp[1], '"'); return $ver; } /************************************************************************************************ * Subroutine Name : loadMachineConfigurations * Objective : Load the NAS machine configurations. * Added By : Yogesh Kumar ************************************************************************************************/ function loadMachineConfigurations() { GLOBAL $machine,$permissionVal; $machineDetails = getMachineDetails(); $_SESSION['webDir'] = $machineDetails['documentroot']; // Path to our Application's root directory $_SESSION['nasUser'] = $machineDetails['superuser']; // Name of the super user of this machine $_SESSION['machine'] = $machine; // NAS machine name, where this app is installed in $configFile = ("webDir " . $_SESSION['webDir'] . "\n"); $configFile .= ("user " . $_SESSION['nasUser'] . "\n"); $configFile .= ("machine " . $_SESSION['machine'] . "\n"); $configFile .= ("cronCat " . $machineDetails['cronCat'] . "\n"); file_put_contents((dirname(__FILE__) . '/'.CONFIG_FILE), $configFile); @chmod((dirname(__FILE__) . '/'.CONFIG_FILE),$permissionVal); return TRUE; } /**************************************************************************************************** * Function Name : backupJobList * Objective : Getting machine based backup Job List * Added By : Senthil Pandian ******************************************************************************************************/ function backupJobList($jobs='',$type=''){ GLOBAL $machine; if($machine=='twotier' || $type == 'localBackup'){ $job = ($type=='backup')?DEFAULT_BACKUPSET_NAME:0; print ' '; print "Contents of Backup Set"; print ""; } else { print 'Backup Set Name: Backup Schedule: '; } } /**************************************************************************************************** * Function Name : periodicCronupdate * Objective : Updating crontab entry for Periodic Cleanup * Added By : Sajana K *****************************************************************************************************/ function periodicCronupdate() { GLOBAL $periodic_days; GLOBAL $job_name; GLOBAL $machine; $startDate = date("Y-m-d"); $cronTimearr = getCrontime(); $periodInterval = "*/".$periodic_days; $content = getCronContent($cronTimearr[2], $cronTimearr[1], "*", "*", "*"); $command = Scheduler::CreateJobCommand(ARCHIVE_JOB."_".$job_name, ARCHIVE_JOB); //$phpBinaryPath = "php"; //if($machine == "QNAP") $phpBinaryPath = PHP_PATH_FOR_QNAP; $phpBinaryPath = getphpPath(); $content .= $command." '$startDate' '$periodic_days' '$phpBinaryPath'"; Scheduler::AddCronJob(ARCHIVE_JOB."_".$job_name, "Archive", $content); } /********************************************************************************************************* * Subroutine Name : getSharedList * Objective : To get machine based shared folder/file lists. * Added By : Yogesh Kumar P * Modified By : Sabin Cheruvattil - 2016-05-18 | modified if to switch **********************************************************************************************************/ function getSharedList() { GLOBAL $machine; unset($_SESSION['sharedDirectoriesRaw']); switch($machine) { case 'synology': saveSynologySharedFolders(); break; case 'QNAP': saveQNAPSharedFolders(); break; case 'netgear': saveNetgearSharedFolders(); break; case 'twotier': saveTwotierSharedFolders(); break; case ASUSTOR: saveASUSTORSharedFolders(); break; default: break; } } /********************************************************************************************************* * Subroutine Name : getProxySettings * Objective : To get proxy settings. * Added By : Yogesh Kumar P **********************************************************************************************************/ function getProxySettings() { GLOBAL $machine; $output = array(); if($machine==QNAP){ $proxyDetails = shell_exec("/sbin/getcfg \"System\" \"proxy server\" -d \"\""); $proxyDetails = trim($proxyDetails); if($proxyDetails != ""){ $proxyUser = shell_exec("/sbin/getcfg \"System\" \"proxy username\" -d \"\""); $proxyUser = trim($proxyUser); if($proxyUser === ""){ $output[2] = ""; } else{ $output[2] = $proxyUser; } $proxyPass = shell_exec("/sbin/getcfg \"System\" \"proxy password\" -d \"\""); $proxyPass = trim($proxyPass); if($proxyPass === ""){ $output[3] = ""; } else{ $output[3] = $proxyPass; } $proxyFields = explode(":", $proxyDetails); $output[0] = str_replace('/','',$proxyFields[1]); $output[1] = $proxyFields[2]; } } else if($machine==ASUSTOR){ $proxy_enabled=1; $auth_enabled=1; $proxyConfFile = ASUSTOR_PROXYCONF; if(file_exists($proxyConfFile) === FALSE) return $output; $contents = file($proxyConfFile); $proxy_data = 0; $i = 0; foreach ($contents as $line) { if(strpos($line, "[Proxy Client]") !== FALSE){ $proxy_data = 1; continue; } if($proxy_data == 1 && $i<6){ if(strpos($line, "IsEnabled =") !== FALSE){ $isProxyEnabled = explode("=", $line); $proxy_enabled_chk = trim($isProxyEnabled[1]); if($proxy_enabled_chk == 'No'){ $proxy_enabled = 0; break; } $i++; } else if(strpos($line, "ServerAddress =") !== FALSE){ $proxyAddrField = explode("=", $line); $server_ip = preg_replace("(https?://)", "", trim($proxyAddrField[1])); $output[0] = $server_ip; $i++; } else if(strpos($line, "ServerPort =") !== FALSE){ $proxyAddrField = explode("=", $line); $output[1] = trim($proxyAddrField[1]); $i++; } else if(strpos($line, "AuthEnabled =") !== FALSE){ $proxyAddrField = explode("=", $line); $auth_enabled_chk = trim($proxyAddrField[1]); if($auth_enabled_chk == 'No') $auth_enabled = 0; $i++; } else if(strpos($line, "AuthUsername =") !== FALSE){ $proxyAddrField = explode("=", $line); $output[2] = trim($proxyAddrField[1]); $i++; } else if(strpos($line, "AuthPassword =") !== FALSE){ $proxyAddrField = explode("=", $line); $output[3] = trim($proxyAddrField[1]); $i++; } } } if($proxy_enabled==0) $output = array(); else if($auth_enabled==0){ $output[2] = ""; $output[3] = ""; } } else if($machine=="netgear"){ $proxyConfFile = NETGEAR_PROXYCONF; $https = 0; if(file_exists($proxyConfFile) === FALSE) return $output; $cmd = "cat $proxyConfFile"; $outputData = systemCmdExecutionViaPhp($cmd, Scheduler::$user_dir); $contents = explode("\n",$outputData); if(count($contents) > 0 && $contents[0] != ''){ foreach ($contents as $line) { if($https == 1) break; if (strpos($line, 'https_proxy') !== false) { $arrayData = explode('https_proxy',$line); $https = 1; }else{ $arrayData = explode('http_proxy',$line); } $str = ltrim($arrayData[1], '='); $str1 = explode('@',$str); if(count($str1) == 2){ $user_detail = explode(':',$str1[0]); $output[2] = $user_detail[0]; $output[3] = $user_detail[1]; $server_detail = explode(':',$str1[1]); $output[0] = $server_detail[0]; $output[1] = $server_detail[1]; }else{ $server_detail = explode(':',$str1[0]); $output[0] = $server_detail[0]; $output[1] = $server_detail[1]; $output[2] = ""; $output[3] = ""; } } }else{ $output = array(); } } else{ $proxy_enabled=1; $auth_enabled=1; $proxyConfFile = SYNOLOGY_PROXYCONF; if(file_exists($proxyConfFile) === TRUE){ $isProxyEnabled = array(); $contents = file($proxyConfFile); foreach ($contents as $line) { if(strpos($line, "proxy_enabled=") !== FALSE){ $isProxyEnabled = explode("=", $line); $temp = trim($isProxyEnabled[1]); if($temp == "no"){ $proxy_enabled=0; } } elseif(strpos($line, "https_host=") !== FALSE){ $proxyAddrField = explode("=", $line); $output[0] = $proxyAddrField[1]; } elseif(strpos($line, "https_port=") !== FALSE){ $proxyPassField = explode("=", $line); $output[1] = $proxyPassField[1]; } elseif(strpos($line, "auth_enabled=") !== FALSE){ $isAuthEnabled = explode("=", $line); $temp = trim($isAuthEnabled[1]); if($temp == "no"){ $auth_enabled=0; } } elseif(strpos($line, "proxy_user=") !== FALSE){ $proxyUser = explode("=", $line); if($proxyUser === ""){ $output[2] = ""; } else{ $output[2] = $proxyUser[1]; } } elseif(strpos($line, "proxy_pwd=") !== FALSE){ $proxyPass = explode("=", $line); if($proxyPass === ""){ $output[3] = ""; } else{ $output[3] = $proxyPass[1]; } } } } if($proxy_enabled==0){ $output = array(); } elseif($auth_enabled==0){ $output[2] = ""; $output[3] = ""; } } return $output; } /********************************************************************************************************* * Function Name : sendCGIMail * Objective : This function helps to send email * Added By : Sabin Cheruvattil **********************************************************************************************************/ function sendCGIMail($path, $data) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $path); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); /* For Proxy - Start*/ if(isset($_SESSION['isProxyEnabled']) && $_SESSION['isProxyEnabled'] === true) { # IP & Port if(isset($_SESSION['ipAddress']) && !empty($_SESSION['ipAddress'])) { $proxy = $_SESSION['ipAddress'] . ":" . $_SESSION['port']; curl_setopt($ch, CURLOPT_PROXY, $proxy); } # Username & Password if(isset($_SESSION['proxyUserName']) && !empty($_SESSION['proxyUserName'])) { $proxyauth = $_SESSION['proxyUserName'] . ":" . $_SESSION['proxyPassword']; curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth); } } /* For Proxy - End*/ $server_output = curl_exec($ch); $server_error = curl_error($ch); curl_close ($ch); if(trim($server_error) != '') { Scheduler::Log("Curl output: ".$server_output, "Curl error: ".$server_error); } return array('output' => $server_output, 'error' => $server_error); } /********************************************************************************************************* * Subroutine Name : validateRestoreFileList * Objective : Validate every item of file list * Added By : Vijay Vinoth **********************************************************************************************************/ function validateRestoreFileList($filePath, $refreshItem,$jobPath) { $tempfile = $jobPath."/".TEMP_OPERATION_FILE; $fileArrData = file($filePath); if(!($logHandle = fopen($tempfile, "w"))){ Scheduler::Log("validateRestoreFileList ".customErrorMsg()); return false; } $itemList = ''; foreach ($fileArrData as $key => $value){ $value = trim($value,"\n"); if($key%4 == 0 && $value != ''){ $itemList .= $value; } else if(!empty($value)){ if($value=='file') $itemList .= "\n"; else if($value=='folder') $itemList .= "/\n"; } } fwrite($logHandle, $itemList); fclose($logHandle); validateRestoreFileDataConstruct($tempfile,$jobPath); return true; } /**************************************************************************************************** * Function Name : getLocalDriveListHTML * Objective : This function will return Local Backup Location List as HTML element * Added By : Senthil Pandian Modified By : Sabin Cheruvattil | Common method for USB/Express Drives ******************************************************************************************************/ function getLocalDriveListHTML(){ GLOBAL $machine; GLOBAL $diskRootPath; GLOBAL $localMPCfile; $devicesArr = getMountedDevices(); $hostName = getLocalBackupLocation(); machineBasedContent($machine); $selected = ''; $checkMPC = false; if(SYNOLOGY_LOCAL == strtolower($machine)){ foreach($devicesArr as $name){ $pathName = "$name/IDriveLocal"; $selected = ""; if($pathName==$hostName){ $selected = "selected='selected'"; $checkMPC = true; } print ""; } } else if(strtolower(ASUSTOR) == strtolower($machine)) { foreach($devicesArr as $name) { $pathName = "$name/IDriveLocal"; $selected = ""; if($pathName == $hostName) { $selected = "selected='selected'"; $checkMPC = true; } print ""; } } else if('qnap' == strtolower($machine)) { foreach($devicesArr as $name) { $pathName = "{$name}/IDriveLocal"; $selected = ''; if($pathName == $hostName) { $selected = "selected='selected'"; $checkMPC = TRUE; } print ""; } } else if('netgear' == strtolower($machine)) { foreach($devicesArr as $name) { $pathName = "{$name}/IDriveLocal"; $selected = ''; if($pathName == $hostName) { $selected = "selected='selected'"; $checkMPC = TRUE; } print ""; } } else if($machine == "twotier"){ $diskRootPathLength = strlen($diskRootPath); foreach($devicesArr as $name){ $pathName = "$name/IDriveLocal"; $name = substr($name,$diskRootPathLength); $selected = ""; if($pathName==$hostName){ $selected = "selected='selected'"; $checkMPC = true; } print ""; } } if(!$checkMPC){ @unlink($localMPCfile); } } /**************************************************************************************************** * Function Name : getLocalBackupLocationHTML * Objective : This function will return current Local Backup Location as HTML element * Added By : Senthil Pandian ******************************************************************************************************/ function getLocalBackupLocationHTML(){ GLOBAL $machine; if($_SESSION['dedup']){ $deviceList = $_SESSION['deviceList']; $selectedNickName = ''; $option = ''; foreach($deviceList as $deviceID => $bucketTypeList){ foreach($bucketTypeList as $bucketType=>$nickName) { if($deviceID==$_SESSION['deviceID']) $selectedDeviceID = ""; else $option .= ""; } } print $selectedDeviceID.$option; $hostName = getLocalBackupLocation(); if(!empty($hostName)){ return $hostName; } } else { $hostName = getLocalBackupLocation(); return $hostName; } } /**************************************************************************************************** * Function Name : getMountedDevices * Objective : Getting mounted devices list * Added By : Senthil Pandian * Modified By : Sabin Cheruvattil | Common method for USB/Express Drives ******************************************************************************************************/ function getMountedDevices() { GLOBAL $machine; GLOBAL $diskRootPath; machineBasedContent($machine); $res = array(); if($machine == "synology") { $mountedVolumes = `df`; preg_match_all('/\/volumeUSB(.*)/', $mountedVolumes, $resources); foreach($resources[0] as $expDrv) { $expDetails = explode("\n", `df $expDrv | awk '{print $2}'`); if((int)$expDetails[1] > 500000) { $res[] = $expDrv; } } } else if($machine == ASUSTOR) { $mountedVolumes = `df`; preg_match_all('/\/share\/USB(.*)/', $mountedVolumes, $res); $res = $res[0]; } else if($machine == 'QNAP') { $mountedVolumes = `df`; preg_match_all('/\/share\/external\/(.*)/', $mountedVolumes, $resources); $res = array(); # filter the drives for duplicates foreach($resources[0] as $expRes) { if(!in_array($expRes, $res)) { $res[] = $expRes; } } } else if($machine == 'netgear') { $mountedVolumes = `df`; preg_match_all('/\/media\/USB(.*)/', $mountedVolumes, $res); $res = $res[0]; } else if($machine == "twotier"){ $mountedFolders = systemCmdExecution("ls -d -1 $diskRootPath*"); if(!empty($mountedFolders)) { $diskList1 = explode("\n",trim($mountedFolders)); //Checking currently mounted volumes $mountedVolumes = systemCmdExecutionViaPhp("df $diskRootPath*", Scheduler::$user_dir); if(!empty($mountedVolumes)) $diskList2 = explode("\n",trim($mountedVolumes)); $index=1; foreach($diskList1 as $diskName){ if(preg_match("/\[restricted\]$/",$diskList2[$index])) { array_push($res,$diskName); } array_push($res,$diskName); //Needs to be removed later - Senthil added for PerlPHP Migration $index++; } } } return $res; } /**************************************************************************************************** * Function Name : clearReindexPid * Objective : To Remove reindex related files. * Added By : Senthil Pandian ******************************************************************************************************/ function clearReindexPid($jobPath){ GLOBAL $processPath; GLOBAL $pidPath; GLOBAL $reIndexDirPath; GLOBAL $appPath; $jobKilled = false; /* check pid.txt existance */ $jobs = glob($jobPath . '*' , GLOB_ONLYDIR); for($k = 0; $k < count($jobs); $k++){ $actualPidPath = $jobs[$k]."/$pidPath"; if(file_exists($actualPidPath)){ $reIndexDir = "$reIndexDirPath/*"; /* check lock on pid.txt */ if(!($handle = fopen($actualPidPath, "r"))){ Scheduler::Log("path.php "."clearPid "."failed to open $actualPidPath"); exit; } else{ if(!flock($handle, LOCK_EX|LOCK_NB, $lockFlag)){ $command = "$processPath | grep '".DB_REINDEX_FILE."' | grep -v 'grep' | grep -v 'ps'"; $reIndexPIDs = shell_exec($command); Scheduler::Log("clearPid ". "reIndexPIDs". "$reIndexPIDs"); $reIndexPIDs = trim($reIndexPIDs); if(empty($reIndexPIDs)){ $jobKilled = true; if($reIndexDir!="/") systemCmdExecutionViaPhp("rm -rf $reIndexDir", Scheduler::$user_dir); } } else { Scheduler::Log("clearPid :: lock is not found going to delete"); $jobKilled = true; if($reIndexDir!="/") systemCmdExecutionViaPhp("rm -rf $reIndexDir", Scheduler::$user_dir); } if($jobKilled == true){ $php = getPhpPath(); $phpPath = "$appPath/".CONFIG; $cmd = "$php $phpPath/".DB_REINDEX_FILE; $cmd = "cd '$reIndexDirPath'; $cmd"; #Scheduler::Log("jobKilled: dbReIndex cmd ",$cmd ); pclose(popen("$cmd &","r")); } } } } } /**************************************************************************************************** * Function Name : isScheduledJobRunning * Objective : Checking whether scheduled job is running or not. * Added By : Senthil Pandian ******************************************************************************************************/ function isScheduledJobRunning($jobType,$jobName){ GLOBAL $machine; $jobstatus = false; if(strcmp($jobType, "Backup") === 0){ if($machine=='twotier') $jobName = DEFAULT_BACKUPSET; $jobPidPath = Scheduler::$backup_dir.$jobName."/".START_PID; $jobstatus = isJobRunning($jobPidPath); } return $jobstatus; } /**************************************************************************************************** * Function Name : isDirectoryWritable * Objective : Check if directory is created and writable * Added By : Cheruvattil Sabin ******************************************************************************************************/ function isDirectoryWritable($directory) { GLOBAL $drlFile, $permissionVal; $dirPerms = array('is_exists' => FALSE, 'is_writable' => FALSE); $tempWrite = $directory . '/write.test'; if(is_dir($directory)) { $dirPerms['is_exists'] = TRUE; } if(@file_put_contents($tempWrite, 'IDrive')) { @chmod($drlFile, $permissionVal); $dirPerms['is_writable'] = TRUE; unlink($tempWrite); } return $dirPerms; } /**************************************************************************************************** * Function Name : isAJAX * Objective : Check if the incoming request is AJAX or not * Added By : Cheruvattil Sabin ******************************************************************************************************/ function isAJAX() { if($_SERVER['X-Requested-With'] == 'XMLHttpRequest') { return TRUE; } return FALSE; } /**************************************************************************************************** * Function Name : getNASUsersList * Objective : This helps to get the list of NAS users * Added By : Cheruvattil Sabin ******************************************************************************************************/ function getNASUsersList() { $nasUserList = explode("\n", trim(`cut -d: -f1 /etc/passwd`)); if(empty($nasUserList) || !count($nasUserList)) { if(!file_exists('/etc/passwd') || !is_readable('/etc/passwd')) { # this will be array by default return $nasUserList; } foreach(file('/etc/passwd') as $userParams) { $expUserParams = explode(':', $userParams); $nasUserList[] = $expUserParams[0]; } } return $nasUserList; } /**************************************************************************************************** * Function Name : isValidNASUser * Objective : This helps to validate the NAS user name | Case checking * Added By : Cheruvattil Sabin ******************************************************************************************************/ function isValidNASUser($checkNASUserName) { $nasUserList = getNASUsersList(); if(count($nasUserList) > 0) { # If needle is a string/number, the comparison is done in a case-sensitive manner. if(!in_array($checkNASUserName, $nasUserList)) { return FALSE; } } return TRUE; } /**************************************************************************************************** * Function Name : getValidSynologyNASUser * Objective : This helps to get the list of NAS users * Added By : Cheruvattil Sabin ******************************************************************************************************/ function getValidSynologyNASUser($checkNASUserName) { $nasUserList = getNASUsersList(); $nasUserListLower = $nasUserList; array_walk($nasUserListLower, 'strtolower'); if(count($nasUserList) > 0) { # If needle is a string, the comparison is done in a case-sensitive manner. $nasUserKey = array_search(strtolower($checkNASUserName), $nasUserListLower); if($nasUserKey !== FALSE) { return trim($nasUserList[$nasUserKey]); } } return FALSE; } /**************************************************************************************************** * Function Name : getDirPermissionHTML * Objective : This helps generate HTML for user guidance of pre-requisites * Added By : Cheruvattil Sabin ******************************************************************************************************/ function getDirPermissionHTML($headerMessage, $contentMessage) { GLOBAL $machine; $warningTemplate = '
'; $preRequisiteURL = ''; switch($machine) { case 'synology'; $preRequisiteURL = SYNOLOGY_PREREQUISITES_URL; break; case 'QNAP': $preRequisiteURL = QNAP_PREREQUISITES_URL; break; case 'twotier': $preRequisiteURL = TWOTIER_PREREQUISITES_URL; break; case 'netgear': $preRequisiteURL = NETGEAR_PREREQUISITES_URL; break; default: break; } if($contentMessage == '') { $contentMessage = $contentMessage = 'For more details please refer to pre-requisites. Click Here!'; } return str_replace(array('{:ERROR_HEADER:}', '{:ERROR_MESSAGE:}'), array($headerMessage, $contentMessage), $warningTemplate); } /**************************************************************************************************** * Function Name : getValidNASUser * Objective : This helps to get the list of NAS users * Added By : Cheruvattil Sabin ******************************************************************************************************/ function getValidNASUser($checkNASUserName) { $nasUserList = getNASUsersList(); $nasUserListLower = $nasUserList; $nasUserListLower = convertStrToLower($nasUserListLower); if(count($nasUserList) > 0) { # If needle is a string, the comparison is done in a case-sensitive manner. $nasUserKey = array_search(strtolower($checkNASUserName), $nasUserListLower); if($nasUserKey !== FALSE) { return trim($nasUserList[$nasUserKey]); } } return FALSE; } /**************************************************************************************************** * Function Name : hasPHPSafeModeEnabled * Objective : This function check for older version of PHP with safe mode[safe_mode_exec_dir] | This is enabled for Synology * Added By : Sabin Cheruvattil ******************************************************************************************************/ function hasPHPSafeModeEnabled() { GLOBAL $machine; # safe_mode_exec_dir has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0 if($machine == SYNOLOGY_LOCAL && version_compare(PHP_VERSION, '5.4.0', '<') && ini_get('safe_mode_exec_dir') != '') { return TRUE; } return FALSE; } /**************************************************************************************************** * Function Name : isOpenBaseDirValid * Objective : This function check for the open_basedir settings and validates the entry * Added By : Sabin Cheruvattil ******************************************************************************************************/ function isOpenBaseDirValid() { $openBasedir = ini_get('open_basedir'); if($openBasedir != '' && strpos($openBasedir, '/etc:') === FALSE) { return FALSE; } return TRUE; } #**************************************************************************************************** # Subroutine Name : customFileSize. # Objective : Check File size. If file is more that 2GB in 32 bit machine filesize will not work. # Added By : Vijay Vinoth #*****************************************************************************************************/ function customFileSize($path){ $file_size = sprintf("%u",filesize("$path")); if($file_size < 0){ clearstatcache(); $file_size = @filesize("$path"); if($file_size < 0){ GLOBAL $machine, $appPath; $lsPath = 'ls -aln'; if($machine == "netgear"){ $lsPath = $appPath."/ls -aln"; } $output = shell_exec("$lsPath | grep \"$path\""); $split = preg_split('/\s+/', $output,6); $file_size = trim($split[4]); } } return $file_size; } #**************************************************************************************************** # Subroutine Name : customErrorMsg. # Objective : Check File size. If file is more that 2GB in 32 bit machine filesize will not work. # Added By : Vijay Vinoth #*****************************************************************************************************/ function customErrorMsg(){ $errorMsg = error_get_last(); return $errorMsg['message']; } /**************************************************************************************************** * Function Name : getASUSTORSharedFolders * Objective : Getting ASUSTOR shared folders list * Added By : Vijay Vinoth ******************************************************************************************************/ function getASUSTORSharedFolders() { $dir_list = array(); isRootLevelDisplayEnabled(); if($_SESSION['displayRoot'] === 0) { if(!empty($_SESSION['sharedDirectoriesRaw']) && count($_SESSION['sharedDirectoriesRaw']) === 1) { $sharedCheckArr = json_decode($_SESSION['sharedDirectoriesRaw'], TRUE); $sharedFirstDir = current($sharedCheckArr); if($sharedFirstDir['filename'] === 'Home') { unset($_SESSION['sharedDirectoriesRaw']); } } if(@empty($_SESSION['sharedDirectoriesRaw'])){ if(isset($_SESSION['sharedDirectoriesRaw'])) unset($_SESSION['sharedDirectoriesRaw']); saveASUSTORSharedFolders(); } if(isset($_SESSION['sharedDirectoriesRaw']) && !empty($_SESSION['sharedDirectoriesRaw'])) { $sharedDirList = $_SESSION['sharedDirectoriesRaw']; # check whether we get a valid object or not $dir_list = json_decode($sharedDirList, true); if(!$dir_list){ unset($_SESSION['sharedDirectoriesRaw']); saveASUSTORSharedFolders(); $sharedDirList = $_SESSION['sharedDirectoriesRaw']; $dir_list = json_decode($sharedDirList, true); } ksort($dir_list); } } else{ saveASUSTORRootLevelFolders(); $sharedDirList = $_SESSION['sharedDirectoriesRaw']; $dir_list = json_decode($sharedDirList, true); ksort($dir_list); } return $dir_list; } function saveASUSTORRootLevelFolders() { GLOBAL $appPath; $rootDirList = ''; $list = array(); $path = 'ls -alen \'/\' | grep \'^d\|^-\''; $dirList = systemCmdExecution($path); $res = parseRootLevelFilesForQNAP($dirList,'/','/'); $rootDirList = json_encode($res); $_SESSION['sharedDirectoriesRaw'] = $rootDirList; } /**************************************************************************************************** * Function Name : saveASUSTORSharedFolders * Objective : Saving ASUSTOR shared folders list into text file * Added By : Vijay Vinoth ******************************************************************************************************/ function saveASUSTORSharedFolders() { GLOBAL $appPath; $sharedDirList = ''; if(file_exists(ASUSTOR_SHARE_CGI_PATH)){ $shareURL = getNasURL(); if(!isset($_SESSION['CGI_SID'])) { header("Location:../index.php"); exit; } else $sid = $_SESSION['CGI_SID']; $sharedDirURL = $shareURL.ASUSTOR_SHARED_DIR_CGI_PATH; $sharedDirData = "sid=$sid&path=share&showrecyclebin=true&showhome=true&act=file_list&onlydir=true"; $sharedDirListArray = getCurlOutput($sharedDirURL, $sharedDirData); if($sharedDirListArray['status']===false){ Scheduler::Log("Asus share list CGI: "." Output: ".$sharedDirListArray['output']. " Error: ".$sharedDirListArray['error']); } $arr = json_decode($sharedDirListArray['output']); # Fall back logic. If SID is expired the response will be false. Regenerating SID if(!$arr->success){ $str = $_SESSION['encryptedToken'].$_COOKIE['encryptedToken']; $configPath = "$appPath/".CONFIG; $phpPath = getPhpPath(); $command = "$phpPath $configPath/token.php $str ".$_SESSION['encryptionFlag']; $stOutput=shell_exec($command); asustorNASlogin($_SESSION['nasUserName'],$stOutput); saveASUSTORSharedFolders(); } $sharedDirObject = $arr->data; $dir_list = array(); foreach($sharedDirObject as $dirList){ $dirname = $dirList->physical_path; $type = $dirList->is_dir =='1'?"D":"F"; $size = $dirList->is_dir =='1'?"--":$dirList->size; $dir_list[$dirname]["size"] = $size; $dir_list[$dirname]["datetime"] = date("Y/m/d h:i:s A",$dirList->modify_time_second); $dir_list[$dirname]["type"] = $type; $dir_list[$dirname]["filename"] = $dirList->filename; } ksort($dir_list); $sharedDirList = json_encode($dir_list); if(empty($sharedDirList)) { unset($_SESSION['CGI_SID']); header("Location:../index.php"); exit; } } // If the shared folders are empty, fallback to manual listing. $shareArray = json_decode($sharedDirList); if (count($shareArray)<=0) { $list = array(); // Listing shared folders from DB path ( volume0 ) $sharedDbDir = systemCmdExecution("ls -l ".ASUSTOR_VOL_SYSTEM_SHARED_PATH); $sharedList = explode("\n",trim($sharedDbDir)); // Listing shared folders from shared path $sharedDir = systemCmdExecution("ls -len /share"); $sharedDirRes = parseLocalDirList($sharedDir,"/"); $sharedDirRes['/home']['filename'] = "Home"; #$_SESSION['shared_folders'] = array(); $sharedDbDirHome = systemCmdExecution("ls -l ".ASUSTOR_VOL_SYSTEM_HOME_PATH); $sharedListHome = explode("\n",trim($sharedDbDirHome)); // comparing both array and updating real path insted of dir name foreach($sharedList as $nameVal) { $nameData = explode("-> ",trim($nameVal)); $name = $nameData[1]; if($name == '') continue; $dir_name = str_replace("/.@CNID",'',$name,$i); if($i < 1) { foreach($sharedListHome as $nameHomeVal) { $nameHomeData = explode("-> ",trim($nameHomeVal)); $name = $nameHomeData[1]; if($name == '') continue; $dir_name = str_replace("/.@CNID",'',$name,$i); } } $sharedDirName = end(explode('/', $dir_name)); foreach ($sharedDirRes as $key => $value) { if($key == '/'.$sharedDirName){ if($sharedDirName == 'home'){ if($_SESSION['nasUserName'] =='root') $dir_name = $dir_name.'/admin'; else $dir_name = $dir_name.'/'.$_SESSION['nasUserName']; } $sharedDirRes1[$dir_name] = $sharedDirRes[$key]; unset($sharedDirRes[$key]); #array_push($_SESSION['shared_folders'], ($dir_name . '/')); } } } $sharedDirList = json_encode($sharedDirRes1); } $_SESSION['sharedDirectoriesRaw'] = $sharedDirList; } /**************************************************************************************************** * Function Name : getNetgearSharedPath * Objective : reading Netgear shared path * Added By : Vijay Vinoth ******************************************************************************************************/ function getNetgearSharedPath() { $getNetgearSharedPath = '/data/'; if(!file_exists('/data/._share/')){ $cmd = "find / -maxdepth 2 -name '._share'"; $output = trim(strtok(`$cmd`, "\n")); $getNetgearSharedPath = "/".trim(strtok($output, "//"))."/"; } $_SESSION['getNetgearSharedPath'] = $getNetgearSharedPath; return $getNetgearSharedPath; } /**************************************************************************************************** * Function Name : strToUtf8 * Objective : Encoding Non-ASCII character to UTF8 char * Added By : Senthil Pandian ******************************************************************************************************/ function strToUtf8($str) { if(mb_detect_encoding($str, 'UTF-8', true) === false) $str = utf8_encode($str); return $str; } /**************************************************************************************************** * Function Name : createExpressDBMap * Objective : This will create mapping for the Express Device and Actual DB Mapping * Added By : Sabin Cheruvattil ******************************************************************************************************/ function createExpressDBMap() { GLOBAL $dedupDetailFile, $userName; $expressDrive = getLocalBackupLocation(); $dedupDeviceID = ''; $mapTime = time(); if(file_exists($dedupDetailFile)) { $deviceArray = json_decode((is_readable($dedupDetailFile)? file_get_contents($dedupDetailFile) : ''), TRUE); $dedupDeviceID = preg_replace("/^5c0b/", '', trim($deviceArray['deviceID']), 1); $dedupDeviceID = preg_replace("/4b5z$/", '', $dedupDeviceID, 1); } $expressDBMapPath = "{$expressDrive}/{$userName}/LDBNEW/"; if(!file_exists($expressDBMapPath) || !is_dir($expressDBMapPath)) { mkdir($expressDBMapPath, 0777, TRUE); @chmod($expressDBMapPath, 0777); } # use glob to check if the map file is there or not $mapPath = $expressDBMapPath . EXPRESSDBMAPFILE; if(file_exists($mapPath)) { return TRUE; } if(file_put_contents($mapPath, $mapTime)) { mkdir(Scheduler::$expressDBPath . $mapTime . '/' . $dedupDeviceID, 0777, TRUE); @chmod(Scheduler::$expressDBPath, 0777); @chmod(Scheduler::$expressDBPath . $mapTime, 0777); @chmod(Scheduler::$expressDBPath . $mapTime . '/' . $dedupDeviceID, 0777); return TRUE; } return FALSE; } /**************************************************************************************************** * Function Name : getExpressDBPath * Objective : This will map the device and express DB real path * Added By : Sabin Cheruvattil ******************************************************************************************************/ function getExpressDBPath($path = '', $bucket = '') { GLOBAL $dedupDetailFile, $userName; $expressDrive = (($path == '')? getLocalBackupLocation() : $path); $dedupDeviceID = ''; if($bucket != '') { $dedupDeviceID = preg_replace("/^5c0b/", '', $bucket, 1); $dedupDeviceID = preg_replace("/4b5z$/", '', $dedupDeviceID, 1); } else if(file_exists($dedupDetailFile)) { $deviceArray = json_decode((is_readable($dedupDetailFile)? file_get_contents($dedupDetailFile) : ''), TRUE); $dedupDeviceID = preg_replace("/^5c0b/", '', trim($deviceArray['deviceID']), 1); $dedupDeviceID = preg_replace("/4b5z$/", '', $dedupDeviceID, 1); } $expressDBMapPath = "{$expressDrive}/{$userName}/LDBNEW/"; $mapFile = $expressDBMapPath . EXPRESSDBMAPFILE; if(!file_exists($mapFile)) { createExpressDBMap(); } $expressDBDir = file_get_contents($mapFile); if($dedupDeviceID != '') { $expressDBDir .= '/' . $dedupDeviceID; } $expressDBPath = Scheduler::$expressDBPath . $expressDBDir . '/' . $userName . '.ibenc'; if(!file_exists(Scheduler::$expressDBPath . $expressDBDir) || !is_dir(Scheduler::$expressDBPath . $expressDBDir)) { mkdir(Scheduler::$expressDBPath . $expressDBDir, 0777, TRUE); @chmod(Scheduler::$expressDBPath, 0777); @chmod(Scheduler::$expressDBPath . $expressDBDir, 0777); } return $expressDBPath; } /**************************************************************************************************** * Function Name : getServerRootByDeviceID * Objective : It will parse the device XML and give back server root for selected device id * Added By : Sabin Cheruvattil ******************************************************************************************************/ function getServerRootByDeviceID($bucketID) { GLOBAL $dedupDetailFile, $userName; $expressDrive = getLocalBackupLocation(); $availableDeviceList = array(); $expressXMLPath = "{$expressDrive}/{$userName}/dbpaths.xml"; $bucketID = preg_replace("/4b5z$/", '', preg_replace("/^5c0b/", '', $bucketID, 1), 1); if(file_exists($expressXMLPath)) { $xml = simplexml_load_file($expressXMLPath); foreach($xml->children() as $child) { $attr = $child->attributes(); if(trim($attr['deviceid']) == $bucketID) { return trim($attr['serverroot']); } } } return FALSE; } /**************************************************************************************************** * Function Name : getAvailableBucketsInDevice * Objective : Get available buckets in current device * Added By : Sabin Cheruvattil ******************************************************************************************************/ function getAvailableBucketsInDevice($device = '') { GLOBAL $dedupDetailFile, $userName; $expressDrive = (($device == '')? getLocalBackupLocation() : $device); $availableDeviceList = array(); $expressXMLPath = "{$expressDrive}/{$userName}/dbpaths.xml"; if(file_exists($expressXMLPath)) { $xml = simplexml_load_file($expressXMLPath); foreach($xml->children() as $child) { $attr = $child->attributes(); $availableDeviceList[] = array('device_id' => trim($attr['deviceid']), 'nickname' => trim($attr['nickname'])); } return $availableDeviceList; } return array(); } /**************************************************************************************************** * Function Name : renameExpressNickNameOnBucketUpdate * Objective : This function helps us to rename the bucket in express devices * Added By : Sabin Cheruvattil ******************************************************************************************************/ function renameExpressNickNameOnBucketUpdate($nickName, $oldDedupDeviceID = '') { GLOBAL $dedupDetailFile, $userName; # update XML file in the selected backup device | CVS if(!file_exists($dedupDetailFile)) { return FALSE; } $availableDedupDevs = getMountedDevices(); $deviceArray = json_decode(file_get_contents($dedupDetailFile), TRUE); if(!$deviceArray || empty($deviceArray)) { return FALSE; } $curDedupDeviceID = trim($deviceArray['deviceID']); foreach($availableDedupDevs as $stDev) { $storagePath = $stDev . '/IDriveLocal/' . $userName; $devXMLPath = $storagePath . '/dbpaths.xml'; if(!file_exists($storagePath) || !is_dir($storagePath) || !file_exists($devXMLPath)) { continue; } $index = 0; $xml = simplexml_load_file($devXMLPath); foreach($xml->children() as $child) { $attr = $child->attributes(); if($oldDedupDeviceID != '' && $oldDedupDeviceID == '5c0b' . trim($attr['deviceid']) . '4b5z') { try { $child['nickname'] = $nickName; $child['deviceid'] = preg_replace("/^5c0b/", '', preg_replace("/4b5z$/", '', $curDedupDeviceID, 1), 1); file_put_contents($devXMLPath, $xml->asXML()); } catch(Exception $e) { Scheduler::Log($e->getMessage()); } } if($oldDedupDeviceID == '' && '5c0b' . trim($attr['deviceid']) . '4b5z' == $curDedupDeviceID) { try { $child['nickname'] = $nickName; file_put_contents($devXMLPath, $xml->asXML()); } catch(Exception $e) { Scheduler::Log($e->getMessage()); } } $index++; } } } /**************************************************************************************************** * Function Name : backwardCompOfNASUser * Objective : This method is used to move the the existing users data to appr. NAS user dir. * Added By : Anil Kumar ******************************************************************************************************/ function backwardCompOfNASUser($nasUserName,$userName) { $userProfilePath = Scheduler::$service_dir.USER_PROFILE."/"; $sizeFilePath = $userProfilePath.$userName."/sizeOutput.txt"; if(file_exists($sizeFilePath)) { $cmd = "ls -al $sizeFilePath"; $commandToGetOwn = shell_exec($cmd); $commandToGetOwn = trim($commandToGetOwn,"\n"); $parseDetails = preg_split('/\s+/', $commandToGetOwn,8); $fileOwner = $parseDetails[2]; if($nasUserName == $fileOwner) { $move_cmd = "mv -f ".$userProfilePath.$userName." ".$userProfilePath.$nasUserName."/"; systemCmdExecution($move_cmd); } } else { $move_cmd = "mv -f ".$userProfilePath.$userName." ".$userProfilePath.$nasUserName."/"; systemCmdExecution($move_cmd); } } /**************************************************************************************************** * Function Name : updateBackupAndRestoreSetFiles * Objective : This method is used to update backup and restore sets as per new updated values * Added By : Anil Kumar ******************************************************************************************************/ function updateBackupAndRestoreSetFiles() { $jobs = Scheduler::ReadJobs(); foreach($jobs as $k=>$job) { $len = strpos($k,"_"); $jobName = substr($k,$len+1)."/"; if($job["job_type"] == "Backup") { $oldPath = Scheduler::$user_dir.$job["job_type"]."/".$jobName.BACKUPSETFILEFORDISPLAY; $pathNew = Scheduler::$user_dir.$job["job_type"]."/".$jobName.BACKUPSETFILEDISPLAY; if(file_exists($oldPath) && !file_exists($pathNew)) updateBackupSetFilesData($oldPath,$pathNew); } else if($job["job_type"] == "Restore") { $oldPath = Scheduler::$user_dir.$job["job_type"]."/".$jobName.RESTORESETFILEFORDISPLAY; $pathNew = Scheduler::$user_dir.$job["job_type"]."/".$jobName.RESTORESETFILEDISPLAY; if(file_exists($oldPath) && !file_exists($pathNew)) updateRestoreSetFilesData($oldPath,$pathNew); } } } /**************************************************************************************************** * Function Name : updateExcludeFiles * Objective : This method is used to migrate exclude file list. * Added By : Anil Kumar ******************************************************************************************************/ function updateExcludeFiles() { GLOBAL $permissionVal; $excludeFullFile = Scheduler::$user_dir.EXCLUDE_FULL_PATH_FILE; // Updating exclude fileset also with four fields. if(file_exists($excludeFullFile)) { $itemArray = file($excludeFullFile, FILE_IGNORE_NEW_LINES); $len = count($itemArray); $dataToWrite = ""; for($i=0; $i<$len; $i++) { $fileName = $itemArray[$i]; $itemType = $itemArray[$i+1]; if(($itemType == "file") || ($itemType == "folder")) { $dataToWrite .= $fileName."\n".$itemType."\nundefined\nundefined\n"; } } $fullPathExclude = Scheduler::$user_dir.FULL_PATH_EXCLUDE_FILE; file_put_contents($fullPathExclude, $dataToWrite); @chmod($fullPathExclude, 0777); @unlink($excludeFullFile); } } /**************************************************************************************************** * Function Name : updateRestoreSetFilesData * Objective : This method is used to update restore sets values * Added By : Anil Kumar ******************************************************************************************************/ function updateRestoreSetFilesData($oldPath,$newPath) { $itemArray = file($oldPath, FILE_IGNORE_NEW_LINES); $newFile = fopen($newPath, "w"); $fileName = $itemType = $fileSize = $fileLmodTime = ""; $len = count($itemArray); for($i=0,$j=1; $i<$len; $i+=2,$j+=2) { $fileName = $itemArray[$i]; $itemType = $itemArray[$j]; if($itemType == "file") { $itemName = phpRealEscapeString($fileName); $arr = getPropertiesForResComp($itemName); $fileSize = $arr[1][0]; $moddate=date_create($arr[1][1]); $fileLmodTime = date_format($moddate,"D M j H:i:s Y"); } else if($itemType == "folder") { $fileSize = "undefined"; $fileLmodTime = "undefined"; } $dataToWrite = $fileName."\n".$itemType."\n".$fileSize."\n".$fileLmodTime."\n"; fwrite($newFile, $dataToWrite); @chmod($newFile, $permissionVal); } fclose($newFile); @unlink($oldPath); } /**************************************************************************************************** * Function Name : updateBackupSetFilesData * Objective : This method is used to update backup sets values * Added By : Anil Kumar ******************************************************************************************************/ function updateBackupSetFilesData($oldPath,$newPath) { $itemArray = file($oldPath, FILE_IGNORE_NEW_LINES); $newFile = fopen($newPath, "w"); $fileName = $itemType = $fileSize = $fileLmodTime = ""; $len = count($itemArray); for($i=0,$j=1; $i<$len; $i+=2,$j+=2) { $fileName = $itemArray[$i]; $itemType = $itemArray[$j]; if($itemType == "file") { if(PHP_INT_MAX > 2147483647) { $stat = stat($fileName); $fileSize = $stat[7]; $fileLmodTime = date('D M d H:i:s Y', $stat[9]); } else { $fileName = $fileName; $fullPath = str_replace("'","'\''",$fileName); $fullPath = str_replace('\\','\\\\',$fullPath); $fullPath = preg_replace("/\"/","\\\"",$fullPath); $fullPath = str_replace('$','\$',$fullPath); $fullPath = str_replace('`','\`',$fullPath); $file_size_cal = systemCmdExecution("ls -aln --time-style=+'%a %b %d %H:%M:%S %Y' ".escapeshellarg($fullPath)); $parseDetails = preg_split('/\s+/', $file_size_cal,11); $fileSize = $parseDetails[4]; $fileLmodTime = $parseDetails[5]." ".$parseDetails[6]." ".$parseDetails[7]." ".$parseDetails[8]." ".$parseDetails[9]; } } else if($itemType == "folder") { $fileSize = "undefined"; $fileLmodTime = "undefined"; } $dataToWrite = $fileName."\n".$itemType."\n".$fileSize."\n".$fileLmodTime."\n"; fwrite($newFile, $dataToWrite); @chmod($newFile, $permissionVal); } fclose($newFile); @unlink($oldPath); } /**************************************************************************************************** * Function Name : removeItems * Objective : This is used to centralise the remove method with basic validation. * Added By : Anil Kumar ******************************************************************************************************/ function removeItems($path) { GLOBAL $appPath; $list = array(); if (is_scalar($path)) { array_push($list, $path); } else { foreach($path as $val) { array_push($list, $val); } } foreach($list as $pathVal) { $val = $pathVal; if(($val == "/") || ($val == "") || ($val == "*")) continue; $cmd = 'rm'; $firstItem = substr($val, 0, 1); if($firstItem != "/") $val = getcwd()."/".$val; $lastItem = ""; $lastItem = substr($val, -1); if((!is_dir($val) && !is_file($val)) && ($lastItem == "*")){ $lastItem = substr($val, -1); $val = substr($val, 0, -1); } else { $lastItem = ""; } if(is_dir($val)){ $checkPath = substr($val, -1); if($checkPath == '/') $checkPath = substr($val, 0, -1); $servicePath = getOriginalServicePath(); if(($checkPath == "/") or ($checkPath == "") or ($servicePath == $checkPath) or ($appPath == $checkPath)) continue; $cmd .= " -rf '$val'$lastItem"; } else{ $cmd .= " '$val'$lastItem"; } $needToExec = ($cmd === 'rm')?0:1; if($needToExec) { system($cmd); } } } /**************************************************************************************************** * Function Name : validateLSOutput * Objective : This methos is used to validate and get the size value when ls output messed up. * Added By : Anil Kumar ******************************************************************************************************/ function validateLSOutput($split,$gid,$uid) { $size = 0; if(strlen($split[0]) > 10) { $size = $split[3]; }else{ if($split[1] > $uid){ if($uid == substr($split[1], -(strlen($uid)))) { $size = $split[3]; } else{ if($split[2] > $uid){ $size = $split[3]; } else{ $size = preg_replace("/".$gid."/", "", $split[3], 1); } } } else{ if($split[2] > $uid){ $size = $split[3]; } else{ $size = preg_replace("/".$gid."/", "", $split[3], 1); } } } return $size; }