예제 #1
0
 private function CheckCDN()
 {
     $this->Log('{lightblue}Checking CDN subdomains');
     $Questions = ['cdn.level3.cs.steampowered.com', 'cdn.akamai.cs.steampowered.com', 'cdn.highwinds.cs.steampowered.com'];
     $Response = [];
     for ($i = 1; $i < 11; $i++) {
         $Questions[] = 'content' . $i . '.steampowered.com';
     }
     foreach ($Questions as $Question) {
         Exec('dig +short ' . EscapeShellArg($Question), $Answer);
         $Answer = Array_Shift($Answer);
         $Answer = RTrim($Answer, '.');
         $Response[$Question] = $Answer;
     }
     File_Put_Contents(__DIR__ . '/Random/CDNs.json', JSON_Encode($Response, JSON_PRETTY_PRINT));
 }
예제 #2
0
}
#-------------------------------------------------------------------------------
$MYSQL_BIN = @$_ENV['MYSQL_BIN'];
#-------------------------------------------------------------------------------
if ($MYSQL_BIN) {
    echo SPrintF("Use mysql in (%s)\n", $MYSQL_BIN);
} else {
    $MYSQL_BIN = 'c:\\Program Files\\MySQL\\MySQL Server 5.1\\bin\\mysql.exe';
}
#-------------------------------------------------------------------------------
foreach (array('structure', 'views', 'permissions', 'triggers', 'functions', 'db') as $File) {
    #-----------------------------------------------------------------------------
    $Path = SPrintF('./../../db/%s/%s.sql', $jHost, $File);
    #-----------------------------------------------------------------------------
    if (File_Exists($Path)) {
        #---------------------------------------------------------------------------
        echo SPrintF("Install %s\n", $File);
        #---------------------------------------------------------------------------
        $MySQL = SPrintF('%s -u %s --password=%s --host=%s --port=%u %s', $MYSQL_BIN, $dUser, $dPassword, $dServer, $dPort, $dName);
        #---------------------------------------------------------------------------
        $Result = Exec(SPrintF('%s < %s 2>&1', $MySQL, $Path));
        #---------------------------------------------------------------------------
        if ($Result) {
            #-------------------------------------------------------------------------
            echo SPrintF("%s\n", $Result);
            #-------------------------------------------------------------------------
            exit("Error\n");
        }
    }
}
#-------------------------------------------------------------------------------
예제 #3
0
function unzip_file($zipfile, $destination = '', $showstatus = true)
{
    //Unzip one zip file to a destination dir
    //Both parameters must be FULL paths
    //If destination isn't specified, it will be the
    //SAME directory where the zip file resides.
    global $CFG;
    //Extract everything from zipfile
    $path_parts = pathinfo(cleardoubleslashes($zipfile));
    $zippath = $path_parts["dirname"];
    //The path of the zip file
    $zipfilename = $path_parts["basename"];
    //The name of the zip file
    $extension = $path_parts["extension"];
    //The extension of the file
    //If no file, error
    if (empty($zipfilename)) {
        return false;
    }
    //If no extension, error
    if (empty($extension)) {
        return false;
    }
    //Clear $zipfile
    $zipfile = cleardoubleslashes($zipfile);
    //Check zipfile exists
    if (!file_exists($zipfile)) {
        return false;
    }
    //If no destination, passed let's go with the same directory
    if (empty($destination)) {
        $destination = $zippath;
    }
    //Clear $destination
    $destpath = rtrim(cleardoubleslashes($destination), "/");
    //Check destination path exists
    if (!is_dir($destpath)) {
        return false;
    }
    //Check destination path is writable. TODO!!
    //Everything is ready:
    //    -$zippath is the path where the zip file resides (dir)
    //    -$zipfilename is the name of the zip file (without path)
    //    -$destpath is the destination path where the zip file will uncompressed (dir)
    $list = array();
    require_once "{$CFG->libdir}/filelib.php";
    do {
        $temppath = "{$CFG->dataroot}/temp/unzip/" . random_string(10);
    } while (file_exists($temppath));
    if (!check_dir_exists($temppath, true, true)) {
        return false;
    }
    if (empty($CFG->unzip)) {
        // Use built-in php-based unzip function
        include_once "{$CFG->libdir}/pclzip/pclzip.lib.php";
        $archive = new PclZip(cleardoubleslashes("{$zippath}/{$zipfilename}"));
        if (!($list = $archive->extract(PCLZIP_OPT_PATH, $temppath, PCLZIP_CB_PRE_EXTRACT, 'unzip_cleanfilename', PCLZIP_OPT_EXTRACT_DIR_RESTRICTION, $temppath))) {
            if (!empty($showstatus)) {
                notice($archive->errorInfo(true));
            }
            return false;
        }
    } else {
        // Use external unzip program
        $separator = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? ' &' : ' ;';
        $redirection = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? '' : ' 2>&1';
        $command = 'cd ' . escapeshellarg($zippath) . $separator . escapeshellarg($CFG->unzip) . ' -o ' . escapeshellarg(cleardoubleslashes("{$zippath}/{$zipfilename}")) . ' -d ' . escapeshellarg($temppath) . $redirection;
        //All converted to backslashes in WIN
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
            $command = str_replace('/', '\\', $command);
        }
        Exec($command, $list);
    }
    unzip_process_temp_dir($temppath, $destpath);
    fulldelete($temppath);
    //Display some info about the unzip execution
    if ($showstatus) {
        unzip_show_status($list, $temppath, $destpath);
    }
    return true;
}
예제 #4
0
파일: lib.php 프로젝트: nadavkav/MoodleTAO
function fm_unzip_file($zipfile, $destination = '', $showstatus = false, $currentdir = 0, $groupid)
{
    //Unzip one zip file to a destination dir
    //Both parameters must be FULL paths
    //If destination isn't specified, it will be the
    //SAME directory where the zip file resides.
    // Modded for Myfiles
    // Michael Avelar 1/24/06
    global $CFG, $USER;
    //Extract everything from zipfile
    $path_parts = pathinfo(cleardoubleslashes($zipfile));
    $zippath = $path_parts["dirname"];
    //The path of the zip file
    $zipfilename = $path_parts["basename"];
    //The name of the zip file
    $extension = $path_parts["extension"];
    //The extension of the file
    //If no file, error
    if (empty($zipfilename)) {
        return false;
    }
    //If no extension, error
    if (empty($extension)) {
        return false;
    }
    //If no destination, passed let's go with the same directory
    if (empty($destination)) {
        $destination = $zippath;
    }
    //Clear $destination
    $destpath = rtrim(cleardoubleslashes($destination), "/");
    //Check destination path exists
    if (!is_dir($destpath)) {
        return false;
    }
    //Check destination path is writable. TODO!!
    //Everything is ready:
    //    -$zippath is the path where the zip file resides (dir)
    //    -$zipfilename is the name of the zip file (without path)
    //    -$destpath is the destination path where the zip file will uncompressed (dir)
    if (empty($CFG->unzip)) {
        // Use built-in php-based unzip function
        include_once "{$CFG->libdir}/pclzip/pclzip.lib.php";
        $archive = new PclZip(cleardoubleslashes("{$zippath}/{$zipfilename}"));
        if (!($list = $archive->extract(PCLZIP_OPT_PATH, $destpath, PCLZIP_CB_PRE_EXTRACT, 'unzip_cleanfilename'))) {
            notice($archive->errorInfo(true));
            return false;
        }
    } else {
        // Use external unzip program
        $separator = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? ' &' : ' ;';
        $redirection = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? '' : ' 2>&1';
        $command = 'cd ' . escapeshellarg($zippath) . $separator . escapeshellarg($CFG->unzip) . ' -o ' . escapeshellarg(cleardoubleslashes("{$zippath}/{$zipfilename}")) . ' -d ' . escapeshellarg($destpath) . $redirection;
        //All converted to backslashes in WIN
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
            $command = str_replace('/', '\\', $command);
        }
        Exec($command, $list);
    }
    // Inserts unzipped objects into myfiles api
    $afolder = $currentdir;
    // Reorders list so that folders are inserted into database before links
    $list2 = array();
    foreach ($list as $l) {
        if ($l['folder'] == 1) {
            $list2[] = $l;
        }
    }
    // Reorders folders list to extract them in order, so the database has the folder before
    // inserting stuff into that folder
    usort($list2, 'fm_reorder_folders_list');
    // Recompiles the completed list...with ordered folders first, then files
    foreach ($list as $l) {
        if ($l['folder'] != 1) {
            $list2[] = $l;
        }
    }
    foreach ($list2 as $l) {
        if ($l['folder'] == 1) {
            // is an unzipped folder
            $newfolder = NULL;
            if ($groupid == 0) {
                $newfolder->owner = $USER->id;
            } else {
                $newfolder->owner = $groupid;
            }
            $tmp = explode('/', $l['stored_filename']);
            // compiles the path of the folder
            $tmppath = '/';
            foreach ($tmp as $t) {
                if ($t != '') {
                    $tmppath .= $t . "/";
                }
            }
            $tmp = array_reverse($tmp);
            $tmppath = substr($tmppath, 0, strrpos($tmppath, $tmp[1]));
            $newfolder->name = $tmp[1];
            $newfolder->category = 0;
            if ($tmp[2] == NULL) {
                // Folder is root folder
                $newfolder->path = '/';
                $newfolder->pathid = 0;
            } else {
                // Puts all folders in their place :)
                $pathtmp = '/';
                $count = count($tmp);
                while ($count > 3) {
                    $pathtmp .= $tmp[$count - 1] . '/';
                    $count--;
                }
                $rec = get_record('fmanager_folders', "name", $tmp[2], "path", $pathtmp);
                $afolder = $rec->id;
                $newfolder->path = fm_get_folder_path($afolder, false, $groupid) . "/";
                $newfolder->pathid = $afolder;
            }
            $newfolder->timemodified = time();
            if (!($afolder = insert_record('fmanager_folders', $newfolder))) {
                error(get_string('errnoinsert', 'block_file_manager'));
            }
        } else {
            $tmp = explode('/', $l['stored_filename']);
            $newlink = NULL;
            if ($groupid == 0) {
                $newlink->owner = $USER->id;
            } else {
                $newlink->owner = $groupid;
            }
            $newlink->type = TYPE_FILE;
            $rootlinkstr = '';
            // Compiles path string
            $count = count($tmp);
            $count = $count - 2;
            foreach ($tmp as $t) {
                if ($count > 0) {
                    if ($t != '') {
                        $rootlinkstr .= '/' . $t;
                    }
                    $count--;
                }
            }
            if (substr($rootlinkstr, 0, 1) != '/') {
                $rootlinkstr = '/' . $rootlinkstr;
            }
            if ($rootlinkstr != '/') {
                $rootlinkstr = $rootlinkstr . '/';
            }
            $tmp = array_reverse($tmp);
            if ($groupid == 0) {
                $owner = $USER->id;
                $newlink->ownertype = 0;
            } else {
                $owner = $groupid;
                $newlink->ownertype = 1;
            }
            if (!($foldstr = get_record('fmanager_folders', "owner", $owner, "name", $tmp[1], "path", $rootlinkstr))) {
                $foldstr->id = $currentdir;
            }
            $newlink->folder = $foldstr->id;
            $newlink->category = 0;
            $newlink->name = substr($tmp[0], 0, -4);
            $newlink->description = '';
            $newlink->link = $tmp[0];
            $newlink->timemodified = time();
            if (!($alink = insert_record('fmanager_link', $newlink))) {
                error(get_string('errnoinsert', 'block_file_manager'));
            }
        }
    }
    //Display some info about the unzip execution
    if ($showstatus) {
        fm_unzip_show_status($list, $destpath);
    }
    return $list;
}
예제 #5
0
파일: 1000020.php 프로젝트: carriercomm/jbs
<?php

#-------------------------------------------------------------------------------
Exec(SPrintF('%s/hosts/JBsServer', SYSTEM_PATH));
#-------------------------------------------------------------------------------
예제 #6
0
/**
 * Unzip one zip file to a destination dir
 * Both parameters must be FULL paths
 * If destination isn't specified, it will be the
 * SAME directory where the zip file resides.
 * @return boolean
 */
function unzip_file($zipfile, $destination = '', $showstatus = true)
{
    global $CFG;
    //Extract everything from zipfile
    $path_parts = pathinfo(cleardoubleslashes($zipfile));
    $zippath = $path_parts["dirname"];
    //The path of the zip file
    $zipfilename = $path_parts["basename"];
    //The name of the zip file
    $extension = $path_parts["extension"];
    //The extension of the file
    //If no file, error
    if (empty($zipfilename)) {
        return false;
    }
    //If no extension, error
    if (empty($extension)) {
        return false;
    }
    //Clear $zipfile
    $zipfile = cleardoubleslashes($zipfile);
    //Check zipfile exists
    if (!file_exists($zipfile)) {
        return false;
    }
    //If no destination, passed let's go with the same directory
    if (empty($destination)) {
        $destination = $zippath;
    }
    //Clear $destination
    $destpath = rtrim(cleardoubleslashes($destination), "/");
    //Check destination path exists
    if (!is_dir($destpath)) {
        return false;
    }
    //Check destination path is writable. TODO!!
    //Everything is ready:
    //    -$zippath is the path where the zip file resides (dir)
    //    -$zipfilename is the name of the zip file (without path)
    //    -$destpath is the destination path where the zip file will uncompressed (dir)
    if (empty($CFG->unzip)) {
        // Use built-in php-based unzip function
        include_once "{$CFG->libdir}/pclzip/pclzip.lib.php";
        $archive = new PclZip(cleardoubleslashes("{$zippath}/{$zipfilename}"));
        if (!($list = $archive->extract(PCLZIP_OPT_PATH, $destpath, PCLZIP_CB_PRE_EXTRACT, 'unzip_cleanfilename'))) {
            notice($archive->errorInfo(true));
            return false;
        }
    } else {
        // Use external unzip program
        $separator = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? ' &' : ' ;';
        $redirection = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? '' : ' 2>&1';
        $command = 'cd ' . escapeshellarg($zippath) . $separator . escapeshellarg($CFG->unzip) . ' -o ' . escapeshellarg(cleardoubleslashes("{$zippath}/{$zipfilename}")) . ' -d ' . escapeshellarg($destpath) . $redirection;
        //All converted to backslashes in WIN
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
            $command = str_replace('/', '\\', $command);
        }
        Exec($command, $list);
    }
    //Display some info about the unzip execution
    if ($showstatus) {
        unzip_show_status($list, $destpath);
    }
    return true;
}
예제 #7
0
}
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
foreach ($HostsIDs as $HostID) {
    #-------------------------------------------------------------------------------
    $Path = SprintF('%s/db/%s/functions.sql', SYSTEM_PATH, $HostID);
    #-------------------------------------------------------------------------------
    if (File_Exists($Path)) {
        #-------------------------------------------------------------------------------
        echo SPrintF("Перезагрузка функций для хоста (%s)\n", $HostID);
        #-------------------------------------------------------------------------------
        $Command = SPrintF('mysql --defaults-extra-file=%s %s 2>&1 < %s', $MyCnf, $DBConnection['DbName'], $Path);
        #-------------------------------------------------------------------------------
        $Log = array();
        #-------------------------------------------------------------------------------
        if (Exec($Command, $Log)) {
            return SPrintF("ERROR: ошибка перезагрузки функций:\n%s", Implode("\n", $Log));
        }
        #-------------------------------------------------------------------------------
    }
    #-------------------------------------------------------------------------------
}
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
echo "\n\n";
#-------------------------------------------------------------------------------
if (File_Exists(SPrintF('%s/template_c', $Tmp))) {
    #-------------------------------------------------------------------------------
    if (Is_Error(IO_RmDir(SPrintF('%s///template_c', $Tmp)))) {
        return ERROR | @Trigger_Error(500);
    }
예제 #8
0
파일: index.php 프로젝트: carriercomm/jbs
if ($__STEP_ID == 1) {
    #-----------------------------------------------------------------------------
    $Tests = array('Проверка окружения');
    #-----------------------------------------------------------------------------
    $PhpVersion = PhpVersion();
    #-----------------------------------------------------------------------------
    $Tests[] = array('Name' => 'Версия PHP интерпретатора (phpversion)', 'Status' => $PhpVersion, 'IsOk' => $PhpVersion >= 5, 'Comment' => 'Ваша версия PHP не совместима с биллинговой системой (требуется PHP >= 5), пожалуйста, установите нужную версию PHP.');
    #-----------------------------------------------------------------------------
    #-----------------------------------------------------------------------------
    $Tests[] = 'Поиск приложений';
    #-----------------------------------------------------------------------------
    $Tests[] = $TestMySQL;
    #-----------------------------------------------------------------------------
    if (isset($MySQLbin)) {
        #---------------------------------------------------------------------------
        $Result = Exec(SPrintF('%s --version 2>&1', $MySQLbin));
        #---------------------------------------------------------------------------
        if (Preg_Match('/[0-9]+\\.[0-9]+\\.[0-9]/', $Result, $MySQL)) {
            #-------------------------------------------------------------------------
            $MySQL = Current($MySQL);
            #-------------------------------------------------------------------------
            if (IntVal($MySQL) >= 5) {
                $Test = array('Status' => SPrintF('%s (совместимо)', $MySQL), 'IsOk' => TRUE);
            } else {
                $Test = array('Status' => SPrintF('%s (несовместимо)', $MySQL), 'IsOk' => FALSE, 'Comment' => 'Несовместимая версия mysql. Требуется версия mysql 5+.');
            }
        } else {
            $Test = array('Status' => 'Версия не определена', 'IsOk' => FALSE, 'Comment' => 'Не удалось определить версию mysql. Попробуйте, выполнить следующу команду mysql --version.');
        }
    } else {
        $Test = array('Status' => 'Не найдено', 'IsOk' => FALSE, 'Comment' => 'Приложение mysql не найдено. Пожалуйста, воспользуйтесь менеджером пакетов для установки данной программы <A target="blank" href="http://wiki.joonte.com/?title=Документация:Подготовка_к_установке">[подробнее...]</A>');
예제 #9
0
 #-------------------------------------------------------------------------------
 $Server = DB_Select('Servers', array('*'), array('UNIQ', 'ID' => $Order['ServerID']));
 #-------------------------------------------------------------------------------
 switch (ValueOf($Server)) {
     case 'error':
         return ERROR | @Trigger_Error(500);
     case 'exception':
         break;
     case 'array':
         break;
     default:
         return ERROR | @Trigger_Error(101);
 }
 #-------------------------------------------------------------------------------
 #-------------------------------------------------------------------------------
 Exec(SPrintF('"%s" "%s" "OnCreate" "%s" "%s" "%s" 2>&1', $File, $Order['Email'], $Number, $Order['Keys'], Is_Array($Server) ? Base64_Encode(JSON_Encode($Server)) : 'server not exists'), $Out, $ReturnValue);
 #-------------------------------------------------------------------------------
 Debug(SPrintF('[comp/Tasks/ServiceCreate]: exec return code = %s, Out = %s', $ReturnValue, print_r($Out, true)));
 #-------------------------------------------------------------------------------
 if ($ReturnValue != 0) {
     return new gException('ERROR_EXECUTE_COMMAND', 'Произошла ошибка при выполнении команды назначенной статусу');
 }
 #-------------------------------------------------------------------------------
 #-------------------------------------------------------------------------------
 $Comp = Comp_Load('www/API/StatusSet', array('ModeID' => 'Orders', 'StatusID' => 'Active', 'RowsIDs' => $ServiceOrderID, 'Comment' => 'Заказ создан', 'IsNoTrigger' => TRUE));
 #-------------------------------------------------------------------------------
 switch (ValueOf($Comp)) {
     case 'error':
         return ERROR | @Trigger_Error(500);
     case 'exception':
         return ERROR | @Trigger_Error(400);
예제 #10
0
파일: WhoIs.php 프로젝트: carriercomm/jbs
function WhoIs_Check($DomainName, $ZoneName, $IsAvalible = FALSE)
{
    #-------------------------------------------------------------------------------
    Debug(SPrintF('[system/libs/WhoIs]: run function WhoIs_Check, Domain = %s.%s', $DomainName, $ZoneName));
    #-------------------------------------------------------------------------------
    #-------------------------------------------------------------------------------
    $CacheID = SPrintF('WhoIs-%s.%s', $DomainName, $ZoneName);
    #-------------------------------------------------------------------------------
    $Answer = CacheManager::get($CacheID);
    #-------------------------------------------------------------------------------
    if (!$Answer) {
        #-------------------------------------------------------------------------------
        # смотрим доменную зону, на предмет того использовать ли данные whois сервера, или юзать запросы к регистратору
        $DomainZones = System_XML('config/DomainZones.xml');
        if (Is_Error($DomainZones)) {
            return ERROR | @Trigger_Error('[comp/www/API/WhoIs]: не удалось загрузить базу WhoIs серверов');
        }
        #-------------------------------------------------------------------------------
        $IsSuppoted = FALSE;
        #-------------------------------------------------------------------------------
        foreach ($DomainZones as $Zone) {
            #-------------------------------------------------------------------------------
            if ($Zone['Name'] == $ZoneName) {
                #-------------------------------------------------------------------------------
                $IsSuppoted = TRUE;
                #-------------------------------------------------------------------------------
                break;
                #-------------------------------------------------------------------------------
            }
            #-------------------------------------------------------------------------------
        }
        #-------------------------------------------------------------------------------
        if (!$IsSuppoted || $Zone['IsUseRegistratorWhoIs']) {
            #-------------------------------------------------------------------------------
            if (!$IsSuppoted) {
                Debug(SPrintF('[comp/www/API/WhoIs]: доменная зона не поддерживается'));
            }
            #-------------------------------------------------------------------------------
            if ($IsSuppoted && $Zone['IsUseRegistratorWhoIs']) {
                Debug(SPrintF('[comp/www/API/WhoIs]: принудительное использование WhoIs регистратора'));
            }
            #-------------------------------------------------------------------------------
            #-------------------------------------------------------------------------------
            # чекаем доменную зону
            $Regulars = Regulars();
            #-------------------------------------------------------------------------------
            if (!Preg_Match($Regulars['DomainZone'], $ZoneName)) {
                return ERROR | @Trigger_Error(SPrintF('[comp/www/API/WhoIs]: неверная доменная зона (%s)', $ZoneName));
            }
            #-------------------------------------------------------------------------------
            # достаём список серверов на которых есть такой тариф
            $Servers = DB_Select('DomainSchemes', array('ServerID'), array('Where' => SPrintF('`Name` = "%s"', $ZoneName)));
            #-------------------------------------------------------------------------------
            switch (ValueOf($Servers)) {
                case 'error':
                    return ERROR | @Trigger_Error(500);
                case 'exception':
                    return new gException('REGISTRATOR_SERVER_NOT_FOUND', 'Не найдены активные сервера регистраторов');
                case 'array':
                    #-------------------------------------------------------------------------------
                    $Array = array();
                    #-------------------------------------------------------------------------------
                    foreach ($Servers as $Server) {
                        $Array[] = $Server['ServerID'];
                    }
                    #-------------------------------------------------------------------------------
                    break;
                    #-------------------------------------------------------------------------------
                #-------------------------------------------------------------------------------
                default:
                    return ERROR | @Trigger_Error(101);
            }
            #-------------------------------------------------------------------------------
            # достаём список активных серверов регистраторов
            $Servers = DB_Select('Servers', array('ID', 'Address', 'Params'), array('Where' => array(SPrintF('`ID` IN (%s)', Implode(',', $Array)), '`IsActive` = "yes"'), 'SortOn' => 'Address'));
            #-------------------------------------------------------------------------------
            switch (ValueOf($Servers)) {
                case 'error':
                    return ERROR | @Trigger_Error(500);
                case 'exception':
                    return new gException('REGISTRATOR_SERVER_NOT_FOUND', 'Не найдены активные сервера регистраторов');
                case 'array':
                    break;
                default:
                    return ERROR | @Trigger_Error(101);
            }
            #-------------------------------------------------------------------------------
            # перебираем регистраторов
            $UseServer = FALSE;
            #-------------------------------------------------------------------------------
            foreach ($Servers as $iServer) {
                #-------------------------------------------------------------------------------
                # если это не проверка доступности и в настройках сервера не стоит галка про получение WhoIs - пропускаем
                if (!$IsAvalible) {
                    if (!$iServer['Params']['IsFetchWhoIs']) {
                        continue;
                    }
                }
                #-------------------------------------------------------------------------------
                # достаём использованные запросы к регистратору, на данную минуту
                $RatelimitID = SPrintF('ratelimit-%s-%s-00', $iServer['Address'], Date('H-i'));
                #-------------------------------------------------------------------------------
                $Ratelimit = CacheManager::get($RatelimitID);
                #-------------------------------------------------------------------------------
                # если из кэша что-то досталось и оно больше разрешённой частоты запросов - пропускаем цикл
                if ($Ratelimit && $Ratelimit >= $iServer['Params']['RatelimitAPI']) {
                    #-------------------------------------------------------------------------------
                    Debug(SPrintF('[comp/www/API/WhoIs]: превышена частота запросов к серверу %s (разрешено %u, использовано %u)', $iServer['Address'], $iServer['Params']['RatelimitAPI'], $Ratelimit));
                    #-------------------------------------------------------------------------------
                    continue;
                    #-------------------------------------------------------------------------------
                }
                #-------------------------------------------------------------------------------
                # сохраняем, на пару минут, в кэш новое число запросов к регистратору
                CacheManager::add($RatelimitID, IntVal($Ratelimit) + 1, 120);
                #-------------------------------------------------------------------------------
                $UseServer = $iServer;
                #-------------------------------------------------------------------------------
                break;
                #-------------------------------------------------------------------------------
            }
            #-------------------------------------------------------------------------------
            # если не задан сервер - частота превышена для всех серверов
            if (!$UseServer) {
                return new gException('REGISTRATOR_SERVER_RATELIMIT', 'Превышена максимальная частота запросов к интерфейсу регистратора');
            }
            #-------------------------------------------------------------------------------
            #-------------------------------------------------------------------------------
            # выбираем сервер регистратора
            if (Is_Error(System_Load('classes/DomainServer.class.php'))) {
                return ERROR | @Trigger_Error(500);
            }
            #-------------------------------------------------------------------------------
            $Server = new DomainServer();
            #-------------------------------------------------------------------------------
            $IsSelected = $Server->Select((int) $UseServer['ID']);
            #-------------------------------------------------------------------------------
            switch (ValueOf($IsSelected)) {
                case 'error':
                    return ERROR | @Trigger_Error(500);
                case 'exception':
                    return new gException('CANNOT_SELECT_REGISTRATOR', 'Не удалось выбрать регистратора');
                case 'true':
                    break;
                default:
                    return ERROR | @Trigger_Error(101);
            }
            #-------------------------------------------------------------------------------
            # делаем запрос к API - функция в зависимости от $IsAvalible
            if ($IsAvalible) {
                #-------------------------------------------------------------------------------
                $DomainCheck = $Server->DomainCheck($DomainName, $ZoneName);
                #-------------------------------------------------------------------------------
                switch (ValueOf($DomainCheck)) {
                    case 'error':
                        return ERROR | @Trigger_Error(500);
                    case 'exception':
                        return ERROR | @Trigger_Error(400);
                    case 'true':
                        return TRUE;
                    case 'false':
                        return array();
                    case 'array':
                        break;
                    default:
                        return ERROR | @Trigger_Error(101);
                }
                #-------------------------------------------------------------------------------
            } else {
                #-------------------------------------------------------------------------------
                $DomainWhoIs = $Server->DomainWhoIs($DomainName, $ZoneName);
                #-------------------------------------------------------------------------------
                switch (ValueOf($DomainWhoIs)) {
                    case 'error':
                        return ERROR | @Trigger_Error(500);
                    case 'exception':
                        # a функции нет ... вылезаем на обычную проверку whois
                        break;
                    case 'true':
                        return TRUE;
                    case 'string':
                        #-------------------------------------------------------------------------------
                        CacheManager::add($CacheID, $DomainWhoIs, 1800);
                        #-------------------------------------------------------------------------------
                        break;
                        #-------------------------------------------------------------------------------
                    #-------------------------------------------------------------------------------
                    default:
                        return ERROR | @Trigger_Error(101);
                }
                #-------------------------------------------------------------------------------
            }
            #-------------------------------------------------------------------------------
        }
        #-------------------------------------------------------------------------------
    }
    #-------------------------------------------------------------------------------
    #-------------------------------------------------------------------------------
    $Config = Config();
    #-------------------------------------------------------------------------------
    $UseSystemApplication = $Config['Other']['Libs']['WhoIs']['UseSystemApplication'];
    #-------------------------------------------------------------------------------
    $Regulars = Regulars();
    #-------------------------------------------------------------------------------
    if (!Preg_Match($Regulars['DomainName'], $DomainName)) {
        return new gException('WRONG_DOMAIN_NAME', 'Неверное доменное имя');
    }
    #-------------------------------------------------------------------------------
    $DomainZones = System_XML('config/DomainZones.xml');
    if (Is_Error($DomainZones)) {
        return ERROR | @Trigger_Error('[WhoIs_Check]: не удалось загрузить базу WhoIs серверов');
    }
    #-------------------------------------------------------------------------------
    $IsSuppoted = FALSE;
    #-------------------------------------------------------------------------------
    foreach ($DomainZones as $DomainZone) {
        #-------------------------------------------------------------------------------
        if ($DomainZone['Name'] == $ZoneName) {
            #-------------------------------------------------------------------------------
            $IsSuppoted = TRUE;
            #-------------------------------------------------------------------------------
            break;
            #-------------------------------------------------------------------------------
        }
        #-------------------------------------------------------------------------------
    }
    #-------------------------------------------------------------------------------
    if (!$IsSuppoted && !isset($DomainWhoIs)) {
        return FALSE;
    }
    #-------------------------------------------------------------------------------
    if (Mb_StrLen($DomainName) < ($MinChars = $DomainZone['MinChars'])) {
        return new gException('WRONG_DOMAIN_NAME_LENGTH', SPrintF('Длина доменного имени должна быть не менее %u символа(ов)', $MinChars));
    }
    #-------------------------------------------------------------------------------
    $Domain = SPrintF('%s.%s', $DomainName, $DomainZone['Name']);
    #-------------------------------------------------------------------------------
    $Answer = CacheManager::get($CacheID);
    #-------------------------------------------------------------------------------
    if (!$Answer) {
        #-------------------------------------------------------------------------------
        $IDNAConverter = new IDNAConvert();
        #-------------------------------------------------------------------------------
        if ($UseSystemApplication) {
            #-------------------------------------------------------------------------------
            $IsExec = Exec(SPrintF('whois %s', $IDNAConverter->encode($Domain)), $Answer);
            #-------------------------------------------------------------------------------
            $Answer = Implode("\n", $Answer);
            #-------------------------------------------------------------------------------
        } else {
            #-------------------------------------------------------------------------------
            $Socket = @FsockOpen($DomainZone['Server'], 43, $nError, $sError, 5);
            #-------------------------------------------------------------------------------
            if (!$Socket) {
                return ERROR | @Trigger_Error('[WhoIs_Check]: ошибка соединения с сервером WhoIs');
            }
            #-------------------------------------------------------------------------------
            if (!@Fputs($Socket, SPrintF("%s\r\n", $IDNAConverter->encode($Domain)))) {
                return ERROR | @Trigger_Error('[WhoIs_Check]: ошибка работы с серверов WhoIs');
            }
            #-------------------------------------------------------------------------------
            $Answer = '';
            #-------------------------------------------------------------------------------
            do {
                #-------------------------------------------------------------------------------
                $Line = @Fgets($Socket, 10);
                #-------------------------------------------------------------------------------
                $Answer .= $Line;
                #-------------------------------------------------------------------------------
            } while ($Line);
            #-------------------------------------------------------------------------------
            Fclose($Socket);
            #-------------------------------------------------------------------------------
            CacheManager::add($CacheID, $Answer, 1800);
            #-------------------------------------------------------------------------------
        }
        #-------------------------------------------------------------------------------
        Debug(SPrintF('[system/libs/WhoIs.php]: Answer = %s', print_r($Answer, true)));
        #-------------------------------------------------------------------------------
    }
    #-------------------------------------------------------------------------------
    if (Preg_Match(SPrintF('/%s/', $DomainZone['Available']), $Answer)) {
        return TRUE;
    }
    #-------------------------------------------------------------------------------
    if (Preg_Match(SPrintF('/%s/', $DomainZone['NotAvailable']), $Answer)) {
        return new gException('DOMAIN_NOT_AVAILABLE', 'Доменное имя не доступно для регистрации');
    }
    #-------------------------------------------------------------------------------
    $Result = array('Info' => Preg_Replace('/\\n\\s+\\n/sU', "\n", Preg_Replace('/\\%.+\\n/sU', '', $Answer)), 'ExpirationDate' => 0);
    #-------------------------------------------------------------------------------
    $ExpirationDate = $DomainZone['ExpirationDate'];
    #-------------------------------------------------------------------------------
    if ($ExpirationDate) {
        #-------------------------------------------------------------------------------
        if (Preg_Match(SPrintF('/%s/', $ExpirationDate), $Answer, $Mathes)) {
            #-------------------------------------------------------------------------------
            if (Count($Mathes) < 2) {
                return ERROR | @Trigger_Error('[WhoIs_Check]: шаблон поиска даты окончания задан неверно');
            }
            #-------------------------------------------------------------------------------
            $ExpirationDate = $Mathes[1];
            #-------------------------------------------------------------------------------
            $Months = array('jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec');
            #-------------------------------------------------------------------------------
            if (Preg_Match('/^[0-9]{4}\\.[0-9]{2}\\.[0-9]{2}$/', $ExpirationDate)) {
                #-------------------------------------------------------------------------------
                $Date = Array_Combine(array('Year', 'Month', 'Day'), Explode('.', $ExpirationDate));
                #-------------------------------------------------------------------------------
                $ExpirationDate = MkTime(0, 0, 0, $Date['Month'], $Date['Day'], $Date['Year']);
                #-------------------------------------------------------------------------------
            } elseif (Preg_Match('/^[0-9]{4}\\-[0-9]{2}\\-[0-9]{2}$/', $ExpirationDate)) {
                #-------------------------------------------------------------------------------
                $Date = Array_Combine(array('Year', 'Month', 'Day'), Explode('-', $ExpirationDate));
                #-------------------------------------------------------------------------------
                $ExpirationDate = MkTime(0, 0, 0, $Date['Month'], $Date['Day'], $Date['Year']);
                #-------------------------------------------------------------------------------
            } elseif (Preg_Match('/^[0-9]{2}\\-[a-zA-Z]{3}\\-[0-9]{4}$/', $ExpirationDate)) {
                #-------------------------------------------------------------------------------
                $Date = Array_Combine(array('Day', 'Month', 'Year'), Explode('-', $ExpirationDate));
                #-------------------------------------------------------------------------------
                $Month = Array_Search(StrToLower($Date['Month']), $Months);
                #-------------------------------------------------------------------------------
                $ExpirationDate = MkTime(0, 0, 0, $Month + 1, $Date['Day'], $Date['Year']);
                #-------------------------------------------------------------------------------
            } elseif (Preg_Match('/^[0-9]{2}\\s[a-zA-Z]{2,10}\\s[0-9]{4}$/', $ExpirationDate)) {
                #-------------------------------------------------------------------------------
                $Months = array('january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'octember', 'november', 'decemeber');
                #-------------------------------------------------------------------------------
                $Date = Array_Combine(array('Day', 'Month', 'Year'), Preg_Split('/\\s+/', $ExpirationDate));
                #-------------------------------------------------------------------------------
                $Month = Array_Search(StrToLower($Date['Month']), $Months);
                #-------------------------------------------------------------------------------
                $ExpirationDate = MkTime(0, 0, 0, $Month + 1, $Date['Day'], $Date['Year']);
                #-------------------------------------------------------------------------------
            } else {
                #-------------------------------------------------------------------------------
                $Date = Array_Combine(array('Week', 'Month', 'Day', 'Time', 'GMT', 'Year'), Preg_Split('/\\s+/', $ExpirationDate));
                #-------------------------------------------------------------------------------
                $Month = Array_Search(StrToLower($Date['Month']), $Months);
                #-------------------------------------------------------------------------------
                $ExpirationDate = MkTime(0, 0, 0, $Month + 1, $Date['Day'], $Date['Year']);
                #-------------------------------------------------------------------------------
            }
            #-------------------------------------------------------------------------------
            $Result['ExpirationDate'] = $ExpirationDate;
            #-------------------------------------------------------------------------------
        }
        #-------------------------------------------------------------------------------
    }
    #-------------------------------------------------------------------------------
    $NsName = $DomainZone['NsName'];
    #-------------------------------------------------------------------------------
    if ($NsName) {
        #-------------------------------------------------------------------------------
        if (Preg_Match_All(SPrintF('/%s/', $NsName), $Answer, $Mathes)) {
            #-------------------------------------------------------------------------------
            if (Count($Mathes) < 2) {
                return ERROR | @Trigger_Error('[WhoIs_Check]: шаблон поиска именных серверов задан неверно');
            }
            #-------------------------------------------------------------------------------
            $NsNames = $Mathes[1];
            #-------------------------------------------------------------------------------
            for ($i = 0; $i < Count($NsNames); $i++) {
                #-------------------------------------------------------------------------------
                $NsName = Trim(StrToLower($NsNames[$i]), '.');
                #-------------------------------------------------------------------------------
                $Result[SPrintF('Ns%uName', $i + 1)] = $NsName;
                #-------------------------------------------------------------------------------
                if ($NsName) {
                    #-------------------------------------------------------------------------------
                    if (Mb_SubStr($NsName, -Mb_StrLen($Domain)) == $Domain) {
                        #-------------------------------------------------------------------------------
                        $IP = GetHostByName($NsName);
                        #-------------------------------------------------------------------------------
                        if ($IP != $NsName) {
                            $Result[SPrintF('Ns%uIP', $i + 1)] = $IP;
                        }
                        #-------------------------------------------------------------------------------
                    }
                    #-------------------------------------------------------------------------------
                }
                #-------------------------------------------------------------------------------
            }
            #-------------------------------------------------------------------------------
        }
        #-------------------------------------------------------------------------------
    }
    #-------------------------------------------------------------------------------
    $Registrar = $DomainZone['Registrar'];
    #-------------------------------------------------------------------------------
    if ($Registrar) {
        #-------------------------------------------------------------------------------
        if (Preg_Match(SPrintF('/%s/', $Registrar), $Answer, $Mathes)) {
            #-------------------------------------------------------------------------------
            if (Count($Mathes) < 2) {
                return ERROR | @Trigger_Error('[WhoIs_Check]: шаблон поиска регистратора серверов задан неверно');
            }
            #-------------------------------------------------------------------------------
            $Registrar = Next($Mathes);
            #-------------------------------------------------------------------------------
            $Result['Registrar'] = $Registrar;
            #-------------------------------------------------------------------------------
        }
        #-------------------------------------------------------------------------------
    }
    #-------------------------------------------------------------------------------
    return $Result;
    #-------------------------------------------------------------------------------
}
예제 #11
0
파일: 1000023.php 프로젝트: carriercomm/jbs
<?php

#-------------------------------------------------------------------------------
Exec(SPrintF('rm -rf %s/scripts/JBsServer', SYSTEM_PATH));
#-------------------------------------------------------------------------------
예제 #12
0
#-------------------------------------------------------------------------------
$Lines = Max(10, $Lines);
#-------------------------------------------------------------------------------
$Tmp = System_Element('tmp');
if (Is_Error($Tmp)) {
    return ERROR | @Trigger_Error(500);
}
#-------------------------------------------------------------------------------
$Logs = SPrintF('%s/logs', $Tmp);
#-------------------------------------------------------------------------------
$Command = SPrintF('tail -n %u %s/%s', $Lines, $Logs, $Log);
#-------------------------------------------------------------------------------
if ($Search) {
    $Command .= SPrintF(' | grep %s', EscapeShellArg($Search));
}
#-------------------------------------------------------------------------------
$Command .= ' 2>&1';
#-------------------------------------------------------------------------------
Exec($Command, $Result);
#-------------------------------------------------------------------------------
Array_UnShift($Result, SPrintF("%s\n", $Command));
#-------------------------------------------------------------------------------
if ($IsWrap) {
    #-----------------------------------------------------------------------------
    for ($i = 0; $i < Count($Result); $i++) {
        $Result[$i] = WordWrap($Result[$i], 100, "\n", TRUE);
    }
}
#-------------------------------------------------------------------------------
return Implode("\n", $Result);
#-------------------------------------------------------------------------------
예제 #13
0
#-------------------------------------------------------------------------------
if ($disable_functions = Ini_Get('disable_functions')) {
    if ($Settings['IsEvent']) {
        $Messages[] = SPrintF('Внимание! В PHP выключены следюущие функции: "%s". Возможно данные функции потребуются для работы системы. Найдите в файле %s опцию "disable_functions" и установите для нее пустое значение.', $disable_functions, PHP_INI_PATH);
    }
}
#-------------------------------------------------------------------------------
if (Ini_Get('open_basedir')) {
    if ($Settings['IsEvent']) {
        $Messages[] = SPrintF('Включено ограничение open_basedir. Если необходимые для работы приложения не будут найдены, необходимо закомментировать опцию "open_basedir" в файле %s, или в конфигурации виртуалхоста apache', PHP_INI_PATH);
    }
}
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
# проверяем наличие утилиты htmldoc
$Result = Exec('htmldoc --version 2>&1');
#-------------------------------------------------------------------------------
if (!Preg_Match('/not\\sfound/', $Result)) {
    #-------------------------------------------------------------------------------
    if (Preg_Match('/[0-9]+\\.[0-9]+\\.[0-9]/', $Result, $HtmlDoc)) {
        #-------------------------------------------------------------------------------
        $HtmlDoc = Current($HtmlDoc);
        #-------------------------------------------------------------------------------
        Debug(SPrintF('[comp/Tasks/GC/CheckSoftWare]: htmldoc version: %s', $HtmlDoc));
        #-------------------------------------------------------------------------------
        if (FloatVal($HtmlDoc) < 1.8) {
            if ($Settings['IsEvent']) {
                $Messages[] = 'Несовместимая версия htmldoc. Требуется версия htmldoc 1.8+';
            }
        }
        #-------------------------------------------------------------------------------
예제 #14
0
파일: Image.php 프로젝트: carriercomm/jbs
function Image_Resize($Source, $Width, $Height)
{
    /****************************************************************************/
    $__args_types = array('string', 'integer');
    #-----------------------------------------------------------------------------
    $__args__ = Func_Get_Args();
    eval(FUNCTION_INIT);
    /****************************************************************************/
    if (!Function_Exists('ImageCreateFromString')) {
        return ERROR | Trigger_Error('[Image_Resize]: модуль работы с изображениями не установлен');
    }
    #-----------------------------------------------------------------------------
    $Real = @ImageCreateFromString($Source);
    if (!Is_Resource($Real)) {
        return ERROR | @Trigger_Error("[Image_Resize]: не возможно создать изображение");
    }
    #-----------------------------------------------------------------------------
    if (Function_Exists('imageantialias')) {
        ImageAntiAlias($Real, TRUE);
    }
    #-----------------------------------------------------------------------------
    $Result = ImageCreateTrueColor($Width, $Height);
    if (!$Result) {
        return ERROR | @Trigger_Error('[Image_Resize]: не удалось создать пустое изображение');
    }
    #-----------------------------------------------------------------------------
    $White = ImageColorAllocate($Result, 230, 230, 230);
    #-----------------------------------------------------------------------------
    if (!ImageFill($Result, 0, 0, $White)) {
        return ERROR | @Trigger_Error('[Image_Resize]: не удалось закрасить изображение');
    }
    #-----------------------------------------------------------------------------
    $Sx = @ImageSx($Real);
    if (!$Sx) {
        return ERROR | @Trigger_Error("[Image_Resize]: не возможно получить ширину изображения");
    }
    #-----------------------------------------------------------------------------
    $Sy = @ImageSy($Real);
    if (!$Sy) {
        return ERROR | @Trigger_Error("[Image_Resize]: не возможно получить высоту изображения");
    }
    #-----------------------------------------------------------------------------
    $Folder = System_Element('tmp');
    if (Is_Error($Folder)) {
        return ERROR | @Trigger_Error('[Image_Resize]: не удалось найти временную папку');
    }
    #-----------------------------------------------------------------------------
    if ($Width < $Sx || $Height < $Sy) {
        #---------------------------------------------------------------------------
        $HW = $Sy / $Sx;
        $WH = $Sx / $Sy;
        #---------------------------------------------------------------------------
        $WNew = $Width;
        $HNew = $Height;
        #---------------------------------------------------------------------------
        if ($Sx < $Sy) {
            $HNew = (int) ($WNew * $HW);
        } else {
            $WNew = (int) ($HNew * $WH);
        }
        #---------------------------------------------------------------------------
        if (!Preg_Match('/no\\sconvert/', Exec('which convert'))) {
            #-------------------------------------------------------------------------
            $File = SPrintF('%s/%s', $Folder, UniqID('Image'));
            #-------------------------------------------------------------------------
            if (!ImageJpeg($Real, $File, 100)) {
                return ERROR | @Trigger_Error('[Image_Resize]: не удалось сохранить временное изображение');
            }
            #-------------------------------------------------------------------------
            $Command = SPrintF('convert %s -thumbnail %ux%u^ -gravity North -extent %ux%u %s', $File, $Width, $Height, $Width, $Height, $File);
            #-------------------------------------------------------------------------
            Debug($Command);
            #-------------------------------------------------------------------------
            if (Exec($Command, $Log)) {
                return ERROR | @Trigger_Error(SPrintF("[Image_Resize]: ошибка выполнения команды:\n%s", Implode("\n", $Log)));
            }
            #-------------------------------------------------------------------------
            $Result = IO_Read($File);
            if (Is_Error($Result)) {
                return ERROR | @Trigger_Error('[Image_Resize]: не удалось прочитать изображение');
            }
            #-------------------------------------------------------------------------
            if (!UnLink($File)) {
                return ERROR | @Trigger_Error('[Image_Resize]: не удалось удалить временный файл');
            }
            #-------------------------------------------------------------------------
            return $Result;
        } else {
            #-------------------------------------------------------------------------
            if (!ImageCopyResized($Result, $Real, 0, 0, 0, 0, $WNew, $HNew, $Sx, $Sy)) {
                return ERROR | @Trigger_Error('[Image_Resize]: не удалось уменьшить изображение');
            }
        }
    } else {
        #---------------------------------------------------------------------------
        if (!ImageCopy($Result, $Real, ($Width - $Sx) / 2, ($Height - $Sy) / 2, 0, 0, $Sx, $Sy)) {
            return ERROR | @Trigger_Error('[Image_Resize]: не удалось уменьшить изображение');
        }
    }
    #-----------------------------------------------------------------------------
    $File = SPrintF('%s/%s', $Folder, UniqID('Image'));
    #-----------------------------------------------------------------------------
    if (!ImageJpeg($Result, $File, 95)) {
        return ERROR | @Trigger_Error('[Image_Resize]: не удалось сохранить временное изображение');
    }
    #-----------------------------------------------------------------------------
    if (!ImageDestroy($Result)) {
        return ERROR | @Trigger_Error('[Image_Resize]: не удалось освободить ресурс изображения');
    }
    #-----------------------------------------------------------------------------
    $Result = IO_Read($File);
    if (Is_Error($Result)) {
        return ERROR | @Trigger_Error('[Image_Resize]: не удалось прочитать изображение');
    }
    #-----------------------------------------------------------------------------
    if (!UnLink($File)) {
        return ERROR | @Trigger_Error('[Image_Resize]: не удалось удалить временный файл');
    }
    #-----------------------------------------------------------------------------
    return $Result;
}