Files
resatennis_tyroltenn/IDrive/.config/common.php

7338 lines
248 KiB
PHP
Executable File

<?php
if( ! ini_get('date.timezone') ){date_default_timezone_set('GMT');} //Added to avoid "Warning: date(): It is not safe to rely on the system's timezone settings."
$appPath = "$webDir/".APPDIR;
$mode = 'testing';
//Alternate function to handle if function not exists
if (!function_exists('cal_days_in_month'))
{
function cal_days_in_month($calendar, $month, $year)
{
return date('t', mktime(0, 0, 0, $month, 1, $year));
}
}
$idevsutilBinaryPath = $appPath."/idevsutil_IDrive";
if(!isset($_SESSION['userName']) && empty($_SESSION['userName'])) {
$userName = getUserName();
$_SESSION['userName'] = $userName;
}
elseif(!isset($userName) && empty($userName)){
$userName = $_SESSION['userName'];
}
$nasUserName = isset($_SESSION['nasUserName'])?$_SESSION['nasUserName']:getNasUserName();
// Setting the Scheduler path, added by Sreenath P. on 01-04-2014
Scheduler::SetSchedulerPath($webDir, $userName, $nasUserName, $machine);
if(!empty($_SESSION['userName'])) {
$nasUserDirectory = Scheduler::$nasUser_dir;
$idriveUserDirectory = "$nasUserDirectory$userName";
$bandwidthFilePath = "$idriveUserDirectory/".BW_FILE;
$relativeFile = "$idriveUserDirectory/".RELATIVE_FILE;
$mpc = "$idriveUserDirectory/".MPC_FILE;
$drlFile = "$idriveUserDirectory/".RESTORE_LOCATION_FILE;
$OutErrorFilePath = "$idriveUserDirectory/".ERROR_FILE;
$OutOutputFilePath = "$idriveUserDirectory/".OUTPUTFILE;
$searchDirLocal = "$idriveUserDirectory/Backup/.+searchList";
$searchDirRemote = "$idriveUserDirectory/Restore/.+searchList";
$temp_file = "$idriveUserDirectory/".TEMP_OPERATION_FILE;
$excludeFullFile = "$idriveUserDirectory/" . FULL_PATH_EXCLUDE_FILE;
$excludePartialFilePath = "$idriveUserDirectory/".EXCLUDE_LIST_PARTIAL_FILE;
$userDirListsFile = "$webDir/".SERVICE."/".USERDIRLISTS;
$localMPCfile = "$idriveUserDirectory/localBackupLocation.txt";
$reIndexDirPath = "$idriveUserDirectory/DBReindex";
$quotaSQLite = "$idriveUserDirectory/Quota_SQLite";
$detailsSQLite = "$idriveUserDirectory/Details_SQLite";
$remoteListSQLite = "$idriveUserDirectory/RemoteList_SQLite";
$searchSQLite = "$idriveUserDirectory/Search_SQLite";
$searchDirTrashRemote = "$idriveUserDirectory/Restore/.+trashList";
$dedupDetailFile = "$idriveUserDirectory/".DEDUP_DETAIL_FILE;
$dedupRestoreDeviceID = "$idriveUserDirectory/".DEDUP_RESTORE_DEVICE_FILE;
if($_SESSION['dedup']){
$idevsutilBinaryPath = "$webDir/".APPDIR."/idevsutil_IDrive_Dedup";
if(!isset($_SESSION['deviceID']) || !$_SESSION['deviceID']){
if(file_exists($dedupDetailFile)) {
$deviceJSON = file_get_contents($dedupDetailFile);
$deviceArray = json_decode($deviceJSON, true);
$_SESSION['deviceID'] = trim($deviceArray['deviceID']);
}
}
}
else if(file_exists($dedupDetailFile)){
$idevsutilBinaryPath = "$webDir/".APPDIR."/idevsutil_IDrive_Dedup";
$deviceJSON = file_get_contents($dedupDetailFile);
$deviceArray = json_decode($deviceJSON, true);
$_SESSION['deviceID'] = trim($deviceArray['deviceID']);
$_SESSION['dedup'] = true;
}
} else {
$userName = "";
$nasUserName = "";
$bandwidthFilePath = "";
$relativeFile = "";
$mpc = "";
$drlFile = "";
$OutErrorFilePath = "";
$OutOutputFilePath = "";
$searchDirLocal = "";
$searchDirRemote = "";
$searchDirTrashRemote = "";
$temp_file = "$webDir/".SERVICE."/".USER_PROFILE."/".TEMP_OPERATION_FILE;
$excludePartialFilePath = "";
$excludeFullFile = "";
$userDirListsFile = "";
$localMPCfile = "";
$reIndexDirPath = "";
$quotaSQLite = "";
$detailsSQLite = "";
$remoteListSQLite = "";
$searchSQLite = "";
$dedupDetailFile = "";
$dedupRestoreDeviceID = "";
}
/************************************************************************************************
* Function Name : __autoload
* Objective : To include classes in PHP
* Added By : Sreenath P.
************************************************************************************************/
/*function __autoload($class_name) {
if($class_name == 'SQLite3') {
return FALSE;
}
include "c.".$class_name . ".php";
}
spl_autoload_register('my_autoloader');
*/
/*
function my_autoloader($class_name) {
if($class_name == 'SQLite3') {
return FALSE;
}
include "c.".$class_name . ".php";
}
spl_autoload_register('my_autoloader');
// Or, using an anonymous function as of PHP 5.3.0
spl_autoload_register(function ($class_name) {
if($class_name == 'SQLite3') {
return FALSE;
}
include "c.".$class_name . ".php";
});
*/
if(!isset($_SESSION['serverIPAddress']))
$_SESSION['serverIPAddress'] = getLocalServerip();
$serverIPAddress = $_SESSION['serverIPAddress'];
$totalEngineBackup = 4;
$totalEngineRestore = 4;
$isLocalBackup = 4;
$isLocalRestore = 4;
// Setting the Scheduler path, added by Sreenath P. on 01-04-2014
#Scheduler::SetSchedulerPath($webDir, $userName, $user, $machine);
if(!empty($_SESSION['userName'])) {
$readAccountSettingsFileData = readAccountSettingsFile();
if($readAccountSettingsFileData['engineCount'] == 2) {
$totalEngineBackup = 2;
$totalEngineRestore = 2;
$isLocalBackup = 2;
$isLocalRestore = 2;
}
if(!empty($_SESSION['PROXY'])){
$proxyString = trim($_SESSION['PROXY']);
$proxy_Array = preg_split( "/[:@]/", $proxyString);
$_SESSION['proxy_option'] = 'Manual';
$_SESSION['proxyUserName'] = $proxy_Array[0];
$_SESSION['proxyPassword'] = $proxy_Array[1];
$_SESSION['ipAddress'] = $proxy_Array[2];
$_SESSION['port'] = $proxy_Array[3];
}
}
checkIfHtaccessExists();
$whiteSpace = " ";
$assignmentOperator = "=";
$pathSeparator = "/";
$lineFeed = "\n";
$idevsutilArgument = "--utf8-cmd";
$searchHandle = 0;
$countItem = 0;
$isOpened = 0;
$pidPath = PID_FILE;
$pagePath = "";
$startPid = START_PID;
$userCancelFile = CANCEL_PATH;
$empty_trash = 0;
$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",
"PROGRESS" => "--100percent-progress",
"QUOTAFROMFILE" => "--quota-fromfile",
"CREATEDIR" => "--create-dir",
"SEARCH" => "--search",
"VERSIONINFO" => "--version-info",
"RENAME" => "--rename",
"OLDPATH" => "--old-path",
"DELETE" => "--delete-items",
"PUT_BACK" => "--moveto-original",
"DELETE_TRASH" => "--deletefrom-trash",
"EMPTY_TRASH" => "--empty-trash",
"NEWPATH" => "--new-path",
"ITEMSTATUS" => "--items-status",
"ITEMSTATUS3" => "--items-status3",
"TRASH" => "--trash",
"PORTABLE"=>"--portable",
"PORTABLE_DEST"=>"--portable-dest",
"DB_RECREATE"=>"--expressdb-recreate",
"DEVICE_ID"=>"--device-id",
"SEARCH_KEY"=>"--search-key",
"LISTDEVICE"=>"--list-device",
"CREATEBUCKET"=>"--create-bucket",
"NICKNAME"=>"--nick-name",
"UID"=>"--uid",
"BUCKET_TYPE"=>"--bucket-type",
"OS_NAME"=>"--os",
"LINK_BUCKET"=>"--link-bucket",
"NICK_UPDATE"=>"--nick-update",
"FILEONLY"=>"--file"
);
#********************************************************************************************************************
# Subroutine Name : getOperationFile.
# Objective : Create utf8 file for EVS command respective to operation type(backup/restore/validate...).
# Added By : Avinash Kumar
#********************************************************************************************************************/
function getOperationFile($optType, $input = '', $searchPath = '')
{
GLOBAL $webDir;
GLOBAL $userName;
GLOBAL $nasUserName;
GLOBAL $hashEvsParameters;
GLOBAL $lineFeed;
GLOBAL $pathSeparator;
GLOBAL $assignmentOperator;
GLOBAL $OutErrorFilePath;
GLOBAL $OutOutputFilePath;
GLOBAL $selected_backupset;
GLOBAL $archive;
GLOBAL $trash_Search;
GLOBAL $trashList;
GLOBAL $trashListingFlag;
GLOBAL $searchDirRemote,$permissionVal,$mpc,$dedupDetailFile;
$encPwdPath = Scheduler::$user_dir."IDPWD";
$encPvtkeyPath = Scheduler::$user_dir."IDPVT";
$utfPath = Scheduler::$user_dir.UTF8_FILE;
// added by anil to alert the user when server address is not found in backend.
if(($optType != "GetServerAddress" && $optType != "Validate" && $optType != "Reindex" && $optType != "Config") && !isset($_SESSION['serverAddr']) || (isset($_SESSION['serverAddr']) && $_SESSION['serverAddr'] == "") )
{
getEVSServerAddr();
validateServerAddreValue();
}
$serverAddressOperator = "@";
$serverName = "home";
$serverNameOperator = "::";
$privateEncryptionKey = "private";
$encryptionType = "";
$proxyString = "";
if(isset($_SESSION['ipAddress']) && $_SESSION['ipAddress'] != "")
$proxyString = $_SESSION['proxyUserName'].":".$_SESSION['proxyPassword']."@".$_SESSION['ipAddress'].":".$_SESSION['port'];
$dedupDeviceID = '';
$currentDeviceID = '';
if($_SESSION['dedup']){
if(file_exists($dedupDetailFile)){
$deviceJSON = file_get_contents($dedupDetailFile);
$deviceArray = json_decode($deviceJSON, true);
$_SESSION['deviceID'] = trim($deviceArray['deviceID']);
$_SESSION['serverRoot'] = trim($deviceArray['serverRoot']);
#$_SESSION['deviceID'] = trim($deviceID);
} else {
deviceIDExists();
}
if(isset($_SESSION['deviceID']))
$dedupDeviceID = $hashEvsParameters["DEVICE_ID"].$assignmentOperator.$_SESSION['deviceID'].$lineFeed;
if(isset($_SESSION['selectedRestoreDeviceID']))
{
$currentDeviceID = $hashEvsParameters["DEVICE_ID"].$assignmentOperator.$_SESSION['selectedRestoreDeviceID'].$lineFeed;
}
}
$deviceid = "";
switch ($optType) {
case VERSIONINFOOP:
$utfParam = $hashEvsParameters["PASSWORD"].$assignmentOperator.$encPwdPath.$lineFeed.
$hashEvsParameters["VERSIONINFO"].$lineFeed.
$hashEvsParameters["PROXY"].$assignmentOperator.$proxyString.$lineFeed.
$hashEvsParameters["ENCODE"].$lineFeed.
$hashEvsParameters["ERROR"].$assignmentOperator.$OutErrorFilePath.$lineFeed;
if($trash_Search == 1)
$utfParam .= $hashEvsParameters["TRASH"].$lineFeed;
$utfParam .= $currentDeviceID.$hashEvsParameters["XMLOUTPUT"].$lineFeed;
$utfParam .= $userName.$serverAddressOperator.
$_SESSION['serverAddr'].$serverNameOperator.
$serverName.$pathSeparator.$input;
break;
case PROPERTIESOP:
$utfParam = $hashEvsParameters["PASSWORD"].$assignmentOperator.$encPwdPath.$lineFeed.
$hashEvsParameters["PROPERTIES"].$lineFeed.
$hashEvsParameters["PROXY"].$assignmentOperator.$proxyString.$lineFeed.
$hashEvsParameters["ENCODE"].$lineFeed.
$hashEvsParameters["ERROR"].$assignmentOperator.$OutErrorFilePath.$lineFeed;
$utfParam .= $currentDeviceID.$hashEvsParameters["XMLOUTPUT"].$lineFeed;
$utfParam .= $userName.$serverAddressOperator.
$_SESSION['serverAddr'].$serverNameOperator.
$serverName.$input."/";
break;
case CREATEDIROP:
$utfParam = $hashEvsParameters["PASSWORD"].$assignmentOperator.$encPwdPath.$lineFeed.
$hashEvsParameters["CREATEDIR"].$assignmentOperator.$input[0].$lineFeed;
if($input[2] == "Private")
$utfParam .= $hashEvsParameters["PVTKEY"].$assignmentOperator.$encPvtkeyPath.$lineFeed;
$utfParam .= $currentDeviceID;
$utfParam .= $hashEvsParameters["PROXY"].$assignmentOperator.$proxyString.$lineFeed.
$hashEvsParameters["ENCODE"].$lineFeed.
$userName.$serverAddressOperator.
$_SESSION['serverAddr'].$serverNameOperator.
$serverName.$pathSeparator.$input[1];
break;
case RENAMEOP:
$utfParam = $hashEvsParameters["PASSWORD"].$assignmentOperator.$encPwdPath.$lineFeed.
$hashEvsParameters["RENAME"].$lineFeed.
$hashEvsParameters["OLDPATH"].$assignmentOperator.$input[0].$lineFeed.
$hashEvsParameters["NEWPATH"].$assignmentOperator.$input[1].$lineFeed;
if($_SESSION["encType"] == "Private")
$utfParam .= $hashEvsParameters["PVTKEY"].$assignmentOperator.$encPvtkeyPath.$lineFeed;
$utfParam .= $hashEvsParameters["PROXY"].$assignmentOperator.$proxyString.$lineFeed.
$hashEvsParameters["ENCODE"].$lineFeed.
$hashEvsParameters["ERROR"].$assignmentOperator.$OutErrorFilePath.$lineFeed.
$userName.$serverAddressOperator.
$_SESSION['serverAddr'].$serverNameOperator.
$serverName.$pathSeparator;
break;
case SPEEDOP:
$utfParam = $hashEvsParameters["PASSWORD"].$assignmentOperator.$encPwdPath.$lineFeed.
$input.$lineFeed;
if($_SESSION["encType"] == "Private")
$utfParam .= $hashEvsParameters["PVTKEY"].$assignmentOperator.$encPvtkeyPath.$lineFeed;
$utfParam .= $hashEvsParameters["PROXY"].$assignmentOperator.$proxyString.$lineFeed.
$hashEvsParameters["ENCODE"].$lineFeed.
$hashEvsParameters["ERROR"].$assignmentOperator.$OutErrorFilePath.$lineFeed.
$userName.$serverAddressOperator.
$_SESSION['serverAddr'].$serverNameOperator.
$serverName.$pathSeparator;
break;
case ARCHIVEOP:
case PERIODICARCHIVEOP:
$utfParam = $hashEvsParameters["PASSWORD"].$assignmentOperator.$encPwdPath.$lineFeed;
$OutErrorFilePath = Scheduler::$archiveclean_dir.$selected_backupset."/".ERROR_FILE;
$OutOutputFilePath = Scheduler::$archiveclean_dir.$selected_backupset."/".OUTPUTFILE;
$utfPath = Scheduler::$archiveclean_dir.$selected_backupset."/".UTF8_FILE;;
if(file_exists($encPvtkeyPath))
$utfParam .= $hashEvsParameters["PVTKEY"].$assignmentOperator.$encPvtkeyPath.$lineFeed;
$utfParam .= $dedupDeviceID.$hashEvsParameters["XMLOUTPUT"].$lineFeed;
$utfParam .= $hashEvsParameters["PROXY"].$assignmentOperator.$proxyString.$lineFeed.
$hashEvsParameters["ENCODE"].$lineFeed.
$hashEvsParameters["DELETE"].$lineFeed.
$hashEvsParameters["FROMFILE"].$assignmentOperator.$input.$lineFeed.
$hashEvsParameters["ERROR"].$assignmentOperator.$OutErrorFilePath.$lineFeed.
$hashEvsParameters["OUTPUT"].$assignmentOperator.$OutOutputFilePath.$lineFeed.
$userName.$serverAddressOperator.
$_SESSION['serverAddr'].$serverNameOperator.
$serverName.$pathSeparator;
break;
case FILESTATUSOP:
if(empty($searchPath)){
$OutErrorFilePath = Scheduler::$archiveclean_dir.$selected_backupset."/".ERROR_FILE;
$OutOutputFilePath = Scheduler::$archiveclean_dir.$selected_backupset."/".OUTPUTFILE;
$utfPath = Scheduler::$archiveclean_dir.$selected_backupset."/".UTF8_FILE;
$deviceid = $dedupDeviceID;
} else {
$OutErrorFilePath = $searchPath."/operation_".ERROR_FILE;
$OutOutputFilePath = $searchPath."/operation_".OUTPUTFILE;
$utfPath = $searchPath."/operation_".UTF8_FILE;
$deviceid = $currentDeviceID;
}
$utfParam = $hashEvsParameters["PASSWORD"].$assignmentOperator.$encPwdPath.$lineFeed;
if(file_exists($encPvtkeyPath))
$utfParam .= $hashEvsParameters["PVTKEY"].$assignmentOperator.$encPvtkeyPath.$lineFeed;
if($_SESSION['dedup']){
//$utfParam .= $currentDeviceID.$hashEvsParameters["ITEMSTATUS3"].$lineFeed;
$utfParam .= $deviceid.$hashEvsParameters["ITEMSTATUS3"].$lineFeed;
$utfParam .= $hashEvsParameters["XMLOUTPUT"].$lineFeed;
}
else
$utfParam .= $hashEvsParameters["ITEMSTATUS"].$lineFeed;
$utfParam .= $hashEvsParameters["PROXY"].$assignmentOperator.$proxyString.$lineFeed.
$hashEvsParameters["ENCODE"].$lineFeed.
$hashEvsParameters["FROMFILE"].$assignmentOperator.$input.$lineFeed.
$hashEvsParameters["ERROR"].$assignmentOperator.$OutErrorFilePath.$lineFeed.
$hashEvsParameters["OUTPUT"].$assignmentOperator.$OutOutputFilePath.$lineFeed.
$userName.$serverAddressOperator.
$_SESSION['serverAddr'].$serverNameOperator.
$serverName.$pathSeparator;
break;
case DELETEOP:
$utfParam = $hashEvsParameters["PASSWORD"].$assignmentOperator.$encPwdPath.$lineFeed;
$OutErrorFilePath = Scheduler::$delete_dir.ERROR_FILE;
$OutOutputFilePath = Scheduler::$delete_dir.OUTPUTFILE;
$utfPath = Scheduler::$delete_dir.UTF8_FILE;
if(file_exists($encPvtkeyPath))
$utfParam .= $hashEvsParameters["PVTKEY"].$assignmentOperator.$encPvtkeyPath.$lineFeed;
$utfParam .= $currentDeviceID.$hashEvsParameters["XMLOUTPUT"].$lineFeed;
$utfParam .= $hashEvsParameters["PROXY"].$assignmentOperator.$proxyString.$lineFeed.
$hashEvsParameters["ENCODE"].$lineFeed.
$hashEvsParameters["DELETE"].$lineFeed.
$hashEvsParameters["FROMFILE"].$assignmentOperator.$input.$lineFeed.
$hashEvsParameters["ERROR"].$assignmentOperator.$OutErrorFilePath.$lineFeed.
$hashEvsParameters["OUTPUT"].$assignmentOperator.$OutOutputFilePath.$lineFeed.
$userName.$serverAddressOperator.
$_SESSION['serverAddr'].$serverNameOperator.
$serverName.$pathSeparator;
break;
case PUT_BACKOP:
$utfPath = UTF8_FILE;
$OutErrorFilePath = "./".ERROR_FILE;
$OutOutputFilePath = "./".OUTPUTFILE;
$utfParam = $hashEvsParameters["PASSWORD"].$assignmentOperator.$encPwdPath.$lineFeed;
if($_SESSION["encType"] == "Private")
$utfParam .= $hashEvsParameters["PVTKEY"].$assignmentOperator.$encPvtkeyPath.$lineFeed;
$utfParam .= $currentDeviceID.$hashEvsParameters["XMLOUTPUT"].$lineFeed;
if($_SESSION['dedup']){
$utfParam .= $hashEvsParameters["DEVICE_ID"].$assignmentOperator.$_SESSION['deviceID'].$lineFeed;
}
$utfParam .= $hashEvsParameters["PROXY"].$assignmentOperator.$proxyString.$lineFeed.
$hashEvsParameters["ENCODE"].$lineFeed.
$hashEvsParameters["PUT_BACK"].$lineFeed.
$hashEvsParameters["FROMFILE"].$assignmentOperator.$input.$lineFeed.
$hashEvsParameters["ERROR"].$assignmentOperator.$OutErrorFilePath.$lineFeed.
$hashEvsParameters["OUTPUT"].$assignmentOperator.$OutOutputFilePath.$lineFeed.
$userName.$serverAddressOperator.
$_SESSION['serverAddr'].$serverNameOperator.
$serverName.$pathSeparator;
break;
case REMOVE_FROM_TRASHOP:
$utfPath = UTF8_FILE;
$OutErrorFilePath = "./".ERROR_FILE;
$OutOutputFilePath = "./".OUTPUTFILE;
$utfParam = $hashEvsParameters["PASSWORD"].$assignmentOperator.$encPwdPath.$lineFeed;
if($_SESSION["encType"] == "Private")
$utfParam .= $hashEvsParameters["PVTKEY"].$assignmentOperator.$encPvtkeyPath.$lineFeed;
if($_SESSION['dedup']) {
$utfParam .= $currentDeviceID.$hashEvsParameters["EMPTY_TRASH"].$lineFeed;
} else {
$utfParam .= $hashEvsParameters["DELETE_TRASH"].$lineFeed;
}
$utfParam .= $hashEvsParameters["XMLOUTPUT"].$lineFeed.
$hashEvsParameters["PROXY"].$assignmentOperator.$proxyString.$lineFeed.
$hashEvsParameters["ENCODE"].$lineFeed.
$hashEvsParameters["FROMFILE"].$assignmentOperator.$input.$lineFeed.
$hashEvsParameters["ERROR"].$assignmentOperator.$OutErrorFilePath.$lineFeed.
$hashEvsParameters["OUTPUT"].$assignmentOperator.$OutOutputFilePath.$lineFeed.
$userName.$serverAddressOperator.
$_SESSION['serverAddr'].$serverNameOperator.
$serverName.$pathSeparator;
break;
case VALIDATEOP:
$utfParam = $hashEvsParameters["VALIDATE"].$lineFeed.
$hashEvsParameters["USERNAME"].$assignmentOperator.$userName.$lineFeed.
$hashEvsParameters["PASSWORD"].$assignmentOperator.$encPwdPath.$lineFeed.
$hashEvsParameters["PROXY"].$assignmentOperator.$proxyString.$lineFeed.
$hashEvsParameters["ENCODE"].$lineFeed;
break;
case CONFIGOP:
$utfParam = $hashEvsParameters["CONFIG"].$lineFeed.
$hashEvsParameters["USERNAME"].$assignmentOperator.$userName.$lineFeed.
$hashEvsParameters["PASSWORD"].$assignmentOperator.$encPwdPath.$lineFeed.
$hashEvsParameters["ENCTYPE"].$assignmentOperator.$input.$lineFeed;
if($input == "Private")
$utfParam .= $hashEvsParameters["PVTKEY"].$assignmentOperator.$encPvtkeyPath.$lineFeed;
$utfParam .= $hashEvsParameters["PROXY"].$assignmentOperator.$proxyString.$lineFeed.
$hashEvsParameters["ENCODE"].$lineFeed;
break;
case GETSERVERADDRESSOP:
$utfParam = $hashEvsParameters["XMLOUTPUT"].$lineFeed.
$hashEvsParameters["SERVERADDRESS"].$lineFeed.
$userName.$lineFeed.
$hashEvsParameters["PASSWORD"].$assignmentOperator.$encPwdPath.$lineFeed.
$hashEvsParameters["PROXY"].$assignmentOperator.$proxyString.$lineFeed.
$hashEvsParameters["ENCODE"].$lineFeed;
break;
case SEARCHOP:
if($archive == 1){
$volumePath = getOriginalServicePath();
$OutErrorFilePath = Scheduler::$archiveclean_dir.$selected_backupset."/".ERROR_FILE;
$OutOutputFilePath = Scheduler::$archiveclean_dir.$selected_backupset."/".OUTPUTFILE;
$utfPath = Scheduler::$nasUser_dir."/$userName/".Scheduler::$archive."/".$selected_backupset."/".UTF8_FILE;
}
else{
if($trash_Search)
$session_var = $_SESSION['currentRemoteTrashSearchPath'];
else
$session_var = $_SESSION['currentRemoteSearchPath'];
$OutErrorFilePath = $session_var.ERROR_FILE;
$OutOutputFilePath = $session_var.OUTPUTFILE;
$utfPath = $session_var.UTF8_FILE;
}
# adding timeout to exit instead of waiting for a long time with out any response
$timeOut = "--timeout=600";
$utfParam = $hashEvsParameters["PASSWORD"].$assignmentOperator.$encPwdPath.$lineFeed.
$hashEvsParameters["PROXY"].$assignmentOperator.$proxyString.$lineFeed.
$hashEvsParameters["ENCODE"].$lineFeed.$timeOut.$lineFeed.
$hashEvsParameters["ERROR"].$assignmentOperator.$OutErrorFilePath.$lineFeed.
$hashEvsParameters["OUTPUT"].$assignmentOperator.$OutOutputFilePath.$lineFeed.
$hashEvsParameters["SEARCH"].$lineFeed;
if($trash_Search) {
$utfParam .= $hashEvsParameters["TRASH"].$lineFeed;
if($searchPath == '')
$searchPath = '/';
}
if($_SESSION['dedup']){
if((($trash_Search && $input!='*') || !$trash_Search) && $archive != 1) {
$utfParam .= $hashEvsParameters["SEARCH_KEY"].$assignmentOperator.$input.$lineFeed;
if($searchPath != '/')
$utfParam .= $hashEvsParameters["FILEONLY"].$lineFeed;
}
if($archive == 1)
$utfParam .= $hashEvsParameters["DEVICE_ID"].$assignmentOperator.$_SESSION['deviceID'].$lineFeed;
else
{
$utfParam .= $currentDeviceID;
//$utfParam .= $hashEvsParameters["DEVICE_ID"].$assignmentOperator.$_SESSION['deviceID'].$lineFeed;
}
$utfParam .= $hashEvsParameters["XMLOUTPUT"].$lineFeed.
$userName.$serverAddressOperator.$_SESSION['serverAddr'].$serverNameOperator.
$serverName.$searchPath.$lineFeed;
} else {
$utfParam .= $userName.$serverAddressOperator.
$_SESSION['serverAddr'].$serverNameOperator.
$serverName.$searchPath."*".$input."*".$lineFeed;
}
break;
case AUTHLISTOP:
$utfPath = preg_replace(('/' . UTF8_FILE . '/'), (AUTHLISTOP . '_' . UTF8_FILE), $utfPath);
$OutErrorFilePath = $OutOutputFilePath = createFullRestoreDir($input);
$OutErrorFilePath .= "/".ERROR_FILE;
$OutOutputFilePath .= "/" . OUTPUTFILE;
$utfParam = $hashEvsParameters["AUTHLIST"].$lineFeed;
if($input == "Private")
$utfParam .= $hashEvsParameters["PVTKEY"].$assignmentOperator.$encPvtkeyPath.$lineFeed;
$utfParam .= $currentDeviceID.$hashEvsParameters["XMLOUTPUT"].$lineFeed;
$utfParam .= $hashEvsParameters["PASSWORD"].$assignmentOperator.$encPwdPath.$lineFeed.
$hashEvsParameters["PROXY"].$assignmentOperator.$proxyString.$lineFeed.
$hashEvsParameters["ENCODE"].$lineFeed.
$hashEvsParameters["ERROR"].$assignmentOperator.$OutErrorFilePath.$lineFeed.
$hashEvsParameters["OUTPUT"].$assignmentOperator.$OutOutputFilePath.$lineFeed.
$userName.$serverAddressOperator.
$_SESSION['serverAddr'].$serverNameOperator.
$serverName.$input."/".$lineFeed;
break;
case GETQUOTAOP:
$utfParam = $hashEvsParameters["XMLOUTPUT"].$lineFeed.
$hashEvsParameters["PASSWORD"].$assignmentOperator.$encPwdPath.$lineFeed.
$hashEvsParameters["ENCODE"].$lineFeed;
$utfParam .= $hashEvsParameters["GETQUOTA"].$lineFeed;
$utfParam .= $hashEvsParameters["PROXY"].$assignmentOperator.$proxyString.$lineFeed.
$hashEvsParameters["ERROR"].$assignmentOperator.$OutErrorFilePath.$lineFeed.
$userName.$serverAddressOperator.
$_SESSION['serverAddr'].$serverNameOperator.
$serverName.$pathSeparator.$lineFeed;
break;
case REINDEX:
$utfPath = UTF8_FILE;
$OutErrorFilePath = ERROR_FILE;
$OutOutputFilePath = OUTPUTFILE;
$localPath = getLocalBackupLocation();
#$localPath = "{$localPath}/{$userName}/{$nasUserName}/" . $input;
$localPath = "{$localPath}/{$userName}/" . $input;
$utfParam = $hashEvsParameters["DB_RECREATE"] . $lineFeed.
$hashEvsParameters["USERNAME"] . $assignmentOperator . $userName . $lineFeed.
$hashEvsParameters["ERROR"] . $assignmentOperator . $OutErrorFilePath . $lineFeed.
$hashEvsParameters["OUTPUT"] . $assignmentOperator . $OutOutputFilePath . $lineFeed.
$hashEvsParameters["PORTABLE_DEST"] . $assignmentOperator . $localPath . $lineFeed;
break;
case LISTDEDUPDEVICESOP:
$utfParam = $hashEvsParameters["LISTDEVICE"].$lineFeed.
$hashEvsParameters["PASSWORD"].$assignmentOperator.$encPwdPath.$lineFeed.
$hashEvsParameters["PROXY"].$assignmentOperator.$proxyString.$lineFeed.
$hashEvsParameters["ENCODE"].$lineFeed;
if($_SESSION["encType"] == "Private")
$utfParam .= $hashEvsParameters["PVTKEY"].$assignmentOperator.$encPvtkeyPath.$lineFeed;
$utfParam .= $userName.$serverAddressOperator.
$_SESSION['serverAddr'].$serverNameOperator.
$serverName.$pathSeparator.$lineFeed;
break;
case CREATEBUCKETOP:
$uid = getDedupUID();
$osName = OSNAME;
$bucketType = BUCKETTYPE;
$utfParam = $hashEvsParameters["CREATEBUCKET"].$lineFeed.
$hashEvsParameters["PASSWORD"].$assignmentOperator.$encPwdPath.$lineFeed.
$hashEvsParameters["PROXY"].$assignmentOperator.$proxyString.$lineFeed.
$hashEvsParameters["ENCODE"].$lineFeed;
if($_SESSION["encType"] == "Private")
$utfParam .= $hashEvsParameters["PVTKEY"].$assignmentOperator.$encPvtkeyPath.$lineFeed;
$utfParam .= $hashEvsParameters["NICKNAME"].$assignmentOperator.$input.$lineFeed.
$hashEvsParameters["UID"].$assignmentOperator.$uid.$lineFeed.
$hashEvsParameters["OS_NAME"].$assignmentOperator.$osName.$lineFeed.
$hashEvsParameters["BUCKET_TYPE"].$assignmentOperator.$bucketType.$lineFeed.
$userName.$serverAddressOperator.
$_SESSION['serverAddr'].$serverNameOperator.
$serverName.$pathSeparator.$lineFeed;
break;
case LINKBUCKETOP:
$uid = getDedupUID();
$osName = OSNAME;
$bucketType = BUCKETTYPE;
$utfParam = $hashEvsParameters["LINK_BUCKET"].$lineFeed.
$hashEvsParameters["PASSWORD"].$assignmentOperator.$encPwdPath.$lineFeed.
$hashEvsParameters["PROXY"].$assignmentOperator.$proxyString.$lineFeed.
$hashEvsParameters["ENCODE"].$lineFeed;
if($_SESSION["encType"] == "Private")
$utfParam .= $hashEvsParameters["PVTKEY"].$assignmentOperator.$encPvtkeyPath.$lineFeed;
$utfParam .= $hashEvsParameters["NICKNAME"].$assignmentOperator.$input.$lineFeed.
$hashEvsParameters["UID"].$assignmentOperator.$uid.$lineFeed.
$hashEvsParameters["OS_NAME"].$assignmentOperator.$osName.$lineFeed.
$hashEvsParameters["BUCKET_TYPE"].$assignmentOperator.$bucketType.$lineFeed.
$hashEvsParameters["DEVICE_ID"].$assignmentOperator.$searchPath.$lineFeed.
$userName.$serverAddressOperator.
$_SESSION['serverAddr'].$serverNameOperator.
$serverName.$pathSeparator.$lineFeed;
break;
case NICKNAMEUPDATEOP:
$osName = OSNAME;
$utfParam = $hashEvsParameters["NICK_UPDATE"].$lineFeed.
$hashEvsParameters["PASSWORD"].$assignmentOperator.$encPwdPath.$lineFeed.
$hashEvsParameters["PROXY"].$assignmentOperator.$proxyString.$lineFeed.
$hashEvsParameters["ENCODE"].$lineFeed;
if($_SESSION["encType"] == "Private")
$utfParam .= $hashEvsParameters["PVTKEY"].$assignmentOperator.$encPvtkeyPath.$lineFeed;
$utfParam .= $hashEvsParameters["NICKNAME"].$assignmentOperator.$input.$lineFeed.
$hashEvsParameters["OS_NAME"].$assignmentOperator.$osName.$lineFeed.
$hashEvsParameters["DEVICE_ID"].$assignmentOperator.$_SESSION['deviceID'].$lineFeed.
$userName.$serverAddressOperator.
$_SESSION['serverAddr'].$serverNameOperator.
$serverName.$pathSeparator.$lineFeed;
break;
}
file_put_contents($utfPath, $utfParam);
@chmod($utfPath,$permissionVal);
Scheduler::Log("$optType operation has been executed.");
return $utfPath;
}
/*********************************************************************************************************
* Subroutine Name : remoteList.
* Objective : List of user data from IDrive server(--auth-list) for specific path.
* Added By : Avinash Kumar.
* Modified By : Yogesh Kumar, Sabin Cheruvattil
**********************************************************************************************************/
function remoteList( $remotePath ) {
GLOBAL $webDir;
GLOBAL $idevsutilBinaryPath;
GLOBAL $whiteSpace;
GLOBAL $idevsutilArgument;
GLOBAL $assignmentOperator;
GLOBAL $lineFeed;
GLOBAL $userName;
GLOBAL $permissionVal, $handle;
$rListIntPath = '';
$restoreFile = '';
$terminate = false;
$authListUtfFile = getOperationFile(AUTHLISTOP, $remotePath);
$restoreListDirPath = createFullRestoreDir($remotePath);
$pidFile = $restoreListDirPath.'/'.PID_FILE;
$OutOutputFilePath = $restoreListDirPath.'/'.OUTPUTFILE;
$OutErrorFilePath = $restoreListDirPath.'/'.ERROR_FILE;
if(!($handle = fopen($pidFile, "w"))){
Scheduler::Log("Failed to create $pidFile");
exit;
}
else if(!flock($handle, LOCK_EX|LOCK_NB)){
# process is running already
Scheduler::Log("Not able to lock " . PID_FILE);
# @unlink($pidFile);
exit;
}
$idevsutilCommandLine = $idevsutilBinaryPath.$whiteSpace.$idevsutilArgument.$assignmentOperator."\"$authListUtfFile\"";
if(file_exists($OutOutputFilePath))
unlink($OutOutputFilePath);
if(file_exists($OutErrorFilePath))
unlink($OutErrorFilePath);
Scheduler::Log('Requesting remote list: ' . $remotePath);
$restoreDir = Scheduler::$restore_list_dir;
if( !is_dir($restoreDir) ) {
if( !mkdir($restoreDir, $permissionVal) ) {
Scheduler::Log("Could not create directory $restoreDir, Reason : ".customErrorMsg());
@unlink($authListUtfFile);
@unlink($pidFile);
return;
}
@chmod($restoreDir, $permissionVal);
}
pclose(popen("$idevsutilCommandLine &","r"));
while((!file_exists($OutOutputFilePath) || !customFileSize($OutOutputFilePath)) && (!file_exists($OutErrorFilePath) || !customFileSize($OutErrorFilePath))){
if(!file_exists($pidFile))
break;
sleep(WAIT_FOR);
}
$extraString = '';
$fp = fopen($OutOutputFilePath, 'r');
if(!$fp){
Scheduler::Log("Could not open file $OutOutputFilePath, Reason : ".customErrorMsg());
@unlink($authListUtfFile);
@unlink($pidFile);
return;
}
$pageNumber = 0;
$numberOfLines = 0;
$maxNumberOfLines = MAX_NUM_OF_ITEMS;
$arrayList = array();
$lastLine ='';
$authfailed = FALSE;
while(1) {
$buffer = '';
$buffer = fread($fp, (1024 * 10));
if ($buffer == '') {
if(file_exists($OutErrorFilePath) && customFileSize($OutErrorFilePath)) {
$error = file_get_contents($OutErrorFilePath);
$reason = checkErrorAndReason($error);
Scheduler::Log("EVS error on $OutErrorFilePath, Reason : $reason");
if(stripos($reason, 'password mismatch') !== FALSE || stripos($reason, 'service not known') !== FALSE || stripos($reason, 'encryption verification failed') !== FALSE) {
$authfailed = TRUE;
@unlink(Scheduler::$user_dir . "IDPWD");
}
break;
}
sleep(WAIT_FOR);
fseek($fp, 0, 1); //to clear eof flag
continue;
}
//need to check appending partial record to packet or to first line of packet
if("" != $lastLine){
$buffer = $lastLine.$buffer;
}
if(!preg_match('/\n$/', $buffer)){
$lastNewlinePos = strrpos($buffer, "\n");
$resultList = substr($buffer,0,$lastNewlinePos+1);
$lastLine = substr($buffer,$lastNewlinePos+1);
} else {
$resultList = $buffer;
$lastLine = '';
}
if(preg_match('/bytes\/sec/', $resultList))
$terminate = true;
$xml = verifyXMLoutput($resultList);
if(!$xml){
Scheduler::Log("xml:$resultList".customErrorMsg());
$resultListXML = checkAndConstructXML($resultList);
$resultListXML = "<root>$resultListXML</root>";
$xml = simplexml_load_string($resultListXML);
}
foreach ($xml->item as $value)
{
$fname = (string)$value['fname'];
$type = (string)$value['restype'];
$modTime = (string)$value['mod_time'];
if($type == "D") {
$arrayList["$fname"]['size'] = '--';
$arrayList["$fname"]['datetime'] = $modTime;
$arrayList["$fname"]['type'] = "D";
} else {
$size = (string)$value['size'][0];
$arrayList["$fname"]['size'] = $size;
$arrayList["$fname"]['datetime'] = $modTime;
$arrayList["$fname"]['type'] = "F";
}
++$numberOfLines;
if ($numberOfLines == $maxNumberOfLines) {
$rListPath = constructRestoreFileName($remotePath, $pageNumber);
file_put_contents($rListPath, json_encode($arrayList), LOCK_EX);
@chmod($rListPath, $permissionVal);
$arrayList = array();
$numberOfLines = 0;
$pageNumber++;
}
}
if ($terminate)
break;
}
fclose($fp);
//if (count($arrayList) > 0) { //Commented to fill with empty if there is no items - Senthil (May30-2017)
$rListPath = constructRestoreFileName($remotePath, $pageNumber);
file_put_contents($rListPath, json_encode($arrayList), LOCK_EX);
@chmod($rListPath, $permissionVal);
//}
@unlink($authListUtfFile);
@unlink($pidFile);
if(file_exists($OutOutputFilePath))
unlink($OutOutputFilePath);
if(file_exists($OutErrorFilePath))
unlink($OutErrorFilePath);
if($authfailed) {
exit(header('Location:./logout.php'));
}
}
#****************************************************************************************************
# Subroutine Name : remoteSearch.
# Objective : This function will execute the EVS search command and parse the output file
# to provide the expected output to user.
# Modified By : Vijay Vinoth, Senthil Pandian
#*****************************************************************************************************/
function remoteSearch($searchItem,$searchPath,$trashSearch)
{
GLOBAL $idevsutilBinaryPath;
GLOBAL $whiteSpace;
GLOBAL $idevsutilArgument;
GLOBAL $assignmentOperator;
GLOBAL $OutErrorFilePath;
GLOBAL $OutOutputFilePath;
GLOBAL $webDir;
GLOBAL $userName;
GLOBAL $searchHandle;
GLOBAL $countItem;
GLOBAL $isOpened;
GLOBAL $searchDirRemote;
GLOBAL $pagePath;
GLOBAL $pidPath;
GLOBAL $permissionVal;
GLOBAL $trash_Search;
GLOBAL $searchDirTrashRemote;
GLOBAL $pidPathForSearch;
GLOBAL $isSearchDir;
GLOBAL $searchUtfFile;
if($trashSearch) {
$trash_Search = 1;
$searchDirRemote = $searchDirTrashRemote;
}
else $trash_Search = 0;
if(!is_dir($searchDirRemote)){
if(!mkdir($searchDirRemote, $permissionVal)){
$resp[] = false;
$resp[] = "Failed to create Directory ".$searchDirRemote." : ".customErrorMsg();
unset($_SESSION['currentRemoteSearchPath']);
unset($_SESSION['currentRemoteTrashSearchPath']);
echo json_encode($resp);
exit;
}
@chmod($searchDirRemote,$permissionVal);
}
if("" == $searchItem){
unset($_SESSION['currentRemoteSearchPath']);
unset($_SESSION['currentRemoteTrashSearchPath']);
return;
}
$volumePath = @readlink("$webDir");
if(empty($volumePath))
$volumePath = "$webDir";
$isSearchDir = createSearchDir($searchPath.$searchItem,$searchDirRemote);
if($isSearchDir === false){
print "Search pattern directory not created";
return;
} else if($_SESSION['dedup'] && !empty($isSearchDir) && $isSearchDir!="/"){
removeItems($isSearchDir."/*");
}
$pidPathForSearch = "$isSearchDir/$pidPath";
if(!$trashSearch)
$_SESSION['currentRemoteSearchPath'] = $isSearchDir."/";
else
$_SESSION['currentRemoteTrashSearchPath'] = $isSearchDir."/";
session_write_close();
//to get the php error message in customErrorMsg() variable.
ini_set('track_errors', 1);
//Terminating if result is already there for search pattern
if($trash_Search) $pages = "/trash_page1";
else $pages = "/page1";
if(file_exists($isSearchDir.$pages))
return;
if(!($handle = fopen($pidPathForSearch, "w"))){
Scheduler::Log(customErrorMsg());
return;
}
else{
@chmod($pidPathForSearch,$permissionVal);
if(!flock($handle, LOCK_EX|LOCK_NB))
Scheduler::Log("Not able to lock " . PID_FILE);
fclose($handle);
}
$lastLine = "";
$pageCount = 0;
$flag = 0;
$buffer = "";
$byteRead = 0;
$len = 0;
$toSearchStr = "";
$type = "";
$size = "";
$dateTime = "";
$item = "";
$pattern = "";
$tmpArr = array();
$isNotOpened = 0;
$totalCount = 0;
$searchUtfFile = getOperationFile(SEARCHOP, $searchItem, $searchPath);
@chmod($searchUtfFile,$permissionVal);
if(!file_exists($searchUtfFile)){
Scheduler::Log(customErrorMsg());
return false;
}
$searchUtfFile = str_replace("'","'\''",$searchUtfFile);
$idevsutilCommandLine = $idevsutilBinaryPath.$whiteSpace.$idevsutilArgument.$assignmentOperator."'$searchUtfFile'";
if(!file_exists($pidPathForSearch)){
$errStr = ERR_STR_VAL;
userCancelremoteSearch($errStr);
return;
}
else{
Scheduler::Log("Requesting remote search: " . $searchItem);
pclose(popen("$idevsutilCommandLine &","r"));
}
while(!customFileSize($OutOutputFilePath) and !customFileSize($OutErrorFilePath)){
if(!file_exists($pidPathForSearch) || customFileSize($OutErrorFilePath)){
$errStr = ERR_STR_VAL;
userCancelremoteSearch($errStr);
if(file_exists($OutErrorFilePath)){
$error = file_get_contents($OutErrorFilePath);
$reason = checkErrorAndReason($error);
}
return;
}
sleep(1);
}
/* update server address if cmd failed due to wrong evs server address. */
if(checkErrorAndUpdateServerAddr($OutErrorFilePath)){
userCancelremoteSearch();
return;
}
if(!customFileSize($OutOutputFilePath)){
userCancelremoteSearch();
return;
}
$handle = fopen($OutOutputFilePath, "r");
if(!$handle) {
$errStr = "not able to open file $OutOutputFilePath.\n";
userCancelremoteSearch($errStr);
return;
}
//Parse output.txt file for search results
if(isset($_SESSION['dedup']) && $_SESSION['dedup']){
while(1)
{
if(!file_exists($pidPathForSearch)){
fclose($handle);
if($searchHandle)
fclose($searchHandle);
$errStr = ERR_STR_VAL;
userCancelremoteSearch($errStr);
return;
//goto USER_CANCEL;
}
$buffer = fread($handle, LIMIT);
if(0 === strlen($buffer)){
if(customFileSize($OutErrorFilePath)){
$error = file_get_contents($OutErrorFilePath);
$reason = checkErrorAndReason($error);
Scheduler::Log("EVS error on $OutErrorFilePath, Reason : $reason");
unlink($pidPathForSearch);
break;
}
sleep(WAIT_FOR);
fseek($handle, 0, 1); //to clear eof flag
continue;
}
//need to check appending partial record to packet or to first line of packet
if("" != $lastLine)
$buffer = $lastLine.$buffer;
if(!preg_match('/\n$/', $buffer)){
$lastNewlinePos = strrpos($buffer, "\n");
$resultList = substr($buffer,0,$lastNewlinePos+1);
$lastLine = substr($buffer,$lastNewlinePos+1);
} else {
$resultList = $buffer;
$lastLine = '';
}
if(preg_match('/items_found/', $resultList))
$flag = 1;
$noOfLines = substr_count($resultList,"\n");
$resultListXML = "<root>$resultList</root>";
$xml = simplexml_load_string($resultListXML);
if(!$xml){
Scheduler::Log("Not XML: \n \n".$resultListXML);
if($flag == 1)
break;
continue;
//$resultListXML = checkAndConstructXML($resultList);
//$resultListXML = "<root>".utf8_encode($resultListXML)."</root>";
//$xml = simplexml_load_string($resultListXML);
}
foreach ($xml->item as $value)
{
if(0 == $isOpened)
{
$pageCount++;
if($searchHandle)
fclose($searchHandle);
if($trash_Search) $pageName = "trash_page";
else $pageName = "page";
$searchHandle = fopen("$pagePath/$pageName$pageCount", "w");
if(!$searchHandle)
{
Scheduler::Log(customErrorMsg());
unlink($pidPathForSearch);
return;
}
$isOpened = 1;
}
if(isset($value['items_found']))
break;
$item = trim($value['fname']);
if($countItem == 0){
if(stristr($item,$searchItem)){
$dateTime = trim($value['mod_time']);
$size = trim($value['size']);
$size = humanReadableSize($size);
$type = trim($value['restype']);
if($type == "D")
$pattern = $item;
addListWithType($type, $item, $dateTime, $size);
}
continue;
}
$retVal = "";
if($pattern){
$retVal = stripos($item, $pattern);
$orgPattern = $pattern;
}
/* Check for all previous patterns based on current pattern */
$arrTmp = array();
if($retVal === FALSE) {
$arrTmp = explode("/", $pattern);
}
if($retVal === FALSE and sizeof($arrTmp) > 2 and $arrTmp[sizeof($arrTmp) -1] == "")
$tmp = array_pop($arrTmp);
while($retVal === FALSE and sizeof($arrTmp) > 2) {
$tmp = array_pop($arrTmp);
if(1 == sizeof($arrTmp)) {
$pattern = $orgPattern;
break;
}
$pattern = implode("/", $arrTmp);
$retVal = "";
$retVal = stripos($item, $pattern);
}
if($retVal !== FALSE and $retVal === 0){
$len = strlen($pattern);
$toSearchStr = substr($item, $len);
$exitMatch = 0;
if("" != $toSearchStr){
if(!stristr($toSearchStr,$searchItem)){
if(FALSE === stripos($toSearchStr, "/") and substr($item, $len-1, 1) !== "/")
$exitMatch = 1;
}
else
$exitMatch = 1;
}
if($exitMatch){
//$pattern = $item;
$dateTime = trim($value['mod_time']);
$size = trim($value['size']);
$size = humanReadableSize($size);
$type = trim($value['restype']);
if($type == "D")
$pattern = $item;
addListWithType($type, $item, $dateTime, $size);
}
}
else {
//$pattern = $item;
$dateTime = trim($value['mod_time']);
$size = trim($value['size']);
$size = humanReadableSize($size);
$type = trim($value['restype']);
if($type == "D")
$pattern = $item;
addListWithType($type, $item, $dateTime, $size);
}
if(!file_exists($pidPathForSearch)){
fclose($handle);
if($searchHandle){
fclose($searchHandle);
}
$errStr = ERR_STR_VAL;
userCancelremoteSearch($errStr);
return;
//goto USER_CANCEL;
}
}
if(1 == $flag)
break;
}
}
else {
while(1){
if(!file_exists($pidPathForSearch)){
fclose($handle);
if($searchHandle)
fclose($searchHandle);
$errStr = ERR_STR_VAL;
userCancelremoteSearch($errStr);
return;
}
$buffer = fread($handle, LIMIT);
if(0 === strlen($buffer)){
if(customFileSize($OutErrorFilePath)){
$error = file_get_contents($OutErrorFilePath);
$reason = checkErrorAndReason($error);
break;
}
sleep(WAIT_FOR);
fseek($handle, 0, 1); //to clear eof flag
continue;
}
//need to check appending partial record to packet or to first line of packet
if("" != $lastLine)
$buffer = $lastLine . $buffer;
$resultList = explode("\n", $buffer);
$bufIndex = count($resultList);
$bufIndex -= 1;
//keep last line of buffer only when it not ends with newline.
if(!preg_match('/\n$/', $buffer))
$lastLine = $resultList[$bufIndex];
else
$lastLine = "";
if(0 < $bufIndex and preg_match('/Total files found/', $resultList[$bufIndex-1])){
$flag = 1;
$bufIndex -= 1;
}
$totalCount += $bufIndex;
for($index = 0; $index < $bufIndex; $index++)
{
$tmpArr = explode("] [", $resultList[$index], 6);
if(count($tmpArr) < 6)
continue;
if(0 == $isOpened)
{
$pageCount++;
if($searchHandle){
fclose($searchHandle);
}
if($trash_Search) $pageName = "trash_page";
else $pageName = "page";
$searchHandle = fopen("$pagePath/$pageName$pageCount", "w");
if(!$searchHandle)
{
Scheduler::Log(customErrorMsg());
unlink($pidPathForSearch);
return;
}
$isOpened = 1;
}
$tmpArr = explode("] [", $resultList[$index], 6);
$tmpArr[count($tmpArr) - 1] = rtrim($tmpArr[count($tmpArr) - 1], "]");
$item = $tmpArr[count($tmpArr) - 1];
if($countItem == 0){
if(stristr($item,$searchItem)){
$dateTime = preg_replace("/^\[/", "", $tmpArr[0]); //remove '['
$size = trim($tmpArr[1]);
$size = humanReadableSize($size);
$type = trim($tmpArr[2])==0?"D":"F";
if($type == "D")
$pattern = $item;
addListWithType($type, $item, $dateTime, $size);
}
continue;
}
$retVal = "";
if($pattern){
$retVal = stripos($item, $pattern);
$orgPattern = $pattern;
}
/* Check for all previous patterns based on current pattern */
$arrTmp = array();
if($retVal === FALSE) {
$arrTmp = explode("/", $pattern);
}
if($retVal === FALSE and sizeof($arrTmp) > 2 and $arrTmp[sizeof($arrTmp) -1] == "")
$tmp = array_pop($arrTmp);
while($retVal === FALSE and sizeof($arrTmp) > 2) {
$tmp = array_pop($arrTmp);
if(1 == sizeof($arrTmp)) {
$pattern = $orgPattern;
break;
}
$pattern = implode("/", $arrTmp);
$retVal = "";
$retVal = stripos($item, $pattern);
}
if($retVal !== FALSE and $retVal === 0){
$len = strlen($pattern);
$toSearchStr = substr($item, $len);
$exitMatch = 0;
if("" != $toSearchStr){
if(!stristr($toSearchStr,$searchItem)){
if(FALSE === stripos($toSearchStr, "/") and substr($item, $len-1, 1) !== "/"){
$exitMatch = 1;
}
}
else{
$exitMatch = 1;
}
}
if($exitMatch){
$dateTime = preg_replace("/^\[/", "", $tmpArr[0]);
$size = trim($tmpArr[1]);
$size = humanReadableSize($size);
$type = trim($tmpArr[2])==0?"D":"F";
if($type == "D")
$pattern = $item;
addListWithType($type, $item, $dateTime, $size);
}
}
else {
$dateTime = preg_replace("/^\[/", "", $tmpArr[0]);
$size = trim($tmpArr[1]);
$size = humanReadableSize($size);
$type = trim($tmpArr[2])==0?"D":"F";
if($type == "D")
$pattern = $item;
addListWithType($type, $item, $dateTime, $size);
}
if(!file_exists($pidPathForSearch)){
fclose($handle);
if($searchHandle){
fclose($searchHandle);
}
$errStr = ERR_STR_VAL;
userCancelremoteSearch($errStr);
return;
}
}
if(1 == $flag)
break;
}
}
if($searchHandle)
fclose($searchHandle);
if($handle)
fclose($handle);
userCancelremoteSearch($errStr);
return;
}
/*******************************************************************************************************
* Subroutine Name : userCancelremoteSearch.
* Objective :
* Added By :
********************************************************************************************************/
function userCancelremoteSearch($errStr = '')
{
GLOBAL $pidPathForSearch, $isSearchDir, $searchUtfFile;
if($errStr != ""){
Scheduler::Log("Remote Search Error : $errStr");
}
if(file_exists($pidPathForSearch)){
unlink($pidPathForSearch);
}
else{
$isSearchDir = str_replace("'","'\''",$isSearchDir);
$isSearchDir = "'".$isSearchDir;
if(!empty($isSearchDir) && $isSearchDir!="/"){
$val = array($isSearchDir."/page*", $isSearchDir."/trash_page*");
removeItems($val);
}
$isSearchDir = ltrim ($isSearchDir, "'");
}
$searchUtfFile = str_replace("'\''","'",$searchUtfFile);
if(file_exists($searchUtfFile)){
unlink($searchUtfFile);
}
$isSearchDirError = $isSearchDir."/".ERROR_FILE;
if(file_exists($isSearchDirError)){
unlink($isSearchDirError);
}
$isSearchDirOutput = $isSearchDir."/".OUTPUTFILE;
if(file_exists($isSearchDirOutput)){
unlink($isSearchDirOutput);
}
}
/*******************************************************************************************************
* Subroutine Name : createSearchDir.
* Objective : Create search folder recursively with pattern folder.
* Added By : Avinash Kumar.
********************************************************************************************************/
function createSearchDir($searchData,$searchDirRemote)
{
GLOBAL $pagePath;
GLOBAL $permissionVal;
$searchData = preg_replace("/\*+/", "", $searchData); //remove character '*'.
$dirArr = explode("/", $searchData);
$len = count($dirArr);
$path = $searchDirRemote;
$init = empty($dirArr[0])?1:0;
for($i = $init; $i < $len; $i++)
{
$path .= "/$dirArr[$i]";
if(! file_exists($path))
{
if(!mkdir($path,$permissionVal))
{
if($i == $len - 1)
{
$lastItemLen = strlen($dirArr[$i]);
$path = substr($path, 0, -$lastItemLen); //remove last item when mkdir fails.
$path .= "pattern";
if(file_exists($path))
{
$path = str_replace("'","'\''",$path);
$path = "'".$path."'";
removeItems($path);
}
if(!mkdir($path,$permissionVal))
{
Scheduler::Log(customErrorMsg());
return false;
}
@chmod($path,$permissionVal);
}
Scheduler::Log(customErrorMsg());
return false;
}
@chmod($path,$permissionVal);
}
}
$pagePath = $path;
return $pagePath;
}
#*******************************************************************************************************
# Subroutine Name : addListWithType.
# Objective : Create list with file or directory type.
# Added By : Avinash Kumar.
#*******************************************************************************************************/
function addListWithType($type, $item, $dateTime, $size)
{
GLOBAL $countItem;
GLOBAL $searchHandle;
GLOBAL $isOpened;
GLOBAL $empty_trash;
if("" == $item)
return;
if("D" == $type)
$size = '--';
if($empty_trash)
$str = $item . "\n";
else
$str = $item . "\n" . $size . "\n" . $dateTime . "\n" . $type . "\n";
// flush(); Commented by Senthil on 05/05/2017 for HR_Synology_2.04.13_05
fwrite($searchHandle, $str);
$countItem++;
if(0 == $countItem % NO_OF_LINES && !$empty_trash)
$isOpened = 0;
}
#*******************************************************************************************************
# Subroutine Name : convertFileSize.
# Objective : file size of a file which has been result of search in readable format.
# Added By : Avinash Kumar.
#*******************************************************************************************************/
function convertFileSize($fileSize)
{
$fileSpec = "bytes";
GLOBAL $whiteSpace;
if($fileSize > 1023)
{
$fileSize /= 1024;
$fileSpec = "KB";
}
if($fileSize > 1023)
{
$fileSize /= 1024;
$fileSpec = "MB";
}
if($fileSize > 1023)
{
$fileSize /= 1024;
$fileSpec = "GB";
}
if($fileSize > 1023)
{
$fileSize /= 1024;
$fileSpec = "TB";
}
$fileSize = sprintf("%.2f", $fileSize);
if(0 == ($fileSize - intval($fileSize)))
{
$fileSize = sprintf("%.0f", $fileSize);
}
return $fileSize.$whiteSpace.$fileSpec;
}
/*********************************************************************************************************
* Subroutine Name : deleteItems.
* Objective : Delete set of file/folder from server.
* Added By : Avinash Kumar.
* Modified By : (26-Aug-2015) Modified by sajana for Archive Cleanup.
**********************************************************************************************************/
function deleteItems($operationType, $input, $itemsForDeleteType = '', $totalFileToDelete = 0)
{
GLOBAL $idevsutilBinaryPath;
GLOBAL $whiteSpace;
GLOBAL $idevsutilArgument;
GLOBAL $assignmentOperator;
GLOBAL $OutErrorFilePath;
GLOBAL $OutOutputFilePath;
GLOBAL $webDir;
GLOBAL $userName;
GLOBAL $searchDirRemote;
GLOBAL $searchDirTrashRemote;
GLOBAL $permissionVal;
GLOBAL $archive_per;
GLOBAL $selected_backupset;
GLOBAL $total_perc;
GLOBAL $periodic_perc_error;
GLOBAL $empty_trash,$returnArray ;
GLOBAL $pidhandle, $deleteUtfFile,$pidPath;
GLOBAL $dedupDetailFile;
GLOBAL $nasUserName;
$pidhandle = "";
$lastLine = "";
$commLine = 5;
$flag = 0;
$logHandle = "";
$countDeleted = 0;
$logStatus = "";
$outputFile = "";
$flagTerm = 1;
$errStr = "";
$jobName = Scheduler::$manual_dir;
$countFile = Scheduler::$archiveclean_dir.$jobName."/".ARCHIVECOUNT;
$archiveErrorDir = Scheduler::$archiveclean_dir.$selected_backupset."/error/";
if (is_dir($archiveErrorDir))
`rm -rf $archiveErrorDir`;
`mkdir $archiveErrorDir`;
`chmod 777 $archiveErrorDir`;
file_put_contents($countFile,'');
if(!is_dir(Scheduler::$delete_dir)){
if(!mkdir(Scheduler::$delete_dir, $permissionVal)){
Scheduler::Log(customErrorMsg());
$retVal = userCancelDeleteItems($operationType, $input,"");
return $retVal;
}
@chmod(Scheduler::$delete_dir,$permissionVal);
}
if(!is_dir(Scheduler::$delete_log_dir)){
if(!mkdir(Scheduler::$delete_log_dir, $permissionVal)){
$errStr = 'AR_DEL_LOG_DIR';
$retVal = userCancelDeleteItems($operationType, $input, $errStr);
return $retVal;
}
@chmod(Scheduler::$delete_log_dir,$permissionVal);
}
$logDate = shell_exec('date +"%Y-%m-%d %I:%M:%S %p"');
if(ARCHIVEOP == $operationType || PERIODICARCHIVEOP == $operationType)
$pidPath = Scheduler::$archiveclean_dir.$selected_backupset."/".PID_FILE;
else if($empty_trash)
$pidPath = $searchDirTrashRemote."/EmptyTrash/".PID_FILE;
else
$pidPath = Scheduler::$delete_dir.PID_FILE;
$restoreList = Scheduler::$restore_list_dir."/";
$_SESSION['deleteCommand'] = 0;
/* to get the php error message in customErrorMsg() variable. */
ini_set('track_errors', 1);
if(ARCHIVEOP != $operationType && PERIODICARCHIVEOP != $operationType){
if(!($pidhandle = fopen($pidPath, "w"))){
Scheduler::Log(customErrorMsg());
$retVal = userCancelDeleteItems($operationType, $input,"");
return $retVal;
}
else{
@chmod($pidhandle,$permissionVal);
if(!flock($pidhandle, LOCK_EX|LOCK_NB)){
$errStr = "Not able to lock " . PID_FILE;
Scheduler::Log($errStr);
$retVal = userCancelDeleteItems($operationType, $input, $errStr);
return $retVal;
}
if(DELETEOP == $operationType || REMOVE_FROM_TRASHOP == $operationType)
fwrite($pidhandle,"Delete");
if(PUT_BACKOP == $operationType)
fwrite($pidhandle,"PUTBACK");
@chmod($pidPath,$permissionVal);
}
}
$linecount = 0;
//need to replace with not_exist_count
//$linecount = `cat $input | wc -l`;
$linecount = $totalFileToDelete;
$linecount = trim($linecount, "\n");
# need to split input file to generate 10000 set in each . return count. fill in hash, recreate failed files and make the loop to pick those files for retry.
#need to get this value from not_exist_count
$count = (int)$totalFileToDelete;
$_SESSION['totalFileToDelete'] = $count;
(int)$countVal = (int)$count/10000;
if(($count%10000) > 0)
(int)$countVal = (int)$countVal + 1;
$noOfFiles = $countVal;
/* log file name creation as per operation type. */
$logpid = Scheduler::$delete_dir.LOG_PID_FILE;
if(DELETEOP == $operationType)
$outputFile = Scheduler::$delete_log_dir.trim($logDate) . " DELETE";
else if(PUT_BACKOP == $operationType)
$outputFile = Scheduler::$delete_log_dir.trim($logDate) . " PUTBACK";
else if(REMOVE_FROM_TRASHOP == $operationType)
$outputFile = Scheduler::$delete_log_dir.trim($logDate) . " TRASHDELETE";
else if(ARCHIVEOP == $operationType || PERIODICARCHIVEOP == $operationType)
{
$logDir = Scheduler::$archiveclean_dir.$selected_backupset."/LOGS/";
if(!is_dir($logDir)){
if(!mkdir($logDir, $permissionVal)){
$errStr = 'AR_DEL_LOG_DIR';
$retVal = userCancelDeleteItems($operationType, $input, $errStr);
return $retVal;
}
@chmod($logDir,$permissionVal);
}
$logpid = Scheduler::$archiveclean_dir.$selected_backupset."/".LOG_PID_FILE;
$outputFile = Scheduler::$archiveclean_dir.$selected_backupset."/LOGS/".trim($logDate)." ".ARCHIVECLEANUP_TITLE;
}
if(!($logHandle = fopen($outputFile, "w"))){
Scheduler::Log(customErrorMsg());
if($operationType == ARCHIVEOP){
$errStr = 'AR_DEL_LOG';
$retVal = userCancelDeleteItems($operationType, $input, $errStr);
return $retVal;
}
else if($operationType == DELETEOP)
return customErrorMsg();
}
if(!($logProgresshandle = openFile($logpid)) && $operationType == ARCHIVEOP) {
$errStr = 'AR_PID';
$retVal = userCancelDeleteItems($operationType, $input, $errStr);
return $retVal;
}
fwrite($logProgresshandle, $outputFile);
fclose($logProgresshandle);
$logStartEndTime = shell_exec('date +"%a %b %d %T %Y"');
/* write the operation start time with content corresponding to operation type. */
if(DELETEOP == $operationType || REMOVE_FROM_TRASHOP == $operationType){
fwrite($logHandle, "Delete Start Time: ".$logStartEndTime."\n\n");
}
else if(ARCHIVEOP == $operationType || PERIODICARCHIVEOP == $operationType)
{
/* changed by Avinash 04-07-2016 */
fwrite($logHandle, "Archive Cleanup Start Time: ".trim($logStartEndTime)."\n\n");
fwrite($logHandle, "NAS User name: ".$nasUserName."\n");
fwrite($logHandle, "Username: ".Scheduler::$user_name."\n");
$hostName = shell_exec("hostname");
$machineName = "Machine Name: ".$hostName;
fwrite($logHandle, $machineName);
if(PERIODICARCHIVEOP == $operationType)
fwrite($logHandle, "Backup set: ".$selected_backupset."\n");
if(ARCHIVEOP == $operationType)
fwrite($logHandle, "Backup set: ".$_SESSION['user_backup_set']."\n");
if(PERIODICARCHIVEOP == $operationType)
fwrite($logHandle, "Periodic Cleanup Operation"."\n");
else
fwrite($logHandle, "\n"."Archive Cleanup Operation"."\n");
fwrite($logHandle, " "."\n");
/* If no % error then write deleted content */
if(!isset($periodic_perc_error))
/* changed by Avinash 04-07-2016 */
fwrite($logHandle, "[Deleted Content]"."\n");
else if((PERIODICARCHIVEOP == $operationType) && ($periodic_perc_error == 0)){
$flagTerm = 0; /* setting flag to skip delete operation for % error */
fwrite($logHandle, "[Periodic Cleanup Operation] Aborted due to the number of files considered for deletion is ".$total_perc."%, which is more than ".$archive_per."%"."\n");
}
}
else if(PUT_BACKOP == $operationType)
fwrite($logHandle, "Put Back Start Time: ".$logStartEndTime."\n\n");
if(!file_exists($pidPath)){
$flagTerm = 0;
$errStr = ERR_STR_VAL;
}
if($flagTerm ==1){
$_SESSION['deleteCommand'] = 1;
session_write_close();
/******** added new changes by anil **********/
//$errorLogFile = Scheduler::$archiveclean_dir.$selected_backupset."/errorLog.txt";
//$logHandleTemp = fopen($errorLogFile, "w");
$counter = $noOfFiles * 5;
for($i = 1; $i <= $noOfFiles && $counter > 0; $i++) {
if(!file_exists($pidPath)){
$flagTerm = 0;
$errStr = ERR_STR_VAL;
break;
}
$archiveHash = array();
$flag = 0;
$tempfile = Scheduler::$archiveclean_dir.$selected_backupset."/temp/result".$i.".txt";
$archiveSet = file($tempfile);
reset($archiveSet);
foreach($archiveSet as $item){
$item = trim($item,"\n");
if(!empty($item))
$archiveHash[$item] = 0;
}
$deleteUtfFile = getOperationFile($operationType, $tempfile);
$idevsutilCommandLine = $idevsutilBinaryPath.$whiteSpace.$idevsutilArgument.$assignmentOperator."\"$deleteUtfFile\"";
system("$idevsutilCommandLine", $output);
$oldErrorFile = $archiveErrorDir."error".$i.".txt";
if(file_exists($oldErrorFile))
removeItems($oldErrorFile);
/* if error file size is positive then return from here "with error". */
if(!($errHandle = fopen($OutErrorFilePath, "r")))
{
$errStr = customErrorMsg();
Scheduler::Log($errStr);
}
else{
while(! feof($errHandle)){
$errContent = fgets($errHandle);
/*if($errContent != "")
fwrite($logHandleTemp, $errContent);
*/
$reason = checkErrorAndReason($errContent);
/* update server address if cmd failed due to wrong evs server address. */
if(FALSE != (strpos($errContent, SERVER_ERROR))){
getServerAddress();
}
}
fclose($errHandle);
}
/* if($operationType == DELETEOP)
return OPERATION_FAILED;*/
if($handle = fopen($OutOutputFilePath, "r"))
{
$dedupRestoreDeviceIDVal = '';
$serverRoot = "";
if(file_exists($dedupDetailFile)){
#$dedupRestoreDeviceIDVal = rtrim(ltrim(file_get_contents($dedupRestoreDeviceID),"5c0b"),"4b5z");
$deviceJSON = file_get_contents($dedupDetailFile);
$deviceArray = json_decode($deviceJSON, true);
$deviceID = trim($deviceArray['deviceID']);
$serverRoot = trim($deviceArray['serverRoot']);
$dedupRestoreDeviceIDVal = preg_replace("/^5c0b/", '', $deviceID, 1);
$dedupRestoreDeviceIDVal = preg_replace("/4b5z$/", '', $dedupRestoreDeviceIDVal, 1);
}
while($flagTerm)
{
$buffer = fread($handle, LIMIT);
if(0 === strlen($buffer))
{
/* sleep(WAIT_FOR);
fseek($handle, 0, 1); //to clear eof flag
if(!file_exists($pidPath)){
$flagTerm = 0;
$errStr = ERR_STR_VAL;
}
continue; */
break;
}
/* Append partial record to packet */
if("" != $lastLine)
$buffer = $lastLine . $buffer;
$resultList = explode("\n", $buffer);
$bufIndex = sizeof($resultList);
$lastLine = $resultList[$bufIndex - 1];
$bufIndex -= 1;
if($bufIndex != 0 and (preg_match('/End of operation/',$resultList[$bufIndex - 1]))){
$flag = 1;
$bufIndex -= 2; // To remove 1 empty line & Number of items deleted.
}
else if(1 < $bufIndex and preg_match('/End of operation/',$resultList[$bufIndex-2])){
$flag = 1;
$bufIndex -= 3; // To remove 2 empty lines & Number of items deleted. In case delete multiple entries in delete set with exist data and non exist data.
}
else if($bufIndex != 0 and preg_match('/Incomplete operation/',$resultList[$bufIndex - 1]))
{
$flag = 1;
$bufIndex -= 4; // To remove 2 empty lines, End of operation & Number of items deleted. In case delete from trash multiple entries in delete set with exist data and non exist data.
}
if(preg_match('/No items found/',$resultList[$bufIndex - 1]))
break;
$noOfLines = substr_count($buffer,"\n");
if( $lastLine != ""){
array_pop($resultList);
$buffer = implode("\n", $resultList);
}
/*if($dedupRestoreDeviceIDVal!=''){
$buffer = preg_replace('/fname="\/[^\/]*[^\/]*\//', 'fname="/', $buffer); ;
}*/
$resultListXML = "<root>$buffer</root>";
$xml = simplexml_load_string($resultListXML);
if(!$xml){
$resultListXML = checkAndConstructXML($buffer);
//$resultListXML = "<root>".utf8_encode($resultListXML)."</root>"; //Commented by Senthil w.r.t Multi-language issue
$resultListXML = "<root>$resultListXML</root>";
$xml = simplexml_load_string($resultListXML);
}
$toCheck = 0;
foreach ($xml->item as $value)
{
if(isset($value['op_end'])){
$flag =1;
break;
} else if(isset($value['op'])){
$op = trim($value['op']);
$fname = trim($value['fname']);
$output = "[$op] [$fname]\n";
fwrite($logHandle, $output);
if($serverRoot!=''){
$from = "/".$serverRoot."/";
$fname = str_replace($from, '/', $fname);
}
if(isset($archiveHash[$fname])) {
$archiveHash[$fname] = 1;
}
$countDeleted++;
file_put_contents($countFile,$countDeleted);
}
}
if(1 == $flag){
break;
}
}
fclose($handle);
}
getFailedItemList($archiveHash, $noOfFiles);
$counter--;
unlink($tempfile);
}
/* Deleting contents inside the .RestoreList Dir .*/
$pathsToDelete = "\"$restoreList\"* \"$searchDirRemote\" \"$searchDirTrashRemote\"";
$file_data = array();
if($itemsForDeleteType != ''){
$fp = fopen($input, 'r');
$file_data = explode("\n", fread($fp, 10240));
}
if($itemsForDeleteType == 'file' && $linecount == 1 && REMOVE_FROM_TRASHOP != $operationType){
$dir = dirname($file_data[0]);
$parent_dir = "\"$restoreList$dir/\"list_* \"$searchDirRemote\" \"$searchDirTrashRemote\"";
}else if($itemsForDeleteType == 'folder' && $linecount == 1 && REMOVE_FROM_TRASHOP != $operationType){
$dir = trim($file_data[0]);
$remove_current_dir_arr = explode('/',$dir);
unset($remove_current_dir_arr[count($remove_current_dir_arr)-1]);
$parent_dir = implode('/',$remove_current_dir_arr);
$pathsToDelete = "\"$restoreList$dir\" \"$restoreList$parent_dir/\"list_* \"$searchDirRemote\" \"$searchDirTrashRemote\"";
}
else if( REMOVE_FROM_TRASHOP == $operationType)
$pathsToDelete = "\"$searchDirTrashRemote\"";
if($empty_trash == 0){
removeDirContent($pathsToDelete);
}
//fclose($logHandleTemp);
}
session_start();
$failToDelete = $linecount - $countDeleted;
$returnArray = array();
#to read all error files inside error directory and update error info to user log.
$buffer = '';
if ($handle = opendir($archiveErrorDir)) {
while (false !== ($errorLogFile = readdir($handle))) {
if(('.' === $errorLogFile) || ('..' === $errorLogFile))
continue;
$path = $archiveErrorDir.$errorLogFile;
if (file_exists($path))
{
$logHandleTemp = fopen($path, "r");
$buffer = fread($logHandleTemp, (1024 * 10));
if($buffer != "")
fwrite($logHandle, "\n" . $buffer);
fclose($logHandleTemp);
}
}
closedir($handle);
}
removeItems($archiveErrorDir);
/*
$logHandleTemp = fopen($errorLogFile, "r");
$buffer = fread($logHandleTemp, (1024 * 10));
fwrite($logHandle, "\n" . $buffer);
fclose($logHandleTemp);*/
//removeItems($archiveErrorDir);
//unlink($errorLogFile);
fwrite($logHandle, "\n" . SUMMARY);
$logEndTime = shell_exec('date +"%a %b %d %T %Y"');
if(DELETEOP == $operationType || REMOVE_FROM_TRASHOP == $operationType)
{
fwrite($logHandle, "\n" . TOAL_CONSIDERD_DELETE . $linecount."\n");
fwrite($logHandle, TOTAL_DELETED . $countDeleted."\n");
fwrite($logHandle, TOTAL_FAIL_TO_DELETE . $failToDelete."\n");
fwrite($logHandle, "\n" . DELETE_END_TIME . $logEndTime."\n");
$returnArray['DELETEOP']['CONSIDERED'] = $linecount;
$returnArray['DELETEOP']['HAPPENED'] = $countDeleted;
$returnArray['DELETEOP']['FAILED'] = $failToDelete;
if($empty_trash){
$logHandle1 = fopen($pidPath, "w");
fwrite($logHandle1,json_encode($returnArray));
fclose($logHandle1);
}
fclose($pidhandle);
}
if(ARCHIVEOP == $operationType || PERIODICARCHIVEOP == $operationType)
{
fwrite($logHandle, "\n" . TOAL_CONSIDERD_DELETE . $linecount."\n");
fwrite($logHandle, TOTAL_DELETED . $countDeleted."\n");
fwrite($logHandle, TOTAL_FAIL_TO_DELETE . $failToDelete."\n");
fwrite($logHandle, "\n" . "Archive Cleanup End Time: " . trim($logEndTime)."\n");
}
else if(PUT_BACKOP == $operationType)
{
fwrite($logHandle, "\n" . TOTAL_CONSIDERED_MOVE . $linecount."\n");
fwrite($logHandle, TOTAL_MOVED . $countDeleted."\n");
fwrite($logHandle, TOTAL_FAIL_TO_MOVE . $failToDelete."\n");
fwrite($logHandle, "\n" . MOVE_END_TIME . $logEndTime."\n");
$returnArray['PUT_BACKOP']['CONSIDERED'] = $linecount;
$returnArray['PUT_BACKOP']['HAPPENED'] = $countDeleted;
$returnArray['PUT_BACKOP']['FAILED'] = $failToDelete;
fclose($pidhandle);
}
if("" != $errStr)
{
fwrite($logHandle, ERR_SEPERATOR . "\n");
fwrite($logHandle, $errStr ."\n");
fwrite($logHandle, ERR_SEPERATOR . "\n");
}
/* log error as additional information */
/*if(customFileSize($OutErrorFilePath) and customFileSize($OutOutputFilePath))
{
if(!($errHandle = fopen($OutErrorFilePath, "r")))
{
Scheduler::Log(customErrorMsg());
$errStr = customErrorMsg();
}
if(customFileSize($OutErrorFilePath)> 0) {
fwrite($logHandle, "\n" . ADDITIONAL_INFO . "\n");
}
while(! feof($errHandle))
fwrite($logHandle, fgets($errHandle));
fclose($errHandle);
}
*/
fclose($logHandle);
if($linecount == $countDeleted)
$logStatus = SUCCESS;
else if(!file_exists($pidPath) || ((PERIODICARCHIVEOP == $operationType) && ($periodic_perc_error==0)))
$logStatus = ABORTED;
else
$logStatus = FAILURE;
rename($outputFile, $outputFile."_".$logStatus);
$outputFile = $outputFile."_".$logStatus;
if(($logProgresshandle = openFile($logpid))) {
fwrite($logProgresshandle, $outputFile."_".$logStatus);
fclose($logProgresshandle);
}
$emptyFoldersList = Scheduler::$archiveclean_dir.$selected_backupset."/".EMPTY_FOLDERS_LIST;
if((ARCHIVEOP == $operationType || PERIODICARCHIVEOP == $operationType) && file_exists($emptyFoldersList)){
$deleteUtfFile = getOperationFile($operationType, $emptyFoldersList);
$idevsutilCommandLine = $idevsutilBinaryPath.$whiteSpace.$idevsutilArgument.$assignmentOperator."\"$deleteUtfFile\"";
shell_exec($idevsutilCommandLine);
if(file_exists($OutErrorFilePath)){
$errContent = file_get_contents($OutErrorFilePath);
Scheduler::Log("Error on Empty folder Delete: " . $errContent);
}
}
$retVal = userCancelDeleteItems($operationType, $input, $errStr);
return $retVal;
}
/*********************************************************************************************************
* Subroutine Name : userCancelDeleteItems
* Objective :
* Added By :
**********************************************************************************************************/
function userCancelDeleteItems($operationType, $input, $errStr = '')
{
GLOBAL $outputFile, $OutErrorFilePath, $OutOutputFilePath, $deleteUtfFile, $pidPath, $empty_trash, $logpid, $returnArray, $selected_backupset;
if($errStr =='AR_DEL_LOG_DIR' || $errStr == 'AR_DEL_LOG' || $errStr =='AR_PID')
unlink($outputFile);
if(file_exists($OutErrorFilePath))
unlink($OutErrorFilePath);
if(file_exists($OutOutputFilePath))
unlink($OutOutputFilePath);
if(file_exists($deleteUtfFile))
unlink($deleteUtfFile);
if(file_exists($pidPath) && $empty_trash == 0)
unlink($pidPath);
if(file_exists($logpid))
unlink($logpid);
if(file_exists($input))
unlink($input);
if(file_exists($emptyFoldersList))
unlink($emptyFoldersList);
$emptyTempDir = Scheduler::$archiveclean_dir.$selected_backupset."/temp/";
if(file_exists($emptyTempDir))
shell_exec("rm -rf \"$emptyTempDir\"");
if($operationType == ARCHIVEOP)
return $errStr;
else {
if($empty_trash){
if(($logProgresshandle = fopen($logpid, "w"))){
fwrite($logProgresshandle, $returnArray);
fclose($logProgresshandle);
}
}
else
return $returnArray;
}
}
/*********************************************************************************************************
* Subroutine Name : encodePathWrapper
* Objective : Wrapper func to createEncodeFile.
* Added By : Basavaraj Bennur
**********************************************************************************************************/
function encodePathWrapper($passwrd, $encType, $pvtKey)
{
GLOBAL $webDir;
GLOBAL $userName;
GLOBAL $permissionVal;
$encPwdPath = Scheduler::$user_dir."IDPWD";
$encPvtkeyPath = Scheduler::$user_dir."IDPVT";
if(empty($passwrd)){
Scheduler::Log("Password entry is missing.");
}
else {
createEncodeFile($passwrd, $encPwdPath);
@chmod($encPwdPath, $permissionVal);
}
if($encType == "Private"){
if(empty($pvtKey)){
Scheduler::Log("Private entry is missing.");
}
else{
createEncodeFile($pvtKey, $encPvtkeyPath);
@chmod($encPvtkeyPath, $permissionVal);
}
}
}
#****************************************************************************************************
# Subroutine Name : createPwdFile.
# Objective : Create password encrypted file.
# Added By : Avinash Kumar.
#*****************************************************************************************************/
function createEncodeFile($data, $path)
{
GLOBAL $idevsutilBinaryPath;
GLOBAL $assignmentOperator;
GLOBAL $whiteSpace;
GLOBAL $hashEvsParameters;
$utfFile = "";
if(file_exists($path)){
unlink($path);
}
$utfFile = getUtf8File($data, $path);
$idevsutilCommandLine = $idevsutilBinaryPath.$whiteSpace.$hashEvsParameters["UTF8CMD"].$assignmentOperator."\"$utfFile\"";
$commandOutput = `$idevsutilCommandLine`;
unlink($utfFile);
}
#****************************************************************************************************
# Subroutine Name : getUtf8File.
# Objective : utf8 encode file creation.
# Added By : Avinash Kumar.
#*****************************************************************************************************/
function getUtf8File($data, $path)
{
GLOBAL $webDir;
GLOBAL $userName;
GLOBAL $permissionVal;
//create utf8 file.
$utfFile = Scheduler::$user_dir.UTF8_FILE;
file_put_contents($utfFile, "--string-encode=$data\n--out-file=$path");
@chmod($utfFile, $permissionVal);
return $utfFile;
}
/*********************************************************************************************************
* Subroutine Name : validateIDriveLoginCGI
* Objective : Validates IDrive account using CGI. Returns TRUE on Success and FALSE on failure
* Added By : Senthil Pandian
**********************************************************************************************************/
function validateIDriveLoginCGI($passwrd)
{
GLOBAL $webDir;
GLOBAL $idevsutilBinaryPath;
GLOBAL $whiteSpace;
GLOBAL $idevsutilArgument;
GLOBAL $assignmentOperator;
GLOBAL $lineFeed;
GLOBAL $userName;
$usedQuota ='';
$totalQuota ='';
if(empty($_SESSION['userName']) || !isset($_SESSION['userName'])){
GLOBAL $bandwidthFilePath;
GLOBAL $relativeFile;
GLOBAL $mpc;
GLOBAL $drlFile;
GLOBAL $OutErrorFilePath;
$_SESSION['userName'] = $userName;
$bandwidthFilePath = Scheduler::$user_dir.BW_FILE;
$relativeFile = Scheduler::$user_dir.RELATIVE_FILE;
$mpc = Scheduler::$user_dir.MPC_FILE;
$drlFile = Scheduler::$user_dir.RESTORE_LOCATION_FILE;
$OutErrorFilePath = Scheduler::$user_dir.ERROR_FILE;
}
$data = "username=".rawurlencode($userName)."&password=".rawurlencode($passwrd);
$shareOutputArr = getCurlOutput(getHash("01"), $data);
if($shareOutputArr['status'] == FALSE) {
Scheduler::Log("Login CGI: "," Output: ".$shareOutputArr['output'], " Error: ".$shareOutputArr['error']);
if(stripos($shareOutputArr['error'], 'could not resolve') !== FALSE) {
return 'nointernet';
}
if(stripos($shareOutputArr['error'], 'failed to connect') !== FALSE && stripos($shareOutputArr['error'], 'connection refused') !== FALSE) {
return 'invalidproxy';
}
return FALSE;
}
$validOutput = $shareOutputArr['output'];
$pos1 = strpos($validOutput, "ERROR");
$pos2 = strpos($validOutput, "FAILURE");
if($pos1 !== false || $pos2 !== false){
if($pos2 !== false)
{
if(strpos($validOutput, "windows_user"))
return "windows_user";
}
return FALSE;
}
$xml = simplexml_load_string($validOutput);
$xmlArray = $xml->login;
if(isset($xmlArray['accstat']) && ($xmlArray['accstat'] == "C")) {
$xmlArray['message'] = "CANCELED_ACC";
}elseif(isset($xmlArray['accstat']) && ($xmlArray['accstat'] == "M")) {
$xmlArray['message'] = "ACC_UNDER_MAINTENANCE";
}elseif(isset($xmlArray['accstat']) && ($xmlArray['accstat'] == "B")) {
$xmlArray['message'] = "BLOCKED_ACC";
}else if((string)$xmlArray['plan_type'] == "MobileOnly"){
$xmlArray['message'] = "INVALID_PLAN_TYPE";
}else if(isset($xmlArray['accstat']) && ($xmlArray['accstat'] == "Y")){
if((string)$xmlArray['message'] == "SUCCESS"){
if(isset($xmlArray['parent_account'])) {
$_SESSION['isSubAccount'] = true;
}else
$_SESSION['isSubAccount'] = false;
$serverOutput = (string)$xmlArray['evssrvrip'];
$usedQuota = (string)$xmlArray['quota_used'];
$totalQuota = (string)$xmlArray['quota'];
$dedup = (string)$xmlArray['dedup'];
$_SESSION['accountUsage'] = $usedQuota."#".$totalQuota;
if($serverOutput != '')
$_SESSION['serverAddr'] = $serverOutput;
$_SESSION['dedup'] = false;
if(strtolower($dedup)==='on')
$_SESSION['dedup'] = true;
}
} else {
$xmlArray['message'] = $xmlArray['desc'];
}
$retVal=(string)$xmlArray['message']."_".(string)$xmlArray['cnfgstat']."_".(string)$xmlArray['enctype']."_".(string)$xmlArray['evswebsrvr']."#".$usedQuota."#".$totalQuota;
return $retVal;
}
/*********************************************************************************************************
* Subroutine Name : confAccount
* Objective : Configures idrive account. Returns TRUE on Success and FALSE on failure
* Added By : Basavaraj Bennur
**********************************************************************************************************/
function confAccount($encType,$pvtKey)
{
$configAccount = "https://".$_SESSION['evswebsrvr']."/evs/configureAccount";
$data = "uid=".rawurlencode($_SESSION['userName'])."&pwd=".rawurlencode(base64_decode($_SESSION['password']));
if($encType == "Private")
$data .= "&enctype=private&pvtkey=".rawurlencode($pvtKey);
else
$data .= "&enctype=default";
$out = getCurlOutput("https://".$_SESSION['evswebsrvr'].getHash("09"), $data);
if($out['status']) {
$out = $out['output'];
$out = str_replace('<?xml version="1.0" encoding="UTF-8"?>', '', $out);
$xml = simplexml_load_string("<root>$out</root>");
$xmlArray = $xml->tree;
return $xmlArray;
}
else{
Scheduler::Log("conf account CGI: " . " Output: ".$out['output'] . " Error: ".$out['error']);
$arrOutput = array('message'=>false);
return $arrOutput;
}
}
/*********************************************************************************************************
* Subroutine Name : getServerAddress
* Objective : Gets Server Address. Returns TRUE on Success and FALSE on failure
* Added By : Basavaraj Bennur
* Modified By : Avinash Kumar
**********************************************************************************************************/
function getServerAddress()
{
GLOBAL $permissionVal;
$data = "username=".rawurlencode($_SESSION['userName'])."&password=".rawurlencode(base64_decode($_SESSION['password']));
$shareOutputArr = getCurlOutput(getHash("01"), $data);
$validOutput = $shareOutputArr['output'];
$validOutput = str_replace('<?xml version="1.0" encoding="UTF-8"?>', '', $validOutput);
$xml = simplexml_load_string($validOutput);
$xmlArray = $xml->login;
if(isset($xmlArray['message']) && isset($xmlArray['evssrvrip']) && ($xmlArray['message'] == "SUCCESS")){
$_SESSION['evswebsrvr'] = $xmlArray['evssrvr'];
$arrOutput = array(TRUE, (string)$xmlArray['evssrvrip']);
/* Update evs server address in .serverAddr.txt */
$file = Scheduler::$user_dir.SERVER_ADDR_PATH;
file_put_contents($file, (string)$xmlArray['evssrvrip']);
@chmod($file,$permissionVal);
unset($_SESSION['serverAddr']);
}
else
{
return array(FALSE,$shareOutputArr['error']);
}
return $arrOutput;
}
/*********************************************************************************************************
* Subroutine Name : getVersionInfo
* Objective : Gets version details of supplied file. Returns TRUE on Success and FALSE on failure
* Added By : Basavaraj Bennur
* Modified By : Yogesh Kumar
**********************************************************************************************************/
function getVersionInfo($input, $isLocal = FALSE)
{
GLOBAL $idevsutilBinaryPath;
GLOBAL $whiteSpace;
GLOBAL $idevsutilArgument;
GLOBAL $assignmentOperator;
GLOBAL $OutErrorFilePath;
GLOBAL $trash_Search;
if(isset($_REQUEST['trash']))
$trash_Search = 1;
$localPath = '';
$versionUtfFile = getOperationFile(VERSIONINFOOP, $input, $localPath);
$idevsutilCommandLine = $idevsutilBinaryPath.$whiteSpace.$idevsutilArgument.$assignmentOperator."\"$versionUtfFile\"";
$out =`$idevsutilCommandLine`;
@unlink($versionUtfFile);
/* update server address if cmd failed due to wrong evs server address. */
checkErrorAndUpdateServerAddr($OutErrorFilePath);
$pos = strpos($out, "ERROR");
if(0 < customFileSize($OutErrorFilePath) || $pos !== false){
$arrOutput = array(FALSE, array('err' => 'Failed to get version of file.'));
return $arrOutput;
}
@unlink($OutErrorFilePath);
$arrOutput = array(TRUE, array('err' => 'No version found.'));
$xml = verifyXMLoutput($out);
if(!$xml)
return array(FALSE);
$data = array();
foreach ($xml->item as $value){
$data[] = trim($value['mod_time']);
$data[] = trim($value['size']);
$data[] = trim($value['ver']);
}
if(count($data)>0)
$arrOutput = array(TRUE, $data);
return $arrOutput;
}
/*********************************************************************************************************
* Subroutine Name : getProperties
* Objective : Gets properties of a file. Returns TRUE on Success and FALSE on failure
* Added By : Basavaraj Bennur
**********************************************************************************************************/
function getProperties($input)
{
GLOBAL $idevsutilBinaryPath;
GLOBAL $whiteSpace;
GLOBAL $idevsutilArgument;
GLOBAL $assignmentOperator;
GLOBAL $OutErrorFilePath;
$propertiesUtfFile = getOperationFile(PROPERTIESOP, $input);
$idevsutilCommandLine = $idevsutilBinaryPath.$whiteSpace.$idevsutilArgument.$assignmentOperator."\"$propertiesUtfFile\"";
$out = `$idevsutilCommandLine`;
unlink($propertiesUtfFile);
// update server address if cmd failed due to wrong evs server address.
checkErrorAndUpdateServerAddr($OutErrorFilePath);
$pos = strpos($out, "ERROR");
if(0 < customFileSize($OutErrorFilePath) || $pos !== false){
$out = (0 < customFileSize($OutErrorFilePath))?file_get_contents($OutErrorFilePath):$out;
$reason = checkErrorAndReason($out);
return $arrOutput = array(FALSE,$reason);
}
unlink($OutErrorFilePath);
$xml = verifyXMLoutput($out);
if(!$xml)
return array(FALSE);
$arr = array();
foreach ($xml->item as $value){
if(isset($value['create_time'])) {
$expDate = explode(' ',trim($value['create_time']));
$arr[2] = $expDate[0]." ".ampmTimeFormat($expDate[1]);
} else if(isset($value['files_count'])){
$arr[1] = trim($value['files_count']);
} else if(isset($value['size'])) {
$size = explode(' ',trim($value['size']));
$arr[0] = humanReadableSize($size[0]);
}
}
$arrOutput = array(TRUE, $arr);
return $arrOutput;
}
/*********************************************************************************************************
* Subroutine Name : createDir
* Objective : Creates directory on server. Returns TRUE on Success and FALSE on failure
* Added By : Basavaraj Bennur
**********************************************************************************************************/
function createDir($dirName, $path, $encType)
{
GLOBAL $idevsutilBinaryPath;
GLOBAL $whiteSpace;
GLOBAL $idevsutilArgument;
GLOBAL $assignmentOperator;
GLOBAL $OutErrorFilePath;
GLOBAL $lineFeed;
$errorRedirection = "2>&1";
$input = array($dirName, $path, $encType);
$createDirUtfFile = getOperationFile(CREATEDIROP, $input);
$idevsutilCommandLine = $idevsutilBinaryPath.$whiteSpace.$idevsutilArgument.$assignmentOperator."\"$createDirUtfFile\"".$whiteSpace.$errorRedirection.$lineFeed;
$out = `$idevsutilCommandLine`;
/* update server address if cmd failed due to wrong evs server address. */
checkErrorAndUpdateServerAddr($OutErrorFilePath);
$pos = strpos($out, "ERROR");
$reason = '';
if(0 < customFileSize($OutErrorFilePath) || $pos !== false){
$out = (0 < customFileSize($OutErrorFilePath))?file_get_contents($OutErrorFilePath):$out;
$reason = checkErrorAndReason($out);
return $arrOutput = array(FALSE,$reason);
}
if($_SESSION['dedup']){
$xml = verifyXMLoutput($out);
if(!$xml || strtolower($xml->item['op_status'])=="failed"){
$reason = isset($xml->item['reason'])?$xml->item['reason']:'failed';
$arrOutput = array(FALSE, $reason);
@unlink($OutErrorFilePath);
return $arrOutput;
}
} else {
$pos = strpos($out, "ERROR");
//if(0 < @customFileSize($OutErrorFilePath) || $pos !== false){ //Changed by Senthil on 23/12/2016
if($pos !== false){
$arrOutput = array(FALSE, $out);
return $arrOutput;
}
}
@unlink($OutErrorFilePath);
$arrOutput = array(TRUE, $out);
return $arrOutput;
}
/*********************************************************************************************************
* Subroutine Name : renamePath
* Objective : Renames old path to newpath on server. Returns TRUE on Success and FALSE on failure
* Added By : Basavaraj Bennur
**********************************************************************************************************/
function renamePath($oldPath, $newPath)
{
GLOBAL $idevsutilBinaryPath;
GLOBAL $whiteSpace;
GLOBAL $idevsutilArgument;
GLOBAL $assignmentOperator;
GLOBAL $OutErrorFilePath;
$input = array($oldPath, $newPath);
$renameUtfFile = getOperationFile(RENAMEOP, $input);
$idevsutilCommandLine = $idevsutilBinaryPath.$whiteSpace.$idevsutilArgument.$assignmentOperator."\"$renameUtfFile\"";
$out = `$idevsutilCommandLine`;
$error = file_get_contents($OutErrorFilePath);
unlink($renameUtfFile);
/* update server address if cmd failed due to wrong evs server address. */
checkErrorAndUpdateServerAddr($OutErrorFilePath);
$success = strpos($out, "renamed");
if(is_int($success)){
return true;
} else {
if($error != ""){
$stringParts = explode("reason:", $error);
$error = $stringParts[1];
} else {
$error = "Rename failed";
}
$pos = strpos($out, "ERROR");
return $error;
}
}
/*********************************************************************************************************
* Subroutine Name : renameRestoreSetItems
* Objective : Renames old path to newpath in Restore Set file in all job if old path exists.
* Added By : Senthil Pandian.K
**********************************************************************************************************/
function renameRestoreSetItems($oldPath, $newPath){
GLOBAL $permissionVal;
$jobs = Scheduler::ReadJobs();
$jobType = "Restore";
$jobTypeLen = strlen($jobType)+1;
$find = array($oldPath."\n",$oldPath."/");
$replace = array($newPath."\n",$newPath."/");
foreach($jobs as $k=>$job) {
if($job["job_type"] == $jobType) {
$jobNameDir = substr($k,$jobTypeLen);
$jobNameDirPath = Scheduler::$user_dir."$jobType/$jobNameDir";
$displayFile_content = file_get_contents("$jobNameDirPath/".RESTORESETFILEDISPLAY);
$displayFile_content = str_replace($find,$replace,$displayFile_content);
file_put_contents("$jobNameDirPath/".RESTORESETFILEDISPLAY,$displayFile_content);
@chmod("$jobNameDirPath/".RESTORESETFILEDISPLAY, $permissionVal);
}
}
}
/*********************************************************************************************************
* Subroutine Name : renameBackupLocation
* Objective : Renames old path to newpath for BackupLocation if old path exists.
* Added By : Senthil Pandian.K
**********************************************************************************************************/
function renameBackupLocation($oldPath, $newPath)
{
GLOBAL $userName, $permissionVal;
$backupLocation = Scheduler::GetHost($userName);
if($backupLocation==$oldPath){
$backupLocation = $newPath;
file_put_contents(Scheduler::$user_dir.MPC_FILE,$backupLocation);
} elseif(strpos($backupLocation,$oldPath."/")==0){
$backupLocation = str_replace($oldPath."/",$newPath."/",$backupLocation);
file_put_contents(Scheduler::$user_dir.MPC_FILE,$backupLocation);
}
@chmod(Scheduler::$user_dir.MPC_FILE, $permissionVal);
return $backupLocation;
}
/*********************************************************************************************************
* Subroutine Name : renameRestoreList
* Objective : Renames old path to newpath for RestoreList if old path exists.
* Added By : Senthil Pandian.K
**********************************************************************************************************/
function renameRestoreList($oldPath, $newPath){
GLOBAL $user,$permissionVal;
//$filePath = Scheduler::$user_dir.".RestoreList";
$filePath = Scheduler::$restore_list_dir;
if(file_exists($filePath.$oldPath)){
$cmd = "mv '$filePath$oldPath' '$filePath$newPath'";
`$cmd`;
}
//To rename the item in list.txt
$rootPath = explode('/',$oldPath);
$oldItem = array_pop($rootPath);
$rootPath = implode("/",$rootPath);
if(file_exists($filePath.$rootPath)){
$exp2 = explode('/',$newPath);
$newItem = end($exp2); //Last element from array
$toFind = json_encode(array($newItem));
$lastItemLen = strlen(trim($toFind));
$newItem = substr($toFind, 1, ($lastItemLen-2));
$toFind = json_encode(array($oldItem));
$lastItemLen = strlen(trim($toFind));
$oldItem = substr($toFind, 1, ($lastItemLen-2));
$restoreFile = constructRestoreFileName($rootPath);
$restoreFileContent = file_get_contents($restoreFile);
$oldItem = preg_replace("/^(?:.*\n){2,5}/","",$oldItem);
$newItem = preg_replace("/^(?:.*\n){2,5}/","",$newItem);
$renamedString = str_replace($oldItem,$newItem,$restoreFileContent);
file_put_contents($restoreFile,$renamedString);
@chmod($restoreFile, $permissionVal);
}
}
/*********************************************************************************************************
* Subroutine Name : updateNewDirInRestoreList
* Objective : Update new directory in RestoreList if path exists.
* Added By : Senthil Pandian.K
**********************************************************************************************************/
function updateNewDirInRestoreList($currPath,$newDir){
GLOBAL $permissionVal;
$restoreFile = constructRestoreFileName($currPath);
if(file_exists($restoreFile)){
$restoreFileContent = file_get_contents($restoreFile);
if(trim($restoreFileContent)!=''){
$oldDirArray = json_decode($restoreFileContent, true);
$oldDirArray[$newDir]["size"] = "--";
$oldDirArray[$newDir]["datetime"] = date('Y/m/d h:m:s');
$oldDirArray[$newDir]['type'] = "D";
$newDirString = json_encode($oldDirArray);
} else {
$newDirArray[$newDir]["size"] = "--";
$newDirArray[$newDir]["datetime"] = date('Y/m/d h:m:s');
$newDirArray[$newDir]['type'] = "D";
$newDirString = json_encode($newDirArray);
}
file_put_contents($restoreFile,$newDirString);
@chmod($restoreFile, $permissionVal);
}
}
/*********************************************************************************************************
* Subroutine Name : rateOfTransfer
* Objective : Tests the upload / download transfer rate. Returns TRUE on Success and FALSE on failure
* Added By : Basavaraj Bennur
**********************************************************************************************************/
function rateOfTransfer($input)
{
GLOBAL $idevsutilBinaryPath;
GLOBAL $whiteSpace;
GLOBAL $idevsutilArgument;
GLOBAL $assignmentOperator;
GLOBAL $OutErrorFilePath;
$speeUtfFile = getOperationFile(SPEEDOP, $input);
$idevsutilCommandLine = $idevsutilBinaryPath.$whiteSpace.$idevsutilArgument.$assignmentOperator."\"$speeUtfFile\"";
$out = `$idevsutilCommandLine`;
unlink($speeUtfFile);
/* update server address if cmd failed due to wrong evs server address. */
checkErrorAndUpdateServerAddr($OutErrorFilePath);
$pos = strpos($out, "ERROR");
if(0 < customFileSize($OutErrorFilePath) || $pos !== false){
$out = (0 < customFileSize($OutErrorFilePath))?file_get_contents($OutErrorFilePath):$out;
$reason = checkErrorAndReason($out);
return $arrOutput = array(FALSE,$reason);
}
unlink($OutErrorFilePath);
$arrOutput = array(TRUE, $out);
return $arrOutput;
}
#****************************************************************************************************
# Subroutine Name : parseXMLOutput.
# Objective : Parse evs command output and return values of corresponding message.
# Added By : Basavaraj Bennur.
#*****************************************************************************************************/
function parseXMLOutput($commandOutput)
{
preg_match_all("/\<tree (.*?)\"\/>/", $commandOutput, $xmlOutput);
$out =$xmlOutput[1][0];
$exp = explode('" ',$out);
foreach($exp as $item){
$fields = explode('="',$item);
$arr[$fields[0]] = $fields[1];
}
return $arr;
}
/************************************************************************************************
* Subroutine Name : readAccountSettingsFile
* Objective : Reads ACCOUNT_SETTINGS_FILE and copies values into a Session array
* Added By : Basavaraj Bennur
************************************************************************************************/
function readAccountSettingsFile()
{
GLOBAL $webDir, $accountSettingsFilePath;
GLOBAL $userName, $permissionVal;
if(empty($accountSettingsFilePath))
$accountSettingsFilePath = Scheduler::$user_dir."ACCOUNT_SETTINGS_FILE";
if(file_exists($accountSettingsFilePath) === TRUE) {
$accountSettingsArray = json_decode(file_get_contents($accountSettingsFilePath),TRUE);
if (json_last_error() != JSON_ERROR_NONE) {
$linesAccountSettingsFile = file($accountSettingsFilePath);
$accountSettingsData = array();
foreach($linesAccountSettingsFile as $line){
$keyValuePair = preg_split('/=/', $line);
$accountSettingsData[trim($keyValuePair[0])] = trim($keyValuePair[1]);
}
#$accountSettingsData['engineCount'] = "4";
if(($file = fopen($accountSettingsFilePath, "a+")) != FALSE)
{
ftruncate($file, 0);
fwrite($file, json_encode($accountSettingsData,TRUE));
fclose($file);
@chmod($accountSettingsFilePath, $permissionVal);
}
$accountSettingsArray = $accountSettingsData;
}
/* if(isset($_SESSION['password']) && $_SESSION['password'] != '') {
unset($accountSettingsArray['password']);
} */
if($_SESSION['password'] == '' && $_SESSION['userName'] != '') {
$_SESSION['password'] = $accountSettingsArray['password'];
}
if(!isset($_SESSION['accountSettingsArrayValData']) || !$_SESSION['accountSettingsArrayValData']){
foreach($accountSettingsArray as $accountSettingsArrayKey => $accountSettingsArrayVal) {
if($accountSettingsArrayKey != 'password' and $accountSettingsArrayKey != 'userName'){
$_SESSION[$accountSettingsArrayKey] = $accountSettingsArrayVal;
}
}
$_SESSION['accountSettingsArrayValData'] = true;
}
//$_SESSION['configVerified'] = true; # commented for Harish_1.00.16_1_1
return $accountSettingsArray;
}
}
/****************************************************************************************************
* Subroutine Name : ampmTimeFormat.
* Objective : Convert the given time in 24-hour format to 12 hour format.
* Added By : Basavaraj Bennur.
* Modified By : Senthil Pandian
******************************************************************************************************/
function ampmTimeFormat($hourMin)
{
$result='';
$timeArr=explode(":",$hourMin);
$hour = $timeArr[0];
$min = str_pad($timeArr[1], 2, '0', STR_PAD_LEFT);
$sec = str_pad($timeArr[2], 2, '0', STR_PAD_LEFT);
$finalHr = $hour;
$amPm =" PM";
if($hour < 12){
if($hour == "00")
$finalHr = "12";
$amPm = " AM";
}
else if($hour > 12){
$finalHr = $hour - 12;
}
$finalHr = str_pad($finalHr, 2, '0', STR_PAD_LEFT);
$result = "$finalHr:$min:$sec$amPm";
return $result;
}
/****************************************************************************************************
* 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 : createFullRestoreDir.
* Objective : Create full restore directory.
* Added By : Yogesh Kumar.
******************************************************************************************************/
function createFullRestoreDir($restorePath) {
GLOBAL $webDir;
GLOBAL $userName;
GLOBAL $permissionVal;
ini_set('track_errors', 1);
$restoreListFolderPath = Scheduler::$restore_list_dir;
if($_SESSION['dedup']){
if (!file_exists($restoreListFolderPath))
{
if(!mkdir($restoreListFolderPath, $permissionVal, true))
{
Scheduler::Log("Could not create directory $restoreListFolderPath, Reason : ".customErrorMsg());
die("Failed to create directory $restoreListFolderPath, Reason : ".customErrorMsg());
}
@chmod($restoreListFolderPath,$permissionVal);
}
$restorePath = "/".$_SESSION['selectedRestoreDeviceID'].$restorePath;
$restoreDir = $restoreListFolderPath.$restorePath;
} else {
$restoreDir = $restoreListFolderPath.$restorePath;
}
if (!file_exists($restoreDir))
{
if(!mkdir($restoreDir, $permissionVal, true))
{
Scheduler::Log("Could not create directory $restoreDir, Reason : ".customErrorMsg());
die("Failed to create directory $restoreDir, Reason : ".customErrorMsg());
}
@chmod($restoreDir,$permissionVal);
}
return $restoreDir;
}
/****************************************************************************************************
* Subroutine Name : constructRestoreFileName.
* Objective : Create restore file name.
* Added By : Basavraj Bennur.
* Modified By : Yogesh Kumar.
******************************************************************************************************/
function constructRestoreFileName($restorePath, $pageNumber='0',$trashRequest=FALSE)
{
$restoreDir = createFullRestoreDir($restorePath);
$rListPath = $restoreDir."/list_{$pageNumber}.txt";
if($trashRequest) $rListPath = $restoreDir."/Trashlist.txt";
return $rListPath;
}
/****************************************************************************************************
* Subroutine Name : getUserName.
* Objective : Get current user logged on with IDrive account.
* Added By : Avinash Kumar.
* Modified : Sabin Cheruvattil, Senthil Pandian
******************************************************************************************************/
function getUserName($currentPath = '')
{
if($currentPath == '')
$currentPath = getcwd();
# try to find the user name from currentPath
$needle = "/" . USER_PROFILE . "/";
$tmp = explode($needle, $currentPath);
if(count($tmp) > 1) {
$splitPath = explode("/" , $tmp[1]);
return $splitPath[1];
}
# 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 = '')
{
/*$nas_user = exec('whoami');
$nas_user = trim($nas_user);
return $nas_user;*/
// Commented by anil to make backup and restore operations to work on in the same way.
if($currentPath == '')
$currentPath = getcwd();
# try to find the user name from currentPath
//$needle = "/" . SERVICE . "/" . 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 : encrypt.
* Objective : Encryption for password and private key.
* Added By : Avinash Kumar.
******************************************************************************************************/
function encrypt($arg)
{
for($j = 0; $j != strlen($arg); $j++){
$ascPassword[$j] = dechex(ord($arg[$j]));
}
if(count($ascPassword)>0){
$ascPasswordStr = implode('-', $ascPassword);
$ascPasswordStr = rand(10,99) . "-" . $ascPasswordStr . "-" . rand(10,99);
return $ascPasswordStr;
}
}
/****************************************************************************************************
* Subroutine Name : getLocalServerip.
* Objective : Get NAS IP Adddress.
* Added By : Avinash Kumar.
* Modified By : Senthil Pandian
******************************************************************************************************/
function getLocalServerip()
{
if(isset($_SERVER["SERVER_NAME"]))
return $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"];
else
return '';
}
/****************************************************************************************************
* Function Name : getLogFilesList.
* Objective : Get Log Files list.
* Added By : Senthil Pandian
******************************************************************************************************/
function getLogFilesList($jobname){
GLOBAL $fileNames;
GLOBAL $hash;
GLOBAL $logFilePath;
$jobLogDirPath = $jobname."/LOGS";
$exp = explode("/",$jobname);
$jobname = $exp[count($exp)-1];
if(is_dir($jobLogDirPath)){
if($dh = opendir($jobLogDirPath))
{
while(($file = readdir($dh)) !== false)
{
if (($file === ".") || ($file === "..") || (strpos($file, "_ERRORFILE") !== FALSE) || ($file === "PROGRESS_DETAILS") || ($file === "LOG_DETAILS") || (strpos($file, ".pid") !== FALSE))
continue;
else
{
$absPath = "$jobLogDirPath/$file";
$fileNames[filemtime($absPath)] = $file;
$logFilePath[trim($file)] = $absPath;
$hash[trim($file)] = $jobname;
}
}
closedir($dh);
}
}
}
/****************************************************************************************************
* Function Name : getRunningJobLogs.
* Objective : Get Log Files list which is running.
* Added By : Senthil Pandian
******************************************************************************************************/
function getRunningJobLogs($jobname){
GLOBAL $runningJobName;
GLOBAL $completedJobName;
GLOBAL $completedJob;
GLOBAL $runningJob;
$jobLogDirPath = $jobname."/".LOG_PID_FILE;
if(file_exists($jobLogDirPath)){
$runningFile = trim(file_get_contents($jobLogDirPath));
$absPath = "$jobname/$runningFile";
if(strstr($runningFile,"SUCCESS") || strstr($runningFile,"FAILURE") || strstr($runningFile,"ABORTED")){
$completedJob[]['jobName'] = $jobname;
$completedJob[]['path'] = $absPath;
$completedJob[]['logFile'] = $runningFile;
} else {
$runningJob[]['jobName'] = $jobname;
$runningJob[]['path'] = $absPath;
$runningJob[]['logFile'] = $runningFile;
}
}
}
/****************************************************************************************************
* Function Name : ordinal_suffix.
* Objective : Get the suffix of number.
* Added By : Senthil Pandian
******************************************************************************************************/
function ordinal_suffix($num){
if($num < 11 || $num > 13){
switch($num % 10){
case 1: return 'st';
case 2: return 'nd';
case 3: return 'rd';
}
}
return 'th';
}
/****************************************************************************************************
* Function Name : restartSession.
* Objective : Restarting session
* Added By : Senthil Pandian
******************************************************************************************************/
function restartSession(){
$proxyOption = isset($_SESSION['proxy_option'])?$_SESSION['proxy_option']:'';
$ipAddress = isset($_SESSION['ipAddress'])?$_SESSION['ipAddress']:'';
$port = isset($_SESSION['port'])?$_SESSION['port']:'';
$proxyUserName = isset($_SESSION['proxyUserName'])?$_SESSION['proxyUserName']:'';
$proxyPassword = isset($_SESSION['proxyPassword'])?$_SESSION['proxyPassword']:'';
$encryptedToken = $_SESSION['encryptedToken'];
$nasUserName = $_SESSION['nasUserName'];
$cgiSID = $_SESSION['CGI_SID'];
$encryptionFlag = $_SESSION['encryptionFlag'];
$serverAddr = isset($_SESSION['serverAddr'])?$_SESSION['serverAddr']:0;
$evswebsrvr = isset($_SESSION['evswebsrvr'])?$_SESSION['evswebsrvr']:'';
$multiUser = isset($_SESSION['multiUser'])?$_SESSION['multiUser']:false;
$_SESSION = array();
//session_destroy();
session_start();
$_SESSION['validUser'] = true;
$_SESSION['proxy_option'] = $proxyOption;
$_SESSION['ipAddress'] = $ipAddress;
$_SESSION['port'] = $port;
$_SESSION['proxyUserName'] = $proxyUserName;
$_SESSION['proxyPassword'] = $proxyPassword;
$_SESSION['encryptedToken'] = $encryptedToken;
$_SESSION['nasUserName'] = $nasUserName;
$_SESSION['CGI_SID'] = $cgiSID;
$_SESSION['encryptionFlag'] = $encryptionFlag;
$_SESSION['multiUser'] = $multiUser;
if($serverAddr)
$_SESSION['serverAddr'] = $serverAddr;
if($evswebsrvr != "")
$_SESSION['evswebsrvr'] = $evswebsrvr;
}
/****************************************************************************************************
* 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);
/* For Proxy - Start*/
if(isset($_SESSION['isProxyEnabled']) && $_SESSION['isProxyEnabled']==true){
//IP & Port
if(isset($_SESSION['ipAddress']) && !empty($_SESSION['ipAddress'])){
$proxy = $_SESSION['ipAddress'].":".$_SESSION['port'];
curl_setopt($ch, CURLOPT_PROXY, $proxy);
}
//Username & Password
if(isset($_SESSION['proxyUserName']) && !empty($_SESSION['proxyUserName'])){
$proxyauth = $_SESSION['proxyUserName'].":".$_SESSION['proxyPassword'];
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth);
}
}
/* For Proxy - End*/
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);
}
/****************************************************************************************************
* Function Name : getLocalSearchResult.
* Objective : Get local search result from particular page if page/pid.txt exist
* Added By : Senthil Pandian
******************************************************************************************************/
function getSearchResult($currPage, $pid='', $count=0){
GLOBAL $dedupDetailFile;
session_write_close();
$timeOutCount=20;
START:
$arr = array();
$resArray = array();
$linesCount = intval(exec('wc -l '.escapeshellarg($currPage).' 2>/dev/null'));
$OutErrorFilePath = substr($pid, 0, strrpos($pid, "/"))."/".ERROR_FILE;
//Checking line count is more than previous call
$remaining = $linesCount - $count;
$parItems = $linesCount%4;
$linesCount = $linesCount - $parItems;
if($remaining >= 4) {
$list = file_get_contents($currPage);
$exp = explode("\n", $list);
for($i = $count; $i < $linesCount; $i += 4) {
if(($i + 4) > $linesCount) {
break;
}
/* $checkDir = explode('/', rtrim($exp[$i], '/'));
foreach($checkDir as $hiddenDir) {
if(strpos($hiddenDir, '.') === 0) {
continue 2;
}
} */
$checkDir = rtrim($exp[$i], '/');
if($_SESSION['showHidden'] == 'Hide' && strpos($checkDir, '/.') !== FALSE) {
continue;
}
$expDate = explode(' ',substr(trim($exp[$i + 2]), 0, -1));
$dirDate = $expDate[0]." ".ampmTimeFormat($expDate[1]);
$resArray[] = array('name' => rtrim($exp[$i], '/'), 'size' => $exp[$i + 1], 'date' => $dirDate, 'type' => $exp[$i + 3]);
}
$arr[] = 1;
$arr[] = $i;
$arr[] = $resArray;
$arr[] = $linesCount;
return $arr;
}
if($timeOutCount and @file_exists($pid)){
sleep(1);
$timeOutCount--;
goto START;
}
else if(@file_exists($pid)){
$arr[] = 1;
$arr[] = $count;
$arr[] = 0;
$arr[] = 0;
}
else {
if(isset($_SESSION['dedup']) && $_SESSION['dedup'] && !file_exists($dedupDetailFile))
exit(header("Location: ./logout.php"));
$arr[] = 0;
}
return $arr;
}
/****************************************************************************************************
* Function Name : simple_encrypt
* Objective : Get encrypted string of key String & actual string which is needs to be secured
* Added By : Senthil Pandian
******************************************************************************************************/
function simple_encrypt($str,$keyIndex) {
list($encrypted, $_SESSION['encryptionFlag']) = encryptNasPassword($str, $keyIndex, $_SESSION['encryptionFlag']);
if(!trim($encrypted)) return ;
$len = $keyIndex+strlen($encrypted);
$divided = ($len/2);
$first = floor($divided);
$last = ($len-$first);
$digit1 = strlen($first);
$digit2 = strlen($last);
return $digit1.$first.$encrypted.$last.$digit2;
}
/****************************************************************************************************
* Function Name : simple_decrypt
* Objective : Get decrypted string of actual string which is needs to be secured using key String
* Added By : Senthil Pandian
******************************************************************************************************/
function simple_decrypt($isHashVal) {
GLOBAL $staticString;
GLOBAL $appPath ;
$configPath = "$appPath/".CONFIG;
$phpPath = getPhpPath();
$command = "";
if(!$isHashVal) {
$str = $_SESSION['encryptedToken'].$_COOKIE['encryptedToken'];
$command = "$phpPath $configPath/token.php $str ".$_SESSION['encryptionFlag'];
}
else {
$command = "$phpPath $configPath/token.php ".HASH_DATA." 0";
}
$stOutput = shell_exec($command);
return $stOutput;
/*$digit1 = substr($str,0,1);
$digit2 = substr($str,-1,1);
$first = substr($str,1,$digit1);
$last = substr($str,-($digit2+1),$digit2);
$actual = substr($str,$digit1+1);
$actual = substr($actual,0,strlen($actual)-($digit2+1));
$key = ($first+$last)-(strlen($actual));
$keyString = $staticString[$key];
$val = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $keyString, base64_decode($actual), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)));
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $keyString, base64_decode($actual), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))); */
}
/****************************************************************************************************
* Function Name : encryptAndSaveNasPassword
* Objective : Encrypt & Save Nas Password in session & cookie
* Added By : Senthil Pandian
******************************************************************************************************/
function encryptAndSaveNasPassword($nasPassword){
$keyIndex = rand(1,1000);
$_SESSION['encryptionFlag'] = checkMcryptDecryptWorks($nasPassword,$keyIndex);
$encryptedToken = simple_encrypt($nasPassword,$keyIndex);
$getLen = strlen($encryptedToken);
$divided = ($getLen/2);
$first = floor($divided);
$_SESSION['encryptedToken'] = substr($encryptedToken,0,$first);
setcookie("encryptedToken", substr($encryptedToken,$first),0);
$_COOKIE['encryptedToken'] = substr($encryptedToken,$first);
}
/****************************************************************************************************
* Function Name : checkShowHidden
* Objective : Displaying/hiding the files/folders based on preference settings
* Added By : Senthil Pandian
******************************************************************************************************/
function checkShowHidden($printJSvar=true){
GLOBAL $excludePartialFilePath;
if(file_exists($excludePartialFilePath)){
$excludePartial = file_get_contents($excludePartialFilePath);
$exp = explode("\n",$excludePartial);
if(trim($exp[0])=="\/."){
$_SESSION['showHidden']="Hide";
if($printJSvar) print "<script>sh='Hide';</script>";
}
else {
$_SESSION['showHidden']="Show";
if($printJSvar) print "<script>sh='Show';</script>";
}
}
else {
if($printJSvar)
print "<script>var sh='Show';</script>";
if(!empty($excludePartialFilePath))
$_SESSION['showHidden']="Show";
}
if(!isset($_SESSION['showHidden']))
$_SESSION['showHidden']="Show";
return $_SESSION['showHidden'];
}
/****************************************************************************************************
* Function Name : showHiddenStatus
* Objective : Checking the status of show/hidden
* Added By : Senthil Pandian
******************************************************************************************************/
function showHiddenStatus(){
GLOBAL $excludePartialFilePath;
$showHidden = "Show";
if(file_exists($excludePartialFilePath)){
$excludePartial = file_get_contents($excludePartialFilePath);
$exp = explode("\n",$excludePartial);
if(trim($exp[0])=="\/.")
$showHidden = "Hide";
}
return $showHidden;
}
/****************************************************************************************************
* Function Name : checkAppUpdate
* Objective : Checking the status of new version
* Added By : Senthil Pandian
******************************************************************************************************/
function checkAppUpdate() {
GLOBAL $appUpdateKey, $appVersion, $userName, $releaseDate;
if($userName == '') {
getProxyDetail();
}
session_write_close();
$currVersion = trim(str_replace("Version","",$appVersion));
// Added for custom package
$currVersionArr = explode('.', $currVersion);
$currVersion = $currVersionArr[0].'.'.$currVersionArr[1].'.'.$currVersionArr[2];
// Added for custom package
$upgradeDataURL = "product=" . $appUpdateKey;
$shareOutputArr = getCurlOutput(getHash("07"), $upgradeDataURL);
if($shareOutputArr['status']==false){
Scheduler::Log("Version Upgrade CGI: "." Output: ".$shareOutputArr['output']. " Error: ".$shareOutputArr['error']);
return 'N';
}
$res = json_decode($shareOutputArr['output'], true);
session_start();
if (isset($res['version_no'])) {
if (strstr($res['version_no'], '_major') !== FALSE) {
$exp = explode('_', $res['version_no']);
$_SESSION['latest_version'] = $exp[0];
return 'M';
}
else if ($res['version_no'] !== $currVersion) {
$_SESSION['latest_version'] = $res['version_no'];
return 'Y';
}
else if (strtotime($res['release_date']) > strtotime($releaseDate)) {
$_SESSION['latest_version'] = $res['version_no'];
return 'Y';
}
}
$_SESSION['latest_version'] = $appVersion;
return 'N';
}
/****************************************************************************************************
* Function Name : getEVSServerAddr
* Objective : Getting EVS server address
* Added By : Senthil Pandian
******************************************************************************************************/
function getEVSServerAddr(){
$file = Scheduler::$user_dir.SERVER_ADDR_PATH;
if(isset($_SESSION['serverAddr'])){
$serverAddr = $_SESSION['serverAddr'];
} else if(file_exists($file) && customFileSize($file)>0){
$serverAddr = file_get_contents($file);
$serverAddr = trim($serverAddr);
$_SESSION['serverAddr'] = $serverAddr;
} else {
$serverOutput = getServerAddress();
$_SESSION['serverAddr'] = $serverOutput[1];
$serverAddr = trim($serverOutput[1]);
}
return $serverAddr;
}
/****************************************************************************************************
* Function Name : readFileChunkByChunk
* Objective : Read a file and display its content chunk by chunk
******************************************************************************************************/
function readFileChunkByChunk($filename, $offset = 0, $readCount = 0,$currentPage = "")
{
$retry_count = 0;
$stop = 0;
$logFileSize = 0;
if($currentPage == "last" && $readCount == 0){
$resultStatus = getLogStatus($filename);
clearstatcache();
$logFileSize = customFileSize($filename);
$lastPageChunkSize = $logFileSize%CHUNK_SIZE;
if($lastPageChunkSize == 0)
$lastPageChunkSize = CHUNK_SIZE;
if($resultStatus['stop'] == LOG_COMPLETE && $lastPageChunkSize < LAST_LOGPAGE_MIN_CHUNK+100){
$lastPageChunkSize = LAST_LOGPAGE_MIN_CHUNK+100;
}
$offset = $logFileSize-$lastPageChunkSize;
if($offset<0)
$offset = 0;
}
$handle = fopen($filename, "r");
if ($handle === false)
return array("status"=>0,"data"=>"","offset"=>$offset,"stop"=>$stop,"readCount"=>$readCount);
fseek($handle,$offset);
while(1){
$buffer = fread($handle,CHUNK_SIZE);
if($buffer != FALSE && trim($buffer) != "")
{
if($readCount + strlen($buffer) >= CHUNK_SIZE)
$stop = CURRENT_LOGPAGE_COMPLETE;
else
{
$resultStatus = getLogStatus($filename);
$stop = $resultStatus['stop'];
}
//remove the first partial line
if($currentPage == "previous" || $currentPage == "last")
{
$firstNewLinePos = strpos($buffer,"\n");
if($firstNewLinePos !== false){
$buffer = substr($buffer,$firstNewLinePos+1);
$offset += $firstNewLinePos+1;
}
}
//remove the last partial line
if($stop != LOG_COMPLETE && $currentPage != "previous")
{
$lastNewLinePos = strrpos($buffer,"\n");
if($lastNewLinePos !== false){
$lastNewLinePos++;
$buffer = substr($buffer,0,$lastNewLinePos);
}else $buffer = "";
}
$offset += strlen($buffer);
$readCount += strlen($buffer);
//if log file is completed and only little data left to read then read it in this call itself
if($stop == LOG_COMPLETE && ($currentPage == "next" || $currentPage == "last"))
{
clearstatcache();
$logFileSize = customFileSize($filename);
if($logFileSize - $offset <= LAST_LOGPAGE_MIN_CHUNK)
{
$partialBuffer = fread($handle,CHUNK_SIZE);
$offset += strlen($partialBuffer);
$readCount += strlen($partialBuffer);
$buffer = $buffer.$partialBuffer;
}
}
break;
}
else
{
$buffer = '';
$resultStatus = getLogStatus($filename);
$stop = $resultStatus['stop'];
if($stop == LOG_INPROGRESS && $retry_count <= 20 )
{
$retry_count++;
sleep(1);
}
else
break;
}
}
fclose($handle);
return array("status"=>1,"data"=>$buffer,"offset"=>$offset,"stop"=>$stop,"readCount"=>$readCount);
}
/****************************************************************************************************
* Function Name : checkIfHtaccessExists
* Objective : Checks for .htaccess file inside working folder if not creates one
******************************************************************************************************/
function checkIfHtaccessExists()
{
GLOBAL $webDir;
GLOBAL $permissionVal;
$orgSerPath = "/var/packages/IDrive/target/etc/";
$servicePath = Scheduler::$service_dir;
if($webDir != "") {
$htaccess_file = "$webDir/".SERVICE."/.htaccess";
if(!file_exists($htaccess_file))
{
$linkPath = substr($servicePath, 0, -1);
if(!is_link($linkPath)){
`ln -s $orgSerPath $linkPath`;
}
@chmod($servicePath,$permissionVal);
// as we removed web folder dependency, we are commenting this section.
/*$appDirPerms = isDirectoryWritable($webDir);
if(!$appDirPerms['is_writable']) {
$servDirErrorHeader = str_replace("{:APP_PATH:}", $webDir, APP_DIR_WRITE_PERM_MISSING);
echo getDirPermissionHTML($servDirErrorHeader, '');
exit;
}*/
/*if(!file_exists($servicePath))
mkdir($servicePath,$permissionVal);
@chmod($servicePath,$permissionVal);
*/
file_put_contents($htaccess_file,"Deny from all");
@chmod($htaccess_file, $permissionVal);
}
}
}
/****************************************************************************************************
* Function Name : accountUsage
* Objective : To fetch quota details using the api and calculate the percentage.
* Added By : Pooja H
* Modified By : Anil Kumar
******************************************************************************************************/
function accountUsage()
{
//$url = "https://".$_SESSION['evswebsrvr']."/evs/getAccountQuota";
$data = "uid=".rawurlencode($_SESSION['userName'])."&pwd=".rawurlencode(base64_decode($_SESSION['password']));
$out = getCurlOutput("https://".$_SESSION['evswebsrvr'].getHash("10"), $data);
if($out['status']) {
$out = $out['output'];
$out = str_replace('<?xml version="1.0" encoding="UTF-8"?>', '', $out);
$xml = simplexml_load_string("<root>$out</root>");
$xmlArray = $xml->tree;
$totalquota = "";
$usedquota = "";
$quotaUsed = "";
if(isset($xmlArray['message']) && ($xmlArray['message'] == "SUCCESS")){
$usedquota = (float)$xmlArray['usedquota'];
$totalquota = (float)$xmlArray['totalquota'];
if(!empty($totalquota) and $totalquota > 0){
//if(!empty($usedquota)){
//session_start();
percentQuotaUsed($usedquota,$totalquota);
//$_SESSION['usedQuotaOrg'] = $exp[1];
if(($usedquota == 0 ) and ($usedquota < $_SESSION['usedQuotaOrg'])) {
#need to call auth list and confirm whether to logout or not.
remoteList("/");
//exit(header("Location: ./logout.php"));
}
$_SESSION['usedQuotaOrg'] = $usedquota;
$totalquota = humanReadableSize($totalquota);
$usedquota = humanReadableSize($usedquota);
$_SESSION['totalQuota'] = empty($totalquota)?'0':$totalquota;
$_SESSION['usedQuota'] = empty($usedquota)?'0':$usedquota;
// }
}
}
else {
$error = $xmlArray['desc'];
if(FALSE != (strpos($error, "INVALID PASSWORD")) || FALSE != (strpos($error, "INVALID USER"))){
session_destroy();
}
if(FALSE != (strpos($error, "INVALID SERVER ADDRESS"))){
getServerAddress();
}
exit(header("Location: ./logout.php"));
}
}
else{
Scheduler::Log("QUOTA Update CGI: " . " Output: ".$out['output'] . " Error: ".$out['error']);
if(FALSE != (strpos($error, "resolve host"))){
exit(header("Location: ./logout.php"));
}
}
}
/****************************************************************************************************
* Function Name : getEncrypted
* Objective : Encrypt the given data using BLOWFISH cipher and mcrypt mode cbc.
* Added By : Yogesh Kumar
*****************************************************************************************************/
function getEncrypted($data, $privateKey, $iv) {
$data = base64_encode($data);
$npc = mcrypt_module_open(MCRYPT_BLOWFISH,'','cbc','');
mcrypt_generic_init($npc, $privateKey, $iv);
$encrypted = mcrypt_generic($npc, $data);
mcrypt_generic_deinit($npc);
return $encrypted;
}
/****************************************************************************************************
* Function Name : getDecrypted
* Objective : Decrypt the given data using BLOWFISH cipher and mcrypt mode cbc.
* Added By : Yogesh Kumar
*****************************************************************************************************/
function getDecrypted($data, $privateKey, $iv) {
$npc = mcrypt_module_open(MCRYPT_BLOWFISH,'','cbc','');
mcrypt_generic_init($npc, $privateKey, $iv);
$decrypted = base64_decode(mdecrypt_generic($npc, $data));
mcrypt_generic_deinit($npc);
return $decrypted;
}
/****************************************************************************************************
* Function Name : phpRealEscapeString
* Objective : Escapes special chars in the unescaped strings.
* Added By : Yogesh Kumar
*****************************************************************************************************/
function phpRealEscapeString($stringValue) {
if(get_magic_quotes_gpc()) {
$stringValue = stripcslashes($stringValue);
}
return $stringValue;
}
/****************************************************************************************************
* Function Name : removeDirContent
* Objective : Remove all directory content.
* Added By : Sajana
******************************************************************************************************/
function removeDirContent($directoryPaths)
{
if($directoryPaths!="/")
removeItems($directoryPaths);
}
/****************************************************************************************************
* Function Name : checkIfJobRunning
* Objective : find the running manual/scheduled archive job and returns on success
* Added By : Sajana K
* Modified By : Pooja Havaldar
******************************************************************************************************/
function checkIfJobRunning($jobpath)
{
$archiveJobInProgress = 0;
$directories = glob($jobpath . '*' , GLOB_ONLYDIR);
for($k=0;$k<count($directories);$k++){
$directories[$k] = trim($directories[$k]);
$pid = $directories[$k]."/".PID_FILE;
if(isFileLocked($pid)){
Scheduler::Log("Backup Job running");
$archiveJobInProgress = 1;
break;
}
}
return $archiveJobInProgress;
}
/************************************************************************************************
* 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 : fileStatusRemote.
* Objective : Getting file status from server.
* Added By : Sajana K.
**********************************************************************************************************/
function fileStatusRemote($operationType, $filesOnly)
{
GLOBAL $idevsutilBinaryPath;
GLOBAL $whiteSpace;
GLOBAL $idevsutilArgument;
GLOBAL $assignmentOperator;
GLOBAL $OutErrorFilePath;
GLOBAL $OutOutputFilePath;
GLOBAL $selected_backupset;
GLOBAL $deleteUtfFile, $permissionVal;
$pidPathForSearch = Scheduler::$archiveclean_dir.$selected_backupset."/$pidPath";
$openedfile = false;
/* to get the php error message in customErrorMsg() variable. */
ini_set('track_errors', 1);
$deleteUtfFile = getOperationFile($operationType, $filesOnly);
$idevsutilCommandLine = $idevsutilBinaryPath.$whiteSpace.$idevsutilArgument.$assignmentOperator."\"$deleteUtfFile\"";
system("$idevsutilCommandLine");
if(!customFileSize($OutOutputFilePath) && !customFileSize($OutErrorFilePath)){
if(!file_exists($pidPathForSearch)){
Scheduler::Log("Pid file does not exist.");
}
userCancelfileStatusRemote();
return $openedfile;
}
/* update server address if cmd failed due to wrong evs server address. */
if(checkErrorAndUpdateServerAddr($OutErrorFilePath)){
userCancelfileStatusRemote();
return $openedfile;
}
if(!customFileSize($OutOutputFilePath)){
Scheduler::Log("Output file is empty.");
userCancelfileStatusRemote();
return $openedfile;
}
$handle = fopen($OutOutputFilePath, "r");
$outfile = Scheduler::$archiveclean_dir.$selected_backupset."/".FILESONLY;
if($_SESSION['dedup'])
file_put_contents($outfile,"connection established\n");
else
file_put_contents($outfile,EVS_SEARCH_HEAD);
while( ($buffer = fgets($handle)) !== false ) {
if(!file_exists($pidPathForSearch)){
Scheduler::Log("Pid file does not exist. Stopping the parsing.");
fclose($handle);
userCancelfileStatusRemote();
return $openedfile;
}
if(!$buffer){
if(customFileSize($OutErrorFilePath)){
$error = file_get_contents(ERRORFILE);
$reason = checkErrorAndReason($error);
Scheduler::Log("EVS error on $OutErrorFilePath, Reason : $reason");
break;
}
}
if($_SESSION['dedup'])
{
if(preg_match('/connection established/', $buffer)){
continue;
}
$bufferXML = "<root>$buffer</root>";
$xml = simplexml_load_string($bufferXML);
$value = $xml->item;
$filename = trim($value['fname']);
$status = trim($value['status']);
if($status == "file exists"){
file_put_contents($outfile,"<item restype=\"F\" fname=\"$filename\" />\n",FILE_APPEND);
$openedfile = true;
}
}
else{
$bufferTmp = explode("] [",$buffer);
if(count($bufferTmp) > 1){
$status = trim(ltrim($bufferTmp[0],"["));
$bufferTmp2 = substr(trim($bufferTmp[1]), 0,-1);
if($status == "file exists"){
file_put_contents($outfile,"[0:00:00] [ 000000] [ 1] [ - ] [ 0] [$bufferTmp2]"."\n",FILE_APPEND);
$openedfile = true;
}
}
else{
if(preg_match('/bytes received/', $buffer))
break;
}
}
}
if($openedfile == true){
if($_SESSION['dedup'])
file_put_contents($outfile,"<item items_found=\"1\" />\n",FILE_APPEND);
else
file_put_contents($outfile,EVS_FINISH_HEAD,FILE_APPEND);
}
fclose($handle);
@chmod($outfile, $permissionVal);
userCancelfileStatusRemote();
return $openedfile;
/*
USER_CANCEL:
if(file_exists($OutErrorFilePath))
unlink($OutErrorFilePath);
if(file_exists($OutOutputFilePath))
unlink($OutOutputFilePath);
if(file_exists($deleteUtfFile))
unlink($deleteUtfFile);
return $openedfile;
*/
}
/****************************************************************************************************
* Function Name : userCancelfileStatusRemote
* Objective : Check the current user has read permissions for the requested file/folder.
* Added By : Yogesh Kumar
*****************************************************************************************************/
function userCancelfileStatusRemote()
{
GLOBAL $OutErrorFilePath, $OutOutputFilePath, $deleteUtfFile;
if(file_exists($OutErrorFilePath))
unlink($OutErrorFilePath);
if(file_exists($OutOutputFilePath))
unlink($OutOutputFilePath);
if(file_exists($deleteUtfFile))
unlink($deleteUtfFile);
}
/****************************************************************************************************
* Function Name : hasReadPermissions
* Objective : Check the current user has read permissions for the requested file/folder.
* Added By : Yogesh Kumar
*****************************************************************************************************/
function hasReadPermissions($path) {
foreach ($_SESSION['shared_folders'] as $sharedFolder) {
if (substr($path, -1) !== '/') {
$path .= '/';
}
if (strpos($path, $sharedFolder) === 0) {
return true;
}
}
return false;
}
/*****************************************************************************************************
* Subroutine Name : trashListing.
* Objective : This function will execute the EVS search command and parse the output file
* to provide the expected output to user.
******************************************************************************************************/
function trashListing($searchItem)
{
GLOBAL $idevsutilBinaryPath;
GLOBAL $whiteSpace;
GLOBAL $idevsutilArgument;
GLOBAL $assignmentOperator;
GLOBAL $OutErrorFilePath;
GLOBAL $OutOutputFilePath;
GLOBAL $baseDir;
GLOBAL $webDir;
GLOBAL $userName;
GLOBAL $searchHandle;
GLOBAL $countItem;
GLOBAL $searchDir;
GLOBAL $pagePath;
GLOBAL $pidPath;
GLOBAL $trashListingFlag;
GLOBAL $restoreListFolderPath;
GLOBAL $trash_Search;
GLOBAL $trashListPath;
GLOBAL $handle;
GLOBAL $pidPathForTrash;
GLOBAL $trashListFile;
GLOBAL $searchUtfFile, $permissionVal;
$trash_Search = 1;
$trashListingFlag = 1;
if("" == $searchItem){
unset($_SESSION['currentRemoteSearchPath']);
return;
}
session_write_close();
ini_set('track_errors', 1);
$pidPathForTrash = $_SESSION['currentRemoteSearchPath'].$pidPath;
file_put_contents($pidPathForTrash,"");
@chmod($pidPathForTrash,$permissionVal);
$lastLine = "";
$pageCount = 0;
$flag = 0;
$buffer = "";
$byteRead = 0;
$len = 0;
$toSearchStr = "";
$type = "";
$size = "";
$dateTime = "";
$item = "";
$pattern = "";
$tmpArr = array();
$isNotOpened = 0;
$totalCount = 0;
$searchUtfFile = getOperationFile(SEARCHOP, $searchItem);
@chmod($searchUtfFile,0777);
if(!file_exists($searchUtfFile)){
Scheduler::Log("TrashList: ".customErrorMsg());
return false;
}
$searchUtfFile = str_replace("'","'\''",$searchUtfFile);
$idevsutilCommandLine = $idevsutilBinaryPath.$whiteSpace.$idevsutilArgument.$assignmentOperator."'$searchUtfFile'";
$trashListFile = constructRestoreFileName($remotePath,$trashListingFlag);
$trashListFile = $trashListPath;
if(!file_exists($pidPathForTrash)){
$errStr = ERR_STR_VAL;
userCanceltrashListing();
return;
}
elseif(file_exists($pidPathForTrash)){
pclose(popen("$idevsutilCommandLine &","r"));
}
while(!customFileSize($OutOutputFilePath) and !customFileSize($OutErrorFilePath)){
if(!file_exists($pidPathForTrash)){
$errStr = ERR_STR_VAL;
userCanceltrashListing();
return;
}
sleep(0.1);
}
if(!customFileSize($OutOutputFilePath)){
Scheduler::Log("Trash List");
userCanceltrashListing();
return;
}
$searchHandle = fopen($trashListFile, "w");
if(!$searchHandle) {
Scheduler::Log("not able to open $trashListFile");
userCanceltrashListing();
return;
}
$handle = fopen($OutOutputFilePath, "r");
if(!$handle) {
Scheduler::Log("not able to open $OutOutputFilePath\n");
userCanceltrashListing();
return;
}
$pattern =array();
while(1)
{
$buffer = fread($handle, LIMIT);
if(0 === strlen($buffer)){
if(customFileSize($OutErrorFilePath)){
break;
}
sleep(WAIT_FOR);
fseek($handle, 0, 1); //to clear eof flag
continue;
}
//need to check appending partial record to packet or to first line of packet
if("" != $lastLine){
$buffer = $lastLine . $buffer;
}
$resultList = explode("\n", $buffer);
$bufIndex = count($resultList);
$bufIndex -= 1;
//keep last line of buffer only when it not ends with newline.
if(!preg_match('/\n$/', $buffer)){
$lastLine = $resultList[$bufIndex];
}
else{
$lastLine = "";
}
if(0 < $bufIndex and preg_match('/Total files found/', $resultList[$bufIndex-1])){
$flag = 1;
$bufIndex -= 1;
}
$totalCount += $bufIndex;
for($index = 0; $index < $bufIndex; $index++)
{
$tmpArr = explode("] [", $resultList[$index], 6);
if(count($tmpArr) < 6)
continue;
$tmpArr[count($tmpArr) - 1] = rtrim($tmpArr[count($tmpArr) - 1], "]");
$item = $tmpArr[count($tmpArr) - 1];
$type = trim($tmpArr[1])==0?"D":"F";
if(!$item) continue;
if(!arraySearchPartial($pattern, $item))
{
$itemPresent = substr($item,strlen($searchItem)); // need to be sure initial match other
$last_Index= strpos($itemPresent,'/');
if($last_Index)
{
$finalItem = substr($itemPresent,0,$last_Index);
$finalItemType = "D";
$patternPush = $searchItem.$finalItem."/";
array_push($pattern,$patternPush);
}
else
{
$finalItem = $itemPresent;
$finalItemType = "F";
//$patternPush = $searchItem.$finalItem;
// array_push($pattern,$patternPush);
}
$dateTime = preg_replace("/^\[/", "", $tmpArr[0]);
$size = trim($tmpArr[1]);
$size = convertFileSize($size);
addListWithType($finalItemType, $finalItem, $dateTime, $size);
}
}
if(1 == $flag){
break;
}
}
userCanceltrashListing();
return;
}
/****************************************************************************************************
* Function Name : userCanceltrashListing
* Objective :
* Added By : Pooja Havaldar
*****************************************************************************************************/
function userCanceltrashListing()
{
GLOBAL $searchHandle, $handle, $pidPathForTrash, $trashListFile, $searchUtfFile, $OutOutputFilePath, $OutErrorFilePath;
if($searchHandle){
fclose($searchHandle);
}
if($handle){
fclose($handle);
}
if(file_exists($pidPathForTrash)){
unlink($pidPathForTrash);
}
else if(file_exists($trashListFile)){
unlink($trashListFile);
}
$searchUtfFile = str_replace("'\''","'",$searchUtfFile);
if(file_exists($searchUtfFile)){
unlink($searchUtfFile);
}
if(file_exists($OutOutputFilePath)){
unlink($OutOutputFilePath);
}
if(file_exists($OutErrorFilePath)){
unlink($OutErrorFilePath);
}
}
/****************************************************************************************************
* Function Name : updateIDriveApp
* Objective : To call operations.pl with the update url
* Added By : Pooja Havaldar
* Modified By : Sabin Cheruvattil | 2016-07-26
*****************************************************************************************************/
function updateIDriveApp()
{
GLOBAL $userName, $permissionVal;
# check for proxy details and store it in .cache so that it can be read by operations.pl
if($userName == '') {
getProxyDetail();
}
$proxyString = '';
if($_SESSION['isProxyEnabled'] == 1 && $_SESSION['ipAddress'] != '') {
$proxyString = 'http://' . (($_SESSION['proxyUserName'] != '')? $_SESSION['proxyUserName'] : '');
$proxyString .= (($_SESSION['proxyUserName'] != '' && $_SESSION['proxyPassword'] != '')? ':' . $_SESSION['proxyPassword'] : '');
$proxyString .= (($_SESSION['proxyUserName'] != '')? '@' : '');
$proxyString .= $_SESSION['ipAddress'] . (($_SESSION['port'] != '')? ':' . $_SESSION['port'] : '');
}
file_put_contents(Scheduler::$temp_file, UPDATE_APP . (($proxyString != '')? "\n" . $proxyString : ''));
@chmod(Scheduler::$temp_file,$permissionVal);
# NOTICE: Do not change the following line which calls app update. user directory path affects the lock path
$output = phpScriptExecution(OPERATIONSFILE, Scheduler::$user_dir, 1, TRUE, FALSE);
return $output;
}
/***********************************************************************************************************************
* Function Name : getLogFileEncodedName
* Objective : Provides the exact and latest log file path with status in encoded form
**************************************************************************************************************************/
function getUpdatedLogFileName($decodedPath = "")
{
if(empty($decodedPath))
return $decodedPath;
$file_to_read = "";
if(file_exists($decodedPath)) {
$file_to_read = $decodedPath;
} else if(file_exists($decodedPath."_SUCCESS")) {
$file_to_read = $decodedPath."_SUCCESS";
} else if(file_exists($decodedPath."_SUCCESS*")) {
$file_to_read = $decodedPath."_SUCCESS*";
} else if(file_exists($decodedPath."_ABORTED")) {
$file_to_read = $decodedPath."_ABORTED";
} else if(file_exists($decodedPath."_FAILURE")) {
$file_to_read = $decodedPath."_FAILURE";
}
return $file_to_read;
}
/***************************************************************************************************************
* Subroutine Name : arraySearchPartial
* Objective : This function will search the item partially matches with the given array
*****************************************************************************************************************/
function arraySearchPartial($arr, $item) {
$LastIndex = count($arr)-1;
for($i=$LastIndex;$i>=0;$i--)
{
$compare = strpos($item,$arr[$i]);
if ($compare === 0) return 1;
}
}
/****************************************************************************************************************************
* Function Name : createOrVerifyOrDeleteLink
* Objective : create a symbolic link for the log file to be downloaded inside IDrive/Downloads if not exists and
* Delete a link if deleteFlag is set
******************************************************************************************************************************/
function createOrVerifyOrDeleteLink($file,$deleteFlag=0)
{
GLOBAL $userName;
$downloadFolder = getWebDirPath()."/".APPDIR."/Downloads/";
$commandArray = array();
$downloadLinkOld ='';
if(!file_exists($downloadFolder) && !$deleteFlag){
array_push($commandArray,"mkdir '".$downloadFolder."'");
array_push($commandArray,"chmod 0777 '".$downloadFolder."'");
}
$filenameLogPos = strpos($file,"/LOGS/");
$logName = substr($file,$filenameLogPos+strlen("/LOGS/"));
$linkName = $userName."_".$logName;
$downloadlink = $downloadFolder.$linkName;
if(!is_link($downloadlink) && !$deleteFlag){
$checkForUnderScore = strpos($logName,"_");
if($checkForUnderScore)
$downloadLinkOld = $downloadFolder.$userName."_".substr($logName,0,$checkForUnderScore);
if(is_link($downloadLinkOld))
array_push($commandArray,"rm -rf '".$downloadLinkOld."'");
array_push($commandArray,"ln -s '".$file."' '".$downloadlink."'");
}
else if($deleteFlag){
$downloadLinkOld = substr($downloadlink,0,strrpos($downloadlink,"_"));
if($downloadLinkOld!="/" && $downloadlink!="/")
array_push($commandArray,"rm -rf '".$downloadlink."' '".$downloadLinkOld."' ");
}
if($commandArray)
systemCmdExecutionViaPhp($commandArray, Scheduler::$user_dir);
return $linkName;
}
/***********************************************************************************************************************
* Function Name : getLogStatus
* Objective : Checks the status of the log file, provides logStatus and stop flag
**************************************************************************************************************************/
function getLogStatus($filename = ""){
$log_file_full_arr = explode("/", $filename);
$log_details = explode("_", $log_file_full_arr[count($log_file_full_arr) - 1]);
$logStatus = "";
if(count($log_details) == 1)
{
array_pop($log_file_full_arr);
array_pop($log_file_full_arr);
$logPidFile = implode("/",$log_file_full_arr)."/".LOG_PID_FILE;
$logStatus = @file_get_contents($logPidFile);
$filename = realpath($filename);
if($logStatus == $filename)
{
$stop = LOG_INPROGRESS;
}
else
$stop = LOG_COMPLETE;
}
else
$stop = LOG_COMPLETE;
return array("logStatus"=>$logStatus,"stop"=>$stop);
}
/****************************************************************************************************
* Function Name : addToExcludeList
* Objective : Add the selected items to excluded list.
* Added By : Yogesh Kumar
*****************************************************************************************************/
function addToExcludeList($itemName, $itemType, $excludeFullFile) {
GLOBAL $permissionVal;
$status = array();
$hasChildren = false;
$new_item_len = strlen($itemName);
$exp = array();
if (file_exists($excludeFullFile)) {
$exp = file($excludeFullFile, FILE_IGNORE_NEW_LINES);
#duplicate check
$flag_skip = in_array($itemName, $exp);
if ($flag_skip == true) {
$status[] = false;
$status[] = ITEM_ALREADY_EXCLUDED;
return $status;
}
$hasParent = $skipCurrentIndex = false;
$newItemLen = strlen($itemName);
if (getOriginalServicePath() == $exp[0])
$skipCurrentIndex = true;
// Checking if parent exist for new item OR if child's exist for new item.
$itemCount = count($exp);
for($i = 0; $i < $itemCount; $i += 4) {
if (! $hasChildren) {
$check_val3 = strpos($itemName, $exp[$i]);
$exclude_item_len = strlen($exp[$i]);
$pos = strpos($itemName, "/", $exclude_item_len);
if (($check_val3 === 0) && ($pos === $exclude_item_len)) {
$hasParent = true;
break;
}
}
if ((! $skipCurrentIndex) && ($itemType == 'folder')) {
$check_val3 = strpos($exp[$i], $itemName);
$pos = strpos($exp[$i], "/", $new_item_len);
if (($check_val3) === 0 && ($pos === $new_item_len)) {
unset($exp[$i]);
unset($exp[($i + 1)]);
$hasChildren = true;
}
}
else {
$skipCurrentIndex = false;
}
}
if ($hasParent == true) {
$status[] = false;
$status[] = ITEM_ALREADY_EXCLUDED;
return $status;
}
}
if ($hasChildren) {
$exp[] = $itemName;
$exp[] = $itemType;
$filesExcluded = (implode("\n", $exp) . "\n");
file_put_contents($excludeFullFile, $filesExcluded."undefined\nundefined\n", LOCK_EX);
}
else {
file_put_contents($excludeFullFile, ($itemName . "\n" . $itemType . "\nundefined\nundefined\n"), FILE_APPEND | LOCK_EX);
}
@chmod($excludeFullFile,$permissionVal);
unset($_SESSION['fullEntry']);
$status[] = true;
$status[] = ITEM_EXCLUDED;
return $status;
}
/****************************************************************************************************
* Function Name : getNextScheduledTask
* Objective : This will calculate the next scheduled task among all jobs
* Added By : Sabin Cheruvattil
* Modified By : Senthil Pandian
*****************************************************************************************************/
function getNextScheduledTask()
{
$jobs = Scheduler::ReadJobs();
$nextSchedule = array();
foreach($jobs as $jobName => $jobData) {
if(!isset($jobData['scheduler']) || !isset($jobData['scheduler']['start_minute'])) {
continue;
}
$nsStartingTimeStamp = 0;
switch($jobData['scheduler']['scheduler_selection']) {
case 'hourly':
$schedulerStartMin = $jobData['scheduler']['start_minute'];
$currentHour = exec('date "+%H"');
$currentMin = exec('date "+%M"');
$serverTimeStampNow = mktime($currentHour, $currentMin, 0);
$thisHourSchedulerStartTime = mktime($currentHour, $schedulerStartMin, 0);
$nextHourSchedulerStartTime = mktime($currentHour + 1, $schedulerStartMin, 0);
# In simple case hourly selection will occur next hour.
# If minute is selected which is greater than current minute, execution needs to be considered as same hour execution.
$nsStartingTimeStamp = (($serverTimeStampNow >= $thisHourSchedulerStartTime)? $nextHourSchedulerStartTime : $thisHourSchedulerStartTime);
break;
case 'daily':
$schedulerStartMin = $jobData['scheduler']['start_minute'];
$schedulerStartHour = (($jobData['scheduler']['start_meridian'] === 'am')? (($jobData['scheduler']['start_hour'] == 12)? 0 : $jobData['scheduler']['start_hour']) : (($jobData['scheduler']['start_hour'] == 12)? $jobData['scheduler']['start_hour'] : ($jobData['scheduler']['start_hour'] + 12)));
$currentHour = exec('date "+%H"');
$currentMin = exec('date "+%M"');
$serverTimeStampNow = mktime($currentHour, $currentMin, 0);
$todaySchedulerStartTime = mktime($schedulerStartHour, $schedulerStartMin, 0);
$tomorrowSchedulerStartTime = mktime($schedulerStartHour, $schedulerStartMin, 0, date("n"), date("j") + 1);
# Daily scheduled tasks in simple case will occur same day.
# If the scheduled time has already passed, then consider next day schedule.
$nsStartingTimeStamp = (($serverTimeStampNow >= $todaySchedulerStartTime)? $tomorrowSchedulerStartTime : $todaySchedulerStartTime);
break;
case 'monthly':
$nsStartingTimeStamp = getMonthlyExecutionTime($jobData);
break;
default:
# If there is no weekday selection, no need to go further
if(trim($jobData['scheduler']['weekday_selection']) == '') {
break;
}
$nsStartingTimeStamp = getWeeklyExecutionTime($jobData);
break;
# switch cases
}
if($nsStartingTimeStamp != 0) {
$nextSchedule[$jobName]['ts'] = $nsStartingTimeStamp;
$nextSchedule[$jobName]['time'] = date('m/d/Y h:i:s A', $nsStartingTimeStamp);
$nextSchedule[$jobName]['jobName'] = preg_replace("/^Backup_|^Restore_/", '', $jobName);
$nextSchedule[$jobName]['jobType'] = $jobData['job_type'];
}
}
if(!empty($nextSchedule)) {
# Obtain a list of columns
$schedulerJobNames = array();
$schedulerJobNamesWithType = array();
$schedulerTimeStamps = array();
foreach($nextSchedule as $key => $row) {
$schedulerJobNames[$key] = $row['jobName'];
$schedulerTimeStamps[$key] = $row['ts'];
$schedulerJobNamesWithType[$key] = $key;
}
# Sort the data, First by Name then by Schedule
array_multisort($schedulerTimeStamps, SORT_ASC, SORT_NUMERIC,
$schedulerJobNamesWithType, SORT_ASC, SORT_STRING,
$schedulerJobNames, SORT_ASC, SORT_STRING,
$nextSchedule);
$nextEvents = array_slice($nextSchedule, 0, 2);
return $nextEvents;
}
return $nextSchedule;
}
/****************************************************************************************************
* Function Name : getWeeklyExecutionTime
* Objective : This will calculate the execution time for weekly schedule
* Added By : Sabin Cheruvattil
* Modified By : Senthil Pandian
*****************************************************************************************************/
function getWeeklyExecutionTime($jobData)
{
$schedulerStartMin = $jobData['scheduler']['start_minute'];
$schedulerStartHour = (($jobData['scheduler']['start_meridian'] === 'am')? (($jobData['scheduler']['start_hour'] == 12)? 0 : $jobData['scheduler']['start_hour']) : (($jobData['scheduler']['start_hour'] == 12)? $jobData['scheduler']['start_hour'] : ($jobData['scheduler']['start_hour'] + 12)));
$schedulerStartDays = explode(',', str_replace(array('[', ']', '"'), "", strtolower(trim($jobData['scheduler']['weekday_selection']))));
$daysOfWeek = array('sun' => 0, 'mon' => 1, 'tue' => 2, 'wed' => 3, 'thu' => 4, 'fri' => 5, 'sat' => 6);
$todayDayOfWeek = strtolower(date('D'));
$nsStartingTimeStamp = 0;
$currentHour = exec('date "+%H"');
$currentMin = exec('date "+%M"');
$serverTimeStampNow = mktime($currentHour, $currentMin, 0);
$todaySchedulerStartTime = mktime($schedulerStartHour, $schedulerStartMin, 0);
if(count($schedulerStartDays) == 1) {
# Single Day Selection: If there is only a single day selection, calculation can be much simpler.
# If the same day is selected and the selected time has not passed consider the same day for scheduled task.
# Otherwise it will occur next week same day. If same day is not selected for the scheduler consider the day ahead in that week.
# If there is no day selected ahead in that week select the day from the beginning of the week and does depends on the scheduler selection.
# check if the selection is for today or not
if($todayDayOfWeek == $schedulerStartDays[0]) {
if($todaySchedulerStartTime < $serverTimeStampNow) {
# Today's execution time already over. Consider the execution for next month
$nsStartingTimeStamp = mktime($schedulerStartHour, $schedulerStartMin, 0, date("n"), date("j") + 7);
} else {
# This event is going to execute today
$nsStartingTimeStamp = $todaySchedulerStartTime;
}
} else {
$nextScheduledDayVal = $daysOfWeek[$schedulerStartDays[0]];
$todayScheduledDayVal = $daysOfWeek[$todayDayOfWeek];
# calculate the number of days to add for the next execution date
$daysToAddForNxtSchd = (($nextScheduledDayVal > $todayScheduledDayVal)? ($nextScheduledDayVal - $todayScheduledDayVal) : (7 - $todayScheduledDayVal + $nextScheduledDayVal));
# Maximum number of days - todays week day + next selected day
# Ex: Execution on Monday[1] and present day is wednesday[3], then: 7 - 3 + 1 = 5 | From wednesday to monday 5 days
$nsStartingTimeStamp = mktime($schedulerStartHour, $schedulerStartMin, 0, date("n"), date("j") + $daysToAddForNxtSchd);
}
} else {
# check if this task is good for running today
if(in_array($todayDayOfWeek, $schedulerStartDays)) {
# Multiple Selection With Present Day Involved: In this case first needs to consider whether today's execution time is passed or not.
# If not passed consider today for execution otherwise the next scheduled day.
# It can come ahead or behind. If it comes ahead consider the day ahead else consider the first selection in the scheduler's weekdays.
if($todaySchedulerStartTime > $serverTimeStampNow) {
# This event is going to execute today
$nsStartingTimeStamp = $todaySchedulerStartTime;
} else {
# Todays exection time already passed
$todayWeekVal = $daysOfWeek[$todayDayOfWeek];
$schdulerTodayWeekIndex = array_search($todayDayOfWeek, $schedulerStartDays);
# Consider todays date value as a pivot element and calculate how many days to next scheduled task
if($schdulerTodayWeekIndex < (count($schedulerStartDays) - 1)) {
$schedulerNextDay = $schedulerStartDays[$schdulerTodayWeekIndex + 1];
$schedulerNextDayVal = $daysOfWeek[$schedulerNextDay];
$daysToAddForNxtSchd = $schedulerNextDayVal - $todayWeekVal;
$nsStartingTimeStamp = mktime($schedulerStartHour, $schedulerStartMin, 0, date("n"), date("j") + $daysToAddForNxtSchd);
} else {
# in this case selected day is ahead in the week and next execution is on some day of the begining of the week
$schedulerNextDay = $schedulerStartDays[0];
$schedulerNextDayVal = $daysOfWeek[$schedulerNextDay];
$daysToAddForNxtSchd = 7 - $todayWeekVal + $schedulerNextDayVal;
$nsStartingTimeStamp = mktime($schedulerStartHour, $schedulerStartMin, 0, date("n"), date("j") + $daysToAddForNxtSchd);
}
}
} else {
# Multiple Selection Without Present Day Involved:
# This calculation is bit complicated as the next probable day should be found when the next execution will happen.
# Consider present day as a pivot element and check for upcoming day.
# If day ahead is present take that day for execution. It can happen when there may not be any days ahead in the selection list or in that week.
# In this case consider the scheduler weekday selection's first element because that will be the next execution time.
# Consider hours and minutes in this case as well.
$todayWeekVal = $daysOfWeek[$todayDayOfWeek];
$schedulerLastSelectedDayVal = $daysOfWeek[$schedulerStartDays[count($schedulerStartDays) - 1]];
if($todayWeekVal < $schedulerLastSelectedDayVal) {
# calcualte number of days to next event and add to number of days ahead
for($i = $todayWeekVal; $i < count($daysOfWeek); $i++) {
$schedulerNextDay = array_search($i, $daysOfWeek);
$schedulerSelNextDayKey = array_search($schedulerNextDay, $schedulerStartDays);
if($schedulerSelNextDayKey != FALSE) {
$schedulerNextDayVal = $daysOfWeek[$schedulerNextDay];
$daysToAddForNxtSchd = $schedulerNextDayVal - $todayWeekVal;
$nsStartingTimeStamp = mktime($schedulerStartHour, $schedulerStartMin, 0, date("n"), date("j") + $daysToAddForNxtSchd);
break;
}
}
} else {
# scheduled event falls on the beginning of the week
$schedulerNextDay = $schedulerStartDays[0];
$schedulerNextDayVal = $daysOfWeek[$schedulerNextDay];
$daysToAddForNxtSchd = 7 - $todayWeekVal + $schedulerNextDayVal;
$nsStartingTimeStamp = mktime($schedulerStartHour, $schedulerStartMin, 0, date("n"), date("j") + $daysToAddForNxtSchd);
}
}
}
return $nsStartingTimeStamp;
}
/****************************************************************************************************
* Function Name : getMonthlyExecutionTime
* Objective : This will calculate the execution time for monthly schedule
* Added By : Sabin Cheruvattil
* Modified By : Senthil Pandian
*****************************************************************************************************/
function getMonthlyExecutionTime($jobData)
{
$nsStartingTimeStamp = 0;
if(!defined('CAL_GREGORIAN'))
define('CAL_GREGORIAN', 0);
# Special cases: As we alreay know the selection allows user to select 29-31 for scheduling.
# 29-31 is not valid for all the months. In this case need to consider present months maximum number of days and next months possible number of days.
# If selection exceeds the expected number of days of month, normalize the date selection by considering the max possible number of days in that month.
# This is applicable in present month calculation and next month calculation.
$schedulerStartMin = $jobData['scheduler']['start_minute'];
$schedulerStartHour = (($jobData['scheduler']['start_meridian'] === 'am')? (($jobData['scheduler']['start_hour'] == 12)? 0 : $jobData['scheduler']['start_hour']) : (($jobData['scheduler']['start_hour'] == 12)? $jobData['scheduler']['start_hour'] : ($jobData['scheduler']['start_hour'] + 12)));
$schedulerStartDate = $jobData['scheduler']['day_of_month'];
$currentHour = exec('date "+%H"');
$currentMin = exec('date "+%M"');
$serverTimeStampNow = mktime($currentHour, $currentMin, 0);
$thisMonthSchedStartTime = 0;
$maxDaysInThisMonth = cal_days_in_month(CAL_GREGORIAN, date('n'), date('Y'));
//print "Today:".date('Y/m/d',$serverTimeStampNow);
# Check whether the date selection exceeds this months maximum number of days
if($schedulerStartDate > $maxDaysInThisMonth) {
$thisMonthSchedStartTime = mktime($schedulerStartHour, $schedulerStartMin, 0, date('n'), $maxDaysInThisMonth);
} else {
$thisMonthSchedStartTime = mktime($schedulerStartHour, $schedulerStartMin, 0, date('n'), $schedulerStartDate);
}
if($serverTimeStampNow >= $thisMonthSchedStartTime) {
# Check whther the date selection exceeds next months maximum number of days
$nextMonth = date('m');
$nextMonth++;
$nextMonth = ($nextMonth<=12)?$nextMonth:01;
$nextYear = date('Y', strtotime('+1 month'));
$maxDaysInNextMonth = cal_days_in_month(CAL_GREGORIAN, $nextMonth, $nextYear);
if($schedulerStartDate > $maxDaysInNextMonth) {
$schedulerStartDate = $maxDaysInNextMonth;
}
# Scheduled Time Has Passed: If present month's time has passed consider the next month's time.
$nsStartingTimeStamp = mktime($schedulerStartHour, $schedulerStartMin, 0, date("n") + 1, $schedulerStartDate);
} else {
# Scheduled Time Ahead: If time has not passed yet consider the same month's execution date for the scheduler.
$nsStartingTimeStamp = $thisMonthSchedStartTime;
}
return $nsStartingTimeStamp;
}
/****************************************************************************************************
* Function Name : isRootLevelDisplayEnabled
* Objective : This helps to check whether root level display is enabled or not
* Added By : Sabin Cheruvattil
*****************************************************************************************************/
function isRootLevelDisplayEnabled() {
GLOBAL $machine;
$_SESSION['displayRoot'] = 0;
if(!file_exists(Scheduler::$user_dir . DISPLAY_ROOT_FILENAME)) {
return 0;
}
$enabledBit = file_get_contents(Scheduler::$user_dir . DISPLAY_ROOT_FILENAME);
if((int)$enabledBit == 1) {
$_SESSION['displayRoot'] = 1;
return 1;
}
return 0;
}
function getRootVal() {
GLOBAL $machine;
$rootVal = "/";
if($machine == SYNOLOGY_LOCAL) {
$webPath = "/var/services/web";
$servicePath = realpath($webPath);
$exp = explode("/web",$servicePath);
$rootVal = $exp[0]."/";
}
else if($machine == QNAP)
$rootVal = "/share/";
else if($machine == NETGEAR_LOCAL) // need to change for netgear and asustor.
$rootVal = QNAP_SHARED_PATH;
else if($machine == ASUSTOR)
$rootVal = QNAP_SHARED_PATH;
return $rootVal;
}
/****************************************************************************************************
* Function Name : migrate
* Objective : To migrate from older versions to new versions.
* Added By : Yogesh Kumar
*****************************************************************************************************/
function migrate() {
GLOBAL $webDir;
GLOBAL $excludeFullFile;
GLOBAL $permissionVal;
GLOBAL $userName;
$excludeFullFilePath = Scheduler::$user_dir.EXCLUDE_LIST_FILE;
$excludeFullFileType = Scheduler::$user_dir.EXCLUDE_LIST_FOR_DISPLAY_FILE;
if ((! file_exists($excludeFullFile)) &&
file_exists($excludeFullFilePath) &&
file_exists($excludeFullFileType)) {
$excludeArray = file($excludeFullFilePath, FILE_IGNORE_NEW_LINES);
$excludeDisplayArray = file($excludeFullFileType, FILE_IGNORE_NEW_LINES);
$exp = array();
foreach($excludeArray as $index => $excludeFileName) {
$exp[] = $excludeFileName;
$exp[] = substr($excludeDisplayArray[$index], 1, -1);
}
$newExp = implode("\n", $exp) . "\n";
file_put_contents($excludeFullFile, $newExp."undefined\nundefined\n", LOCK_EX);
unlink($excludeFullFilePath);
unlink($excludeFullFileType);
@chmod($excludeFullFile, $permissionVal);
}
}
/****************************************************************************************************
* Function Name : Trash List page initial search
* Objective : To List initial content in Trash page and using for empty trash process aswell.
* Added By : Vijay Vinoth
*****************************************************************************************************/
function remoteInitialSearch($searchItem,$searchPath,$searchDirRemote)
{
GLOBAL $idevsutilBinaryPath;
GLOBAL $whiteSpace;
GLOBAL $idevsutilArgument;
GLOBAL $assignmentOperator;
GLOBAL $OutErrorFilePath;
GLOBAL $OutOutputFilePath;
GLOBAL $webDir;
GLOBAL $userName;
GLOBAL $searchHandle;
GLOBAL $countItem;
GLOBAL $isOpened;
GLOBAL $pagePath;
GLOBAL $pidPath;
GLOBAL $permissionVal;
GLOBAL $trash_Search;
GLOBAL $searchDirTrashRemote;
GLOBAL $empty_trash;
GLOBAL $searchUtfFile;
GLOBAL $pidPathForSearch;
//$empty_trash = 0;
$outputArray = "";
if(!is_dir($searchDirRemote)){
if(!mkdir($searchDirRemote, $permissionVal)){
$resp[] = false;
$resp[] = "Failed to create Directory ".$searchDirRemote." : ".customErrorMsg();
unset($_SESSION['currentRemoteSearchPath']);
echo json_encode($resp);
exit;
}
@chmod($searchDirRemote,$permissionVal);
}
if(!is_dir($searchDirRemote)){
if(!mkdir($searchDirRemote, $permissionVal)){
$resp[] = false;
$resp[] = "Failed to create Directory ".$searchDirRemote." : ".customErrorMsg();
unset($_SESSION['currentRemoteSearchPath']);
echo json_encode($resp);
exit;
}
@chmod($searchDirRemote,$permissionVal);
}
if("" == $searchItem){
unset($_SESSION['currentRemoteSearchPath']);
return;
}
$volumePath = @readlink("$webDir");
if(empty($volumePath)){
$volumePath = "$webDir";
}
$isSearchDir = createSearchDir($searchPath.$searchItem,$searchDirRemote);
if($isSearchDir === false){
Scheduler::Log( "Search pattern directory not created");
return;
} else if($_SESSION['dedup'] && !empty($isSearchDir) && $isSearchDir!="/"){
removeItems($isSearchDir."/*");
}
$pidPathForSearch = "$searchDirRemote/$pidPath";
$_SESSION['currentRemoteTrashSearchPath'] = $searchDirRemote."/";
session_write_close();
//to get the php error message in customErrorMsg() variable.
ini_set('track_errors', 1);
$pages = "/trash_page1";
if(!($handle = fopen($pidPathForSearch, "w"))){
Scheduler::Log("remote initial Search :: ".customErrorMsg());
return;
}
else{
@chmod($pidPathForSearch,$permissionVal);
fclose($handle);
}
$lastLine = "";
$pageCount = 0;
$flag = 0;
$buffer = "";
$byteRead = 0;
$len = 0;
$toSearchStr = "";
$type = "";
$size = "";
$dateTime = "";
$item = "";
$pattern = "";
$tmpArr = array();
$isNotOpened = 0;
$totalCount = 0;
$searchUtfFile = getOperationFile(SEARCHOP, $searchItem, $searchPath);
@chmod($searchUtfFile,$permissionVal);
if(!file_exists($searchUtfFile)){
Scheduler::Log("remoteinitialSearch :: ".customErrorMsg());
return false;
}
$searchUtfFile = str_replace("'","'\''",$searchUtfFile);
$idevsutilCommandLine = $idevsutilBinaryPath.$whiteSpace.$idevsutilArgument.$assignmentOperator."'$searchUtfFile'";
if(!file_exists($pidPathForSearch)){
$errStr = ERR_STR_VAL;
userCancelremoteInitialSearch($searchDirRemote,$errStr);
return $outputArray;
}
else{
pclose(popen("$idevsutilCommandLine &","r"));
}
while(!customFileSize($OutOutputFilePath) and !customFileSize($OutErrorFilePath)){
if(!file_exists($pidPathForSearch)){
$errStr = ERR_STR_VAL;
userCancelremoteInitialSearch($searchDirRemote, $errStr);
return $outputArray;
}
sleep(0.1);
}
/* update server address if cmd failed due to wrong evs server address. */
if(checkErrorAndUpdateServerAddr($OutErrorFilePath)){
userCancelremoteInitialSearch($searchDirRemote);
return $outputArray;
}
if(!customFileSize($OutOutputFilePath)){
//errorLog("remoteSearch", false);
userCancelremoteInitialSearch($searchDirRemote);
return $outputArray;
}
$handle = fopen($OutOutputFilePath, "r");
if(!$handle) {
$errStr = "not able to open file , $OutOutputFilePath\n";
userCancelremoteInitialSearch($searchDirRemote, $errStr);
return $outputArray;
}
// for empty trash functionality we are writing comple output data only in trash_page1
if($empty_trash)
$searchHandle = fopen("$pagePath/trash_page1", "w");
if(isset($_SESSION['dedup']) && $_SESSION['dedup']){
//Parse output.txt file for search results
while(1){
if(!file_exists($pidPathForSearch)){
fclose($handle);
if($searchHandle){
fclose($searchHandle);
}
$errStr = ERR_STR_VAL;
userCancelremoteInitialSearch($searchDirRemote, $errStr);
return $outputArray;
}
$buffer = fread($handle, LIMIT);
if(0 === strlen($buffer)){
if(customFileSize($OutErrorFilePath)){
$error = file_get_contents($OutErrorFilePath);
$reason = checkErrorAndReason($error);
break;
}
sleep(WAIT_FOR);
fseek($handle, 0, 1); //to clear eof flag
continue;
}
//need to check appending partial record to packet or to first line of packet
if("" != $lastLine){
$buffer = $lastLine.$buffer;
}
if(!preg_match('/\n$/', $buffer)){
$lastNewlinePos = strrpos($buffer, "\n");
$resultList = substr($buffer,0,$lastNewlinePos+1);
$lastLine = substr($buffer,$lastNewlinePos+1);
} else {
$resultList = $buffer;
$lastLine = '';
}
if(preg_match('/items_found/', $resultList))
$flag = 1;
//Scheduler::Log("resultList: \n \n".$resultList);
$noOfLines = substr_count($resultList,"\n");
$resultListXML = "<root>$resultList</root>";
$xml = simplexml_load_string($resultListXML);
if(!$xml){
Scheduler::Log("Not XML: \n \n".$resultListXML);
if($flag == 1)
break;
continue;
}
foreach ($xml->item as $value)
{
//Scheduler::Log("resultList");
if(0 == $isOpened && 0 == $empty_trash)
{
$pageCount++;
if($searchHandle){
fclose($searchHandle);
}
$pageName = "trash_page";
$searchHandle = fopen("$pagePath/$pageName$pageCount", "w");
if(!$searchHandle)
{
Scheduler::Log("search".customErrorMsg());
unlink($pidPathForSearch);
return;
}
$isOpened = 1;
}
if(isset($value['items_found']))
break;
$item = trim($value['fname']);
if($countItem == 0){
$dateTime = trim($value['mod_time']);
$size = trim($value['size']);
$size = humanReadableSize($size);
$type = trim($value['restype']);
if($type == "D")
$pattern = $item;
addListWithType($type, $item, $dateTime, $size);
continue;
}
$retVal = "";
if($pattern){
$retVal = stripos($item, $pattern);
}
if($retVal === 0 && $retVal !== FALSE){
continue;
}
else{
$dateTime = trim($value['mod_time']);
$size = trim($value['size']);
$size = humanReadableSize($size);
$type = trim($value['restype']);
if($type == "D")
$pattern = $item;
addListWithType($type, $item, $dateTime, $size);
}
if(!file_exists($pidPathForSearch)){
fclose($handle);
if($searchHandle){
fclose($searchHandle);
}
$errStr = ERR_STR_VAL;
userCancelremoteInitialSearch($searchDirRemote, $errStr);
return $outputArray;
}
}
if(1 == $flag){
break;
}
}
} else {
//Parse output.txt file for search results
while(1){
if(!file_exists($pidPathForSearch)){
fclose($handle);
if($searchHandle){
fclose($searchHandle);
}
$errStr = ERR_STR_VAL;
userCancelremoteInitialSearch($searchDirRemote, $errStr);
return $outputArray;
}
$buffer = fread($handle, LIMIT);
if(0 === strlen($buffer)){
if(customFileSize($OutErrorFilePath)){
break;
}
sleep(WAIT_FOR);
fseek($handle, 0, 1); //to clear eof flag
continue;
}
//need to check appending partial record to packet or to first line of packet
if("" != $lastLine){
$buffer = $lastLine . $buffer;
}
$resultList = explode("\n", $buffer);
$bufIndex = count($resultList);
$bufIndex -= 1;
//keep last line of buffer only when it not ends with newline.
if(!preg_match('/\n$/', $buffer)){
$lastLine = $resultList[$bufIndex];
}
else{
$lastLine = "";
}
if(0 < $bufIndex and preg_match('/Total files found/', $resultList[$bufIndex-1])){
$flag = 1;
$bufIndex -= 1;
}
$totalCount += $bufIndex;
for($index = 0; $index < $bufIndex; $index++)
{
if(0 == $isOpened && 0 == $empty_trash)
{
$pageCount++;
if($searchHandle){
fclose($searchHandle);
}
$pageName = "trash_page";
$searchHandle = fopen("$pagePath/$pageName$pageCount", "w");
if(!$searchHandle)
{
Scheduler::Log("search ".customErrorMsg());
unlink($pidPathForSearch);
return;
}
$isOpened = 1;
}
$tmpArr = explode("] [", $resultList[$index], 6);
if(count($tmpArr) < 6)
continue;
$tmpArr[count($tmpArr) - 1] = rtrim($tmpArr[count($tmpArr) - 1], "]");
$item = $tmpArr[count($tmpArr) - 1];
if($countItem == 0){
$dateTime = preg_replace("/^\[/", "", $tmpArr[0]); //remove '['
$size = trim($tmpArr[1]);
$size = convertFileSize($size);
$type = trim($tmpArr[2])==0?"D":"F";
if($type == "D")
$pattern = $item;
addListWithType($type, $item, $dateTime, $size);
continue;
}
$retVal = "";
if($pattern){
$retVal = stripos($item, $pattern);
}
if($retVal === 0 && $retVal !== FALSE){
continue;
}
else{
$dateTime = preg_replace("/^\[/", "", $tmpArr[0]);
$size = trim($tmpArr[1]);
$size = convertFileSize($size);
$type = trim($tmpArr[2])==0?"D":"F";
if($type == "D")
$pattern = $item;
addListWithType($type, $item, $dateTime, $size);
}
if(!file_exists($pidPathForSearch)){
fclose($handle);
if($searchHandle){
fclose($searchHandle);
}
$errStr = ERR_STR_VAL;
userCancelremoteInitialSearch($searchDirRemote, $errStr);
return $outputArray;
}
}
if(1 == $flag){
break;
}
}
}
if($searchHandle){
fclose($searchHandle);
}
if($handle){
fclose($handle);
}
// After listing process done removing file(s)/floder(s) permanatly
if($empty_trash){
chdir("$searchDirRemote/");
$outputArray = deleteItems(REMOVE_FROM_TRASHOP,$searchDirRemote."/trash_page1","");
}
userCancelremoteInitialSearch($searchDirRemote);
return $outputArray;
/*
USER_CANCEL:
if(file_exists($pidPathForSearch) && !$empty_trash){
unlink($pidPathForSearch);
}
else{
$searchDirRemote = str_replace("'","'\''",$searchDirRemote);
$searchDirRemote = "'".$searchDirRemote;
shell_exec("rm -rf $searchDirRemote/trash_page'*");
$searchDirRemote = ltrim ($searchDirRemote, "'");
}
$searchUtfFile = str_replace("'\''","'",$searchUtfFile);
if(file_exists($searchUtfFile)){
unlink($searchUtfFile);
}
$isSearchDirError = $searchDirRemote."/".ERROR_FILE;
if(file_exists($isSearchDirError)){
unlink($isSearchDirError);
}
$isSearchDirOutput = $searchDirRemote."/".OUTPUTFILE;
if(file_exists($isSearchDirOutput)){
unlink($isSearchDirOutput);
}
if($empty_trash)
return $outputArray;
*/
}
function userCancelremoteInitialSearch($searchDirRemote, $errStr = '')
{
GLOBAL $pidPathForSearch, $empty_trash, $searchUtfFile;
if($errStr != "")
Scheduler::Log("userCancelremoteInitialSearch Error : $errStr");
if(file_exists($pidPathForSearch) && !$empty_trash){
unlink($pidPathForSearch);
}
else{
$searchDirRemote = str_replace("'","'\''",$searchDirRemote);
$searchDirRemote = "'".$searchDirRemote;
removeItems($searchDirRemote."/trash_page*");
$searchDirRemote = ltrim ($searchDirRemote, "'");
}
$searchUtfFile = str_replace("'\''","'",$searchUtfFile);
if(file_exists($searchUtfFile)){
unlink($searchUtfFile);
}
$isSearchDirError = $searchDirRemote."/".ERROR_FILE;
if(file_exists($isSearchDirError)){
unlink($isSearchDirError);
}
$isSearchDirOutput = $searchDirRemote."/".OUTPUTFILE;
if(file_exists($isSearchDirOutput)){
unlink($isSearchDirOutput);
}
if($empty_trash)
return $outputArray;
}
function emptyTrashSearch()
{
GLOBAL $pidPath;
GLOBAL $searchDirTrashRemote;
$file_chk = $searchDirTrashRemote."/EmptyTrash/".$pidPath;
$filesize = customFileSize($file_chk);
if($filesize > 0){
$myfile = fopen($file_chk, "r");
$fileData = fread($myfile,$filesize);
$fileArrData = json_decode($fileData, true);
$outputArray['DELETEOP'] = $fileArrData['DELETEOP'];
@unlink($file_chk);
};
if(!empty($outputArray['DELETEOP']))
$outputArray['SIZE'] = $filesize;
else
$outputArray['SIZE'] = 0;
return $outputArray;
}
/****************************************************************************************************
* Function Name : killSizeFd
* Objective : To kill the previous requests for calculation folder size, if running on refresh.
* Added By : Yogesh Kumar
*****************************************************************************************************/
function killSizeFd() {
GLOBAL $webDir, $userName;
$cfsrpid = Scheduler::$user_dir.'sizepid.txt';
if (!file_exists($cfsrpid)) {
return;
}
if(isFileLocked($cfsrpid)){
$pid = file_get_contents($cfsrpid);
if (!empty($pid)) {
$cmd = "kill -9 $pid";
systemCmdExecutionViaPhp($cmd, Scheduler::$user_dir);
}
}
unlink($cfsrpid);
}
/****************************************************************************************************
* Function Name : validateRestoreFileDataConstruct
* Objective : Running EVS command to get status of remote files
* Added By : Vijay Vinoth
* Modified By : Senthil Pandian
*****************************************************************************************************/
function validateRestoreFileDataConstruct($tempfile,$jobPath){
GLOBAL $idevsutilBinaryPath;
GLOBAL $whiteSpace;
GLOBAL $idevsutilArgument;
GLOBAL $assignmentOperator;
$utfPath = getOperationFile(FILESTATUSOP,$tempfile,$jobPath);
$idevsutilCommandLine = $idevsutilBinaryPath.$whiteSpace.$idevsutilArgument.$assignmentOperator."\"$utfPath\"";
pclose(popen("$idevsutilCommandLine &","r"));
return $utfPath;
}
/****************************************************************************************************
* Function Name : Check file available in restore page
* Objective : To List initial content in Trash page and this function is using for empty trash process as well.
* Added By : Vijay Vinoth
*****************************************************************************************************/
function loadValidRestoreSetContent($jobPath)
{
$OutOutputFilePath = $jobPath."/operation_".OUTPUTFILE;
$TempFilePath = $jobPath."/".TEMP_OPERATION_FILE;
$UtfFilePath = $jobPath."/operation_".UTF8_FILE;
$ErrorFilePath = $jobPath."/operation_".ERROR_FILE;
session_write_close();
while((!file_exists($OutOutputFilePath) || !customFileSize($OutOutputFilePath)) && (!file_exists($ErrorFilePath) || !customFileSize($ErrorFilePath))){
if(!file_exists($UtfFilePath)){
Scheduler::Log("File not exists: $UtfFilePath, Reason : ".customErrorMsg());
break;
}
sleep(1);
}
$retry =0;
$response = '';
$reload = false;
$handle = fopen($OutOutputFilePath, "r");
if(!$handle)
Scheduler::Log("Could not open file $OutOutputFilePath, Reason : ".customErrorMsg());
else{
$fileData = $fileName = $explode_val = '';
$exit =0;
while(1){
$buffer = fread($handle,customFileSize($OutOutputFilePath));
if(empty($buffer)){
Scheduler::Log("$OutOutputFilePath content is empty");
if($retry==5)
break;
sleep(1);
$retry++;
continue;
}
if(($_SESSION['dedup'] && !preg_match('/<item/',$buffer)) || (!$_SESSION['dedup'] && !preg_match('/bytes received/',$buffer) && !preg_match('/bytes\/sec/',$buffer))){
if(!customFileSize($ErrorFilePath)){
$reload = true;
$response = '&reloadData=1';
}
break;
}
if($_SESSION['dedup']){
$noOfLines = substr_count($buffer,"\n");
$resultListXML = "<root>$buffer</root>";
$xml = simplexml_load_string($resultListXML);
if(!$xml){
Scheduler::Log("Not XML: \n \n".$resultListXML);
continue;
}
foreach ($xml->item as $value)
{
if(!empty($value['status'])){
$fileType = trim($value['status']);
$fileName = trim($value['fname']);
if($fileType == 'No such file or directory'){
if(!$explode_val){
$explode_val = file($jobPath."/".RESTORESETFILEDISPLAY);
}
$key = array_search($fileName, $explode_val);
$type = str_replace("\n", "", $explode_val[$key+1]);
$response .= '&fileTypes[]='.$type;
$response .= '&fileInfos[]=0';
}
else if($fileType == 'file exists'){
$response .= '&fileTypes[]=file';
$response .= '&fileInfos[]=1';
}
else if($fileType == 'directory exists'){
$response .= '&fileTypes[]=folder';
$response .= '&fileInfos[]=1';
}
else if($fileType == 'directory exists in trash'){
$response .= '&fileTypes[]=folder';
$response .= '&fileInfos[]=0';
}
else if($fileType == 'file exists in trash'){
$response .= '&fileTypes[]=file';
$response .= '&fileInfos[]=0';
}
$response .= '&fileSize[]='.trim($exp[$i+2]);
$response .= '&fileLMod[]='.trim($exp[$i+3]);
if($fileName !='')
$response .= '&fileNames[]='.rtrim($fileName,"/");
}
}
}
else {
$ArrVal = explode("\n", $buffer);
$ArrCount = count($ArrVal);
if($ArrCount > 5){
foreach($ArrVal as $index => $availableFileName) {
if(empty($availableFileName) || preg_match('/connection established/',$availableFileName) || preg_match('/receiving file list/',$availableFileName))
continue;
if(preg_match('/bytes received/',$availableFileName) && preg_match('/bytes\/sec/',$availableFileName)){
$exit = 1;
break;
}
if(empty($availableFileName))
continue;
$fileData = explode("] [",$availableFileName);
$fileType = trim(substr($fileData[0], 1));
if($fileType == 'directory exists'){
$fileName = substr($fileData[1], 0,-2);
}
else{
$fileName = substr($fileData[1], 0,-1);
}
if($fileType == 'No such file or directory'){
if(!$explode_val){
$explode_val = file($jobPath."/".RESTORESETFILEDISPLAY);
}
$key = array_search($fileName, $explode_val);
$type = str_replace("\n", "", $explode_val[$key+1]);
$response .= '&fileTypes[]='.$type;
$response .= '&fileInfos[]=0';
}
else if($fileType == 'file exists'){
$response .= '&fileTypes[]=file';
$response .= '&fileInfos[]=1';
}
else if($fileType == 'directory exists'){
$response .= '&fileTypes[]=folder';
$response .= '&fileInfos[]=1';
}
else if($fileType == 'directory exists in trash'){
$response .= '&fileTypes[]=folder';
$response .= '&fileInfos[]=0';
}
else if($fileType == 'file exists in trash'){
$response .= '&fileTypes[]=file';
$response .= '&fileInfos[]=0';
}
$response .= '&fileSize[]='.trim($exp[$i+2]);
$response .= '&fileLMod[]='.trim($exp[$i+3]);
if($fileName !='')
$response .= '&fileNames[]='.rtrim($fileName,"/");
}
}
if($exit == 1){
Scheduler::Log("Completed");
break;
}
}
}
}
if($response == ''){
$jobItemFile = $jobPath."/".RESTORESETFILEDISPLAY;
if(file_exists($jobItemFile) && customFileSize($jobItemFile)){
$exp = file($jobPath."/".RESTORESETFILEDISPLAY);
for($i=0;$i<count($exp)-1;$i+=4){
$response .= '&fileNames[]='.trim($exp[$i]);
$response .= '&fileTypes[]='.str_replace('#','',trim($exp[$i+1]));
$response .= '&fileInfos[]=1';
$response .= '&fileSize[]='.trim($exp[$i+2]);
$response .= '&fileLMod[]='.trim($exp[$i+3]);
$response .= '&reloadData=0';
}
}
}
if((file_exists($ErrorFilePath) && customFileSize($ErrorFilePath)>0)){
$errStr = file_get_contents($ErrorFilePath);
Scheduler::Log("Failed to list remote directories: $errStr");
}
if(!$reload){
@unlink($OutOutputFilePath);
@unlink($TempFilePath);
@unlink($UtfFilePath);
@unlink($ErrorFilePath);
}
return $response;
}
/****************************************************************************************************
* Function Name : checkIfBackupJobRunning
* Objective : find the running manual/scheduled backup job and returns on success
******************************************************************************************************/
function checkIfBackupJobRunning()
{
$jobs = Scheduler::ReadJobs();
$manualJobInProgress = Scheduler::JobInProgress("+ManualTask","Backup");
if($manualJobInProgress)
return 1;
if(!$jobs)
return 0;
foreach($jobs as $key => $value)
{
$jobType = $value["job_type"];
if($jobType == "Backup")
{
$jobName = substr($key,(strlen($jobType)+1));
$jobInProgress = Scheduler::JobInProgress($jobName, $jobType);
if($jobInProgress)
return 1;
}
}
return 0;
}
/****************************************************************************************************
* Function Name : Delete Process
* Objective : Delete the selected files from Restore / Trash page
* Added By : Vijay Vinoth
******************************************************************************************************/
function deleteAction(){
GLOBAL $webDir, $userName, $searchDirRemote;
$itemsForDelete = $itemsForDeleteType = "";
$outputArray = array();
$restoreListFolderPath = Scheduler::$user_dir.".RestoreList";
$outputArray['STATUS'] = BACKUP_JOB_RUNNING;
if(isset($_POST["items"]))
$itemsForDelete = $_POST["items"];
if(isset($_POST["type"]))
$itemsForDeleteType = $_POST["type"];
chdir(Scheduler::$delete_dir);
if(!is_writable(DELETE_SET_FILE))
chmod(DELETE_SET_FILE,0777);
$deleteFileContent = implode("\n",$itemsForDelete);
switch (true) {
case (file_exists($pidPath)):
$outputArray['STATUS'] = DELETE_INPROGRESS;
return $outputArray;
break;
case (checkIfBackupJobRunning()):
return $outputArray;
break;
case (!$itemsForDelete):
$outputArray['STATUS'] = NO_ITEMS_FOR_DELETE;
return $outputArray;
break;
case (!file_put_contents(DELETE_SET_FILE,$deleteFileContent."\n")):
$outputArray['STATUS'] = DELETEOP_FAILED;
return $outputArray;
break;
default:
$OP = DELETEOP;
if(isset($_GET['deleteFromTrash']) && $_GET['deleteFromTrash'])
$OP = REMOVE_FROM_TRASHOP;
$outputArray = deleteItems($OP,DELETE_SET_FILE,$itemsForDeleteType);
$outputArray['STATUS'] = DELETEOP_FAILED;
if($outputArray['DELETEOP']['CONSIDERED'] > 0 and ($outputArray['DELETEOP']['CONSIDERED'] == $outputArray['DELETEOP']['HAPPENED'])){
if($outputArray['DELETEOP']['CONSIDERED'] > 1){
$outputArray['REMOVE_JS_ARRAY'] = 1;
if($OP != REMOVE_FROM_TRASHOP){
if($restoreListFolderPath!='/' && $searchDirRemote!='/')
systemCmdExecution("rm -rf '$restoreListFolderPath' '$searchDirRemote' ");
}
}
else if($outputArray['DELETEOP']['CONSIDERED'] == 1){
$outputArray['REMOVE_JS_ARRAY'] = 0;
$singleItemDelete = $itemsForDelete[0];
$removeFolder = $restoreListFolderPath.$singleItemDelete;
$singleItemDeleteParentFolder = substr($removeFolder, 0, strrpos($removeFolder, "/"));
$listTxt = $singleItemDeleteParentFolder."/list.txt";
if($OP != REMOVE_FROM_TRASHOP && $searchDirRemote!='/' && $removeFolder!='/')
systemCmdExecution("rm -rf '$searchDirRemote' '$removeFolder' '$listTxt' ");
}
$outputArray['STATUS'] = DELETEOP_SUCCESSFUL;
}
return $outputArray;
break;
}
}
/****************************************************************************************************
* Function Name : getRestoreDirList
* Objective : This function will return the directory/files list
* Added By : Senthil Pandian
* Modified By : Sabin Cheruvattil | sqlite3 to PDO
******************************************************************************************************/
function getRestoreDirList($dirName, $hostName, $pageId = 0, $dedupBucket = '')
{
GLOBAL $webDir, $userName;
$dirNameArray = array();
$dedupServerRoot = getServerRootByDeviceID($dedupBucket);
$dbAppPath = getExpressDBPath($hostName, $dedupBucket);
if(!file_exists($dbAppPath)) {
Scheduler::Log("DB not exists: $dbAppPath");
return $dirNameArray;
}
$count = MAX_NUM_OF_ITEMS;
$start = $pageId * $count;
$dirNameNew = str_replace("'", "''", $dedupServerRoot . $dirName);
$db = openDataBase($dbAppPath);
if(!$db) {
return $dirNameArray;
}
$sql = "SELECT NAME,FILE_LMD,DIRID,FILE_SIZE,LEVEL_NO as TYPE from " . IBFOLDER . " WHERE NAME LIKE '''$dirNameNew%''' AND NAME NOT LIKE '''$dirNameNew%/%/''' AND NAME NOT LIKE '''$dirNameNew''' AND NAME NOT LIKE '''//'''
UNION
SELECT NAME,FILE_LMD,DIRID,FILE_SIZE,FILE_OR_FOLDER as TYPE from " . IBFILE . " WHERE DIRID=(select DIRID from " . IBFOLDER . " where NAME='''$dirNameNew''') ORDER BY TYPE,NAME LIMIT $start,$count;";
$ret = $db->prepare($sql);
$ret->execute();
if($ret) {
while($row = $ret->fetch()) {
if($row['TYPE'] == 0) {
$folderName = str_replace($dedupServerRoot . $dirName, '', $row['NAME']);
$folderName = substr($folderName, 1, -1);
$dirNameArray[$folderName]['type'] = 'D';
$dirNameArray[$folderName]['date'] = $row['FILE_LMD'];
$dirNameArray[$folderName]['size'] = '--';
} else {
if($row['NAME'] == "''") {
continue;
}
$folderName = $row['NAME'];
$folderName = substr($folderName, 1, -1);
$dirNameArray[$folderName]['type'] = 'F';
$dirNameArray[$folderName]['date'] = $row['FILE_LMD'];
$dirNameArray[$folderName]['size'] = $row['FILE_SIZE'];
}
}
}
$ret->closeCursor();
unset($db);
return $dirNameArray;
}
/****************************************************************************************************
* Function Name : getRestoreSearchResult
* Objective : This function will return the directory/files list as per search keyword
* Added By : Senthil Pandian
******************************************************************************************************/
/* function getRestoreSearchResult($keyword,$searchPath,$page=1){
GLOBAL $webDir, $userName, $searchSQLite;
$dedupServerRoot = '';
if(isset($_SESSION['serverRoot']) && ($_SESSION['serverRoot'] != ''))
$dedupServerRoot = $_SESSION['serverRoot']."/";
$dbAppPath = "$hostName/$userName/LDBNEW/$dedupServerRoot$userName.ibenc";
if(!file_exists($dbAppPath)) {
$arr[] = false;
return $arr;
}
$db = openDataBase($dbAppPath);
//Getting the folders list based on search keyword
$sql = "select NAME,FILE_LMD from " . IBFOLDER . " where NAME LIKE '%$keyword%' order by NAME asc;"; // LIMIT 100 OFFSET 0
$ret = $db->prepare($sql);
$ret->execute();
$resArray = array();
$count = 0;
//Adding first record to array
$row = $ret->fetch();
if($row) {
$dirName = trim($row['NAME']);
$prevDirName = $dirName;
$resArray[] = array('name' => $dirName, 'size' => '--', 'date' => $row['FILE_LMD'], 'type' => 'D');
$count = 1;
while($row = $ret->fetch()) {
$dirName = trim($row['NAME']);
$retVal = strpos($dirName, $prevDirName);
if(($retVal !== FALSE) and ($retVal == 0)) {
$remainingStr = str_replace($prevDirName, '', $dirName);
if($remainingStr != "") {
$findStr = strpos($remainingStr, $keyword);
if(($findStr !== FALSE) and ($findStr >= 0)){
$prevDirName = $dirName;
$resArray[] = array('name' => $dirName, 'size' => '--', 'date' => $row['FILE_LMD'], 'type' => 'D');
$count++;
}
}
} else {
$prevDirName = $dirName;
$resArray[] = array('name' => $dirName, 'size' => '--', 'date' => $row['FILE_LMD'], 'type' => 'D');
$count++;
}
}
$ret->closeCursor();
// Getting the files list based on search keyword
$sql = "select folder.NAME,file.NAME,file.FILE_LMD,file.FILE_SIZE from ".IBFILE." as file JOIN ".IBFOLDER." as folder ON folder.DIRID=file.DIRID where file.NAME LIKE '%$keyword%';";
$ret = $db->prepare($sql);
$ret->execute();
if($ret) {
while($row = $ret->fetch()) {
$dirName = $row[0].$row[1];
$resArray[] = array('name' => $dirName, 'size' => humanReadableSize($row[3]), 'date' => $row[2], 'type' => 'F');
$count++;
}
}
$ret->closeCursor();
}
# if there are no records found inside ibfolder, we have to close it here
$ret->closeCursor();
unset($db);
if($count > 0) {
$arr = array(true, $count, $resArray);
} else {
$arr = array(false);
}
return $arr;
}
/****************************************************************************************************
* Function Name : getDirDetail
* Objective : This function will return the detail of directory
* Added By : Senthil Pandian
* Modified By : Sabin Cheruvattil | sqlite3 to PDO
******************************************************************************************************/
function getDirDetail($dirName, $devicePath, $dedupBucket)
{
GLOBAL $webDir;
GLOBAL $userName;
GLOBAL $detailsSQLite;
$arrOutput = array(FALSE);
try {
$hostName = getLocalBackupLocation();
if($devicePath == '') {
$devicePath = $hostName;
}
$dbAppPath = getExpressDBPath($devicePath, $dedupBucket);
if(!file_exists($dbAppPath)){
return $arrOutput;
}
$db = openDataBase($dbAppPath);
if(!$db){
return $arrOutput;
}
if($_SESSION['dedup']) {
$dirName = getServerRootByDeviceID($dedupBucket) . $dirName;
}
$dirNameNew = str_replace("'", "''", $dirName);
$sql = "SELECT TOTAL(ibfile.FILE_SIZE), count(*), (select FILE_LMD from ".IBFOLDER." where NAME= '''$dirNameNew/''' ) FROM ".IBFILE." where ibfile.DIRID IN (select ibfolder.DIRID from ".IBFOLDER." where ibfolder.NAME LIKE '''$dirNameNew/%') AND ibfile.FILE_LMD <> '0000/00/00 00:00:00';";
$ret = $db->prepare($sql);
$ret->execute();
$row = $ret->fetch();
if($row && !empty($row) && count($row) > 0) {
$arr = array(humanReadableSize($row[0]), $row[1], $row[2]);
$arrOutput = array(TRUE, $arr);
}
$ret->closeCursor();
unset($db);
} catch(Exception $e) {
Scheduler::Log($e->getMessage());
}
return $arrOutput;
}
/****************************************************************************************************
* Function Name : getUsedSpace
* Objective : This function will return the total used space
* Added By : Senthil Pandian
* Modified By : Sabin Cheruvattil
******************************************************************************************************/
function getUsedSpace($dbAppPath)
{
GLOBAL $quotaSQLite;
$size = -1;
if(file_exists($dbAppPath)) {
$db = openDataBase($dbAppPath);
if(!$db){
Scheduler::Log('Not able to open DB ' . $dbAppPath);
return $size;
}
$sql = 'SELECT TOTAL(FILE_SIZE) FROM ' . IBFILE . ';';
try {
$statement = $db->prepare($sql);
$statement->execute();
$row = $statement->fetch();
$statement->closeCursor();
if($row) {
if(!empty($row) && count($row) > 0) {
$size = humanReadableSize($row[0]);
}
}
} catch(Exception $e) {
Scheduler::Log('Unable to get used space: ' . $e->getMessage());
}
unset($db);
}
return $size;
}
/*********************************************************************************************************
* Function Name : hasNASUserShellPermission
* Objective : This function helps to check NAS user shell permission
* Added By : Sabin Cheruvattil
**********************************************************************************************************/
function hasNASUserShellPermission() {
if(exec('whoami') == "root") {
return TRUE;
}
GLOBAL $permissionVal, $appPath;
$passwds = file('/etc/passwd');
$curNASUser = $_SESSION['nasUserName'];
$configPath = "$appPath/".CONFIG;
foreach($passwds as $passwd) {
$accessPerms = explode(':', $passwd);
if(trim($accessPerms[0]) == $curNASUser) {
if(trim($accessPerms[6]) == '/bin/sh') {
return TRUE;
}
else
return FALSE;
break;
}
}
return TRUE;
}
/*********************************************************************************************************
* Subroutine Name : validateFileList
* Objective : Validate every item of file list
* Added By : Avinash Kumar
* Mofified By : Sabin Cheruvattil - 2016 May 03
* Modification Reason : PL was getting wrong path from the function 'perlScriptExecution'. This change is intented to make multi user login
**********************************************************************************************************/
function validateFileList($filePath, $refreshItem, $jobPath = '')
{
GLOBAL $temp_file, $permissionVal;
$tmpFileContent = VALIDATE_FILELIST . "\n" . $filePath . "\n" . $refreshItem;
file_put_contents($temp_file, $tmpFileContent);
@chmod($temp_file, $permissionVal);
$output = '';
if($jobPath != '') {
$output = phpScriptExecution(OPERATIONSFILE, $jobPath);
} else {
$output = phpScriptExecution(OPERATIONSFILE, dirname($filePath) . '/');
}
return $output;
}
/************************************************************************************************
* Subroutine Name : checkErrorAndUpdateServerAddr.
* Objective : Read error.txt file check for server error if found update server address.
* Added By : Avinash Kumar.
*************************************************************************************************/
function checkErrorAndUpdateServerAddr($evsErrorPath)
{
if(file_exists($evsErrorPath) && customFileSize($evsErrorPath)){
$evsError = file_get_contents($evsErrorPath);
@unlink($evsErrorPath);
$reason = checkErrorAndReason($evsError);
if(FALSE != (strpos($evsError, SERVER_ERROR))){
getServerAddress();
return TRUE;
}
}
return FALSE;
}
/****************************************************************************************************
* Function Name : getLocalBackupLocation
* Objective : This function will return the local backup location
* Added By : Senthil Pandian
* Modified By : Sabin Cheruvattil | Common method for USB/Express Drives
******************************************************************************************************/
function getLocalBackupLocation()
{
GLOBAL $localMPCfile, $permissionVal, $machine;
$hostName = '';
$idriveLocal = "IDriveLocal";
if(file_exists($localMPCfile)){
//$hostName = file_get_contents($localMPCfile);
$deviceArray = json_decode(file_get_contents($localMPCfile), true);
$hostName = trim($deviceArray['hostName']);
} else {
$devicesArr = getMountedDevices();
if(count($devicesArr)>0){
$hostName = "$devicesArr[0]/$idriveLocal";
$path = json_encode(array('hostName'=>$hostName,'deviceID'=>''));
file_put_contents($localMPCfile,$path);
@chmod($localMPCfile, $permissionVal);
}
}
return $hostName;
}
/****************************************************************************************************
* Function Name : openDataBase
* Objective : This function will open DB & return object for connection
* Added By : Senthil Pandian
* Modified By : Sabin Cheruvattil
******************************************************************************************************/
function openDataBase($dbAppPath, $sensitive = TRUE) {
$db = NULL;
try {
$db = new PDO("sqlite:$dbAppPath");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->exec('PRAGMA journal_mode = wal;');
$db->exec('PRAGMA synchronous = 1;');
$db->exec('PRAGMA read_uncommitted = on;');
if($sensitive) {
$db->exec('PRAGMA case_sensitive_like = 1;');
}
} catch(Exception $e) {
Scheduler::Log($e->getMessage());
$db = false;
/* if( (extension_loaded('pdo')) && (extension_loaded('pdo_sqlite')) ){
Scheduler::Log("pdo exist");
if( (function_exists('pdo')) && (function_exists('pdo_sqlite')) ){
Scheduler::Log("function exist");
}
# need to display the user to enable those extensions.
}
else {
Scheduler::Log("pdo not exist");
echo "in else part";
exit();
}
Scheduler::Log("Done..."); */
//echo "Failed To Open DB!";
//exit;
}
return $db;
}
/****************************************************************************************************
* Function Name : Checking ongoing process
* Objective : Checking ongoing process of restor/backup jobs
* Added By : Vijay Vinoth
*****************************************************************************************************/
function listOngoingJobs($mainBackupPath,$mainRestorePath){
GLOBAL $pidPath, $totalEngineBackup, $totalEngineRestore, $isLocalBackup, $isLocalRestore;
$jobs = Scheduler::ReadJobs();
$activeJobs = array();
$directoriesManualDir = array(Scheduler::$backup_dir.Scheduler::$manual_dir,Scheduler::$restore_dir.Scheduler::$manual_dir);
$jobs['Backup_+ManualTask'] = array("job_type" => "Backup");
$jobs['Restore_+ManualTask'] = array("job_type" => "Restore");
$jobs['LocalBackup_+ManualTask'] = array("job_type" => "LocalBackup");
$jobs['LocalRestore_+ManualTask'] = array("job_type" => "LocalRestore");
foreach($jobs as $k=>$job) {
$jobName = substr($k,(strlen($job["job_type"])+1));
$jobPath = Scheduler::$user_dir.$job["job_type"]."/".$jobName;
$pid = $jobPath."/".$pidPath;
$progress_path = $jobPath."/".PROGRESS_FILE;
$progress_start_pid = $jobPath."/".START_PID;
if($job["job_type"] == "Backup")
$totalEngine = $totalEngineBackup;
elseif($job["job_type"] == "LocalBackup")
$totalEngine = $isLocalBackup;
elseif($job["job_type"] == "LocalRestore")
$totalEngine = $isLocalRestore;
else
$totalEngine = $totalEngineRestore;
if(file_exists($pid) || file_exists($progress_path) || file_exists($progress_start_pid)){
$jobDetails = readProgress($jobPath,$job["job_type"],$jobName, $totalEngine);
$activeJobs[] = $jobDetails;
}
if(!file_exists($progress_start_pid)){
for($i = 1; $i<=$totalEngine; $i++)
{
if(file_exists($progress_path."_".$i))
{
$cmd = str_replace(" ", "\\ ", $progress_path)."_*";
removeItems($cmd);
break;
}
}
}
}
@uasort($activeJobs, "cmp");
$jobArray = array("jobArray"=>$activeJobs);
return $jobArray;
}
/****************************************************************************************************
* Function Name : Reading the % of progress complete in job
* Objective :Reading the % of progress complete in job
* Added By : Vijay Vinoth
*****************************************************************************************************/
function readProgress($filePath,$type,$jobName,$totalEngine)
{
GLOBAL $pidPath;
$progress_path = $filePath."/".PROGRESS_FILE;
$progress_pid = $filePath."/".$pidPath;
$progress_start_pid = $filePath."/".START_PID;
$fileTransferData = 0;
$count = 0;
$speedBytes = 0;
$fileDetails = array();
for($i=1;$i<=$totalEngine;$i++)
{
if(file_exists($progress_path."_$i") && customFileSize($progress_path."_$i"))
{
$temp = file_get_contents($progress_path."_$i");
$details = explode("\n",$temp);
$fileTransferData += $details[3];
$speedKbs = $details[4];
$fileDetails[$i] = array("file_name"=>$details[1],"file_size"=>$details[2]);
$speedKbs = substr($speedKbs,0,-4);
$speedDetails = substr(strtolower($details[4]),-4);
if($speedDetails == 'gb/s')
$speedBytes += $speedKbs * 1024 * 1024 * 1024;
else if($speedDetails == 'mb/s')
$speedBytes += $speedKbs * 1024 * 1024;
else
$speedBytes += $speedKbs * 1024;
$count++;
}
}
if($count > 0)
{
//$randData = array_rand($fileDetails);
$randData =0;
session_start();
if(!isset($_SESSION['sessionToDisp']))
$_SESSION['sessionToDisp'] = 0;
if(isset($_SESSION['freq']) && ($_SESSION['freq'] <= 10)) {
$randData = $_SESSION['sessionToDisp'];
$_SESSION['freq'] = $_SESSION['freq'] + 1;
}else {
$_SESSION['freq'] = 1;
$size = count($fileDetails);
if($size > $_SESSION['sessionToDisp'])
$_SESSION['sessionToDisp'] = $_SESSION['sessionToDisp'] + 1;
if($_SESSION['sessionToDisp'] <= $totalEngine)
$_SESSION['sessionToDisp'] = $_SESSION['sessionToDisp'];
else
$_SESSION['sessionToDisp'] = 1;
$randData = $_SESSION['sessionToDisp'];
}
$details[3] = $fileTransferData;
//$details[4] = round($speedBytes/$count);
$details[4] = $speedBytes;
$getFileSize = formatBytes($fileDetails[$randData]['file_size']);
$getTotalSize = formatBytes($details[5]);
if($details[5] == "calculating" || $details[5] == ""){
$details[5] = -1;
$getTotalSize = -1;
}
$getTotalTransfered = formatBytes($details[3]);
$speedBytes = isset($_SESSION["$jobName"]['speedBytes'])?$_SESSION["$jobName"]['speedBytes']:0;
$rateCount = isset($_SESSION["$jobName"]['rateCount'])?$_SESSION["$jobName"]['rateCount']:0;
//$rateCount++;
$rateCount += $count;
$speedBytes += $details[4];
$effectiveSpeed = $speedBytes/$rateCount;
$_SESSION["$jobName"]['speedBytes'] = $speedBytes;
$_SESSION["$jobName"]['rateCount'] = $rateCount;
//calculating remaining time ...
if($effectiveSpeed > 0){
$seconds1 = ($details[5] - $details[3]) / $effectiveSpeed ;
//As discussed we are about to display maximum time as 150 days only. 150*24*60*60 = 12960000
$maxtime = 12960000;
if($seconds1 > $maxtime)
$remainingTime = secs_to_h(abs($maxtime));
else
$remainingTime = secs_to_h(abs($seconds1));
$_SESSION["$jobName"]['seconds1'] = $seconds1;
$_SESSION["$jobName"]['remainingTime'] = $remainingTime;
}
elseif(isset($_SESSION["$jobName"]['remainingTime'])){
$remainingTime = $_SESSION["$jobName"]['remainingTime'];
$seconds1 = $_SESSION["$jobName"]['seconds1'];
}
else
{
$remainingTime = "0 seconds";
$seconds1 = 0;
$_SESSION["$jobName"]['remainingTime'] = $remainingTime;
$_SESSION["$jobName"]['seconds1'] = $seconds1;
}
if($details[0] == "FILE IN SYNC")
$details[0] = "";
$progressDetails = array("jobType"=>$type,"jobName"=>$jobName,"jobPath"=>$filePath,$type."Type"=>$details[0],"fileScanning"=>$fileDetails[$randData]['file_name'],
"transferedRate"=>$getTotalTransfered,"totalSize"=>$getTotalSize,"speed"=>$effectiveSpeed,"remainingTime"=>$remainingTime,
"getFileSize"=>$getFileSize,"timeinSec"=>abs($seconds1),"total"=>$details[5],"transfered"=>$details[3],"startTime"=>$details[6]);
}
else
{
$progressDetails = array("jobType"=>$type,"jobName"=>$jobName,"jobPath"=>$filePath,$type."Type"=>'',"fileScanning"=>null,
"transferedRate"=>0,"totalSize"=>-1,"speed"=>0,"remainingTime"=>"calculating...",
"getFileSize"=>0,"timeinSec"=>0,"total"=>-1,"transfered"=>null,"startTime"=>null);
$_SESSION["$jobName"]['speedBytes'] = 0;
$_SESSION["$jobName"]['rateCount'] = 0;
$_SESSION["$jobName"]['remainingTime'] = "0 seconds";
$_SESSION["$jobName"]['seconds1'] = 0;
}
if(!file_exists($progress_pid) && !file_exists($progress_start_pid))
{
$cmd = "rm -rf ".$progress_path."*";
removeItems($progress_path."*");
#`$cmd`;
}
return $progressDetails;
}
/****************************************************************************************************
* Function Name : formatBytes
* Objective : This function will convert bytes to human readable format.
*****************************************************************************************************/
function formatBytes($size, $precision = 2)
{
$base = log($size, 1024);
$suffixes = array('B', 'KB', 'MB', 'GB', 'T');
$final_base_val = round(pow(1024, $base - floor($base)), $precision);
if(is_nan($final_base_val))
return "0 B";
else
return $final_base_val .' '. $suffixes[floor($base)];
}
/****************************************************************************************************
* Function Name : secs_to_h
* Objective : This function will convert seconds to hour
*****************************************************************************************************/
function secs_to_h($secs)
{
if( $secs == 0 )
return "0 seconds";
$units = array(
"d" => 24*60*60,
"h" => 60*60,
"m" => 60
);
$dateData = 0;
$s = "";
foreach ( $units as $name => $divisor ) {
if ( $quot = intval($secs / $divisor) ) {
if($quot > 99 && $name == 'd')
$dateData = 1;
if(!($dateData == 1 && $name == 'm')){
$s .= "$quot$name";
$s .= (abs($quot) > 1 ? "" : "") . " ";
$secs -= $quot * $divisor;
}
}
}
return $s;
}
/****************************************************************************************************
* Function Name : cmp
* Objective : Compare the start time of two jobs to find the latest one.
*****************************************************************************************************/
function cmp($a, $b)
{
return (int) $a['startTime'] > (int)$b['startTime'];
}
/* End of Progress Module */
/****************************************************************************************************
* Function Name : openFile
* Objective : To create/open the file with proper permissions.
* Added By : Yogesh Kumar
*****************************************************************************************************/
function openFile($filename) {
GLOBAL $permissionVal;
$handle = fopen($filename, 'w');
if ($handle === FALSE) {
Scheduler::Log("Failed to create/open $filename".customErrorMsg());
}
else {
@chmod($filename, $permissionVal);
}
return $handle;
}
function chkJobInProgress($job_name, $job_type){
$jobPath = Scheduler::$user_dir.$job_type."/".$job_name."/";
$startPidfilePath = $jobPath.START_PID;
$pidfilePath = $jobPath.PID_FILE;
$userCancelPath = $jobPath.CANCEL_PATH;
$session_var = '';
if($job_type == 'Backup')
{
$session_var = 'currentBackupJob';
$file_for_display = BACKUPSETFILEDISPLAY;
}
else if($job_type == 'LocalBackup')
{
$session_var = 'currentLocalBackupJob';
$file_for_display = BACKUPSETFILEDISPLAY;
}
else if($job_type == 'LocalRestore')
$session_var = 'currentLocalRestoreJob';
else if($job_type == 'Restore')
{
$session_var = 'currentRestoreJob';
$file_for_display = RESTORESETFILEDISPLAY;
}
if(file_exists($startPidfilePath) && file_exists($pidfilePath) && !file_exists($userCancelPath)){
$returnData = 'running';
} else if(file_exists($startPidfilePath) && !file_exists($pidfilePath) && file_exists($userCancelPath)){
$returnData = 'cancelling';
} else {
if(!empty($session_var)){
$_SESSION[$session_var] = '';
}
if($job_name == "+ManualTask"){
@unlink($jobPath.$file_for_display);
}
$returnData = 'completed';
}
return $returnData;
}
/****************************************************************************************************
* Function Name : checkMcryptDecryptWorks
* Objective : Decrypt NAS password using mcrypt if module exists or using only base64_decode
* Added By : A.K Kamalraj
******************************************************************************************************/
function checkMcryptDecryptWorks($nasPassword,$keyIndex){
GLOBAL $appPath;
$configPath = "$appPath/".CONFIG;
$phpPath = getPhpPath();
$flag = DEFAULT_ENC;
if(!checkModuleExists(array("mcrypt_encrypt","mcrypt_decrypt","mcrypt_create_iv","mcrypt_get_iv_size")))
return CUSTOM_ENC;
list($encPwd,$flag) = encryptNasPassword($nasPassword,$keyIndex,$flag);
$command = "$phpPath $configPath/token.php ".escapeshellarg($encPwd)." $flag $keyIndex";
$decPwd = trim(shell_exec($command));
if($nasPassword != $decPwd)
$flag = CUSTOM_ENC;
return $flag;
}
/****************************************************************************************************
* Function Name : checkModuleExists
* Objective : Checks a php module is loaded in php.ini
* Added By : A.K Kamalraj
******************************************************************************************************/
function checkModuleExists($moduleName=array()){
if(empty($moduleName))
return 0;
$exists = 1;
foreach ($moduleName as $value){
if(!function_exists($value)){
$exists = 0;
break;
}
}
return $exists;
}
/****************************************************************************************************
* Function Name : encryptNasPassword
* Objective : Encrypt NAS password using mcrypt if module exists or using only base64_encode
* Added By : A.K Kamalraj
******************************************************************************************************/
function encryptNasPassword($str,$keyIndex, $flag){
if(!trim($str) || empty($keyIndex))
return array("",$flag);
GLOBAL $staticString;
$keyString = $staticString[$keyIndex];
$encrypted = "";
if($flag == DEFAULT_ENC){
$encrypted = trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $keyString, $str, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))));
}else{
$basePwd = sprintf('%03d',$keyIndex).$keyString.$str;
$encrypted = trim(base64_encode($basePwd));
$flag = CUSTOM_ENC;
}
return array($encrypted,$flag);
}
/****************************************************************************************************
* Function Name : unsetProxySessions
* Objective : This function will remove the Proxy Session variables
* Added By : Senthil Pandian
******************************************************************************************************/
function unsetProxySessions(){
if(isset($_SESSION['proxy_option']))
unset($_SESSION['proxy_option']);
if(isset($_SESSION['ipAddress']))
unset($_SESSION['ipAddress']);
if(isset($_SESSION['port']))
unset($_SESSION['port']);
if(isset($_SESSION['proxyUserName']))
unset($_SESSION['proxyUserName']);
if(isset($_SESSION['proxyPassword']))
unset($_SESSION['proxyPassword']);
if(isset($_SESSION['PROXY']))
unset($_SESSION['PROXY']);
}
/****************************************************************************************************
* Function Name : convertStrToLower
* Objective : Converting array values to lower case.
* Added By : Senthil Pandian
******************************************************************************************************/
function convertStrToLower($convertedNASUserName)
{
for($i=0;$i<count($convertedNASUserName);$i++){
$convertedNASUserName[$i] = strtolower($convertedNASUserName[$i]);
}
return $convertedNASUserName;
}
/****************************************************************************************************
* Function Name : verifyXMLoutput
* Objective : Verify the content whether it is proper XML output or not
* Added By : Senthil Pandian
******************************************************************************************************/
function verifyXMLoutput($xml)
{
$resultListXML = "<root>$xml</root>";
$xml = simplexml_load_string($resultListXML);
if(!$xml)
return false;
else
return $xml;
}
/****************************************************************************************************
* Function Name : getDedupUID
* Objective : constructing the UID for dedup
* Added By : Senthil Pandian
******************************************************************************************************/
function getDedupUID()
{
$ethernet = `/sbin/ifconfig | grep Ethernet | awk '{print $5}' | sed -e 's/://g'`;
$ethernet = trim($ethernet);
if(strpos($ethernet,"\n")>0){
$exp = explode("\n",$ethernet);
$ethernet = $exp[0];
}
return "Linux".$ethernet;
}
/****************************************************************************************************
* Function Name : getDedupDeviceList
* Objective : Getting the dedup devices list
* Added By : Senthil Pandian
******************************************************************************************************/
function getDedupDeviceList()
{
GLOBAL $idevsutilBinaryPath;
GLOBAL $whiteSpace;
GLOBAL $idevsutilArgument;
GLOBAL $assignmentOperator;
GLOBAL $OutErrorFilePath;
GLOBAL $lineFeed;
$errorRedirection = "2>&1";
$listDevicesUtfFile = getOperationFile(LISTDEDUPDEVICESOP);
$idevsutilCommandLine = $idevsutilBinaryPath.$whiteSpace.$idevsutilArgument.$assignmentOperator."\"$listDevicesUtfFile\"".$whiteSpace.$errorRedirection.$lineFeed;
$out = `$idevsutilCommandLine`;
@unlink($listDevicesUtfFile);
$pos = stripos($out, "ERROR");
if($pos !== false)
return array(FALSE,$out);
$xml = verifyXMLoutput($out);
if(!$xml)
return array(FALSE,$out);
$listDevice = array();
$deDupDevicesDetail = array();
foreach ($xml->item as $value){
$deviceID = trim($value['device_id']);
$nickName = trim($value['nick_name']);
$bucket_type = trim($value['bucket_type']);
$bucket_type = trim($value['bucket_type']);
$server_root = trim($value['server_root']);
$listDevice["5c0b".$deviceID."4b5z"][$bucket_type] = $nickName;
$deDupDevicesDetail[] = array('server_root'=>$server_root, 'link'=>$deviceID,'device_id'=>"5c0b".$deviceID."4b5z",'nick_name'=>$nickName, 'os'=>trim($value['os']), 'ip'=>trim($value['ip']), 'bucket_ctime'=>trim($value['bucket_ctime']),'uid'=>trim($value['uid']),'bucket_type'=>($bucket_type));
}
$_SESSION['deviceList'] = $listDevice;
$_SESSION['deDupDevicesDetail'] = $deDupDevicesDetail;
@unlink($OutErrorFilePath);
return array(true);
}
/****************************************************************************************************
* Function Name : deviceIDExists
* Objective : Checking the existing device id is valid or not
* Added By : Senthil Pandian
******************************************************************************************************/
function deviceIDExists()
{
GLOBAL $dedupDetailFile, $hostName, $mpc, $permissionVal, $dedupRestoreDeviceID;
$deviceIDExists = false;
if(file_exists($dedupDetailFile)){
$deviceJSON = file_get_contents($dedupDetailFile);
$deviceArray = json_decode($deviceJSON, true);
$deviceID = trim($deviceArray['deviceID']);
if(empty($deviceID)){
$deviceIDExists = false;
} else if(isset($_SESSION['deviceList']) && array_key_exists($deviceID, $_SESSION['deviceList'])){
$deviceIDExists = true;
$_SESSION['deviceID'] = $deviceID;
$_SESSION['nickName'] = $_SESSION['deviceList'][$deviceID]['D'];
//if($hostName != $_SESSION['nickName']){
if($hostName == ""){
$hostName = $_SESSION['nickName'];
file_put_contents($mpc,$hostName);
@chmod($mpc, $permissionVal);
return $deviceIDExists;
}
else if($hostName != $_SESSION['nickName']){
$_SESSION['nickName'] = $hostName;
}
}
}
if($deviceIDExists == false && isset($_SESSION['deDupDevicesDetail'])) {
$uid = getDedupUID();
foreach($_SESSION['deDupDevicesDetail'] as $value){
if($value['uid']==$uid) {
$deviceIDExists = true;
$_SESSION['serverRoot'] = $value['server_root'];
$_SESSION['deviceID'] = $value['device_id'];
$_SESSION['nickName'] = $value['nick_name'];
$hostName = $_SESSION['nickName'];
$dedupDetail = json_encode(array('serverRoot'=>$value['server_root'],'deviceID'=>$value['device_id'], 'nick_name' => $value['nick_name']));
file_put_contents($dedupDetailFile,$dedupDetail);
@chmod($dedupDetailFile, $permissionVal);
file_put_contents($dedupRestoreDeviceID, $value['device_id']);
@chmod($dedupRestoreDeviceID, $permissionVal);
file_put_contents($mpc,$hostName);
@chmod($mpc, $permissionVal);
break;
}
}
}
return $deviceIDExists;
}
/****************************************************************************************************
* Function Name : bucketOperation
* Objective : Creating the bucket, Link bucket & update nick-name
* Added By : Senthil Pandian
******************************************************************************************************/
function bucketOperation($operation,$nickName='',$deviceID='')
{
GLOBAL $idevsutilBinaryPath;
GLOBAL $whiteSpace;
GLOBAL $idevsutilArgument;
GLOBAL $assignmentOperator;
GLOBAL $OutErrorFilePath;
GLOBAL $lineFeed;
$errorRedirection = "2>&1";
$listDevicesUtfFile = getOperationFile($operation,$nickName,$deviceID);
$idevsutilCommandLine = $idevsutilBinaryPath.$whiteSpace.$idevsutilArgument.$assignmentOperator."\"$listDevicesUtfFile\"".$whiteSpace.$errorRedirection.$lineFeed;
$out = `$idevsutilCommandLine`;
@unlink($listDevicesUtfFile);
$pos = strpos($out, "ERROR");
if($pos !== false){
$reason = checkErrorAndReason($out);
if(strpos($reason, "encryption verification failed") !== false){
exit(header("Location: ./logout.php"));
}
return array(FALSE,$reason);
}
$xml = verifyXMLoutput($out);
if(!$xml)
return array(FALSE,$out);
$listDevice = array();
if($xml->item){
$value = $xml->item;
if($value['status']=='success'){
$deviceID = trim($value['device_id']);
$nickName = trim($value['nick_name']);
$serverRoot = trim($value['server_root']);
$_SESSION['deviceID'] = "5c0b".$deviceID."4b5z";
$_SESSION['nickName'] = $nickName;
$_SESSION['serverRoot'] = $serverRoot;
} else {
return array(FALSE,$value['status']);
}
}
@unlink($OutErrorFilePath);
return array(true);
}
/****************************************************************************************************
* 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 = Scheduler::$user_dir."ACCOUNT_SETTINGS_FILE";
if((stristr($error,"encryption verification failed") && file_exists($accountSettingPath)) || stristr($error,"password mismatch")){
if($_GET['action'] != 'validateEncryption')
session_destroy();
}
if($_SESSION['dedup'] && (stristr($error,"failed to get the device information")) || stristr($error,"password mismatch")){
@unlink($dedupDetailFile);
}
break;
}
}
return $error;
}
/****************************************************************************************************
* Function Name : clearPidsAndCancelJob
* Objective : This function will call the the functions to clear pid/start pid & cancelJob
* Added By : Senthil Pandian
******************************************************************************************************/
function clearPidsAndCancelJob(){
GLOBAL $searchDirTrashRemote;
$clearStartPidJobArray = array(Scheduler::$backup_dir,Scheduler::$restore_dir,Scheduler::$localbackup_dir,Scheduler::$localrestore_dir,$searchDirTrashRemote);
clearStartPid($clearStartPidJobArray);
$clearPidJobArray = array(Scheduler::$archiveclean_dir,Scheduler::$delete_dir);
clearPid($clearPidJobArray);
$cancelJobArray = array(Scheduler::$backup_dir,Scheduler::$restore_dir,Scheduler::$localbackup_dir,Scheduler::$localrestore_dir);
cancelJobAfterTerminate($cancelJobArray);
}
/****************************************************************************************************
* Function Name : validateServerAddreValue
* Objective : This function will validate the server address session value & display error message if it is empty
* Added By : Anil
******************************************************************************************************/
function validateServerAddreValue()
{
if($_SESSION['serverAddr'] == "")
{
$error_message = '<div class="popup_container" style ="position:absolute; z-index: 1000;left:50px;right:50px;top:50%;">
<section class="popup_header">
<h4>Error</h4>
<a href ="logout.php" ><span class="popup_close_btn hide_popup" ></span></a>
</section>
<span class="nas_warning">'.SERVER_ADDR_MISSING.'</span>
</div>
</div>';
echo $error_message;
}
}
/****************************************************************************************************
* Function Name : getLocalRestoreSearchList
* Objective : This function will return the directory/files list
* Added By : Vijay Vinoth
* Modified By : Sabin Cheruvattil | sqlite3 to PDO
******************************************************************************************************/
function getLocalRestoreSearchList($searchStr, $searchPath, $pageId = 0, $dedupBucket, $deviceID)
{
GLOBAL $userName;
$dirNameArray = array();
$hostName = getLocalBackupLocation();
$dbAppPath = getExpressDBPath($deviceID, $dedupBucket);
if(!file_exists($dbAppPath)) {
Scheduler::Log("DB not exists: $dbAppPath");
return $dirNameArray;
}
$count = MAX_NUM_OF_ITEMS;
$start = $pageId * $count;
$searchStr = str_replace("'", "''", $searchStr);
$searchPath = str_replace("'", "''", $searchPath);
$db = openDataBase($dbAppPath, FALSE);
if(!$db){
return $dirNameArray;
}
$sql = "SELECT
fldr.NAME as fdrName, file.NAME as fileName, file.FILE_SIZE, file.FILE_LMD
from
" . IBFOLDER . " fldr
JOIN
" . IBFILE . " file ON
fldr.DIRID = file.DIRID
where
(fldr.NAME LIKE '''%$searchStr%''' OR file.NAME LIKE '''%$searchStr%''')
AND fldr.NAME IN (select NAME from " . IBFOLDER . " where NAME like '''%$searchPath%''')
AND file.FILE_SIZE != ''
LIMIT
$start, $count;";
$ret = $db->prepare($sql);
$ret->execute();
$i = 0;
if($ret) {
$dedupReplaceReq = FALSE;
if($_SESSION['dedup'] && isset($_SESSION['serverRoot']) && $_SESSION['serverRoot'] != '') {
$dedupReplaceReq = TRUE;
}
while($row = $ret->fetch()) {
$fileName = trim($row['fdrName'], "'").trim($row['fileName'], "'");
if($dedupReplaceReq) {
$fileName = str_replace($_SESSION['serverRoot'], '', $fileName);
if($dedupBucket != '') {
$fileName = str_replace(getServerRootByDeviceID($dedupBucket), '', $fileName);
}
}
$dirNameArray[$fileName]['type'] = 'F';
$dirNameArray[$fileName]['name'] = $fileName;
$dirNameArray[$fileName]['date'] = $row['FILE_LMD'];
$dirNameArray[$fileName]['size'] = humanReadableSize($row['FILE_SIZE']);
$i++;
}
}
$ret->closeCursor();
unset($db);
$retry = false;
if($i > 0) {
$retry = true;
}
$result['retry'] = $retry;
$result['count'] = $i;
$result['data'] = $dirNameArray;
return $result;
}
#****************************************************************************************************************************
# Subroutine Name : checkAndConstructXML
# Objective : This subroutine is for xml parsing
# Added By : Senthil Pandian
# Modified By :
#*****************************************************************************************************************************
function checkAndConstructXML($resultListXML){
GLOBAL $lastLine;
$resultListXML = trim($resultListXML);
$exp = explode("\n",$resultListXML);
$xml = '';
foreach($exp as $data){
if(!empty($data) && strpos($data,"<item")===false && strpos($data,"size=")===false){
#traceLog("Not a XML: $data");
if(!strrpos($data, ">")){
$lastLine = $data.$lastLine; // Sometime partial data having "\n"
#traceLog("lastLine: $lastLine");
}
continue;
}
$itemPos = strpos($data,"<item");
$newXML = substr($data,$itemPos);
$checkXML = "<root>$newXML</root>";
$checkXML = simplexml_load_string($checkXML);
if(!$checkXML){
$newXML = utf8_encode($newXML);
$checkXML = "<root>$newXML</root>";
$checkXML = simplexml_load_string($checkXML);
if(!$checkXML){
continue;
}
}
$xml .= $newXML;
}
return $xml;
}
/****************************************************************************************************
* Function Name : cgiCallForStat
* Objective : Call CGI to update stat of app usage.
* Added By : Anil Kumar
******************************************************************************************************/
function cgiCallForStat($uname,$pwd,$enabled,$machine,$version)
{
$uname = rawurlencode($uname);
$pwd = rawurlencode(base64_decode($pwd));
$devName = rawurlencode(trim(shell_exec("hostname"),"\n"));
$device_id = getDedupUID();
$os = rawurlencode(trim($machine)." ".trim(`uname -s`,"\n"));
$cgiURLData = "username=$uname&password=$pwd&device_name=$devName&device_id=$device_id&enabled=$enabled&os=$os&version=$version";
$OutputArr = getCurlOutput(getHash("04"), $cgiURLData);
if($OutputArr['output'] == "Success"){
//Scheduler::Log("Stat Update CGI: "." Output: ".$OutputArr['output']. " Error: ".$OutputArr['error']);
return "Success";
}
else{
Scheduler::Log("Stat Update CGI: "." Output: ".$OutputArr['output']. " Error: ".$OutputArr['error']);
return "Failure";
}
}
/****************************************************************************************************
* Function Name : executeInstallationScript
* Objective : Call to parse the data for the CGI to execute installation script
* Added By : Anil Kumar
******************************************************************************************************/
function executeInstallationScript()
{
GLOBAL $userName,$appPath,$appVersion,$machine,$webDir, $nasUserName;
//$checkClientInfo = "$appPath/".CONFIG."/".CLIENT_INFO;
$checkClientInfo = "$webDir/".SERVICE."/".CACHE."/".CLIENT_INFO;
$contentsArr = file($checkClientInfo);
if(count($contentsArr) > 0){
if(trim($contentsArr[0],"\n") != trim(str_replace("Version","",$appVersion))){
unlink($checkClientInfo);
unset($contentsArr);
}
}
$file = fopen($checkClientInfo, "a+");
if ($file)
{
$status = false;
if(count($contentsArr) == 0){
@chmod($checkClientInfo, 0777);
fwrite($file, trim(str_replace("Version","",$appVersion))."\n");
}
$test = $nasUserName."/".$userName."/\n";
$enabled = 1;
foreach ($contentsArr as $user) {
if (strpos($user, $test) !== false) {
$enabled = 0;
}
}
if($enabled){
$version = trim(str_replace("Version","",$appVersion));
$Output = cgiCallForStat($userName,$_SESSION['password'],$enabled,$machine,$version);
if($Output == "Success")
{
$userInfo = $nasUserName."/".trim($userName)."/";
fwrite($file, $userInfo."\n");
}
}
}
fclose($file);
}
/****************************************************************************************************
* Function Name : getIDriveUsernameList
* Objective : This function will get & return IDrive Username list associated with EmailAddress
* Added By : Senthil Pandian
******************************************************************************************************/
function getIDriveUsernameList($userName)
{
$userListArray = array();
if(!strstr($userName,'@') || (isset($_SESSION['multiUser']) && $_SESSION['multiUser'])){
$_SESSION['multiUser'] = false;
return $userListArray;
}
$data = "email=".rawurlencode($userName);
$userOutputArr = getCurlOutput(getHash("03"), $data);
if($userOutputArr['status']===false){
Scheduler::Log("Username List CGI: "." Output: ".$userOutputArr['output']. " Error: ".$userOutputArr['error']);
return $userListArray;
}
$validOutput = trim($userOutputArr['output']);
if((!empty($validOutput) && ($validOutput != "")) && (strpos($validOutput, "Not found") === false)){
$_SESSION['multiUser'] = true;
$userList = explode(" ",$validOutput);
foreach($userList as $userval){
if($userval != ""){
$userArray = explode(":",$userval);
if($userArray[1] != "Cancel")
array_push($userListArray, $userArray[0]);
}
}
}
return $userListArray;
}
/*********************************************************************************************************
* Subroutine Name : getPropertiesForResComp
* Objective : Gets properties of a file. Returns TRUE on Success and FALSE on failure
* Added By : Anil Kumar
**********************************************************************************************************/
function getPropertiesForResComp($input)
{
$xml = getPropertiesResult($input);
$arr = array();
foreach ($xml->item as $value){
if(isset($value['mod_time'])){
$arr[1] = trim($value['mod_time']);
} else if(isset($value['size'])) {
$size = explode(' ',trim($value['size']));
$arr[0] = $size[0];
}
}
$arrOutput = array(TRUE, $arr);
return $arrOutput;
}
function getPropertiesResult($input)
{
GLOBAL $idevsutilBinaryPath;
GLOBAL $whiteSpace;
GLOBAL $idevsutilArgument;
GLOBAL $assignmentOperator;
GLOBAL $OutErrorFilePath;
$propertiesUtfFile = getOperationFile(PROPERTIESOP, $input);
$idevsutilCommandLine = $idevsutilBinaryPath.$whiteSpace.$idevsutilArgument.$assignmentOperator."\"$propertiesUtfFile\"";
$out = `$idevsutilCommandLine`;
unlink($propertiesUtfFile);
/* update server address if cmd failed due to wrong evs server address. */
checkErrorAndUpdateServerAddr($OutErrorFilePath);
$pos = strpos($out, "ERROR");
if(0 < customFileSize($OutErrorFilePath) || $pos !== false){
$out = (0 < customFileSize($OutErrorFilePath))?file_get_contents($OutErrorFilePath):$out;
$reason = checkErrorAndReason($out);
return $arrOutput = array(FALSE,$reason);
}
unlink($OutErrorFilePath);
$xml = verifyXMLoutput($out);
if(!$xml)
return array(FALSE);
return $xml;
}
/****************************************************************************************************
* Function Name : moveUserToNASDir
* Objective : This method is used to move the the existing users data to appr. NAS user dir.
* Added By : Anil Kumar (As we are doing migration at the time of installation, we are not using this process.)
******************************************************************************************************/
function moveUserToNASDir($nasUserName,$userName)
{
$userProfilePath = Scheduler::$service_dir.USER_PROFILE."/";
$sizeFilePath = $userProfilePath.$userName."/".SIZEOUTPUT;
if(file_exists($sizeFilePath))
{
$cmd = "ls -al $sizeFilePath";
$commandToGetOwn = shell_exec($cmd);
$commandToGetOwn = trim($commandToGetOwn,"\n");
$parseDetails = preg_split('/\s+/', $commandToGetOwn,8);
$fileOwner = $parseDetails[2];
if(($fileOwner == "") or ($nasUserName == $fileOwner)){
$move_cmd = "mv -f '".$userProfilePath.$userName."' '".$userProfilePath.$nasUserName."'/";
systemCmdExecution($move_cmd);
// new update added here to client info for backward compatibility
$checkClientInfo = Scheduler::$service_dir ."/".CACHE."/".CLIENT_INFO;
$contentsArr = file($checkClientInfo);
$str=file_get_contents($checkClientInfo);
for($i = 1; $i < count($contentsArr); $i++)
{
if(trim($contentsArr[$i],"\n") == trim($userName,"\n"))
{
$userInfo = trim($nasUserName,"\n")."/".trim($userName,"\n")."/";
$str=str_replace(trim($userName,"/")."\n", $userInfo ,$str);
file_put_contents($checkClientInfo, $str);
}
}
}
}
else{
$move_cmd = "mv -f '".$userProfilePath.$userName."' '".$userProfilePath.$nasUserName."'/";
systemCmdExecution($move_cmd);
$checkClientInfo = Scheduler::$service_dir .CACHE."/".CLIENT_INFO;
$contentsArr = file($checkClientInfo);
$str=file_get_contents($checkClientInfo);
for($i = 1; $i < count($contentsArr); $i++)
{
if(trim($contentsArr[$i],"\n") == trim($userName,"\n"))
{
$userInfo = trim($nasUserName,"\n")."/".trim($userName,"\n")."/";
$str=str_replace(trim($userName,"/")."\n", $userInfo ,$str);
file_put_contents($checkClientInfo, $str);
}
}
}
}
/****************************************************************************************************
* Function Name : updateJobSetFiles
* Objective : This method is used to update restore sets values
* Added By : Anil Kumar
******************************************************************************************************/
function updateJobSetFiles($oldPath,$newPath,$jobType)
{
$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($jobType == "Backup")
{
list($fileSize, $fileLmodTime) = getSizeAndModTime($fileName,$jobType);
}
else if($jobType == "Restore")
{
list($fileSize, $fileLmodTime) = getSizeAndModTime($fileName,$jobType);
}
//($size, $modTime) = function();
}
else if($itemType == "folder")
{
$fileSize = "undefined";
$fileLmodTime = "undefined";
}
$dataToWrite = $fileName."\n".$itemType."\n".$fileSize."\n".$fileLmodTime."\n";
fwrite($newFile, $dataToWrite);
}
fclose($newFile);
@unlink($oldPath);
}
function getSizeAndModTime($fileName,$jobType)
{
$fileSize = $fileLmodTime = "";
if($jobType == "Backup")
{
// backup
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);
if ($_SESSION['haslsdatetimeformat'] == 0)
$command = ('ls -aln ' . escapeshellarg($fullPath) . ' --time-style=\"+%a %b %e %H:%M:%S %Y\"');
else
$command = ('ls -alen ' . escapeshellarg($fullPath));
$file_size_cal = systemCmdExecution($command);
$parseDetails = preg_split('/\s+/', $file_size_cal,11);
$fileSize = $parseDetails[4];
$fileLmodTime = $parseDetails[5]." ".$parseDetails[6]." ".$parseDetails[7]." ".$parseDetails[8]." ".$parseDetails[9];
}
}
else if($jobType == "Restore")
{
// Restore
$itemName = phpRealEscapeString($fileName);
$arr = getPropertiesForResComp($itemName);
$fileSize = $arr[1][0];
$moddate=date_create($arr[1][1]);
$fileLmodTime = date_format($moddate,"D M j H:i:s Y");
}
return array($fileSize, $fileLmodTime);
}
/****************************************************************************************************
* Function Name : readConfigureFile
* Objective : Call to read and parse the configure file
* Added By : Anil Kumar
******************************************************************************************************/
function readConfigureFile($configPath = "")
{
GLOBAL $machine;
$file = NULL;
if(empty($configPath))
$configPath = dirname(dirname(__FILE__))."/".CONFIG."/".CONFIG_FILE;
if (file_exists($configPath)){
$file = fopen($configPath ,"r");
$hash = array();
while(! feof($file)) {
$line = fgets($file);
$pair = preg_split ('/\s+/',$line,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;
}
/****************************************************************************************************
* Function Name : getTotalCountOfJobs
* Objective : get total no.of backup jobs
* Added By : Vijay Vinoth
******************************************************************************************************/
function getTotalCountOfJobs()
{
GLOBAL $webDir,$userName;
#$popUpPathTo = "$webDir/".SERVICE."/".USER_PROFILE."/$userName/".POP_UP_LIST_FILE;
$popUpPathTo = Scheduler::$user_dir.POP_UP_LIST_FILE;
$popUpPathToArrayVal = json_decode(file_get_contents($popUpPathTo),true);
$backupJobsCount = count(preg_grep("/Backup_/",array_keys($popUpPathToArrayVal)));
return $backupJobsCount;
}
/****************************************************************************************************
* Function Name : str_replace_first
* Objective : replace only the first match of the given string
* Added By : Vijay Vinoth
******************************************************************************************************/
function str_replace_first($from, $to, $content)
{
$from = '/'.preg_quote($from, '/').'/';
return preg_replace($from, $to, $content, 1);
}
/****************************************************************************************************
* Function Name : percentQuotaUsed
* Objective : Update percent Quota Used session value
* Added By : Vijay Vinoth
******************************************************************************************************/
function percentQuotaUsed($usedquota,$totalquota){
if(is_numeric($usedquota)){
$percentQuotaUsed = ($usedquota/$totalquota) * 100;
if($percentQuotaUsed > 100){
$percentQuotaUsed = 100;
}
$percentQuotaUsed = number_format((float)$percentQuotaUsed, 1, '.', '');
$_SESSION['percentQuotaUsed'] = empty($percentQuotaUsed)?'0':$percentQuotaUsed;
}
}
/****************************************************************************************************
* Function Name : updateServerAddress
* Objective : This is to update server address in account settings file to resolve auth module failed issue.
* Added By : Anil Kumar
******************************************************************************************************/
function updateServerAddress()
{
GLOBAL $linesAccountSettingsFile, $userDir, $permissionVal;
$accountSettingPath = Scheduler::$user_dir."ACCOUNT_SETTINGS_FILE";
if(file_exists($accountSettingPath)) {
$linesAccountSettingsFileData = json_decode(file_get_contents($accountSettingPath),TRUE);
if($_SESSION['serverAddr'] != "" && ($_SESSION['serverAddr'] != $linesAccountSettingsFileData['serverAddr'] )) {
$linesAccountSettingsFileData['serverAddr'] = $_SESSION['serverAddr'];
if(($file = fopen($accountSettingPath, "a+")) != FALSE)
{
ftruncate($file, 0);
fwrite($file, json_encode($linesAccountSettingsFileData,TRUE));
fclose($file);
@chmod($accountSettingPath, $permissionVal);
}
}
}
return 0;
}
/****************************************************************************************************
* Function Name : updateAccountStatus
* Objective : This is to update about user account status
* Added By : Anil Kumar
******************************************************************************************************/
function updateAccountStatus($val)
{
GLOBAL $idriveUserDirectory, $permissionVal;
$accountSettingPath = $idriveUserDirectory."/ACCOUNT_SETTINGS_FILE";
if(file_exists($accountSettingPath)) {
$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 updateEncType()
{
GLOBAL $linesAccountSettingsFile, $userDir, $permissionVal;
$accountSettingPath = Scheduler::$user_dir."ACCOUNT_SETTINGS_FILE";
if(file_exists($accountSettingPath)) {
$linesAccountSettingsFileData = json_decode(file_get_contents($accountSettingPath),TRUE);
if(isset($_SESSION['encType']) && $_SESSION['encType'] != "" && ($_SESSION['encType'] != $linesAccountSettingsFileData['encType'] )) {
$linesAccountSettingsFileData['encType'] = $_SESSION['encType'];
if(($file = fopen($accountSettingPath, "a+")) != FALSE)
{
ftruncate($file, 0);
fwrite($file, json_encode($linesAccountSettingsFileData,TRUE));
fclose($file);
@chmod($accountSettingPath, $permissionVal);
}
}
}
return 0;
}
// need to uncomment
/****************************************************************************************************
* 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)) {
$handle = fopen($logpidFile,'r+');
if(flock($handle, LOCK_EX|LOCK_NB))
{
$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, 'deleted') !== false)){
$data = explode(":", $line);
$success = $data[1];
trim($success);
} 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){
$statusToUpdate = "SUCCESS";
}
}
# need to change the status.
$newName = "$buffer"."_".$statusToUpdate;
$resCmd = "mv \"$buffer\" \"$newName\"";
$res = `$resCmd`;
}
}
}
}
function create1kSetForArchiveCleanUp($resultList)
{
GLOBAL $selected_backupset, $permissionVal;
# need to splite input file to generate 1000 set in each .
$lines=1000;
$i=0;
$j=1;
$buffer='';
$tempList = Scheduler::$archiveclean_dir.$selected_backupset."/temp/";
if( !is_dir($tempList) ) {
if( !mkdir($tempList, $permissionVal) ) {
Scheduler::Log("Could not create directory $tempList, Reason : ".customErrorMsg());
return 0;
}
@chmod($tempList, $permissionVal);
}
$handle = fopen ($resultList, "r");
while (!feof ($handle)) {
$buffer .= fgets($handle, 4096);
$i++;
if (($i >= $lines) || (feof ($handle) && ($buffer != "") )) {
$fname = $tempList.$j.".txt";
if (!$fhandle = fopen($fname, 'w')) {
Scheduler::Log("Cannot open file: ".$fname);
exit;
}
if (!fwrite($fhandle, $buffer)) {
Scheduler::Log("Cannot write to file: ".$fname);
exit;
}
fclose($fhandle);
$j++;
$buffer='';
$i=0;
$line+=1000;
}
}
fclose ($handle);
return ($j - 1);
}
function getFailedItemList($archiveHash, &$noOfFiles)
{
GLOBAL $selected_backupset, $permissionVal, $OutErrorFilePath;
$tempList = Scheduler::$archiveclean_dir.$selected_backupset."/temp/";
$errorList = Scheduler::$archiveclean_dir.$selected_backupset."/error/";
$buffer = "";
foreach($archiveHash as $item => $key)
{
if($key == 0){
$buffer .= $item."\n";
}
}
if($buffer != "") {
$noOfFiles++;
# creating result file
$fname = $tempList."result".$noOfFiles.".txt";
if (!$fhandle = fopen($fname, 'w')) {
echo "Cannot open file ($fname)";
exit;
}
if (!fwrite($fhandle, $buffer)) {
echo "Cannot write to file ($fname)";
exit;
}
chmod($fname, $permissionVal);
fclose($fhandle);
# creating error file
$newErrorFile = $errorList."error".$noOfFiles.".txt";
$copyCMD = "cp -fp \"$OutErrorFilePath\" \"$newErrorFile\"";
`$copyCMD`;
}
}
function getHash($index){
$hashValDec = json_decode(simple_decrypt("true"), true);
return $hashValDec[$index];
}
function resetLoglistXml(){
$logListXmlsDir = Scheduler::$user_dir.LOGLISTXMLS."/";
if(file_exists($logListXmlsDir))
removeItems($logListXmlsDir);
}
/****************************************************************************************************
* Function Name : updateAccountStatus
* Objective : This is to update about user account status
* Added By : Anil Kumar
******************************************************************************************************/
function updateHostName()
{
GLOBAL $idriveUserDirectory, $permissionVal;
$accountSettingPath = $idriveUserDirectory."/ACCOUNT_SETTINGS_FILE";
if(file_exists($accountSettingPath)) {
$linesAccountSettingsFileData = json_decode(file_get_contents($accountSettingPath),TRUE);
$linesAccountSettingsFileData['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;
}
?>