&1"); define('EXCLUDE_FULLPATH', 'ExcludeFullPath.txt'); define('FULL_PATH_EXCLUDE_FILE', 'FullPathExclude.txt'); define('EXCLUDE_PARTIALPATH', 'ExcludeListPartial.txt'); define('EXTENDED_LIST','ExtendedList.txt'); define("FILE_MAX_COUNT","1000"); define("FILE_COUNT_PROCESS_STARTED","1"); define("FILE_COUNT_PROCESS_COMPLETED","2"); define("FOLDER","folder"); define("FAILEDFILES","FailedFiles_ERROR.txt"); define("FORKPROCESSFILE","forkProcess.php"); define('GETSERVERADDRESS',"getServerAddress"); define('GETSCHEDULERDETAILSFILE',"getSchedulerDetails.php"); define('INFOFILE', "tempfiles/info_file"); define('LOCALDBINFOFILE', "db_info.txt"); define('IDEVSUTIL_ARG',"--utf8-cmd"); define('IBFOLDER','ibfolder'); define('IBFILE','ibfile'); define('IDRIVE_LOCAL_DB','IDriveLocal.db'); define('JOBTERMINATIONFILE', "Job_Termination_Script.php"); define('LOG_FILE_SIZE_LIMIT','1 * 1024 * 1024'); define('LOG_FILE_MAX_COUNT','5'); define('LOG_FILE','traceLog.txt'); define('LOCALSEARCH',"LocalSearch"); define('LOGPIDFILE',"logpid.txt"); define('LOCALBACKUP',"LocalBackup"); define('LOCALRESTORE',"LocalRestore"); define('EXPRESSDBDIRNAME', 'ExpressDB'); define('LINEFEED',"\n"); define("LIMIT", 50*1024); define('LDBNEW','LDBNEW'); define('MAX_LOG_FILE_COUNT',5); define('MAX_LOG_FILE_SIZE',1); define('MAX_RETRY',500); define('LIMITED_RETRY',10); define('MPC_FILE','mpc.txt'); define('MANUAL','Manual'); define('MANUALTASK','+ManualTask'); define("NO_SUCH_FILE_OR_DIRECTORY", "No such file or directory"); define('NOSCANERRORFILE', "0"); define('NORELATIVE', "--no-relative"); define('OUTPUTFILE', "output.txt"); define('OPERATIONSFILE', "operations.php"); define('PIDFILE', "pid.txt"); define('PROPERTIES',"properties"); define('CREATECHECKSUM',"CreateChecksum"); define('MDTCHECK',"MDTcheck"); define('LISTDEVICE',"listDevice"); define('CREATEDIR',"createDir"); define('BACKUPLOG',"backupLog"); define('AUTHLIST',"authlist"); define('AUTHLISTOUTPUTFILE', "authlistOutput.txt"); define('AUTHLISTERRORFILE', "authlistError.txt"); define('CHECKSUMOUTPUTFILE', "checksumOutput.txt"); define('CHECKSUMERRORFILE', "checksumError.txt"); define('MDTCHECKOUTPUTFILE', "mdtCheckOutput.txt"); define('MDTCHECKERRORFILE', "mdtCheckError.txt"); define('EXPRESSDBMAPFILE', 'DB.map'); define('ENGINE_LOCKE_FILE', 'engine.lock'); //define('FIVE_GB_DATA_VAL', 5*1024*1024*1024); define('BACKUP_SET_MAX_SIZE', 5*1024*1024*1024); define('TRY_INSERT',1); define('TRY_UPDATE',1); define('PATHSEPARATOR',"/"); define('PERMISSIONVAL', 0777); define('PARTIAL_SYNC_FILE','PartialSyncFile.txt'); define('PHP_IGNORE_OPENBASEDIR', ' -d open_basedir=NULL '); define('PROGRESS_PATH','progress.txt'); define('RESTORE',"Restore"); define('RESTORE_CHILDPROCESSFILE',"Restore_Script_ChildProcess.php"); define('RELATIVE', "--relative"); define('REMOTESEARCH',"RemoteSearch"); define('RETRY_INFOFILE', "tempfiles/retry_info"); define("RESTORE_SUCCESS","11"); define("REMOTE_SEARCH_FAIL","12"); define("REMOTE_SEARCH_CMD_ERROR","13"); define("REMOTE_SEARCH_OUTPUT_PARSE_FAIL","14"); define("REMOTE_SEARCH_SUCCESS","15"); define("REMOTE_SEARCH_THOUSANDS_FILES_SET_ERROR","17"); define("LOCAL_FILE_FOLDER_SELECT_FAILURE","18"); define("LOCAL_SELECT_SUCCESS","19"); define("REMOTE_SEARCH_RELOGIN","20"); define('RESTORESETFILE_RELATIVE', 'RestoresetFile_relative.txt'); define('RESTORESETFILE_NORELATIVE', 'RestoresetFile_no-relative.txt'); define('RESTORESETFILE_ONLYFILES', 'RestoresetFile_onlyFiles.txt'); define('RELATIVE_FILEPATH', '.relative.txt'); define('STARTPIDFILE', "StartPid.txt"); define('SENDMAILFILE', "sendmail.php"); define('SCRIPTS', ".scripts"); define('SCANERRORFILE', "1"); define('STATUSFILE',"STATUS_FILE"); define('SERVERERROR',"unauthorized user"); define("SEARCH","search"); define("SPLIT_LIMIT_OUTPUT_PARSE","6"); define("SPLIT_LIMIT_INFO_LINE","3"); define("SEARCH_LIMIT",200); #6000000 define("SEARCHLEVEL",1); define("SEARCHALL",0); define('SEARCH_FOR_RESTORE','1'); define('SERVER_ADDR_PATH','.serverAddr.txt'); define('SCHEDULED','Scheduled'); define('TOTAL_SIZE_PATH','totalsize.txt'); define('TEMP_FILES', "tempfiles"); define('TEMP_DB_FILES', TEMP_FILES."/DbFiles/"); define('TEMP_OPERATION_FILE', 'temp_operationsfile.txt'); define('TRASHSEARCH',"TrashSearch"); define('UTFFILE',"utf8.txt"); define('USER_PROFILE','user_profile'); define('WHITESPACE'," "); define('DEDUP_DETAIL_FILE','deDupDetail.txt'); define('DEDUP_RESTORE_DEVICE_FILE','dedupRestoreDeviceID.txt'); define('WAIT_FOR', 2); define('RETRY_ABORT_CAUSE', 'retryAbortCause.txt'); define('EXCLUDE_FILE', 'exclude.txt'); define('LS_TMP_OUTPUT', 'lsoutput.txt_'); define('BACKUPSETFORDISPLAY','BackupsetDisplayFile.txt'); define('LS_TMP_ERROR', 'enumerateFromLSOutput.txt_'); define('SERVERERROR2', "Name or service not known"); define('BACKUP_RESTORE_LOGS_DO_NOT_DELETE', "backup_restore_logs_do_not_delete"); define('SUCCESSFULLY_COMPLETED_BACKUP', "Successfully completed backup."); define('SCHEDULE_BACKUP', "Schedule Backup"); define('INTERACTIVE_BACKUP', "Interactive Backup"); define('LOGLISTXMLS', "LogListXmls"); define('CANCELLED', "Cancelled"); define('FAILURE', "Failure"); define('SUCCESS', "Success"); define('OPERATION_SUMMERY_ERROR_FILE','operationSummeryError.txt'); define('FILES_ARE_IN_TRASH','[* If files are in Trash, they may be restored directly to the account if the files match your backup set items during backup. These files will be included in the \'Files already present\' count.]'); define('SOME_OF_THE_FILES_ARE_IN_EXCLUDE','[Some of the files / folders you have chosen may have been excluded from backup. This means that the backup of these particular files / folders will not take place. View the list of excluded files / folders from the Settings tab.]'); define('UNABLE_TO_CONTINUE_BACKUP','[Unable to continue the backup operation. Reason : Possible reasons: 1. Ensure that you do not have an intermittent Internet connection. 2. If you have proxy settings enabled, please check your proxy details once. 3. Check if you have granted the necessary privileges on local firewall settings for it to run correctly.]'); define('FILES_ARE_IN_EXCLUDE','Note: Your IDrive appstore path "/volume1/@appstore/IDrive" will be excluded by default.'); define('DECRYPTIONFAILED','Data you are trying to restore is backed up with different key. Please contact support.'); define('HASH_DATA','3698NjA4OERENzM5MTJBQjRGNjc2MXsiMDEiOiJodHRwczovL3d3dzEuaWRyaXZlLmNvbS9jZ2ktYmluL3YxL3VzZXItZGV0YWlscy5jZ2kiLCIwMiI6Imh0dHBzOi8vd3d3Lmlkcml2ZS5jb20vaWRyaXZlZS9hcHBqc3AvSURFTGl0ZUdlbmVyYXRlU2hhcmVfZXZzX2NvbGxhYi5qc3AiLCIwMyI6Imh0dHBzOi8vd3d3MS5pZHJpdmUuY29tL2NnaS1iaW4vdjEvdXNlci1saXN0LmNnaSIsIjA0IjoiaHR0cHM6Ly93d3cxLmlkcml2ZS5jb20vY2dpLWJpbi91cGRhdGVfdXNlcl9kZXZpY2VfaW5mby5jZ2kiLCIwNSI6Imh0dHBzOi8vd3d3MS5pZHJpdmUuY29tL2NnaS1iaW4vaWRyaXZlX2JhY2t1cF9zdW1tYXJ5LmNnaSIsIjA2IjoiaHR0cHM6Ly93ZWJkYXYuaWJhY2t1cC5jb20vY2dpLWJpbi9Ob3RpZnlfZW1haWxfaWJsIiwiMDciOiJodHRwczovL3d3dy5pYmFja3VwLmNvbS9xbWFuYWdlci9qc3AvZ2V0VmVyc2lvbkZvclByb2R1Y3QuanNwIiwiMDgiOiJodHRwczovL3dlYmRhdi5pYmFja3VwLmNvbS9jZ2ktYmluL05vdGlmeV91bmljb2RlIiwiMDkiOiIvZXZzL2NvbmZpZ3VyZUFjY291bnQiLCIxMCI6Ii9ldnMvZ2V0QWNjb3VudFF1b3RhIn0=6983'); #Machine define('NETGEAR','netgear'); define('QNAP','QNAP'); define('SYNOLOGY','synology'); define('TWOTIER','twotier'); define('ASUSTOR','Asustor'); //VERSION define('SYNOLOGY_VERSION','Version 2.05.03'); define('QNAP_VERSION','Version 2.04.03'); define('NETGEAR_VERSION','Version 1.01.01'); define('TWOTIER_VERSION','Version 1.01.03'); define('ASUSTOR_VERSION','Version 1.01.02'); define('SYNOLOGY_RELEASE_DATE','08 Feb 2021'); define('QNAP_RELEASE_DATE','12 Jul 2019'); define('NETGEAR_RELEASE_DATE','12 Jul 2019'); define('ASUSTOR_RELEASE_DATE','12 Jul 2019'); ################################## #Operation Type # ################################## $totalSize = "calculating"; $mode = 'release'; $taskType = MANUAL; $failedfiles_index = 0; $psPath = ""; $pidIdx = ""; $cronSeparator = ""; $failedFilesCount = 0; $userCancelStr = "Operation could not be completed. Reason : Operation cancelled by User"; $logOutputFilePath = ""; $operationName = ""; $retrycount = 0; $prevFailedCount = -1; $separator = ""; $trash = 0; $headerMsg = ""; $backupStartTime = ""; $backupEndTime = ""; $status = ""; $backupLocation = ""; $flag; $errStr = ""; $cancelFlag = false; $jobrunningDir = `pwd`; $jobrunningDir = trim($jobrunningDir, LINEFEED); $errorFile = $jobrunningDir.PATHSEPARATOR.ERROR_DIR.PATHSEPARATOR.TEMP_FILES.PATHSEPARATOR.FAILEDFILES; $precision = 2; $kilobyte = 1024; $megabyte = $kilobyte * 1024; $gigabyte = $megabyte * 1024; $terabyte = $gigabyte * 1024; $BackupForkchilds = array(); $dbIndexCount = array(); $nonXMLInfo = array(); $localDBCommitFreq = 5; $fileOperationCount = 0; $fileSyncCount = 0; $failedfiles_count = 0; $exit_flag = 0; #Array containing the lines read from Account Settings File $linesAccountSettingsFile = array(); #Hash to hold the values of arguments to be passed to idevsutil binary $hashEvsParameters = array( "SERVERADDRESS" => "--getServerAddress", "USERNAME" => "--user", "PASSWORD" => "--password-file", "ENCTYPE" => "--enc-type", "PVTKEY" => "--pvt-key", "VALIDATE" => "--validate", "CONFIG" => "--config-account", "PROXY" => "--proxy", "UTF8CMD" => "--utf8-cmd", "ENCODE" => "--encode", "FROMFILE" => "--files-from", "TYPE" => "--type", "BWFILE" => "--bw-file", "PROPERTIES" => "--properties", "XMLOUTPUT" => "--xml-output", "GETQUOTA" => "--get-quota", "AUTHLIST" => "--auth-list", "SPEED" => "--trf-", "OUTPUT" => "--o", "ERROR" => "--e", "QUOTAFROMFILE" => "--quota-fromfile", "CREATEDIR" => "--create-dir", "SEARCH" => "--search", "ADDPROGRESS" => "--add-progress", "FILE" => "--file", "ENCOPT" => "--enc-opt", "PORTABLE" => "--portable", "PORTABLEDEST" => "--portable-dest", "MASKNAME" => "--mask-name", "NOVERSIONS" => "--no-versions", "DEVICE_ID"=>"--device-id", "CREATE_CHK"=>"--create-chk", "MDT_CHECK"=>"--mdt-check", "SERVER_ROOT"=>"--server-root", "SEEKID"=>"--seekid", 'LOCALAUTH' => '--def-local', "EVSTEMP"=>"--temp", "LISTDEVICE"=>"--list-device", "BACKUPLOG"=>"--backup-log", ); $filesConsideredCount = ""; $totalFiles = 0; $failedFiles = 0; $summaryMsg = ""; $mailSummaryMsg = ""; $successFiles = 0; $syncedFiles = 0; $httpuser = `whoami`; $httpuser = trim($httpuser); $bacSync = 0; $filecount = 0; $enumerateFileSize = 0; $machine = ''; $IDPVTContent = ""; $enctype = ""; $LogListXmlsFile = ""; #Get config information if(!isset($_SESSION['machine']) || !isset($_SESSION['webDir']) || !isset($_SESSION['nasUser']) || !isset($_SESSION['cronCat'])) { $configFilehash = getVars(); } $webDir = isset($configFilehash['webDir'])? $configFilehash['webDir'] : ''; $user = isset($configFilehash['nasUser'])? $configFilehash['nasUser'] : ''; $machine = isset($configFilehash['machine'])? $configFilehash['machine'] : ''; $cronCat = isset($configFilehash['cronCat'])? $configFilehash['cronCat'] : ''; $webDir = trim($webDir); $user = trim($user); $machine = trim($machine); $cronCat = trim($cronCat); $appPath = "$webDir/".APPDIR; #get user name $username = ""; $nasUsername = getNasUserName(); $username = getUserName(); $userDir = $webDir.PATHSEPARATOR.SERVICE.PATHSEPARATOR.USER_PROFILE.PATHSEPARATOR.$nasUsername.PATHSEPARATOR.$username; $localBackupLocationFile = "$userDir".PATHSEPARATOR."localBackupLocation.txt"; $varLocalBackupManualTask = "/$username/LocalBackup/"; $varLocalRestoreManualTask = "/$username/LocalRestore/"; $isLocalBackup = 0; $isLocalRestore = 0; readAccountSettingsFile(); if(isset($linesAccountSettingsFile['userAccountStatus']) && ($linesAccountSettingsFile['userAccountStatus'] != "active")) { $errMsg = $linesAccountSettingsFile['userAccountStatus']; traceLog($errMsg); unlink(PIDFILE); unlink(STARTPIDFILE); $ver = getSynoDSMVersion(); $wdir = "web" . (($ver >= 7)? '_packages' : ''); $logoutTrigger = "/var/services/$wdir/IDrive/appWasStopped.txt"; if(file_exists($logoutTrigger)) file_put_contents($logoutTrigger, "Need to logout app"); exit; } $totalEngineBackup = 4; $totalEngineRestore = 4; if($linesAccountSettingsFile['engineCount'] == 2) { $totalEngineBackup = 2; $totalEngineRestore = 2; } $jobDir = $jobrunningDir.PATHSEPARATOR; $dedupDetailFile = "$userDir".PATHSEPARATOR.DEDUP_DETAIL_FILE; $dedupRestoreDeviceID = "$userDir".PATHSEPARATOR.DEDUP_RESTORE_DEVICE_FILE; if(TWOTIER != $machine) { $isLocalBackup = 4; $isLocalRestore = 4; } // As preg_match is failing when user names have special characters, replaced with stripos. if (stripos($jobDir, "$varLocalBackupManualTask") !== false) { $isLocalBackup = 1; } if (stripos($jobDir, "$varLocalRestoreManualTask") !== false) { $isLocalRestore = 1; } $host = getNAShostname(); if(QNAP == $machine){ $appVersion = QNAP_VERSION; $releaseDate = QNAP_RELEASE_DATE; $cronSeparator = " "; $pidIdx = 2; $separator = "/"; } elseif(SYNOLOGY == $machine){ $appVersion = SYNOLOGY_VERSION; $releaseDate = SYNOLOGY_RELEASE_DATE; $dsmVersion6 = false; $dsmVersionCmdOut = `cat /etc.defaults/VERSION`; $dsmVersionArr = preg_split('/\n/', $dsmVersionCmdOut); chop($dsmVersionArr[0], "\n"); $keyValuePair = preg_split('/=/', $dsmVersionArr[0]); $ver = (int)trim($keyValuePair[1],'"'); if($ver >= 6){ $dsmVersion6 = true; } if($dsmVersion6){ $psPath = "ps -elf"; $pidIdx = 3; } else{ $psPath = "ps -wwwww"; $pidIdx = 0; } $cronSeparator = "\t"; $separator = " "; } elseif(TWOTIER == $machine){ $appVersion = TWOTIER_VERSION; $psPath = "ps -wwwww -ax"; $pidIdx = 0; $cronSeparator = "\t"; $separator = " "; } else if(ASUSTOR == $machine){ $appVersion = ASUSTOR_VERSION; $releaseDate = ASUSTOR_RELEASE_DATE; $psPath = "ps -elf"; $pidIdx = 0; $cronSeparator = " "; $separator = " "; } else { $appVersion = NETGEAR_VERSION; $releaseDate = NETGEAR_RELEASE_DATE; $psPath = "ps -elf"; $pidIdx = 6; $cronSeparator = "\t"; $separator = " "; } $phpPath = getPhpPath(); $deDup = false; #idevsutil binary path if(file_exists($dedupDetailFile)){ $idevsutilBinaryPath = $webDir.PATHSEPARATOR.APPDIR.PATHSEPARATOR."idevsutil_IDrive_Dedup"; $deDup = true; } else $idevsutilBinaryPath = $webDir.PATHSEPARATOR.APPDIR.PATHSEPARATOR."idevsutil_IDrive"; //-------------------------------------- A ------------------------------------------------ #******************************************************************************************************** # Subroutine Name : addtionalErrorInfo. # Objective : Logs error info into temporay error text file which is displayed in Log page. # Added By : Basavaraj Bennur [11/25/2016] # Modified By : Senthil Pandian #********************************************************************************************************/ function addtionalErrorInfo($error,$tmpErrorPath='') { if($tmpErrorPath!=''){ $tmpErrorPath = ERROR_DIR."/".$tmpErrorPath; file_put_contents($tmpErrorPath, $error, FILE_APPEND); @chmod($tmpErrorPath, PERMISSIONVAL); } } #******************************************************************************************************** # Subroutine Name : appendErrorFileContents. # Objective : # Added By : Pooja H # Added On : # Modified By : # Modified On : #********************************************************************************************************/ function appendErrorFileContents() { $mail_content = ""; $error_dir = ERROR_DIR.PATHSEPARATOR.TEMP_FILES.PATHSEPARATOR; $files_list = scandir($error_dir); $fileopen = 0; foreach ($files_list as $file){ if($file == "." || $file == ".."){ continue; } $file = $error_dir.$file; $file_content = ''; rtrim($file); if(file_exists($file) and customFileSize($file) > 0){ if($fileopen == 0){ $mail_content.=LINEFEED."_______________________________________________________________________________________"; $mail_content.=LINEFEED."|Error Report|".LINEFEED; $mail_content.="_______________________________________________________________________________________".LINEFEED; $fileopen = 1; } $file_content = file_get_contents($file); if($file_content) $mail_content.= $file_content; } } return $mail_content; } #****************************************************************************************************************** # Subroutine Name : autoUpdateBackupset. # Objective : This subroutine is to udpate the default backup set file. # Added By : Deepak Chaurasia. #******************************************************************************************************************/ function autoUpdateBackupset() { GLOBAL $machine, $phpPath, $webDir, $userDir; if(TWOTIER == $machine){ $cmd = $phpPath.$webDir.PATHSEPARATOR.APPDIR.PATHSEPARATOR.CONFIG.PATHSEPARATOR.CHECKDIRECTORIESFILE.WHITESPACE.$userDir; `$cmd`; } } //-------------------------------------- B ------------------------------------------------ //-------------------------------------- C ------------------------------------------------ #******************************************************************************************************** # Subroutine Name : setTimeZone. # Objective : Set server's time zone to PHP if it is different one # Added By : Senthil Pandian [03/16/2017] # Modified By : #********************************************************************************************************/ function setDateTimeZone(){ $timeZoneArray = array('GMT-11:00'=> 'Pacific/Midway', 'GMT-10:00'=> 'Pacific/Honolulu', 'GMT-09:00'=> 'America/Anchorage', 'GMT-08:00'=> 'America/Los_Angeles', 'GMT-07:00'=> 'America/Denver', 'GMT-06:00'=> 'America/Chicago', 'GMT-05:00'=> 'America/New_York', 'GMT-04:30'=> 'America/Caracas', 'GMT-04:00'=> 'Canada/Atlantic', 'GMT-03:30'=> 'America/St_Johns', 'GMT-03:00'=> 'America/Sao_Paulo', 'GMT-02:00'=> 'America/Noronha', 'GMT-01:00'=> 'Atlantic/Azores', 'GMT+00:00'=> 'Europe/London', 'GMT+01:00'=> 'Europe/Rome', 'GMT+02:00'=> 'Europe/Athens', 'GMT+03:00'=> 'Asia/Kuwait', 'GMT+03:30'=> 'Asia/Tehran', 'GMT+04:00'=> 'Asia/Muscat', 'GMT+04:30'=> 'Asia/Kabul', 'GMT+05:00'=> 'Asia/Karachi', 'GMT+05:30'=> 'Asia/Calcutta', 'GMT+05:45'=> 'Asia/Katmandu', 'GMT+06:00'=> 'Asia/Dhaka', 'GMT+07:00'=> 'Asia/Bangkok', 'GMT+08:00'=> 'Asia/Hong_Kong', 'GMT+09:00'=> 'Asia/Tokyo', 'GMT+09:30'=> 'Australia/Adelaide', 'GMT+10:00'=> 'Australia/Brisbane', 'GMT+11:00'=> 'Asia/Vladivostok', 'GMT+12:00'=> 'Pacific/Auckland', 'GMT+13:00'=> 'Pacific/Tongatapu'); $phpTimeZone = date('T'); //Ex:IST $phpTimeZone = trim($phpTimeZone); $serverTimeZone = shell_exec('date +%Z'); //Ex:UST $serverTimeZone = trim($serverTimeZone); if($phpTimeZone != $serverTimeZone){ $serverTimeZone = shell_exec('date +%:z');//Ex:+05:30 $serverTimeZone = trim($serverTimeZone); $timeZone = "GMT$serverTimeZone"; if($timeZone){ $setTimeZone = $timeZoneArray[$timeZone]; date_default_timezone_set($setTimeZone); } else if( ! ini_get('date.timezone') ){ //To avoid "Warning: date(): It is not safe to rely on the system's timezone settings." date_default_timezone_set('GMT'); } } } #******************************************************************************************************** # Subroutine Name : convertFileSize. # Objective : converts the file size of a file into human readable format. # Added By : Senthil Pandian # Added On : 11/25/2016 # Modified By : # Modified On : #********************************************************************************************************/ function convertFileSize($bytes) { GLOBAL $precision, $kilobyte, $megabyte, $gigabyte, $terabyte; if(!is_numeric($bytes)) return $bytes; if ($bytes < $kilobyte) return $bytes . ' B'; elseif (($bytes >= $kilobyte) && ($bytes < $megabyte)) return round($bytes / $kilobyte, $precision) . ' KB'; elseif (($bytes >= $megabyte) && ($bytes < $gigabyte)) return round($bytes / $megabyte, $precision) . ' MB'; elseif (($bytes >= $gigabyte) && ($bytes < $terabyte)) return round($bytes / $gigabyte, $precision) . ' GB'; elseif ($bytes >= $terabyte) return round($bytes / $terabyte, $precision) . ' TB'; } #**************************************************************************************************** # Subroutine Name : copyTempErrorFile # Objective : This subroutine copies the contents of the temporary error file to the # Error File. # Added By : # Modified By : Vijay Vinoth #*****************************************************************************************************/ function copyTempErrorFile($job_error,$engineID='') { if(file_exists(ERRORFILE.$engineID) and customFileSize(ERRORFILE.$engineID)){ # TESTING PURPOSE BY ANIL - to get failure reasons for huge set of files we can duplicate the error files to tmp. /* if(!is_dir("/tmp/verify/")) `mkdir "/tmp/verify/"`; $filename = "/tmp/verify/".time().".txt"; $from = ERRORFILE.$engineID; $copy = `cp -rfp $from $filename`; */ ################################# $file = ERROR_DIR."/$job_error"; // need to append the error content info file is already exist. $errorFileContent = file_get_contents(ERRORFILE.$engineID); file_put_contents($file, $errorFileContent, FILE_APPEND); @chmod ($file,PERMISSIONVAL); } } #**************************************************************************************************** # Subroutine Name : createLogFiles. # Objective : This subroutine creates the Log Directory if not present. It also creates # the Error Log and Output Log files. # Added By : Vijay Vinoth #*****************************************************************************************************/ function createLogFiles($outputFileName) { GLOBAL $logOutputFilePath; $logDirectory = "LOGS"; if(!is_dir($logDirectory)){ if(! mkdir($logDirectory)){ $errMsg = "Unable to create directory $logDirectory, Reason:".customErrorMsg(); traceLog($errMsg); unlink(PIDFILE); unlink(STARTPIDFILE); exit; } chmod($logDirectory,PERMISSIONVAL); } $currentTime = trim(shell_exec('date +"%Y-%m-%d %I:%M:%S %p"')); $logOutputFilePath = $logDirectory.PATHSEPARATOR.$currentTime.WHITESPACE.$outputFileName; if(!is_dir(ERROR_DIR)){ if(! mkdir(ERROR_DIR)){ $errMsg = "Unable to create directory ".ERROR_DIR.", Reason:".customErrorMsg(); exitError($errMsg); } chmod(ERROR_DIR,PERMISSIONVAL); $errorFilePathInter = ERROR_DIR."/".TEMP_FILES; if(! mkdir($errorFilePathInter)){ $errMsg = "Unable to create directory $errorFilePathInter, Reason:".customErrorMsg(); exitError($errMsg); } chmod($errorFilePathInter,PERMISSIONVAL); } } #**************************************************************************************************** # Subroutine Name : checkIfSetEmpty. # Objective : Checks if the Backupset is empty or not # Added By : Pooja Havaldar #*****************************************************************************************************/ function checkIfSetEmpty($fileSet) { if(! customFileSize($fileSet)){ traceLog("$fileSet is empty."); return 1; } return 0; } #**************************************************************************************************** # Subroutine Name : checkIfJobRunning. # Objective : This subroutine will check whether jobs are running in particular path # Modified By : Pooja Havaldar #*****************************************************************************************************/ function checkIfJobRunning($ArchiveJobPath) { if (!file_exists($ArchiveJobPath)) { return 0; } $files_list = getDirList($ArchiveJobPath); if(count($files_list) == 0) return 0; foreach($files_list as $value) { $value = trim($value); if($value == "." or $value == "..") continue; if(isFileLocked($ArchiveJobPath.$value."/".PIDFILE)) return 1; } return 0; } #**************************************************************************************************** # Subroutine Name : checkIfDeleteJobRunning. # Objective : This subroutine will check whether Delete jobs are running in particular path # Modified By : Vijay Vinoth #*****************************************************************************************************/ function checkIfDeleteJobRunning($DeleteJobPath) { $item_pidpath = $DeleteJobPath."/pid.txt"; if(! file_exists($item_pidpath)) return 0; $deleteOpType = file_get_contents($item_pidpath); if($trim($deleteOpType) == "Delete"){ if(isFileLocked($item_pidpath)) return 1; } return 0; } #******************************************************************************************************* # Subroutine Name : checkErrorAndUpdateServerAddr. # Objective : Read error.txt file check for server error if found update server address. # Added By : Avinash Kumar. #*******************************************************************************************************/ function checkErrorAndUpdateServerAddr($engineID='') { $returnData = 0; if(file_exists(ERRORFILE.$engineID) && 0 < customFileSize(ERRORFILE.$engineID)){ $errorContent = file_get_contents(ERRORFILE.$engineID); if(preg_match("/".SERVERERROR."/", $errorContent) || preg_match("/" . SERVERERROR2 . "/", $errorContent)){ updateServerAddr($engineID); $returnData = 1; } } return $returnData; } #************************************************************************************************************************** # Subroutine Name : createPid # Objective : This subroutine creates the pid.txt file for Scheduled Backup if it is not already running. # Added By : Vijay Vinoth #**************************************************************************************************************************/ function createPid($taskType) { GLOBAL $machine, $isLocalBackup, $fhsPid, $jobrunningDir, $fhPid; $fhsPid = ""; $fhPid = ""; $isLocked = false; $isPidLocked = false; if($taskType == SCHEDULED){ if($machine == TWOTIER){ $startPidFile = "..".PATHSEPARATOR.MANUALTASK.PATHSEPARATOR.STARTPIDFILE; if(!isFileLocked($startPidFile)){ traceLog("$jobrunningDir job is already running\n"); exit; } } } $fhsPid = fopen(STARTPIDFILE, 'w+'); if(!$fhsPid){ traceLog("Unable to open file ".STARTPIDFILE.", Reason:".customErrorMsg()); exit; } @chmod(STARTPIDFILE,PERMISSIONVAL); $isLocked = flock($fhsPid, LOCK_EX|LOCK_NB); if(!$isLocked){ # $isLocked will be 0 if FHSPID is locked. traceLog("$jobrunningDir job is already running".customErrorMsg()); exit; } $fhPid = fopen(PIDFILE, 'w+'); if(!$fhPid){ traceLog("Unable to open file ".PIDFILE.", Reason:".customErrorMsg()); @unlink(STARTPIDFILE); exit; } @chmod(PIDFILE,PERMISSIONVAL); $isPidLocked = flock($fhPid, LOCK_EX|LOCK_NB); if($isPidLocked !== TRUE){ # $isPidLocked will be 0 if FHPID is locked. traceLog("$jobrunningDir job is already running".customErrorMsg()); exit; } } #**************************************************************************************************************************** # Subroutine Name : checkAndConstructXML # Objective : This subroutine is for xml parsing # Added By : Senthil Pandian [12/01/2016] # Modified By : #***************************************************************************************************************************** function checkAndConstructXML($resultListXML){ GLOBAL $lastLine; $resultListXML = trim($resultListXML); $exp = explode("\n",$resultListXML); $xml = ''; foreach($exp as $data){ if(!empty($data) && strpos($data,"")){ $lastLine = $data.$lastLine; // Sometime partial data having "\n" traceLog("\ncheckAndConstructXML appended incomplete data in lastline:$data\n"); } continue; } else if(empty($data)){ continue; } $itemPos = strpos($data,"")){ $lastLine = $data.$lastLine; // Sometime partial data having "\n" } $xml .= $data."\n"; continue; } $itemPos = strpos($data,"children() as $child) { $attr = $child->attributes(); if(array_search($attr['fileName'], array_column($nonXMLInfo, 'id')) !== False) { $key = array_search($attr['fullpath'], array_column($nonXMLInfo, 'id')); $attr['fileName'] = $nonXMLInfo[$key]['fileName']; $attr['keyString'] = $nonXMLInfo[$key]['fullPath']; unset($nonXMLInfo[$key]); } } return $xml; } #**************************************************************************************************************************** # Subroutine Name : parseEachXmlRecord # Objective : This subroutine is for xml parsing # Added By : Anil Kumar # Modified By : #***************************************************************************************************************************** function parseEachXmlRecord($xmlContent) { GLOBAL $nonXMLInfo; $fileName = getStringBetween($xmlContent,' fileName = "', '" operation = "'); $randomVal = rand(); $xmlContent = str_replace($fileName, $randomVal, $xmlContent); $fullPath = getStringBetween($xmlContent,'" keyString = "', '" />'); $xmlContent = str_replace($fullPath, $randomVal, $xmlContent); $nonXMLInfo[] = array('id' => $randomVal, 'fileName' => $fileName, 'fullPath' => $fullPath) ; return $xmlContent; } #**************************************************************************************************************************** # Subroutine Name : getStringBetween # Objective : This subroutine is for getting the string between 2 patterns # Added By : Anil Kumar # Modified By : #***************************************************************************************************************************** function getStringBetween($string,$start,$end) { $r = explode($start, $string); $r = explode($end, $r[1]); return $r[0]; } /********************************************************************************************************* * 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 : checkBinaryExists # Objective : This subroutine checks if evs binary exists and whether it is executable. # Added By : Vijay Vinoth #**************************************************************************************************************************/ function checkBinaryExists() { GLOBAL $idevsutilBinaryPath, $logOutputFilePath; $errMsg = ""; if(!is_file($idevsutilBinaryPath)) $errMsg = "idevsutil file does not exist in current directory. Please copy idevsutil file to current directory."; else if(!is_executable($idevsutilBinaryPath)) $errMsg = "idevsutil file does not have executable permission. Please give it executable permission."; if($errMsg != ""){ traceLog("ERROR: $errMsg"); if(!file_put_contents($logOutputFilePath, $errMsg.PHP_EOL , FILE_APPEND | LOCK_EX)) traceLog("Unable to open file $logOutputFilePath, Reason : ".customErrorMsg()); @chmod($logOutputFilePath, PERMISSIONVAL); exitError(''); } } #**************************************************************************************************** # Subroutine Name : checkDedupDeviceError. # Objective : Check dedup device id mismatch error & remove device id related files. # Added By : Senthil Pandian #***************************************************************************************************** function checkDedupDeviceError($error){ GLOBAL $dedupDetailFile, $dedupRestoreDeviceID; if(stristr($error,"failed to get the device information") || stristr($error,"encryption verification failed") || stristr($error,"Unable to proceed as device is deleted/removed")){ @unlink($dedupDetailFile); @unlink($dedupRestoreDeviceID); } } #**************************************************************************************************** # Subroutine Name : checkLastDayOfMonth. # Objective : Check today date is last day of month. # Added By : Pooja Havaldar #***************************************************************************************************** function checkLastDayOfMonth() { GLOBAL $machine; $lastDay = ""; if(TWOTIER == $machine){ $lastDay = `date -v +1d +%d`; } elseif(QNAP == $machine or NETGEAR == $machine){ $lastDay = `date +%d -d tomorrow`; } elseif(SYNOLOGY == $machine || ASUSTOR == $machine){ $cmd = 'date -D "%s" -d $(( $(date +%s ) + 86400 )) +%d'; $lastDay = `$cmd`; } $lastDay = trim($lastDay); if(1 == $lastDay){ return true; } return false; } #**************************************************************************************************** # Subroutine Name : configureAndCommitCron. # Objective : Configure and commit crontab. # Added By : Uttam Tiwari. #*****************************************************************************************************/ function configureAndCommitCron() { GLOBAL $machine; $returnVal = -1; if($machine == QNAP){ $returnVal = commitCrontabChanges(); if($returnVal == 0){ configureCron(); } } if($machine == SYNOLOGY || $machine == ASUSTOR) configureCron(); } #************************************************************************************************************* # Subroutine Name : commitCrontabChanges # Objective : To reflect the changes made in crontab file # Added By : #**************************************************************************************************************/ function commitCrontabChanges() { $retVal = 1; $retVal = system("/usr/bin/crontab /etc/config/crontab"); if($retVal == "") $retVal = 0; else $retVal = 1; return $retVal; } #************************************************************************************************************* # Subroutine Name : configureCron # Objective : # Added By : #**************************************************************************************************************/ function configureCron() { GLOBAL $machine; $retVal = 1; if(SYNOLOGY == $machine){ $retVal = system("/usr/syno/sbin/synoservicectl --restart crond"); # $? perl special variable to collect the error returned by system call if($retVal == ""){ system("synoservice --restart crond"); $retVal = 0; } else $retVal = 1; } else if($machine == ASUSTOR){ system("./etc/init.d/S41crond stop"); system("./etc/init.d/S41crond start"); } else { $retVal = system("/etc/init.d/crond.sh restart"); if($retVal == "") $retVal = 0; else $retVal = 1; } //$retVal = $?; //$retVal = $retVal >> 8; return $retVal; } #**************************************************************************************************** # 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 : checkErrorAndReason * Objective : Checking error and returning the reason * Added By : Senthil Pandian ******************************************************************************************************/ function checkErrorAndReason($out) { GLOBAL $dedupDetailFile; $error = ''; $exp = explode("\n",$out); foreach($exp as $line){ $pos = strpos($line, "ERROR"); if($pos !== false){ $error = trim(str_replace('@ERROR:','',$line)); $error = ucfirst($error); $accountSettingPath = $userDir."ACCOUNT_SETTINGS_FILE"; if((stristr($error,"encryption verification failed") && file_exists($accountSettingPath)) || stristr($error,"password mismatch")) session_destroy(); if(file_exists($dedupDetailFile) && ((stristr($error,"failed to get the device information")) || stristr($error,"password mismatch") || stristr($error,"Unable to proceed as device is deleted/removed"))) @unlink($dedupDetailFile); break; } } return $error; } //-------------------------------------- D ------------------------------------------------ //-------------------------------------- E ------------------------------------------------ #**************************************************************************************************** # Subroutine Name : exitError. # Objective : To remove the temporary files created and exit # Added By : Uttam Tiwari. #*****************************************************************************************************/ function exitError($errStr = '') { traceLog($errStr); unlink(PIDFILE); unlink(STARTPIDFILE); $val = array(TEMP_FILES, ERROR_DIR); removeItems($val); exit; } //-------------------------------------- F ------------------------------------------------ //-------------------------------------- G ------------------------------------------------ /**************************************************************************************************** * Function Name : getMyParentID * Objective : returns the parent id for the process * Added By : Deepak Chaurasia ******************************************************************************************************/ function getMyParentID() { $pid = getmypid(); $PPidRow = `cat /proc/$pid/status | grep PPid:`; $PPid = preg_replace('/PPid:\s+/', '', $PPidRow); return $PPid; } /**************************************************************************************************** * 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 == $machine && is_link($webDir)) $servicePath = readlink("$webDir"); return $servicePath; } #**************************************************************************************************** # Subroutine Name : getJobName. # Objective : This subroutine gets the current working JobName from job running directory # Added By : Pooja Havaldar # Modified By : Senthil Pandian #*****************************************************************************************************/ function getJobName() { GLOBAL $username,$jobrunningDir; $arr = explode('/', $jobrunningDir); $jobName = array_pop($arr); return $jobName; } #****************************************************************************************************************************** # Subroutine Name : getJobTerminationCommand # Objective : This function creates the Job Termination command for Backup/Restore/Local Search/Remote Search/Delete # depending on machine name # Added By : Pooja Havaldar # Modified By : Avinash kumar(02-JUN-2016, Removed return statement from each if block and put to last) #******************************************************************************************************************************/ function getJobTerminationCommand($jobPath, $jobtype) { GLOBAL $machine, $psPath; $jobStatusCmd = ""; if($machine == QNAP){ if($jobtype == "BACKUP_RESTORE_REMOTESEARCH_CLEANUP") $jobStatusCmd = "grep $jobPath /proc/*/cmdline" ; elseif($jobtype == "LOCALSEARCH"){ //$find = rtrim(end(explode('/', $jobPath)),"'"); //$jobStatusCmd = "grep $jobPath /proc/*/cmdline | grep find | grep \"\-name '*.$find*\""; // As discussed with Deepak changed the process $jobStatusCmd = "ps -elf | grep find | grep \"\-name '*.*\""; } else $jobStatusCmd = "grep \"Delete\" /proc/*/cmdline"; } else { if($jobtype == "BACKUP_RESTORE_REMOTESEARCH_CLEANUP") $jobStatusCmd = "$psPath | grep $jobPath | grep idevsutil_IDrive"; elseif($jobtype == "LOCALSEARCH"){ $find = rtrim(end(explode('/', $jobPath)),"'"); $jobStatusCmd = "$psPath | grep \"find\" | grep $jobPath | grep \"\-name '*$find*\""; } else $jobStatusCmd = "$psPath | grep Delete"; } return $jobStatusCmd ; } #****************************************************************************************************************** # Subroutine Name : getLocalFilePath. # Objective : This subroutine returns the full file path # Added By : Pooja Havaldar # Modified By : Senthil Pandian #******************************************************************************************************************/ function getLocalFilePath($filePath) { GLOBAL $machine; if(TWOTIER == $machine){ $filePath = "/BackupData$filePath"; } return $filePath; } #****************************************************************************************************************** # Subroutine Name : getNAShostname. # Objective : This subroutine return host name. # Added By : Senthil Pandian [11/24/2016] # Modified By : #******************************************************************************************************************/ function getNAShostname() { GLOBAL $machine; $hostName = ''; if($machine==TWOTIER || SYNOLOGY == $machine){ 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); return $hostName; } #****************************************************************************************************************** # Subroutine Name : getOperationStatus # Objective : This fills the status of backup/restore operation status e.g SUCCESS, Failure etc. # Added By : Pooja Havaldar # Modified By : #******************************************************************************************************************/ function getOperationStatus() { GLOBAL $cancelFlag, $status, $filesConsideredCount, $successFiles, $syncedFiles, $failedFiles; $status = "FAILURE"; if($cancelFlag == true) $status = "ABORTED"; elseif($filesConsideredCount > 0 and ($filesConsideredCount <= $successFiles + $syncedFiles + $failedFiles)) # if backup/restore operation has attempted backup/restore for all files $status = ($failedFiles == 0) ? "SUCCESS" : "FAILURE"; } #**************************************************************************************************** # Subroutine Name : getParameterValueFromStatusFile. # Objective : Fetches the value of individual parameters which are specified in the # StatusFile. # Added By : Arnab Gupta # Modified By : Deepak Chaurasia, Senthil Pandian #*****************************************************************************************************/ function getParameterValueFromStatusFile($statusFileHashArray,$engineID = '') { if($engineID != '') $statusFileHash = readStatusFile($engineID); else $statusFileHash = readFinalStatus(); $statusFileReturnData = array(); foreach ($statusFileHashArray as $statusFileHashArrayVal) { $statusFileReturnData[] = ($statusFileHash[$statusFileHashArrayVal] != "")?$statusFileHash[$statusFileHashArrayVal]:0 ; } return $statusFileReturnData; } #**************************************************************************************************** # Subroutine Name : getPhpPath. # Objective : This function will return full path for PHP based on machine type # Added By : Senthil Pandian [11/28/2016] # Modified By : #*****************************************************************************************************/ function getPhpPath() { GLOBAL $machine,$phpPath; if(TWOTIER == $machine){ $phpPath = "/usr/pbi/idrive-amd64/bin/php"; } else { $phpPath = `which php`; $phpPath = trim($phpPath); if($phpPath == ""){ if(QNAP == $machine) $phpPath = "/mnt/ext/opt/apache/bin/php"; else if(SYNOLOGY == $machine || NETGEAR == $machine) $phpPath = "/usr/bin/php"; else if(ASUSTOR == $machine) $phpPath = "/usr/builtin/bin/php"; } } return $phpPath.PHP_IGNORE_OPENBASEDIR; } #****************************************************************************************************************** # Subroutine Name : getPrintItem. # Objective : This subroutine return path after 1st level in case of twotier. # Added By : Avinash Kumar. #******************************************************************************************************************/ function getPrintItem($item) { GLOBAL $machine; if(TWOTIER == $machine) $item = preg_replace("/^\/BackupData/", "", $item); return $item; } function getRestoreLocation(){ GLOBAL $machine, $userDir; $restoreFile = "$userDir/restore_location.txt"; $restorePathName = ""; if(file_exists($restoreFile)) { $restorePathName = file_get_contents($restoreFile); } else { if($machine == TWOTIER){ $restorePathName = "$userDir/".DEFAULT_RESTORE_LOCATION; } else { $restorePathName = "/RestoredData/Default/"; } file_put_contents($restoreFile,$restorePathName); @chmod($restoreFile, PERMISSIONVAL); } return $restorePathName; } #**************************************************************************************************** # Subroutine Name : getHeaderMsg. # Objective : This subroutine returns string with machine name, backup type and hidden # file information in case of NAS backup and return machine id for vault # backup. Returns machine name or id dependes on NAS or vault restore. # Modified By : Vijay Vinoth #*****************************************************************************************************/ function getHeaderMsg($operationType = '',$hidden = '') { GLOBAL $host, $machine, $operationName, $taskType, $deDup, $isLocalBackup, $backupStartTime; $header = ""; $backupStartTime = time(); $jobName = getJobName(); $throttle = getThrottleValue(); if($machine == TWOTIER){ $header = "Machine Id: $host ".LINEFEED."Throttle Value: $throttle".LINEFEED; return $header; } if($operationName == BACKUP){ $backupType = ''; if($deDup != TRUE && $isLocalBackup != 1) { $backupType = "Backup Type: $operationType" . LINEFEED; } $header = $backupType."Show hidden files and folders: $hidden".LINEFEED."Throttle Value: $throttle".LINEFEED; } if($taskType != MANUAL) $header .= "Schedule $operationName Job: $jobName".LINEFEED; $header .= "Machine Name: $host".LINEFEED; return $header; } #****************************************************************************************************************** # Subroutine Name : getAppPath # Objective : Get package path # Added By : Deepak Chaurasia #******************************************************************************************************************/ function getAppPath() { GLOBAL $machine, $webDir; $appPath = ""; if($machine == TWOTIER) $appPath = "/usr/pbi/idrive-amd64/www/idrive"; else $appPath = "$webDir/".APPDIR; return $appPath; } #**************************************************************************************************** # Subroutine Name : getThrottleValue. # Objective : This subroutine gets the Throttle Value # Modified By : Vijay Vinoth #*****************************************************************************************************/ function getThrottleValue() { GLOBAL $userDir; $bandwidthFilePath = "$userDir/.bw.txt"; $throttle = 100; if(file_exists($bandwidthFilePath)){ $throttle = file_get_contents($bandwidthFilePath); trim($throttle); } if($throttle == "") $throttle = 100; return $throttle; } /**************************************************************************************************** * Subroutine Name : getUserName. * Objective : Get current user logged on with IDrive account. * Added By : Avinash Kumar * Modified By : Senthil Pandian ******************************************************************************************************/ function getUserName($currentPath = '') { if($currentPath == '') $currentPath = getcwd(); GLOBAL $nasUsername; # try to find the user name from currentPath //$needle = "/" . SERVICE . "/" . USER_PROFILE . "/".$nasUsername."/"; //$needle = "/usr/syno/etc/packages/IDrive/user_profile/".$nasUsername."/"; $needle = "/" . USER_PROFILE . "/".$nasUsername."/"; $tmp = explode($needle, $currentPath); if(count($tmp) > 1) { $splitPath = explode("/" , $tmp[1]); return $splitPath[0]; } # Following condition needed when it runs from command line[Ex: send mail] GLOBAL $username; if($username != '') { return $username; } return ''; } /**************************************************************************************************** * Subroutine Name : getNasUserName * Objective : Get current user logged on with NAS account. * Added By : Senthil Pandian * Modified By : ******************************************************************************************************/ function getNasUserName($currentPath = '') { if($currentPath == '') $currentPath = getcwd(); # try to find the user name from currentPath //$needle = "/" . SERVICE . "/" . USER_PROFILE . "/"; //$needle = "/usr/syno/etc/packages/IDrive/user_profile/"; $needle = "/" . USER_PROFILE . "/"; $tmp = explode($needle, $currentPath); if(count($tmp) > 1) { $splitPath = explode("/" , $tmp[1]); return $splitPath[0]; } # Following condition needed when it runs from command line[Ex: send mail] GLOBAL $nasUsername; if($nasUsername != '') { return $nasUsername; } return ''; } #**************************************************************************************************** # Subroutine Name : getVars. # Objective : Get machine information from config file. # Added By : Uttam Tiwari # Modified By : Senthil Pandian # Modified By : Sabin Cheruvattil #*****************************************************************************************************/ function getVars() { GLOBAL $machine; $file = NULL; $configFile = dirname(dirname(__FILE__)) . PATHSEPARATOR . CONFIG . PATHSEPARATOR . CONFIG_FILE; if (file_exists($configFile)) { $file = fopen($configFile, 'r'); } if(!$file) { loadMachineConfigurations(); $file = fopen($configFile, 'r'); } # break added for indefinite looping if(!file_exists($configFile)) { return FALSE; } $hash = array(); while(!feof($file)) { $pair = preg_split ('/\s+/', fgets($file), 2); $hash[array_shift($pair)] = array_shift($pair); } fclose($file); $machine = $hash['machine']; $_SESSION['webDir'] = $hash['webDir']; $_SESSION['nasUser'] = $hash['user']; $_SESSION['machine'] = $machine; $pair = preg_split ('/\s+/',$hash['cronCat']); $hash['cronCat'] = $pair[1]; $_SESSION['cronCat'] = $hash['cronCat']; return $hash; } #****************************************************************************************************************** # Subroutine Name : getSource. # Objective : This subroutine return source respective to machine. # Added By : Avinash Kumar. #******************************************************************************************************************/ function getSource() { GLOBAL $machine; $source = ""; if(TWOTIER == $machine) $source = "/BackupData/"; else $source = "/"; return $source; } #**************************************************************************************************** # Subroutine Name : getParameterValueFromAccountSettingsFile. # Objective : Fetches the value of individual parameters which are specified in the # Account Settings file. # Added By : Arnab Gupta. #*****************************************************************************************************/ function getParameterValueFromAccountSettingsFile(&$key, &$value) { GLOBAL $linesAccountSettingsFile; if (count($linesAccountSettingsFile) == 0) { readAccountSettingsFile(); } foreach($linesAccountSettingsFile as $linesAccountSettingsFileKey => $linesAccountSettingsFileVal) { if(preg_match("/$key/", $linesAccountSettingsFileKey)){ $value = trim($linesAccountSettingsFileVal); break; } } /*foreach($linesAccountSettingsFile as $line){ if(preg_match("/$key/", $line)){ $keyValuePair = preg_split('/=/', $line); $value = $keyValuePair[1]; $value = trim($value); break; } }*/ } #**************************************************************************************************** # Subroutine Name : getProxyString. # Objective : Reads Account Settings file and returns the proxy details if set or # returns empty otherwise. # Added By : Vijay Vinoth. #*****************************************************************************************************/ function getProxyString() { GLOBAL $userDir; $proxyPath = "$userDir/ACCOUNT_SETTINGS_FILE"; if(! file_exists($proxyPath)){ return ""; } $lines = json_decode(file_get_contents($proxyPath),TRUE); if (json_last_error() !== JSON_ERROR_NONE) { $lines = readAccountSettingsFile(); } $proxyString=$lines['PROXY']; #Need to check with Senthil. if($proxyString !=''){ $proxyString = str_replace("\%([A-Fa-f0-9]{2})","pack('C', hex($1))", $proxyString); #decode the string which was encoded in php $proxyString = str_replace("\R", "", $proxyString); return $proxyString; } return ""; } #**************************************************************************************************** # Subroutine Name : getProxyToValidate. # Objective : Reads entermediate file returns the proxy details. # Added By : Avinash Kumar. #*****************************************************************************************************/ function getProxyToValidate() { GLOBAL $userDir; $authFilePath = "$userDir/.idriveAuthParams.txt"; $proxyData = ""; $content = ""; $contentArr = array(); $contentArr = file($authFilePath); $len = count($contentArr); if(preg_grep("/proxy/", $contentArr)){ $proxyData = "\'".$contentArr[$len - 1]."\'".":"."\'".$contentArr[$len - 2]."\'"."@".$contentArr[$len - 3].":".$contentArr[$len - 4]; } $encTypeDir = $contentArr[3]; return $proxyData; } #******************************************************************************************************************** # Subroutine Name : getOperationFile. # Objective : Create utf8 file for EVS command respective to operation type(backup/restore/validate...). # Added By : Avinash Kumar. #********************************************************************************************************************/ function getOperationFile($paramHash) { GLOBAL $bandwidthFilePath; GLOBAL $hostNameLB, $username; GLOBAL $userDir, $hashEvsParameters; GLOBAL $backupLocation, $trash; GLOBAL $serverAddress, $dedupDetailFile; GLOBAL $dedupRestoreDeviceID; $operationType = $paramHash["opType"]; $engineID = isset($paramHash["engineID"])?$paramHash["engineID"]:""; $realEngineID = $engineID; if($engineID != "") $engineID = "_".$engineID; $opType = ""; $utfFile = ""; $utfValidate = ""; $encPwdPath = $userDir.PATHSEPARATOR."IDPWD"; $encPvtkeyPath = $userDir.PATHSEPARATOR."IDPVT"; $utfPath = $userDir.PATHSEPARATOR.UTFFILE.$engineID; $currentDir = `pwd`; $currentDir = trim($currentDir); $bck_res_utf8 = $currentDir.PATHSEPARATOR.UTFFILE.$engineID; $sreverAddrPath = $userDir.PATHSEPARATOR.SERVER_ADDR_PATH; $bandwidthFilePath = "$userDir/.bw.txt"; $proxyString = getProxyString(); $RestoresetFile = "./RestoresetFile.txt"; $serverAddress = ""; $serverAddressOperator = "@"; $serverName = "home"; $serverNameOperator = "::"; $privateEncryptionKey = "Private"; $encryptionType = ""; $deDupDeviceId = ""; if($operationType != GETSERVERADDRESS){ if(!file_exists($sreverAddrPath) or !is_readable($sreverAddrPath) or customFileSize($sreverAddrPath) <= 0){ $handle = fopen($sreverAddrPath."_lock",'w+'); $isLocked = flock($handle, LOCK_EX); #=====================================lock if(!file_exists($sreverAddrPath) or customFileSize($sreverAddrPath) <= 0) updateServerAddr($realEngineID); #===================================== flock($handle, LOCK_UN); fclose($handle); unlink($sreverAddrPath."_lock"); } # get server address if($SERVERHDL = fopen($sreverAddrPath, "r")){ $serverAddress = fread($SERVERHDL, customFileSize($sreverAddrPath)); fclose($SERVERHDL); } else traceLog("Unable to open file $sreverAddrPath Reason: ".customErrorMsg()); $serverAddress = trim($serverAddress); } $key = "encType"; getParameterValueFromAccountSettingsFile($key,$encryptionType); $deDup = false; $deviceID = ''; $restoreDeviceID =''; $serverRoot = ''; if(file_exists($dedupDetailFile)){ $deDup = true; $deviceJSON = file_get_contents($dedupDetailFile); $deviceArray = json_decode($deviceJSON, true); $deviceID = trim($deviceArray['deviceID']); $serverRoot = trim($deviceArray['serverRoot']); if(file_exists($dedupRestoreDeviceID)){ $restoreDeviceID = file_get_contents($dedupRestoreDeviceID); $restoreDeviceID = trim($restoreDeviceID); } } if($deDup && $restoreDeviceID!='') $deDupDeviceId = $hashEvsParameters["DEVICE_ID"].ASSIGNMENTOP.$restoreDeviceID.LINEFEED; if($operationType == BACKUP){ if(!($UTF8FILE = fopen($bck_res_utf8, "w"))){ traceLog("Unable to open file $bck_res_utf8 Reason: ".customErrorMsg()); exit; } $utfFile = $hashEvsParameters["FROMFILE"].ASSIGNMENTOP.$paramHash["backupsetFile"].LINEFEED. $hashEvsParameters["BWFILE"].ASSIGNMENTOP.$bandwidthFilePath.LINEFEED. $hashEvsParameters["TYPE"].LINEFEED. "--timeout=60".LINEFEED. $hashEvsParameters["PASSWORD"].ASSIGNMENTOP.$encPwdPath.LINEFEED; if($encryptionType === $privateEncryptionKey) $utfFile .= $hashEvsParameters["PVTKEY"].ASSIGNMENTOP.$encPvtkeyPath.LINEFEED; $input = $backupLocation; if($deDup){ $utfFile .= $hashEvsParameters["DEVICE_ID"].ASSIGNMENTOP.$deviceID.LINEFEED; $input = ''; /*if($mdtCheck){ $utfFile .= $hashEvsParameters["SEEKID"].LINEFEED; }*/ } $utfFile .= $hashEvsParameters["ADDPROGRESS"].LINEFEED. $hashEvsParameters["PROXY"].ASSIGNMENTOP.$proxyString.LINEFEED. $hashEvsParameters["ENCODE"].LINEFEED. $hashEvsParameters["OUTPUT"].ASSIGNMENTOP.OUTPUTFILE.$engineID.LINEFEED. $hashEvsParameters["ERROR"].ASSIGNMENTOP.ERRORFILE.$engineID.LINEFEED. $hashEvsParameters["EVSTEMP"].ASSIGNMENTOP.$userDir.LINEFEED. $paramHash["backupType"].LINEFEED. $hashEvsParameters["XMLOUTPUT"].LINEFEED. $paramHash["source"].LINEFEED. $username.$serverAddressOperator. $serverAddress.$serverNameOperator. $serverName.$input.PATHSEPARATOR.LINEFEED; fwrite($UTF8FILE, $utfFile); fclose($UTF8FILE); @chmod($bck_res_utf8, PERMISSIONVAL); $filename = explode("/",$paramHash["backupsetFile"]); traceLog("$operationType has been executed for $filename[1]\n"); return $bck_res_utf8; } elseif($operationType == LOCALBACKUP){ $bandwidthFilePath = "$userDir/.bw.txt"; $relStr = ""; $localMPC = getNAShostname(); if($deDup){ if(file_exists($dedupDetailFile)){ $deviceJSON = file_get_contents($dedupDetailFile); $deviceArray = json_decode($deviceJSON, true); $localMPC = trim($deviceArray['serverRoot']); } } $host = "$backupLocation/$username/$localMPC"; if(!($UTF8FILE = fopen($bck_res_utf8, "w"))){ traceLog("Unable to open file $bck_res_utf8 Reason: ".customErrorMsg()); exit; } $utfFile = $hashEvsParameters["FROMFILE"].ASSIGNMENTOP.$paramHash["backupsetFile"].LINEFEED. $hashEvsParameters["BWFILE"].ASSIGNMENTOP.$bandwidthFilePath.LINEFEED. $hashEvsParameters["TYPE"].LINEFEED. $hashEvsParameters["PASSWORD"].ASSIGNMENTOP.$encPwdPath.LINEFEED; if($encryptionType === $privateEncryptionKey){ $utfFile .= $hashEvsParameters["PVTKEY"].ASSIGNMENTOP.$encPvtkeyPath.LINEFEED; $utfFile .= $hashEvsParameters['LOCALAUTH'] . ASSIGNMENTOP . '0' . LINEFEED; } else { $utfFile .= $hashEvsParameters['LOCALAUTH'] . ASSIGNMENTOP . '1' . LINEFEED; } $utfFile .= $hashEvsParameters["ADDPROGRESS"].LINEFEED. $hashEvsParameters["PROXY"].ASSIGNMENTOP.$proxyString.LINEFEED. $hashEvsParameters["ENCODE"].LINEFEED. $paramHash["backupType"].LINEFEED. $hashEvsParameters["OUTPUT"].ASSIGNMENTOP.OUTPUTFILE.$engineID.LINEFEED. $hashEvsParameters["ERROR"].ASSIGNMENTOP.ERRORFILE.$engineID.LINEFEED. $hashEvsParameters["XMLOUTPUT"].LINEFEED. $hashEvsParameters["ENCOPT"].LINEFEED. $hashEvsParameters["PORTABLE"].LINEFEED. $hashEvsParameters["NOVERSIONS"].LINEFEED. $hashEvsParameters["PORTABLEDEST"].ASSIGNMENTOP.$host.LINEFEED. $paramHash["source"].LINEFEED. $username.$serverAddressOperator. $serverAddress.$serverNameOperator. $serverName.PATHSEPARATOR.$host.PATHSEPARATOR.LINEFEED; fwrite($UTF8FILE, $utfFile); fclose($UTF8FILE); @chmod($bck_res_utf8, PERMISSIONVAL); $filename = explode("/",$paramHash["backupsetFile"]); traceLog("$operationType has been executed for $filename[1]\n"); return $bck_res_utf8; } else if($operationType == RESTORE){ $RestoresetFile = $paramHash["backupsetFile"]; if(!($UTF8FILE = fopen($bck_res_utf8, "w"))){ traceLog("Unable to open file $bck_res_utf8 for restore, Reason: ".customErrorMsg()); } $utfFile = $hashEvsParameters['FROMFILE'].ASSIGNMENTOP.$RestoresetFile.LINEFEED; if($trash == 1){ $utfFile .= "--trash".LINEFEED; } $utfFile .= $hashEvsParameters['TYPE'].LINEFEED. $hashEvsParameters['PASSWORD'].ASSIGNMENTOP.$encPwdPath.LINEFEED; if($encryptionType === $privateEncryptionKey){ $utfFile .= $hashEvsParameters['PVTKEY'].ASSIGNMENTOP.$encPvtkeyPath.LINEFEED; } $restorelocation = getRestoreLocation(); $utfFile .= $hashEvsParameters['ADDPROGRESS'].LINEFEED. $hashEvsParameters['PROXY'].ASSIGNMENTOP.$proxyString.LINEFEED. $hashEvsParameters['ENCODE'].LINEFEED. $hashEvsParameters["XMLOUTPUT"].LINEFEED; if($backupType == NORELATIVE){ $utfFile .= NORELATIVE.LINEFEED; } $utfFile .= $deDupDeviceId; $utfFile .= $hashEvsParameters['OUTPUT'].ASSIGNMENTOP.OUTPUTFILE.$engineID.LINEFEED. $hashEvsParameters['ERROR'].ASSIGNMENTOP.ERRORFILE.$engineID.LINEFEED. $username.$serverAddressOperator. $serverAddress.$serverNameOperator. $serverName.$paramHash["source"].LINEFEED. $restorelocation.LINEFEED; fwrite($UTF8FILE, $utfFile); fclose($UTF8FILE); @chmod($bck_res_utf8,PERMISSIONVAL); $filename = explode("/",$RestoresetFile); traceLog("$operationType has been executed for $filename[1]\n"); return $bck_res_utf8; } else if($operationType == LOCALRESTORE){ $RestoresetFile = $paramHash["backupsetFile"]; $destPath = $hostNameLB."/$username".$paramHash["source"]; if(!($UTF8FILE = fopen($bck_res_utf8, "w"))){ traceLog("Unable to open file $bck_res_utf8 for restore, Reason: ".customErrorMsg()); } $utfFile = $hashEvsParameters['FROMFILE'].ASSIGNMENTOP.$RestoresetFile.LINEFEED. $hashEvsParameters['TYPE'].LINEFEED. $hashEvsParameters['PASSWORD'].ASSIGNMENTOP.$encPwdPath.LINEFEED; if($encryptionType === $privateEncryptionKey){ $utfFile .= $hashEvsParameters['PVTKEY'].ASSIGNMENTOP.$encPvtkeyPath.LINEFEED; $utfFile .= $hashEvsParameters['LOCALAUTH'] . ASSIGNMENTOP . '0' . LINEFEED; } else { $utfFile .= $hashEvsParameters['LOCALAUTH'] . ASSIGNMENTOP . '1' . LINEFEED; } $restorelocation = getRestoreLocation(); $utfFile .= $hashEvsParameters['ADDPROGRESS'].LINEFEED. $hashEvsParameters['PROXY'].ASSIGNMENTOP.$proxyString.LINEFEED. $hashEvsParameters['ENCODE'].LINEFEED. $hashEvsParameters["XMLOUTPUT"].LINEFEED; if($backupType == NORELATIVE){ $utfFile .= NORELATIVE.LINEFEED; } $utfFile .= $hashEvsParameters['OUTPUT'].ASSIGNMENTOP.OUTPUTFILE.$engineID.LINEFEED. $hashEvsParameters['ERROR'].ASSIGNMENTOP.ERRORFILE.$engineID.LINEFEED. $hashEvsParameters['MASKNAME'].LINEFEED. $hashEvsParameters['ENCOPT'].LINEFEED. $hashEvsParameters['PORTABLE'].LINEFEED. $hashEvsParameters['PORTABLEDEST'].ASSIGNMENTOP.$destPath.LINEFEED. $username.$serverAddressOperator. $serverAddress.$serverNameOperator. $serverName.$destPath.LINEFEED. $restorelocation.LINEFEED; fwrite($UTF8FILE, $utfFile); fclose($UTF8FILE); @chmod($bck_res_utf8, PERMISSIONVAL); $filename = explode("/",$RestoresetFile); traceLog("$operationType has been executed for $filename[1]\n"); return $bck_res_utf8; } else if($operationType == SEARCH){ $searchUtfPath = "utf8.txt"; $searchPatteren = $paramHash["searchPatteren"]; if(!($UTF8FILE = fopen($searchUtfPath, "w"))){ traceLog("Unable to open file $searchUtfPath for auth list, Reason: ".customErrorMsg()); } $utfFile = $hashEvsParameters['PASSWORD'].ASSIGNMENTOP.$encPwdPath.LINEFEED; if($trash == 1){ $utfFile .= "--trash".LINEFEED; } $utfFile .= $deDupDeviceId; $utfFile .= $hashEvsParameters['PROXY'].ASSIGNMENTOP.$proxyString.LINEFEED. $hashEvsParameters['ENCODE'].LINEFEED. $hashEvsParameters['OUTPUT'].ASSIGNMENTOP.OUTPUTFILE.LINEFEED. $hashEvsParameters['ERROR'].ASSIGNMENTOP.ERRORFILE.LINEFEED. $hashEvsParameters['SEARCH'].LINEFEED. $hashEvsParameters["XMLOUTPUT"].LINEFEED; # in case of resore search. # Note: this should be implement with archive cleanup. if($paramHash["searchForRestore"] == SEARCH_FOR_RESTORE){ $utfFile .= $hashEvsParameters['FILE'].LINEFEED; if($deDup && $restoreDeviceID!=''){ //$utfFile .= $hashEvsParameters["DEVICE_ID"].ASSIGNMENTOP.$restoreDeviceID.LINEFEED; $searchPatteren .= "/"; } else $searchPatteren .= "/*"; } $utfFile .= $username.$serverAddressOperator. $serverAddress.$serverNameOperator. $serverName.PATHSEPARATOR.$searchPatteren.LINEFEED; fwrite($UTF8FILE, $utfFile); fclose($UTF8FILE); @chmod($searchUtfPath, PERMISSIONVAL); traceLog("$operationType has been executed\n"); return $bck_res_utf8; } else if($operationType == PROPERTIES){ if(!($UTF8FILE = fopen($utfPath, "w"))){ traceLog("Unable to open file $utfPath for properties, Reason: ".customErrorMsg()); } $utfFile = $hashEvsParameters['PASSWORD'].ASSIGNMENTOP.$encPwdPath.LINEFEED. $hashEvsParameters['PROPERTIES'].LINEFEED. $hashEvsParameters['PROXY'].ASSIGNMENTOP.$proxyString.LINEFEED. $hashEvsParameters['ENCODE'].LINEFEED. $hashEvsParameters['ERROR'].ASSIGNMENTOP.ERRORFILE.LINEFEED. $deDupDeviceId. $username.$serverAddressOperator. $serverAddress.$serverNameOperator. $serverName.$paramHash["itemPath"]."/"; /*if($deDup) $utfFile .= $hashEvsParameters["DEVICE_ID"].ASSIGNMENTOP.$deviceID.LINEFEED;*/ fwrite($UTF8FILE, $utfFile); fclose($UTF8FILE); } elseif($operationType == GETSERVERADDRESS) { $proxyData = ""; $authFilePath = "$userDir/.idriveAuthParams.txt"; if(file_exists($authFilePath) and 0 < customFileSize($authFilePath)){ $proxyData = getProxyToValidate(); # only this call was there } if(!($UTF8FILE = fopen($utfPath, "w"))){ traceLog("Unable to open file $utfPath Reason: ".customErrorMsg()); exit; } $utfFile = $hashEvsParameters["SERVERADDRESS"].LINEFEED. $username.LINEFEED. $hashEvsParameters["PASSWORD"].ASSIGNMENTOP.$encPwdPath.LINEFEED. $hashEvsParameters["PROXY"].ASSIGNMENTOP.$proxyData.LINEFEED. $hashEvsParameters["ENCODE"].LINEFEED. $hashEvsParameters["ERROR"].ASSIGNMENTOP.ERRORFILE.LINEFEED; fwrite($UTF8FILE, $utfFile); fclose($UTF8FILE); } else if($operationType == CREATECHECKSUM) { $checksumOutputFile = $currentDir.PATHSEPARATOR.CHECKSUMOUTPUTFILE; $checksumErrorFile = $currentDir.PATHSEPARATOR.CHECKSUMERRORFILE; $utfPath = $currentDir.PATHSEPARATOR."checkSum".UTFFILE.$engineID; if(!($UTF8FILE = fopen($utfPath, "w"))){ traceLog("Unable to open file $utfPath for $operationType, Reason: ".customErrorMsg()); } $utfFile = $hashEvsParameters["FROMFILE"].ASSIGNMENTOP.$paramHash["backupsetFile"].LINEFEED. $hashEvsParameters['PASSWORD'].ASSIGNMENTOP.$encPwdPath.LINEFEED; if($encryptionType === $privateEncryptionKey) $utfFile .= $hashEvsParameters["PVTKEY"].ASSIGNMENTOP.$encPvtkeyPath.LINEFEED; $utfFile .= $hashEvsParameters['CREATE_CHK'].LINEFEED. $hashEvsParameters['PROXY'].ASSIGNMENTOP.$proxyString.LINEFEED. $hashEvsParameters['ENCODE'].LINEFEED. $hashEvsParameters['OUTPUT'].ASSIGNMENTOP.$checksumOutputFile.LINEFEED. $hashEvsParameters['ERROR'].ASSIGNMENTOP.$checksumErrorFile.LINEFEED. $hashEvsParameters['SERVER_ROOT'].ASSIGNMENTOP.$serverRoot.LINEFEED. $username.$serverAddressOperator. $serverAddress.$serverNameOperator.$serverName; fwrite($UTF8FILE, $utfFile); fclose($UTF8FILE); } else if($operationType == MDTCHECK) { $mdtCheckOutputFile = $currentDir.PATHSEPARATOR.MDTCHECKOUTPUTFILE; $mdtCheckErrorFile = $currentDir.PATHSEPARATOR.MDTCHECKERRORFILE; $utfPath = $currentDir.PATHSEPARATOR."mdtCheck".UTFFILE.$engineID; if(!($UTF8FILE = fopen($utfPath, "w"))){ traceLog("Unable to open file $utfPath for properties, Reason: ".customErrorMsg()); } $utfFile = $hashEvsParameters["FROMFILE"].ASSIGNMENTOP.$paramHash["backupsetFile"].LINEFEED. $hashEvsParameters['PASSWORD'].ASSIGNMENTOP.$encPwdPath.LINEFEED; if($encryptionType === $privateEncryptionKey) $utfFile .= $hashEvsParameters["PVTKEY"].ASSIGNMENTOP.$encPvtkeyPath.LINEFEED; $utfFile .= $hashEvsParameters['MDT_CHECK'].LINEFEED. $hashEvsParameters['PROXY'].ASSIGNMENTOP.$proxyString.LINEFEED. $hashEvsParameters['ENCODE'].LINEFEED. $hashEvsParameters['OUTPUT'].ASSIGNMENTOP.$mdtCheckOutputFile.LINEFEED. $hashEvsParameters['ERROR'].ASSIGNMENTOP.$mdtCheckErrorFile.LINEFEED. $deDupDeviceId = $hashEvsParameters["DEVICE_ID"].ASSIGNMENTOP.$deviceID.LINEFEED. $username.$serverAddressOperator. $serverAddress.$serverNameOperator.$serverName; fwrite($UTF8FILE, $utfFile); fclose($UTF8FILE); } else if($operationType == LISTDEVICE) { $encTypeFromLoginCgi = ($paramHash["enctype"] == "PRIVATE")?"Private":$paramHash["enctype"]; $utfPath = $currentDir.PATHSEPARATOR."listDevice".UTFFILE; if(!($UTF8FILE = fopen($utfPath, "w"))){ traceLog("Unable to open file $utfPath for properties, Reason: ".customErrorMsg()); } $utfParam = $hashEvsParameters["LISTDEVICE"].LINEFEED. $hashEvsParameters["PASSWORD"].ASSIGNMENTOP.$encPwdPath.LINEFEED. $hashEvsParameters["PROXY"].ASSIGNMENTOP.$proxyString.LINEFEED. $hashEvsParameters["ENCODE"].LINEFEED; if(($encTypeFromLoginCgi == $encryptionType) && ($encryptionType === $privateEncryptionKey)) $utfParam .= $hashEvsParameters["PVTKEY"].ASSIGNMENTOP.$encPvtkeyPath.LINEFEED; $utfParam .= $username.$serverAddressOperator. $serverAddress.$serverNameOperator.$serverName.LINEFEED; fwrite($UTF8FILE, $utfParam); fclose($UTF8FILE); } else if($operationType == CREATEDIR) { $encTypeFromLoginCgi = ($paramHash["enctype"] == "PRIVATE")?"Private":$paramHash["enctype"]; $utfPath = $currentDir.PATHSEPARATOR."createDir".UTFFILE; if(!($UTF8FILE = fopen($utfPath, "w"))){ traceLog("Unable to open file $utfPath for properties, Reason: ".customErrorMsg()); } $utfParam = $hashEvsParameters["CREATEDIR"].ASSIGNMENTOP.$paramHash["directoryName"].LINEFEED. $hashEvsParameters["PASSWORD"].ASSIGNMENTOP.$encPwdPath.LINEFEED. $hashEvsParameters["PROXY"].ASSIGNMENTOP.$proxyString.LINEFEED. $hashEvsParameters["ENCODE"].LINEFEED; //if($encryptionType === $privateEncryptionKey) if(($encTypeFromLoginCgi == $encryptionType) && ($encryptionType === $privateEncryptionKey)) $utfParam .= $hashEvsParameters["PVTKEY"].ASSIGNMENTOP.$encPvtkeyPath.LINEFEED; $utfParam .= $username.$serverAddressOperator. $serverAddress.$serverNameOperator.$serverName.LINEFEED; fwrite($UTF8FILE, $utfParam); fclose($UTF8FILE); } else if($operationType == BACKUPLOG){ $utfPath = $currentDir.PATHSEPARATOR."backupLog".UTFFILE; if(!($UTF8FILE = fopen($utfPath, "w"))){ traceLog("Unable to open file $utfPath Reason: ".customErrorMsg()); exit; } $utfFile = $hashEvsParameters["FROMFILE"].ASSIGNMENTOP.$paramHash["backupsetFile"].LINEFEED. $hashEvsParameters["BACKUPLOG"].LINEFEED. $hashEvsParameters["TYPE"].LINEFEED. $hashEvsParameters["PASSWORD"].ASSIGNMENTOP.$encPwdPath.LINEFEED; if($encryptionType === $privateEncryptionKey) $utfFile .= $hashEvsParameters["PVTKEY"].ASSIGNMENTOP.$encPvtkeyPath.LINEFEED; if($deDup) $utfFile .= $deDupDeviceId; $utfFile .= $hashEvsParameters["PROXY"].ASSIGNMENTOP.$proxyString.LINEFEED. $hashEvsParameters["ENCODE"].LINEFEED. $hashEvsParameters["OUTPUT"].ASSIGNMENTOP.OUTPUTFILE.$engineID.LINEFEED. $hashEvsParameters["ERROR"].ASSIGNMENTOP.ERRORFILE.$engineID.LINEFEED. NORELATIVE.LINEFEED. $hashEvsParameters["XMLOUTPUT"].LINEFEED. $paramHash["source"].LINEFEED. $username.$serverAddressOperator. $serverAddress.$serverNameOperator. $serverName.PATHSEPARATOR.BACKUP_RESTORE_LOGS_DO_NOT_DELETE.PATHSEPARATOR.$paramHash["backupLocation"].LINEFEED; fwrite($UTF8FILE, $utfFile); fclose($UTF8FILE); @chmod($utfPath, PERMISSIONVAL); traceLog("$operationType has been executed\n"); return $utfPath; } else if($operationType == AUTHLIST){ $authlistOutputFile = $currentDir.PATHSEPARATOR.AUTHLISTOUTPUTFILE; $authlistErrorFile = $currentDir.PATHSEPARATOR.AUTHLISTERRORFILE; $utfPath = $currentDir.PATHSEPARATOR.AUTHLIST.UTFFILE; if(!($UTF8FILE = fopen($utfPath, "w"))){ traceLog("Unable to open file $utfPath Reason: ".customErrorMsg()); exit; } $utfFile = $hashEvsParameters["AUTHLIST"].LINEFEED. $hashEvsParameters["TYPE"].LINEFEED. $hashEvsParameters["PASSWORD"].ASSIGNMENTOP.$encPwdPath.LINEFEED; if($encryptionType === $privateEncryptionKey) $utfFile .= $hashEvsParameters["PVTKEY"].ASSIGNMENTOP.$encPvtkeyPath.LINEFEED; if($deDup) $utfFile .= $deDupDeviceId; $utfFile .= $hashEvsParameters['PROXY'].ASSIGNMENTOP.$proxyString.LINEFEED. $hashEvsParameters['ENCODE'].LINEFEED. $hashEvsParameters['OUTPUT'].ASSIGNMENTOP.$authlistOutputFile.LINEFEED. $hashEvsParameters['ERROR'].ASSIGNMENTOP.$authlistErrorFile.LINEFEED. $username.$serverAddressOperator. $serverAddress.$serverNameOperator.$serverName.$paramHash["source"].LINEFEED; file_put_contents("/tmp/testauthlist.txt", "\n UTF file content : ".$utfFile, FILE_APPEND); fwrite($UTF8FILE, $utfFile); fclose($UTF8FILE); } else { traceLog("Invalid Operation Type For Utf8 File"); } @chmod($utfPath,PERMISSIONVAL); traceLog("$operationType has been executed\n"); return $utfPath; } #****************************************************************************************************************** # Subroutine Name : getDirList. # Objective : get one level listing of particular dir path # Added By : Pooja Havaldar #******************************************************************************************************************/ function getDirList($ArchiveJobPath) { $files_list = array(); $files_list = scandir($ArchiveJobPath); return $files_list; } /************************************************************************************************ * Subroutine Name : getMachineDetails * Objective : Prepare the NAS machine details * Added By : Yogesh Kumar * Modified By : Senthil Pandian ************************************************************************************************/ 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 TWOTIER: $machineDetails['cronCat'] = 'cat /etc/crontab'; $machineDetails['superuser'] = 'root'; break; } return $machineDetails; } return FALSE; } /************************************************************************************************ * Subroutine Name : getMachinePattern * Objective : Finding the machine by verifying the current code path * Added By : Yogesh Kumar * Modified By : Senthil Pandian ************************************************************************************************/ function getMachinePattern() { GLOBAL $machine; $filePatterns = array(); $filePatterns['/var/services/web'] = SYNOLOGY; $filePatterns['/var/services/web_packages'] = SYNOLOGY; $filePatterns['/share/Web'] = QNAP; $filePatterns['/share/Qweb'] = QNAP; $filePatterns['/apps/idrive/web'] = NETGEAR; $filePatterns['/usr/local/www'] = TWOTIER; $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){ if(file_exists($key."/".APPDIR) && dirname(dirname(__FILE__)) == readlink($key)."/".APPDIR) { // For APP Path customization $machinePattern = array($key, $machine); break; } } if($machine===NETGEAR){ if (dirname(dirname(dirname(__FILE__))) == $key){ $machinePattern = array($key, $machine); break; } } } if ($machinePattern == NULL) { return FALSE; } return $machinePattern; } /**************************************************************************************************** * Function Name : getExpressDBPath * Objective : This will map the device and express DB real path * Added By : Sabin Cheruvattil ******************************************************************************************************/ function getExpressDBPath() { GLOBAL $dedupDetailFile, $username, $userDir, $isLocalRestore, $localBackupLocationFile, $isLocalBackup; $expressDrive = readLocalBackupLocation(); $dedupdeviceID = ''; $dedupServerRoot = ''; if($isLocalRestore === 1) { $fileDetails = $localBackupLocationFile; } else { $fileDetails = $dedupDetailFile; } $expressDBMapPath = $expressDrive . PATHSEPARATOR . $username . PATHSEPARATOR . LDBNEW . PATHSEPARATOR; if(file_exists($fileDetails)) { $deviceArray = json_decode((is_readable($fileDetails)? file_get_contents($fileDetails) : ''), TRUE); $dedupdeviceID = trim($deviceArray['deviceID']); if($isLocalRestore !== 1) { $dedupdeviceID = preg_replace("/^5c0b/", '', $dedupdeviceID, 1); $dedupdeviceID = preg_replace("/4b5z$/", '', $dedupdeviceID, 1) . PATHSEPARATOR; $dedupServerRoot = preg_replace("/^5c0b/", '', trim($deviceArray['serverRoot']), 1); $dedupServerRoot = preg_replace("/4b5z$/", '', $dedupServerRoot, 1); } } if($isLocalBackup === 1) { if(file_exists($expressDBMapPath . "{$dedupServerRoot}/{$username}.ibenc")) { @unlink($expressDBMapPath . "{$dedupServerRoot}/{$username}.ibenc"); } } $mapFile = $expressDBMapPath . EXPRESSDBMAPFILE; if(!file_exists($mapFile)) { createExpressDBMap(); } $expressDBDir = file_get_contents($mapFile); $expressDBPath = $userDir . PATHSEPARATOR . EXPRESSDBDIRNAME . PATHSEPARATOR . $expressDBDir . PATHSEPARATOR . $dedupdeviceID . PATHSEPARATOR . $username . '.ibenc'; if(!file_exists($userDir . PATHSEPARATOR . EXPRESSDBDIRNAME) || !is_dir($userDir . PATHSEPARATOR . EXPRESSDBDIRNAME)) { mkdir($userDir . PATHSEPARATOR . EXPRESSDBDIRNAME . PATHSEPARATOR . $expressDBDir . PATHSEPARATOR . $dedupdeviceID, TRUE); @chmod($userDir . PATHSEPARATOR . EXPRESSDBDIRNAME, PERMISSIONVAL); @chmod($userDir . PATHSEPARATOR . EXPRESSDBDIRNAME . PATHSEPARATOR . $expressDBDir, PERMISSIONVAL); @chmod($userDir . PATHSEPARATOR . EXPRESSDBDIRNAME . PATHSEPARATOR . $expressDBDir . PATHSEPARATOR . $dedupdeviceID, PERMISSIONVAL); } return $expressDBPath; } /**************************************************************************************************** * Function Name : getSystemCpuCores * Objective : This function helps us to get the multiplication of total no.of processor and cpu cores * Added By : Vijay Vinoth ******************************************************************************************************/ function getSystemCpuCores(){ $cmd = "uname"; $OS = strtolower(trim(shell_exec($cmd))); $retVal = 2; $cmdCpuProcessor = ""; $cmdCpuCores = ""; $cpuCoreNo = 1; switch($OS){ case('linux'): $cmdCpuProcessor = "cat /proc/cpuinfo | grep processor | wc -l"; $cmdCpuCores = "grep 'cpu cores' /proc/cpuinfo"; break; case('freebsd'): $cmd = "sysctl -a | grep 'hw.ncpu' | cut -d ':' -f2"; break; default: unset($cmd); } if ($cmdCpuProcessor != ''){ $cpuProcessorNo = intval(trim(shell_exec($cmdCpuProcessor))); $cpuProcessorNo = empty($cpuProcessorNo) ? 1 : $cpuProcessorNo; $cpuCoreData = shell_exec($cmdCpuCores); if(!empty($cpuCoreData)) { $cpuCoreData = empty($cpuCoreData) ? 1 : $cpuCoreData; //$coreData = explode(PHP_EOL,$cpuCoreData)[0]; Commented for the issue in 15 machine: Senthil //$coreCount = trim(explode(":",$coreData)[1]); $exp = explode(PHP_EOL,$cpuCoreData); $coreData = $exp[0]; $exp = explode(":",$coreData); $coreCount = trim($exp[1]); $cpuCoreNo = empty($coreCount) ? 1 : $coreCount; } $totalCores = $cpuProcessorNo*$cpuCoreNo; $retVal = ($totalCores == 1 ? 2 : ($totalCores == 2 ? 4 : $totalCores)); } return $retVal; } /**************************************************************************************************** * Function Name : getExtendedASCIIChrOrd * Objective : This function generates the chr and ord for extended ascii * Added By : Sabin Cheruvattil ******************************************************************************************************/ function getExtendedASCIIChrOrd() { $asciiRange = array('10-11', '128-254'); #$asciiRange = array('10-11', '160-383'); $extAsciiOrd = array(); $extAsciiChr = array(); # add ord and chr of 9 & 16 here only to avoid unwanted condition in loop $extAsciiOrd[] = ' '; $extAsciiChr[] = chr(9); $extAsciiOrd[] = ' '; $extAsciiChr[] = chr(16); foreach($asciiRange as $range) { $rangeMap = explode('-', $range); for($i = (int)$rangeMap[0]; $i <= (int)$rangeMap[1]; $i++) { $extAsciiOrd[] = "&#{$i};"; $extAsciiChr[] = chr($i); } } return array('ord' => $extAsciiOrd, 'chr' => $extAsciiChr); } /**************************************************************************************************** * Function Name : getServerRoot * Objective : This function used to receive latest server root * Added By : Sabin Cheruvattil ******************************************************************************************************/ function getServerRoot($dbpaths,$localBackupLocationFile) { $deviceJSON = file_get_contents($localBackupLocationFile); $deviceArray = json_decode($deviceJSON, true); $deviceID = trim($deviceArray['deviceID']); $serverRoot = ""; if(file_exists($dbpaths)) { $xml = simplexml_load_file($dbpaths); foreach($xml->children() as $child) { $attr = $child->attributes(); if(trim($attr['deviceid']) == $deviceID) { $serverRoot = trim($attr['serverroot']); } } } return $serverRoot; } //-------------------------------------- H ------------------------------------------------ //-------------------------------------- I ------------------------------------------------ /************************************************************************************************ * Subroutine Name : isFileLocked * Objective : To find out whether the given file is locked or not. * Added By : Pooja Havaldar * Modified By : * Modified On : ************************************************************************************************/ function isFileLocked($fileName) { if(!file_exists($fileName)){ return false; } $handle = fopen($fileName,'a+'); if(!flock($handle,LOCK_EX|LOCK_NB)){ #flock returns false if file is already locked. fclose($handle); return true; } fclose($handle); return false; } /************************************************************************************************ * Subroutine Name : isAnyEngineRunning * Objective : To find out whether the given file is un locked or not. * Added By : Vijay Vinoth * Modified By : * Modified On : ************************************************************************************************/ function isAnyEngineRunning($fileName) { $handle = fopen($fileName,'a+'); if(!flock($handle,LOCK_EX|LOCK_NB)){ #flock returns false if file is already locked. fclose($handle); return true; } flock($handle, LOCK_UN); fclose($handle); return false; } /************************************************************************************************ * Subroutine Name : isEngineRunning * Objective : To check if current engine in progress * Added By : Vijay Vinoth * Modified By : * Modified On : ************************************************************************************************/ function isEngineRunning($pidProcessFile) { $returnData = true; if(!file_exists($pidProcessFile)) return false; $fp=fopen($pidProcessFile, "a"); if($fp){ if(flock($fp, LOCK_EX|LOCK_NB)){ flock($fp, LOCK_UN); $returnData = false; } fclose($fp); return $returnData; } return false; } //-------------------------------------- J ------------------------------------------------ //-------------------------------------- K ------------------------------------------------ //-------------------------------------- L ------------------------------------------------ /************************************************************************************************ * Subroutine Name : loadMachineConfigurations * Objective : Load the NAS machine configurations. * Added By : Yogesh Kumar * Modified By : Senthil Pandian ************************************************************************************************/ function loadMachineConfigurations() { GLOBAL $machine; $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 $configFileContent = ("webDir " . $_SESSION['webDir'] . "\n"); $configFileContent .= ("user " . $_SESSION['nasUser'] . "\n"); $configFileContent .= ("machine " . $_SESSION['machine'] . "\n"); $configFileContent .= ("cronCat " . $machineDetails['cronCat'] . "\n"); $configFile = dirname(dirname(__FILE__)).PATHSEPARATOR.CONFIG.PATHSEPARATOR.CONFIG_FILE; file_put_contents($configFile, $configFileContent); @chmod($configFile,PERMISSIONVAL); return TRUE; } /************************************************************************************************ * Subroutine Name : loadMachineAppCenterDetails * Objective : Load the NAS App Center Details. * Added By : Vijay Vinoth ************************************************************************************************/ function loadMachineAppCenterDetails() { GLOBAL $machine; switch($machine) { case SYNOLOGY: $appCenterDetail = 'Package Center'; break; case QNAP: $appCenterDetail = 'App Center'; break; case NETGEAR: $appCenterDetail = 'Apps'; break; case ASUSTOR: $appCenterDetail = 'App Central'; break; } return $appCenterDetail; } //-------------------------------------- M ------------------------------------------------ //-------------------------------------- N ------------------------------------------------ //-------------------------------------- O ------------------------------------------------ //-------------------------------------- P ------------------------------------------------ /********************************************************************************************************* * Subroutine Name : phpQuoteMeta * Objective : Perl quotemeta replacement in PHP * Added By : Sabin Cheruvattil | 2016-11-30 **********************************************************************************************************/ function phpQuoteMeta($pattern) { //return quotemeta($pattern); //return addcslashes($pattern, '\-^$.[]|()?*+{} //'); return preg_quote($pattern, '/'); } #**************************************************************************************************** # Subroutine Name : parseXMLOutput. # Objective : Parse evs command output. # Added By : Arnab Gupta. #*****************************************************************************************************/ function parseXMLOutput(&$commandOutput, &$totalquota, &$pattern) { /* if(!empty($commandOutput) and $commandOutput != ""){ if(preg_match("/$pattern/", $commandOutput)){ if($' =~ m/"[^"]+"/){ my $paramVal = $&; $paramVal =~ s/^.//; $paramVal =~ s/.$//; ${$_[1]} = $paramVal; } } } */ } //-------------------------------------- Q ------------------------------------------------ //-------------------------------------- R ------------------------------------------------ #**************************************************************************************************** # Subroutine Name : readLocalBackupLocation. # Objective : Reads the local backup location from file # Added By : Pooja H # Modified By : Senthil Pandian #*****************************************************************************************************/ function readLocalBackupLocation() { GLOBAL $localBackupLocationFile; if(!file_exists($localBackupLocationFile)){ traceLog("\n $localBackupLocationFile doesn't exist. Reason : ".customErrorMsg()); return false; } $deviceArray = json_decode(file_get_contents($localBackupLocationFile), true); $hostNameLB = trim($deviceArray['hostName']); return $hostNameLB; } #**************************************************************************************************** # Subroutine Name : readFinalStatus. # Objective : reads the status file # Added By : Deepak Chaurasia # Modified By : Senthil Pandian #*****************************************************************************************************/ function readFinalStatus() { GLOBAL $totalEngineBackup; $statusFinalHash = array(); for($i=1; $i<= $totalEngineBackup; $i++){ $statusFileHash = array(); $statusFileHash = readStatusFile($i); $statusFinalHash['FILES_COUNT_INDEX'] += $statusFileHash['FILES_COUNT_INDEX']; $statusFinalHash['SYNC_COUNT_FILES_INDEX'] += $statusFileHash['SYNC_COUNT_FILES_INDEX']; $statusFinalHash['FAILED_COUNT_FILES_INDEX'] += $statusFileHash['FAILED_COUNT_FILES_INDEX']; if(!$statusFinalHash['EXIT_FLAG_INDEX'] or !empty($statusFinalHash['EXIT_FLAG_INDEX'])) $statusFinalHash['EXIT_FLAG_INDEX'] = $statusFileHash['EXIT_FLAG_INDEX']; } return $statusFinalHash; } #**************************************************************************************************** # Subroutine Name : readStatusFile. # Objective : reads the status file # Added By : Deepak Chaurasia # Modified By : Senthil Pandian #*****************************************************************************************************/ function readStatusFile($engineID = '') { $statusFileHash = array(); $statusFile = STATUSFILE."_$engineID"; if(file_exists($statusFile) && fileSize($statusFile)>0){ $file = fopen($statusFile ,"r"); if($file) { while(! feof($file)) { $line = trim(fgets($file)); $keyValuePair = preg_split('/=/',$line); if(count($keyValuePair)>=2){ $keyValuePair[0]=trim($keyValuePair[0]); $statusFileHash[$keyValuePair[0]] = trim($keyValuePair[1]); } } fclose($file); } else { traceLog("Unable to open file ".STATUSFILE.", Reason:".customErrorMsg()); } } return $statusFileHash; } #**************************************************************************************************** # Subroutine Name : readBackupLocation. # Objective : Reads the backup location from file # Added By : Deepak Chaurasia #*****************************************************************************************************/ function readBackupLocation() { GLOBAL $userDir, $machine; $mpcName = ""; $mpcFile = "$userDir/mpc.txt"; if(file_exists($mpcFile)){ $mpc = fopen($mpcFile, "r"); if($mpc){ $mpcName = fread($mpc,customFileSize($mpcFile)); fclose($mpc); } else traceLog("Unable to open file : $mpcFile, Reason:".customErrorMsg()); } elseif((TWOTIER == $machine || SYNOLOGY == $machine) and file_exists("/".MPC_FILE)){ $mpc = fopen("/".MPC_FILE, "r"); if($mpc){ $mpcName = fread($mpc,customFileSize("/".MPC_FILE)); fclose($mpc); $mpcName = "/".$mpcName; } else traceLog("Unable to open file : ".MPC_FILE.", Reason:$php_errormsg"); } if(empty($mpcName)){ $mpcName = `hostname`; chop($mpcName,"\n"); } return $mpcName; } #****************************************************************************************************************** # Subroutine Name : readFromUserCancel. # Objective : read cancel.txt to write job cancel message in log # Added By : Avinash Kumar. #******************************************************************************************************************/ function readFromUserCancel() { $cancelMsg = ""; if(file_exists(CANCEL_PATH)) $cancelMsg = file_get_contents(CANCEL_PATH); return $cancelMsg; } #**************************************************************************************************** # Subroutine Name : readAccountSettingsFile. # Objective : Reads the entire Account Settings File. # Added By : Arnab Gupta. #*****************************************************************************************************/ function readAccountSettingsFile() { GLOBAL $linesAccountSettingsFile, $userDir; $accountSettingPath = "$userDir/ACCOUNT_SETTINGS_FILE"; if(file_exists($accountSettingPath) === TRUE) { $linesAccountSettingsFile = json_decode(file_get_contents($accountSettingPath),TRUE); if (json_last_error() !== JSON_ERROR_NONE) { $linesAccountSettingsFileData = file($accountSettingPath); $accountSettingsData = array(); foreach($linesAccountSettingsFileData as $line){ $keyValuePair = preg_split('/=/', $line); $accountSettingsData[trim($keyValuePair[0])] = trim($keyValuePair[1]); } $accountSettingsData['engineCount'] = "4"; if(($file = fopen($accountSettingPath, "a+")) != FALSE) { ftruncate($file, 0); fwrite($file, json_encode($accountSettingsData,TRUE)); fclose($file); @chmod($accountSettingPath, PERMISSIONVAL); } $linesAccountSettingsFile = $accountSettingsData; } return $linesAccountSettingsFile; } } //-------------------------------------- S ------------------------------------------------ #****************************************************************************************************************** # Subroutine Name : sendMail. # Objective : This subroutine sends a mail to the user in case of successful/cancelled/failed backup # Added By : Arnab Gupta # Modified By : Deepak Chaurasia, Pooja Havaldar #******************************************************************************************************************/ function sendMail() { GLOBAL $username, $nasUsername; GLOBAL $operationName; GLOBAL $status; GLOBAL $headerMsg; GLOBAL $mailSummaryMsg; GLOBAL $taskType; GLOBAL $phpPath; GLOBAL $webDir; GLOBAL $jobrunningDir; $content = ""; $mailStatus = ""; if($taskType == MANUAL) return; trim($mailSummaryMsg,"\n"); $content = "Dear IDriveUser, \n\n"; $content .= "Ref: NAS Profile - $nasUsername, IDrive User name - $username \n\n"; $content .= $headerMsg.$mailSummaryMsg; $content .= "\n\nRegards,\nIDrive Support"; $content = str_replace("'","'\\''", $content); if($status == "SUCCESS") $mailStatus = "Successful $operationName"; elseif($status == "ABORTED") $mailStatus = "Cancelled $operationName"; else $mailStatus = "Failed $operationName"; $jobNameForMail = basename($jobrunningDir); $jobType = "$operationName"."_"; $cmd_mail = "$phpPath $webDir".PATHSEPARATOR.APPDIR.PATHSEPARATOR.CONFIG.PATHSEPARATOR.SENDMAILFILE." '$username' '$jobType' '$jobNameForMail' '$mailStatus' '$content'"; `$cmd_mail`; } //-------------------------------------- T ------------------------------------------------ #**************************************************************************************************** # Subroutine Name : traceLog # Objective : This function helps to add log # Added By : Sabin Cheruvattil [2016-05-10] # Modified By : Senthil Pandian #**************************************************************************************************** function traceLog($data = "", $trace = array(), $access = "", $tag = "traceLog_") { GLOBAL $mode, $webDir, $username, $httpuser, $userDir, $machine, $appVersion, $releaseDate; $trace_dir_name = '.trace'; $currVersion =''; if(!empty($appVersion)) $currVersion = trim(str_replace("Version","",$appVersion)); if($mode === 'debug' || $data == '') return; try { if(!is_array($trace) || empty($trace)) $trace = debug_backtrace(); $user = $httpuser; if((ASUSTOR == $machine) and ($user == 'root')){ $user = 'admin'; } $date = date("Y/m/d H:i:s"); $content = "[$date][".basename($trace[0]['file'])."][Line:".$trace[0]['line']."] ".trim($data)."\n"; $traceDir = $userDir . "/{$trace_dir_name}"; if(!is_dir($userDir)) { mkdir($userDir,PERMISSIONVAL); @chmod($userDir, PERMISSIONVAL); } if(!is_dir($traceDir)) { mkdir($traceDir, PERMISSIONVAL); @chmod($traceDir,PERMISSIONVAL); } $log_file = $traceDir . "/" . $tag . $currVersion . '.txt'; $log_file_back = $log_file . '_' . trim(shell_exec('date +"%a %b %d %T %Y"')); $lock_back_pattern = '/'.$tag.'*'; if(file_exists($log_file)) { if(customFileSize($log_file) >= MAX_LOG_FILE_SIZE * 1024 * 1024) { rename($log_file, $log_file_back); # The following code only needs to run when the log is getting renamed # as there will be un necesssary checks for the number of log files whenever log method is called $logs = glob($traceDir.$lock_back_pattern); if(count($logs) > MAX_LOG_FILE_COUNT) { while(count($logs) > MAX_LOG_FILE_COUNT) unlink(array_shift($logs)); } file_put_contents($log_file, "NAS Profile: ".$httpuser."\nIDrive User name: " . $username . "\n$appVersion\nRelease Date:$releaseDate\n"); } } else{ # The following code only needs to run when the log is getting renamed # as there will be un necesssary checks for the number of log files whenever log method is called $logs = glob($traceDir.$lock_back_pattern); if(count($logs) > MAX_LOG_FILE_COUNT) { while(count($logs) > MAX_LOG_FILE_COUNT) unlink(array_shift($logs)); } file_put_contents($log_file, "NAS Profile: ".$httpuser."\nIDrive User name: " . $username . "\n$appVersion\nRelease Date:$releaseDate\n"); } file_put_contents($log_file, $content, FILE_APPEND); @chmod($log_file,PERMISSIONVAL); } catch(Exception $e) {} } #**************************************************************************************************** # Subroutine Name : traceDBLog # Objective : This function helps to add DB log # Added By : Vijay Vinoth [2018-01-23] # Modified By : Senthil Pandian #**************************************************************************************************** function traceDBLog($data = "", $trace = array(), $access = "") { traceLog($data = "", $trace = array(), $access = "", "traceDBLog_"); } //-------------------------------------- U ------------------------------------------------ #****************************************************************************************************************** # Subroutine Name : updateLogFileName. # Objective : This subroutine renames backup log file and update new name to logpid.txt. # Added By : Pooja Havaldar # Modified By : Avinash Kumar #******************************************************************************************************************/ function updateLogFileName() { GLOBAL $logOutputFilePath; GLOBAL $status; $currPath = `pwd`; $currPath = trim($currPath); $newName = "$currPath/$logOutputFilePath"."_".$status; $logPidHandler = fopen(LOGPIDFILE, 'a+'); if (!flock($logPidHandler,LOCK_EX)) { flock($logPidHandler,LOCK_UN); } $resCmd = "mv \"$logOutputFilePath\" \"$newName\""; $res = `$resCmd`; $logOutputFilePath = $newName; file_put_contents(LOGPIDFILE,$newName); chmod(LOGPIDFILE, PERMISSIONVAL); } #****************************************************************************************************************** # Subroutine Name : updateProgressFile. # Objective : Update the progess file. # Added By : Avinash Kumar # Modified By : Senthil Pandian #******************************************************************************************************************/ function updateProgressFile($type, $fileName, $size, $curTransferedSize, $rateOfTransfer, $opStartTime, $offset, $percentage, $progressPath) { GLOBAL $totalSize; if($fileName == '' || $size == '' || $type == '') { return; } if("calculating" == $totalSize && file_exists(TOTAL_SIZE_PATH) && customFileSize(TOTAL_SIZE_PATH) > 0) { $totalSize = trim(file_get_contents(TOTAL_SIZE_PATH)); } file_put_contents($progressPath,"$type\n$fileName\n$size\n$curTransferedSize\n$rateOfTransfer\n$totalSize\n$opStartTime\n$offset\n$percentage"); } #**************************************************************************************************** # Subroutine Name : updateServerAddr. # Objective : Construction of get-server address evs command and execution. # Parse the output and update same in Account Setting File. # Added By : Vijay Vinoth. #*****************************************************************************************************/ function updateServerAddr($engineID = "") { GLOBAL $username, $serverAddr, $linesAccountSettingsFile, $userDir; $arrOutput = array(FALSE); $data = "username=".rawurlencode($username)."&password=".rawurlencode(base64_decode($linesAccountSettingsFile['password'])); $shareOutputArr = getCurlOutput(getHash("01"), $data); $validOutput = $shareOutputArr['output']; $validOutput = str_replace('', '', $validOutput); $xml = simplexml_load_string($validOutput); $xmlArray = $xml->login; $status = ""; if(isset($xmlArray['accstat']) && ($xmlArray['accstat'] == "C")) { $status = "account has been cancelled"; }elseif(isset($xmlArray['accstat']) && ($xmlArray['accstat'] == "M")) { $status = "account is under maintenance"; }elseif(isset($xmlArray['accstat']) && ($xmlArray['accstat'] == "B")) { $status = "account has been blocked"; }else if(isset($xmlArray['accstat']) && ($xmlArray['accstat'] == "Y")){ $status = "active"; if(isset($xmlArray['message']) && isset($xmlArray['evssrvrip']) && ($xmlArray['message'] == "SUCCESS")){ $serverAddr = ''; $arrOutput = array(TRUE, (string)$xmlArray['evssrvrip']); $serverAddr = $arrOutput; /* Update evs server address in .serverAddr.txt */ $file = $userDir.PATHSEPARATOR.SERVER_ADDR_PATH; file_put_contents($file, (string)$xmlArray['evssrvrip']); @chmod($file, PERMISSIONVAL); } } updateUserStatus($status); if($status != "active") { $wdir = "web"; if($machine == SYNOLOGY) { $ver = getSynoDSMVersion(); $wdir .= (($ver >= 7)? '_packages' : ''); } $logoutTrigger = "/var/services/".$wdir."/IDrive/appWasStopped.txt"; if(file_exists($logoutTrigger)) file_put_contents($logoutTrigger, "Need to logout app"); } return $arrOutput; } /**************************************************************************************************** * Function Name : updateUserStatus * Objective : This is to update account status to descide whether it is active or cancelled. * Added By : Anil Kumar ******************************************************************************************************/ function updateUserStatus($val) { GLOBAL $linesAccountSettingsFile, $userDir; $accountSettingPath = "$userDir/ACCOUNT_SETTINGS_FILE"; $linesAccountSettingsFileData = json_decode(file_get_contents($accountSettingPath),TRUE); $linesAccountSettingsFileData['userAccountStatus'] = $val; if(($file = fopen($accountSettingPath, "a+")) != FALSE) { ftruncate($file, 0); fwrite($file, json_encode($linesAccountSettingsFileData,TRUE)); fclose($file); @chmod($accountSettingPath, PERMISSIONVAL); } return 0; } /**************************************************************************************************** * Function Name : getCurlOutput. * Objective : Get response from third party API using cURL * Added By : Senthil Pandian ******************************************************************************************************/ function getCurlOutput($path,$postVars=''){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $path); curl_setopt($ch, CURLOPT_FAILONERROR,1); curl_setopt($ch, CURLOPT_TIMEOUT, 300); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_FOLLOWLOCATION,false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); if($postVars!='') curl_setopt($ch, CURLOPT_POSTFIELDS,$postVars); $proxyString = getProxyString(); if($proxyString == ""){ curl_setopt($ch, CURLOPT_PROXY, $proxyString); // curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth); } curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $retValue = curl_exec($ch); $server_error = curl_error($ch); curl_close($ch); $status = true; if(trim($server_error) != '') { $status = false; //Scheduler::Log("curl_error: " . $server_error ); Scheduler::Log("Curl output: ".$retValue. " Curl error: ".$server_error); } return array('status'=>$status, 'output' => $retValue, 'error' => $server_error); } #****************************************************************************************************************** # Subroutine Name : updateStatusFile. # Objective : Read file and made some changes and overwrite to that file. # Added By : Vijay Vinoth. #******************************************************************************************************************/ function updateStatusFile($failedfiles_index) { $retVal = false; $status_file = file(STATUSFILE); if($status_file){ $status_file[3] = "FILE_COUNT_INDEX = $failedfiles_index \n"; file_put_contents(STATUSFILE, implode("", $status_file)); @chmod(STATUSFILE, PERMISSIONVAL); $retVal = true; }else{ traceLog("update Status file function failed. Reason : ".customErrorMsg()); } return $retVal; } #****************************************************************************************************************** # Subroutine Name : updateRetryCount. # Objective : This subroutine update retry count based on any success backup/sync. # Added By : Vijay Vinoth. #******************************************************************************************************************/ function updateRetryCount($engineID = "") { GLOBAL $retrycount, $prevFailedCount; $curFailedCount = 0; list($curFailedCount) = getParameterValueFromStatusFile(array("FAILED_COUNT_FILES_INDEX")); if((!file_exists("LimitedRetry.txt")) && ($curFailedCount < $prevFailedCount)) $retrycount = 0; else $retrycount++; # assign the latest backuped and synced value to prev. $prevFailedCount = $curFailedCount; } //-------------------------------------- V ------------------------------------------------ //-------------------------------------- W ------------------------------------------------ #********************************************************************************************************** # Subroutine Name : waitForEVS # Objective : This function will continuously check for any error in error.txt and exit from childprocess. # Added By : Pooja Havaldar #**********************************************************************************************************/ function waitForEVS($processPid, $needErrorScan, $engineID='') { $prevErrorSize = ""; while(1){ if(! file_exists("/proc/$processPid")) return; #Child is still running. if($needErrorScan == SCANERRORFILE){ if(checkErrorFile($prevErrorSize,$engineID)) break; } sleep(3); } return; } #**************************************************************************************************** # Subroutine Name : waitForProcess. # Objective : wait for the given process id and also scan error file for process if # needFileScan is true. # Added By : Deepak Chaurasia #****************************************************************************************************/ function waitForProcess($pid, $needFileScan, $engineID='') { if( extension_loaded('pcntl') && function_exists('pcntl_waitpid') ){ pcntl_waitpid($pid,$status); } else{ waitForEVS($pid, $needFileScan, $engineID); } } #**************************************************************************************************** # Subroutine Name : writeBackupErrorMsgToStatusFile. # Objective : append errStr message to STATUS_FILE file. # Added By : Avinash Kumar # Modified By : Senthil Pandian #****************************************************************************************************/ function writeBackupErrorMsgToStatusFile($errStr = '', $engineID = '') { $Backupcount = 0; $Synccount = 0; $failedcount = 0; $failed_index = 0; # read the restore, sync, error count and restore termination status from status file $statusFile = STATUSFILE; if($engineID != '') $statusFile = STATUSFILE."_$engineID"; if(file_exists($statusFile)) list($Backupcount, $Synccount, $failedcount, $failed_index, $exit_flag_data) = getParameterValueFromStatusFile(array('FILES_COUNT_INDEX', 'SYNC_COUNT_FILES_INDEX', 'FAILED_COUNT_FILES_INDEX', 'FILE_COUNT_INDEX', 'EXIT_FLAG_INDEX')); try{ if($exit_flag_data == 0){ $errStr = trim($errStr); $exit_flag = "1-$errStr"; $status = "FILES_COUNT_INDEX = $Backupcount\n"; $status .= "SYNC_COUNT_FILES_INDEX = $Synccount\n"; $status .= "FAILED_COUNT_FILES_INDEX = $failedcount\n"; $status .= "FILE_COUNT_INDEX = $failed_index\n"; $status .= "EXIT_FLAG_INDEX = $exit_flag "; file_put_contents($statusFile, $status); @chmod($statusFile,PERMISSIONVAL); } } catch(Exception $e) { traceLog("Failed to open ".STATUSFILE.", Reason:".$e->getMessage()); return; } } #**************************************************************************************************** # Subroutine Name : writeOperationSummary # Objective : Writes the backup summary to the output file # Added By : Arnab Gupta. # Modified By : Pooja Havaldar #*****************************************************************************************************/ function writeOperationSummary($backupOpParam) { GLOBAL $filesConsideredCount, $totalFiles, $failedFiles, $failedFilesCount, $logOutputFilePath, $summaryMsg, $retrycount; GLOBAL $syncedFiles, $bacSync, $successFiles, $errStr, $mailSummaryMsg, $jobrunningDir, $backupEndTime; $backupEndTime = time(); $backupSetSize = trim(file_get_contents(TOTAL_SIZE_PATH)); $backupSetSize = humanReadableSize(trim($backupSetSize)); $backupSetSize = ($backupSetSize == "")?0:$backupSetSize; $retryCountDisplay = ($retrycount == 0)?0:($retrycount+1); $filesConsideredCount = $totalFiles; $failedFiles += $failedFilesCount; $excludeFile = $jobrunningDir.PATHSEPARATOR.TEMP_FILES.PATHSEPARATOR.EXCLUDE_FILE; $logOutputHandle = NULL; # open output.txt file to write restore summary. if(!($logOutputHandle = fopen($logOutputFilePath, "a"))){ traceLog("Unable to open file $logOutputFilePath, Reason:".customErrorMsg()); return; } if(file_exists($excludeFile) && filesize($excludeFile) > 0){ $mail_content =LINEFEED."_______________________________________________________________________________________"; $mail_content.=LINEFEED."|Excluded Items Report|".LINEFEED; $mail_content.="_______________________________________________________________________________________".LINEFEED; if(($backupOpParam == BACKUP)){ $mail_content .= LINEFEED.FILES_ARE_IN_EXCLUDE.LINEFEED; } $excludeData = file_get_contents($excludeFile); $mailSummaryMsg .= $mail_content.LINEFEED."$excludeData ".LINEFEED; $summaryMsg .= $mail_content.LINEFEED."$excludeData ".LINEFEED; } if($failedFiles <= 0) $failedFiles = 0; else $summaryMsg .= appendErrorFileContents(); trim($filesConsideredCount); # construct summary message. $summaryMsg .= LINEFEED.LINEFEED."Summary: ".LINEFEED; if($backupOpParam == BACKUP){ $syncedFiles = $syncedFiles + $bacSync; $backupSetEmpty = checkIfSetEmpty(BACKUPSETFORDISPLAY); $empty = ""; if($backupSetEmpty) { $empty = "\n\n Your backup set is empty.\n\n"; } $mailSummaryMsg = "Files considered for backup: $filesConsideredCount ".LINEFEED. "Files backed up now: $successFiles ".LINEFEED. "Files already present* in your account: $syncedFiles ".LINEFEED. "Files failed to backup: $failedFiles ".LINEFEED; $summaryMsg .= "$mailSummaryMsg ".LINEFEED."Backup Set Size: ".$backupSetSize .LINEFEED."Total retry attempts: $retryCountDisplay ".LINEFEED."Backup End Time: ".trim(shell_exec('date +"%a %b %d %T %Y"')).LINEFEED; $mailSummaryMsg .= $empty.LINEFEED."Backup Set Size: ".$backupSetSize .LINEFEED."Total retry attempts: $retryCountDisplay ".LINEFEED."Backup End Time: ".WHITESPACE.trim(shell_exec('date +"%a %b %d %T %Y"')).LINEFEED; } else{ $mailSummaryMsg = "Files considered for restore: $filesConsideredCount ".LINEFEED. "Files restored now: $successFiles ".LINEFEED. "Files already present: $syncedFiles ".LINEFEED. "Files failed to restore: $failedFiles ".LINEFEED; $summaryMsg .= "$mailSummaryMsg ".LINEFEED."Restore Set Size: ".$backupSetSize .LINEFEED."Total retry attempts: $retryCountDisplay ".LINEFEED."Restore End Time: ".WHITESPACE.trim(shell_exec('date +"%a %b %d %T %Y"')).LINEFEED; $mailSummaryMsg .= LINEFEED."Restore Set Size: ".$backupSetSize .LINEFEED."Total retry attempts: $retryCountDisplay ".LINEFEED."Restore End Time: ".WHITESPACE.trim(shell_exec('date +"%a %b %d %T %Y"')).LINEFEED; } if("" == $errStr && file_exists(OPERATION_SUMMERY_ERROR_FILE)) $errStr = trim(file_get_contents(OPERATION_SUMMERY_ERROR_FILE)); $errStr = trim($errStr, "\n"); if("" != $errStr){ $mailSummaryMsg .= LINEFEED."$errStr ".LINEFEED; $summaryMsg .= LINEFEED."$errStr ".LINEFEED; } if($failedFiles > 0 && file_exists(RETRY_ABORT_CAUSE)) { if(filesize(RETRY_ABORT_CAUSE) > 0){ $retryErrorCause = file_get_contents(RETRY_ABORT_CAUSE); $retryErrorCause = trim($retryErrorCause, "\n"); if("" != $retryErrorCause) $summaryMsg .= "\n" . $retryErrorCause . "\n"; } unlink(RETRY_ABORT_CAUSE); } if(($backupOpParam == BACKUP) && ("" == $errStr)) { if($failedFiles > 0) $summaryMsg .= LINEFEED.UNABLE_TO_CONTINUE_BACKUP.LINEFEED; $summaryMsg .= LINEFEED.FILES_ARE_IN_TRASH.LINEFEED; } fwrite($logOutputHandle, $summaryMsg); fclose($logOutputHandle); } #**************************************************************************************************** # Subroutine Name : writeParameterValuesToStatusFile # Objective : This subroutine writes the value of the specified parameter to the Status File # Added By : Senthil Pandian [12/01/2016] # Modified By : Vijay Vinoth #***************************************************************************************************** function writeParameterValuesToStatusFile($engineID) { GLOBAL $fileOperationCount, $fileSyncCount, $failedfiles_count, $exit_flag; $fileCount= 0; $Synccount = 0; $failedcount = 0; list($fileCount, $Synccount, $failedcount) = getParameterValueFromStatusFile(array('FILES_COUNT_INDEX', 'SYNC_COUNT_FILES_INDEX', 'FAILED_COUNT_FILES_INDEX'),$engineID); try { # Calculate the backup/restore, sync and error count based on new values $fileCount += $fileOperationCount; $Synccount += $fileSyncCount; $failedcount = $failedfiles_count; $content = "FILES_COUNT_INDEX = $fileCount \n"; $content .= "SYNC_COUNT_FILES_INDEX = $Synccount \n"; $content .= "FAILED_COUNT_FILES_INDEX = $failedcount\n"; $content .= "EXIT_FLAG_INDEX = $exit_flag"; file_put_contents(STATUSFILE."_$engineID",$content); @chmod(STATUSFILE."_$engineID",PERMISSIONVAL); } catch (Exception $e){ traceLog("Unable to open file ".STATUSFILE.". Reason:".$e->getMessage()); } } #**************************************************************************************************** # Subroutine Name : writeOperationErrorToErrorFile # Objective : Writes the Error message to OPERATION_SUMMERY_ERROR_FILE file # Added By : Vijay Vinoth #*****************************************************************************************************/ function writeOperationErrorToErrorFile($errStr){ file_put_contents(OPERATION_SUMMERY_ERROR_FILE,$errStr); } //-------------------------------------- X ------------------------------------------------ #**************************************************************************************************** # Function Name : customFileSizeFromLS # Objective : Calculates the file size # Added By : Anil Kumar. # Modified By : Sabin Cheruvattil #*****************************************************************************************************/ function customFileSizeFromLS($item) { GLOBAL $machine, $appPath; $cmd = ''; if($machine == NETGEAR) { $cmd = "$appPath/ls -aln ".escapeshellarg ($item); } else if($machine == QNAP || $machine == SYNOLOGY || $machine == ASUSTOR) { $cmd = "ls -aln ".escapeshellarg ($item); } else if($machine == TWOTIER) { $cmd = "/bin/ls -aln '$item'"; } $stat = stat($item); if(PHP_INT_MAX > 2147483647) { return $stat[7]; } $listFilesDetails = shell_exec($cmd); $commandOutput = trim($listFilesDetails, "\n"); $parseDetails = preg_split('/\s+/', $commandOutput, 8); $fileSize = $parseDetails[4]; return $fileSize; } /**************************************************************************************************** * 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, $userDir; $expressDrive = readLocalBackupLocation(); $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 = PATHSEPARATOR . preg_replace("/4b5z$/", '', $dedupDeviceID, 1); } $expressDBMapPath = $expressDrive . PATHSEPARATOR . $username . PATHSEPARATOR . LDBNEW . PATHSEPARATOR; if(!file_exists($expressDBMapPath) || !is_dir($expressDBMapPath)) { mkdir($expressDBMapPath, PERMISSIONVAL, TRUE); @chmod($expressDBMapPath, PERMISSIONVAL); } # use glob to check if the map file is there or not $mapFile = $expressDBMapPath . EXPRESSDBMAPFILE; if(file_exists($mapFile)) { return TRUE; } if(file_put_contents($expressDBMapPath . EXPRESSDBMAPFILE, $mapTime)) { mkdir($userDir . PATHSEPARATOR . EXPRESSDBDIRNAME . PATHSEPARATOR . $mapTime . $dedupDeviceID, PERMISSIONVAL, TRUE); @chmod($userDir . PATHSEPARATOR . EXPRESSDBDIRNAME, PERMISSIONVAL); @chmod($userDir . PATHSEPARATOR . EXPRESSDBDIRNAME . PATHSEPARATOR . $mapTime, PERMISSIONVAL); @chmod($userDir . PATHSEPARATOR . EXPRESSDBDIRNAME . PATHSEPARATOR . $mapTime . $dedupDeviceID, PERMISSIONVAL); return TRUE; } return FALSE; } /**************************************************************************************************** * Function Name : removeItems * Objective : This is used to centralise the remove method with basic validation. * Added By : Anil Kumar ******************************************************************************************************/ function removeItems($path) { GLOBAL $appPath, $webDir; $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 = $webDir.PATHSEPARATOR.SERVICE.PATHSEPARATOR; if(($checkPath == "/") or ($checkPath == "") or ($servicePath == $checkPath) or ($appPath == $checkPath)) continue; $cmd .= " -rf '$val'$lastItem 2>/dev/null"; } else{ $cmd .= " '$val'$lastItem 2>/dev/null"; } $needToExec = ($cmd === 'rm')?0:1; if($needToExec) { system($cmd); } } } /**************************************************************************************************** * Function Name : updateBackupSetFilesData * Objective : To Update the contents of backupset from old format with 2 fields to new format with 4 fields * 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 = shell_exec("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 : updateBackupSummaryToServer # In Param : --- # Out Param : --- # Objective : This function is to update summary of backup operation happend in desktop to web # Added By : Anil Kumar [22-04-2020] # Modified By : [Date] #****************************************************************************************************/ function updateBackupSummaryToServer() { GLOBAL $username, $linesAccountSettingsFile, $status, $taskType, $backupLocation, $filesConsideredCount, $successFiles, $syncedFiles, $failedFiles ; $backup_status = ""; $statusVal = substr($status, 0, 1); if($statusVal == "A") $backup_status = "C"; else if($statusVal == "F") $backup_status = "F"; else if($statusVal == "S") $backup_status = "S"; $backupType = ($taskType == MANUAL)?1:2; $backupSetSize = trim(file_get_contents(TOTAL_SIZE_PATH)); $backupSetSize = humanReadableSize(trim($backupSetSize)); $backupSetSize = ($backupSetSize == "")?0:$backupSetSize; $currenVal = trim(shell_exec("hostname"),"\n"); if((!isset($linesAccountSettingsFile['hostNameVal'])) || ($linesAccountSettingsFile['hostNameVal'] != $currenVal)){ updateHostName(); clearLogListXMLDir(); } $hostname = $currenVal; $backupDate = trim(shell_exec('date +"%Y-%m-%d %T"'), "\n"); $data = "username=".$username."&password=".rawurlencode(base64_decode($linesAccountSettingsFile['password']))."&device_type=7&backup_status=".$backup_status."&backup_type=".$backupType."&backup_quota=".$backupSetSize."&backup_date=".$backupDate."&device_name=".$hostname."&backup_file_count=".$filesConsideredCount."&backup_success_file_count=".$successFiles."&backup_failure_file_count=".$failedFiles."&existing_file_count=".$syncedFiles; $outData = getCurlOutput(getHash("05"), $data); } /***************************************************************************************************** # Function : updateBackupLogToServer # In Param : --- # Out Param : --- # Objective : This function is to update backup log of desktop to web. # Added By : Anil Kumar [22-04-2020] # Modified By : [Date] #****************************************************************************************************/ function updateBackupLogToServer() { GLOBAL $logOutputFilePath, $idevsutilBinaryPath, $backupLocation; $backupFile = "logFileSet.txt"; file_put_contents($backupFile, $logOutputFilePath); $key = "hostNameVal"; $hostname = ""; getParameterValueFromAccountSettingsFile($key,$hostname); $backupLogUtf = getOperationFile(array( "opType" => "backupLog", "backupsetFile" => $backupFile, "backupLocation" => $hostname.PATHSEPARATOR."log", "source" => "/")); $listDeviceCmd = $idevsutilBinaryPath.WHITESPACE.IDEVSUTIL_ARG.ASSIGNMENTOP."\"$backupLogUtf\""; $out = exec("$listDeviceCmd 2>".EXEC_ERRORFILE); unlink($backupLogUtf); unlink($backupFile); } /**************************************************************************************************** * Subroutine Name : humanReadableSize. * Objective : returns size in human readable format * Added By : Senthil Pandian ******************************************************************************************************/ function humanReadableSize($bytes) { if(!is_numeric($bytes)) return $bytes; $precision = 2; $kilobyte = 1024; $megabyte = $kilobyte * 1024; $gigabyte = $megabyte * 1024; $terabyte = $gigabyte * 1024; if ($bytes < $kilobyte) return $bytes . ' B'; elseif (($bytes >= $kilobyte) && ($bytes < $megabyte)) return round($bytes / $kilobyte, $precision) . ' KB'; elseif (($bytes >= $megabyte) && ($bytes < $gigabyte)) return round($bytes / $megabyte, $precision) . ' MB'; elseif (($bytes >= $gigabyte) && ($bytes < $terabyte)) return round($bytes / $gigabyte, $precision) . ' GB'; elseif ($bytes >= $terabyte) return round($bytes / $terabyte, $precision) . ' TB'; } /**************************************************************************************************** * Subroutine Name : verifyLastUserLog. * Objective : find the status of user log via summery and decide the status * Added By : Anil Kumar ******************************************************************************************************/ function verifyLastUserLog($logpidFile) { if(file_exists($logpidFile) && (!file_exists("StartPid.txt"))) { if($handle = fopen($logpidFile,'r+')) { $buffer = fread($handle, 1024); fclose($handle); if(file_exists($buffer)) { $statusToUpdate = "ABORTED"; # need to check and update status $considered = $success = $synced = $failed = $status = $logFile = ""; $isSummary = 0; $cmd = "tail -10 \"$buffer\""; $logData = `$cmd`; $res1 = explode("\n", $logData); foreach($res1 as $line){ if(trim($line)!=''){ if (!$isSummary && (strpos($line, 'Summary:') !== false)) { $isSummary = 1; } elseif($isSummary && (strpos($line, 'considered') !== false)){ $data = explode(":", $line); $considered = $data[1]; trim($considered); } elseif($isSummary && ((strpos($line, 'backed') !== false) || (strpos($line, 'restored'!== false)))){ $data = explode(":", $line); $success = $data[1]; trim($success); } elseif($isSummary && (strpos($line, 'already present') !== false)){ $data = explode(":", $line); $synced = $data[1]; trim($synced); } elseif($isSummary && (strpos($line, 'failed') !== false)){ $data = explode(":", $line); $failed = $data[1]; trim($failed); } } } if($isSummary){ if($failed > 0 || $considered == 0){ $statusToUpdate = "FAILURE"; } elseif($considered == ($success+$synced)){ $statusToUpdate = "SUCCESS"; } } # need to change the status. $newName = "$buffer"."_".$statusToUpdate; $resCmd = "mv \"$buffer\" \"$newName\""; $res = `$resCmd`; } } } } /**************************************************************************************************** * Subroutine Name : validatePVTKey. * Objective : This mehod is used to validate private key. * Added By : Anil Kumar ******************************************************************************************************/ function validatePVTKey() { GLOBAL $username, $userDir, $linesAccountSettingsFile, $enctype, $idevsutilBinaryPath, $deDup, $IDPVTContent, $webDir; $encPvtkeyPath = $userDir.PATHSEPARATOR."IDPVT"; #To get encType $postData = "username=".rawurlencode($username)."&password=".rawurlencode(base64_decode($linesAccountSettingsFile['password'])); $outputArr = getCurlOutput(getHash("01"), $postData); $validOutput = $outputArr['output']; $validOutput = str_replace('', '', $validOutput); $xml = simplexml_load_string($validOutput); $xmlArray = $xml->login; if(isset($xmlArray['message']) && isset($xmlArray['enctype']) && ($xmlArray['message'] == "SUCCESS")){ $enctype = $xmlArray['enctype'] ; } else { traceLog("Login CGI: "." Output: ".$xmlArray['output']." Error: ".$xmlArray['error']); } if($enctype != "DEFAULT") { $listDeviceUtf = ""; #To validate PVT key. if($deDup == true){ $listDeviceUtf = getOperationFile(array("opType" => "listDevice", "enctype" => $enctype)); } else { $dir = readBackupLocation(); $listDeviceUtf = getOperationFile(array("opType" => "createDir", "directoryName" => $dir, "enctype" => $enctype)); } # EVS command to execute for properties $listDeviceCmd = $idevsutilBinaryPath.WHITESPACE.IDEVSUTIL_ARG.ASSIGNMENTOP."\"$listDeviceUtf\""; # read IDPVT to store in variable. if(file_exists($encPvtkeyPath)){ $IDPVTContent = file_get_contents($encPvtkeyPath); } $out = exec("$listDeviceCmd 2>".EXEC_ERRORFILE); unlink($listDeviceUtf); if(file_exists(EXEC_ERRORFILE) && (filesize(EXEC_ERRORFILE) > 0)){ $lines = file_get_contents(EXEC_ERRORFILE); unlink(EXEC_ERRORFILE); if(strpos($lines, "encryption verification failed") !== false){ traceLog("List device failed due to encryption key."); unlink(LOGPIDFILE); unlink(STARTPIDFILE); unlink($encPvtkeyPath); return 0; } } } return 1; } function simple_decrypt() { GLOBAL $phpPath, $webDir ; $cmdToDecrypt = "$phpPath $webDir".PATHSEPARATOR.APPDIR.PATHSEPARATOR.CONFIG.PATHSEPARATOR."token.php ".HASH_DATA." 0"; $stOutput = shell_exec($cmdToDecrypt); return $stOutput; } function getHash($index){ $hashValDec = json_decode(simple_decrypt(), true); return $hashValDec[$index]; } /***************************************************************************************************** # Function : uploadLogListXml # In Param : --- # Out Param : --- # Objective : This function is to upload Log list XML to web. # Added By : Anil Kumar [30-04-2020] # Modified By : [Date] #****************************************************************************************************/ function uploadLogListXml() { GLOBAL $idevsutilBinaryPath, $backupLocation, $LogListXmlsFile; $backupSetFile = "logListXml.txt"; file_put_contents($backupSetFile, $LogListXmlsFile); $key = "hostNameVal"; $hostname = ""; getParameterValueFromAccountSettingsFile($key,$hostname); $backupLogUtf = getOperationFile(array( "opType" => "backupLog", "backupsetFile" => $backupSetFile, "backupLocation" => $hostname.PATHSEPARATOR, "source" => "/")); $listDeviceCmd = $idevsutilBinaryPath.WHITESPACE.IDEVSUTIL_ARG.ASSIGNMENTOP."\"$backupLogUtf\""; $out = exec("$listDeviceCmd 2>".EXEC_ERRORFILE); unlink($backupLogUtf); unlink($backupSetFile); } /***************************************************************************************************** # Function : updateLogListXml # In Param : --- # Out Param : --- # Objective : This function is to Create/Update Log list XML. # Added By : Anil Kumar [30-04-2020] # Modified By : [Date] #****************************************************************************************************/ function updateLogListXml() { GLOBAL $userDir, $username, $status, $taskType, $logOutputFilePath, $filesConsideredCount, $successFiles, $syncedFiles, $failedFiles, $backupStartTime, $backupEndTime, $backupLocation, $LogListXmlsFile ; $strArray = explode('/',$logOutputFilePath); $lpath = end($strArray); $duration = $backupEndTime - $backupStartTime; $duration = date("H:i:s", $duration); $backup_status = ""; $statusVal = substr($status, 0, 1); if($statusVal == "A") $backup_status = CANCELLED; else if($statusVal == "F") $backup_status = FAILURE; else if($statusVal == "S") $backup_status = SUCCESS; $backupType = ($taskType == MANUAL)?INTERACTIVE_BACKUP:SCHEDULE_BACKUP; $msg = ($backup_status == "Success")?SUCCESSFULLY_COMPLETED_BACKUP:""; $contentForWebLog = "Ref : Username - ".$username."!!!". "Computer Name : ".$backupLocation."!!!". $backupType."!!!". "Backup Start Time : ".date("m-d-Y H:i:s", $backupStartTime)."!!!". "Backup End Time : ".date("m-d-Y H:i:s", $backupEndTime)."!!!". "Files considered for backup: ".$filesConsideredCount." file(s)!!!". "Files already present in your account: ".$syncedFiles." file(s)!!!". "Files backup up now: ".$successFiles." file(s)!!!".$msg; $content = ''.trim(shell_exec('date +"%Y-%m-%d %T"'), "\n").''. ''.$username.''. ''.$filesConsideredCount.''. ''.$syncedFiles.''. ''.$backup_status.''. ''.$duration.''. ''.$contentForWebLog.''. ''.$backupType.''. ''.$lpath.''. ''.$logOutputFilePath.''; $logListXmlContent = ""; $logListXmlsDir = $userDir."/".LOGLISTXMLS."/"; $date = trim(shell_exec('date "+%m-%d-%Y"'), "\n"); $LogListXmlsFile = $logListXmlsDir.$date.".xml" ; $LogListXmlsLockFile = $logListXmlsDir.$date.".lock" ; $xmlFileLock = fopen($LogListXmlsLockFile, 'a+'); $val = 1; $locked = flock($xmlFileLock, LOCK_EX, $val); if(!file_exists($LogListXmlsFile)) { if(file_exists($logListXmlsDir) && strpos($logListXmlsDir, "/".SERVICE."/") !== false){ `rm $logListXmlsDir."*"`; }else { mkdir($logListXmlsDir); `chmod PERMISSIONVAL $logListXmlsDir`; } $logListXmlContent = ''.$content.''; } else { $existingContent = file_get_contents($LogListXmlsFile); $pos = strpos($existingContent, "", 0); $logListXmlContent = substr_replace( $existingContent, $content, $pos, 0 ); } file_put_contents($LogListXmlsFile, $logListXmlContent); flock($xmlFileLock, LOCK_UN); fclose($xmlFileLock); } function validatePvtKeyUsingAuthList() { GLOBAL $idevsutilBinaryPath, $jobDir, $userDir; $valid = 1; $authListOutputFile = $jobDir.AUTHLISTOUTPUTFILE; $authListErrorFile = $jobDir.AUTHLISTERRORFILE; $authListUtf = getOperationFile(array( "opType" => AUTHLIST, "source" => "/")); $authListCmd = $idevsutilBinaryPath.WHITESPACE.IDEVSUTIL_ARG.ASSIGNMENTOP."\"$authListUtf\""; $out = exec("$authListCmd"); unlink($authListUtf); if(file_exists($authListErrorFile) && customFileSize($authListErrorFile)) { $error = file_get_contents($authListErrorFile); $reason = checkErrorAndReason($error); traceLog("EVS error on $OutErrorFilePath. Reason : $reason"); if(stripos($reason, 'password mismatch') !== FALSE || stripos($reason, 'service not known') !== FALSE || stripos($reason, 'encryption verification failed') !== FALSE) { $encPwdPath = $userDir.PATHSEPARATOR."IDPWD"; unlink($encPwdPath); } $valid = 1; } unlink($authListOutputFile); unlink($authListErrorFile); return $valid; } /**************************************************************************************************** * Function Name : updateUserStatus * Objective : This is to update account status to descide whether it is active or cancelled. * Added By : Anil Kumar ******************************************************************************************************/ function updateHostName() { GLOBAL $linesAccountSettingsFile, $userDir; $accountSettingPath = "$userDir/ACCOUNT_SETTINGS_FILE"; $linesAccountSettingsFileData = json_decode(file_get_contents($accountSettingPath),TRUE); $linesAccountSettingsFileData['hostNameVal'] = trim(shell_exec("hostname"), "\n"); $linesAccountSettingsFile['hostNameVal'] = trim(shell_exec("hostname"), "\n"); if(($file = fopen($accountSettingPath, "a+")) != FALSE) { ftruncate($file, 0); fwrite($file, json_encode($linesAccountSettingsFileData,TRUE)); fclose($file); @chmod($accountSettingPath, PERMISSIONVAL); } return 0; } function clearLogListXMLDir(){ GLOBAL $userDir; $logListXmlsDir = $userDir."/".LOGLISTXMLS."/"; if(file_exists($logListXmlsDir) && strpos($logListXmlsDir, "/".SERVICE."/") !== false){ `rm $logListXmlsDir."*"`; } } //-------------------------------------- Y ------------------------------------------------ //-------------------------------------- Z ------------------------------------------------ ?>