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 .= str_replace(" "," ",htmlentities($dirName,ENT_QUOTES));
$resHtml .= '
";
$resHtml .= str_replace(" "," ",htmlentities($dirName,ENT_QUOTES));
$resHtml .= '
";
$resHtml .= '';
$resHtml .= "";
$resHtml .= str_replace(" "," ",htmlentities($dirName,ENT_QUOTES));
$resHtml .= '
";
$resHtml .= str_replace(" "," ",htmlentities($dir,ENT_QUOTES));
$resHtml .= '
";
$resHtml .= htmlentities($dirName,ENT_QUOTES);
$resHtml .= "
";
$resHtml .= htmlentities($dir,ENT_QUOTES);
$resHtml .= "