Example #1
3
 private function getRandomBytes($count)
 {
     $bytes = '';
     if (function_exists('openssl_random_pseudo_bytes') && strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
         // OpenSSL slow on Win
         $bytes = openssl_random_pseudo_bytes($count);
     }
     if ($bytes === '' && @is_readable('/dev/urandom') && ($hRand = @fopen('/dev/urandom', 'rb')) !== FALSE) {
         $bytes = fread($hRand, $count);
         fclose($hRand);
     }
     if (strlen($bytes) < $count) {
         $bytes = '';
         if ($this->randomState === null) {
             $this->randomState = microtime();
             if (function_exists('getmypid')) {
                 $this->randomState .= getmypid();
             }
         }
         for ($i = 0; $i < $count; $i += 16) {
             $this->randomState = md5(microtime() . $this->randomState);
             if (PHP_VERSION >= '5') {
                 $bytes .= md5($this->randomState, true);
             } else {
                 $bytes .= pack('H*', md5($this->randomState));
             }
         }
         $bytes = substr($bytes, 0, $count);
     }
     return $bytes;
 }
Example #2
0
 protected function getPid()
 {
     if (is_null($this->pid)) {
         $this->pid = getmypid();
     }
     return $this->pid;
 }
Example #3
0
function ParseAllcontacts()
{
    $unix = new unix();
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
    $pidtime = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".time";
    $pid = @file_get_contents($pidfile);
    if ($unix->process_exists($pid)) {
        return;
    }
    @file_put_contents($pidfile, getmypid());
    if ($unix->file_time_min($pidtime) < 120) {
        return;
    }
    @file_put_contents($pidtime, time());
    $ldap = new clladp();
    $suffix = $ldap->suffix;
    $arr = array("uid");
    $sr = @ldap_search($ldap->ldap_connection, "dc=organizations,{$suffix}", '(objectclass=userAccount)', $arr);
    if ($sr) {
        $hash = ldap_get_entries($ldap->ldap_connection, $sr);
        for ($i = 0; $i < $hash["count"]; $i++) {
            ParseContacts($hash[$i]["uid"][0]);
            if (system_is_overloaded(dirname(__FILE__))) {
                $unix->send_email_events(basename(__FILE__) . " Overloaded aborting task", "Zarafa contacts importation has been canceled due to overloaded system", "mailbox");
                return;
            }
            sleep(1);
        }
    }
}
Example #4
0
 public function __construct()
 {
     echo "[*] PocketMine-MP set-up wizard\n";
     echo "[*] Please select a language:\n";
     foreach (InstallerLang::$languages as $short => $native) {
         echo " {$native} => {$short}\n";
     }
     do {
         echo "[?] Language (en): ";
         $lang = strtolower($this->getInput("en"));
         if (!isset(InstallerLang::$languages[$lang])) {
             echo "[!] Couldn't find the language\n";
             $lang = false;
         }
     } while ($lang == false);
     $this->lang = new InstallerLang($lang);
     echo "[*] " . $this->lang->language_has_been_selected . "\n";
     if (!$this->showLicense()) {
         \pocketmine\kill(getmypid());
         exit(-1);
     }
     echo "[?] " . $this->lang->skip_installer . " (y/N): ";
     if (strtolower($this->getInput()) === "y") {
         return;
     }
     echo "\n";
     $this->welcome();
     $this->generateBaseConfig();
     $this->generateUserFiles();
     $this->networkFunctions();
     $this->endWizard();
 }
 function _exclusiveLock($fname = false)
 {
     $mutex =& $this->_mutex();
     while (true) {
         $timestamp = $mutex->lockTS();
         // Note: This does not lock, only checks what the timestamp is.
         if ($timestamp === false) {
             if (!$mutex->lock()) {
                 eZDebug::writeWarning("Failed to acquire lock for file " . $this->filePath);
                 return false;
             }
             $mutex->setMeta('pid', getmypid());
             return true;
         }
         if ($timestamp >= time() - $this->lifetime) {
             usleep(500000);
             // Sleep 0.5 second
             continue;
         }
         $oldPid = $mutex->meta('pid');
         if (is_numeric($oldPid) && $oldPid != 0 && function_exists('posix_kill')) {
             posix_kill($oldPid, 9);
         }
         if (!$mutex->steal()) {
             eZDebug::writeWarning("Failed to steal lock for file " . $this->filePath . " from PID {$oldPid}");
             return false;
         }
         $mutex->setMeta('pid', getmypid());
         return true;
     }
 }
Example #6
0
 public function Observe($obj, $ltype = OBSERVE_INFO)
 {
     if (is_object($obj) || is_array($obj)) {
         $msg = "<pre>" . print_r($obj, 1) . "</pre>";
     } else {
         $msg = $obj;
     }
     $msg = date("Y-m-d H:i:s:u") . "\t" . getmypid() . "\t" . str_replace(array("\t", "\r", "\n"), array(" ", " ", " "), $msg);
     if ($this->eventtype == null || $this->eventtype & $ltype) {
         // this can occur if the file has been closed due to the php script terminating
         if (!$this->fileIsOpen) {
             $this->Init();
             fwrite($this->fh, "WARN:\t" . date("Y-m-d H:i:s:u") . "\tfilehandle was re-opened due to Observe being called after destruction\r\n");
         }
         switch ($ltype) {
             case OBSERVE_DEBUG:
                 fwrite($this->fh, "DEBUG:\t{$msg}\r\n");
                 break;
             case OBSERVE_QUERY:
                 //fwrite($this->fh, "QUERY:\t" . $this->FormatTrace(debug_backtrace()) . " " . $msg . "\r\n");
                 fwrite($this->fh, "QUERY:\t" . $msg . "\r\n");
                 break;
             case OBSERVE_FATAL:
                 fwrite($this->fh, "FATAL:\t{$msg}\r\n");
                 break;
             case OBSERVE_INFO:
                 fwrite($this->fh, "INFO:\t{$msg}\r\n");
                 break;
             case OBSERVE_WARN:
                 fwrite($this->fh, "WARN:\t{$msg}\r\n");
                 break;
         }
     }
 }
Example #7
0
 /**
  * This will log a message to the Qcodo Log.  Location of the log file is defined in __QCODO_LOG__
  * 
  * By default, this will log a "Normal" level log entry in the "default" Qcodo log file, which is
  * located at __QCODO_LOG__/default.log.txt
  * 
  * Either parameter can be overridden.
  * 
  * @param string $strMessage
  * @param integer $intLogLevel
  * @param string $strLogModule
  * @return void
  */
 public static function Log($strMessage, $intLogLevel = QLogLevel::Normal, $strLogModule = 'default')
 {
     // Cancel out if log level is too low
     if ($intLogLevel > self::$MinimumLogLevel) {
         return;
     }
     // Setup Log Path
     if (!defined('__QCODO_LOG__')) {
         throw new QCallerException('__QCODO_LOG__ must be defined before running QLog::Log');
     }
     // Cancel out if log path is null
     if (!__QCODO_LOG__) {
         return;
     }
     // Create the Log Directory if it does NOT yet exist
     if (!is_dir(__QCODO_LOG__)) {
         QApplication::MakeDirectory(__QCODO_LOG__, 0777);
     }
     // Setup the Line
     $strLine = sprintf("%5s | %s | %s | %s\r\n", getmypid(), QLogLevel::$NameArray[$intLogLevel], QDateTime::Now()->NowToString(QDateTime::FormatIso), self::FormatMessage($strMessage));
     // Open the File for Writing
     $strLogFilePath = __QCODO_LOG__ . '/' . $strLogModule . self::$Extension;
     $objFile = fopen($strLogFilePath, 'a');
     // Write the Line
     fwrite($objFile, $strLine);
     fclose($objFile);
 }
Example #8
0
function killRedis($pid)
{
    if (getmypid() !== $pid) {
        return;
        // don't kill from a forked worker
    }
    $config = file_get_contents(REDIS_CONF);
    if (!preg_match('#^\\s*pidfile\\s+([^\\s]+)#m', $config, $matches)) {
        return;
    }
    $pidFile = TEST_MISC . '/' . $matches[1];
    if (file_exists($pidFile)) {
        $pid = trim(file_get_contents($pidFile));
        posix_kill((int) $pid, 9);
        if (is_file($pidFile)) {
            unlink($pidFile);
        }
    }
    // Remove the redis database
    if (!preg_match('#^\\s*dir\\s+([^\\s]+)#m', $config, $matches)) {
        return;
    }
    $dir = $matches[1];
    if (!preg_match('#^\\s*dbfilename\\s+([^\\s]+)#m', $config, $matches)) {
        return;
    }
    $filename = TEST_MISC . '/' . $dir . '/' . $matches[1];
    if (is_file($filename)) {
        unlink($filename);
    }
}
Example #9
0
function _log($message, $style = 'default')
{
    date_default_timezone_set('Europe/Kiev');
    $output = str_pad(getmypid(), 7, ':') . ' |%| ' . date('Y-m-d H:i:s') . ' :: ' . $message . "\n";
    if ($style == 'title') {
        $output = "\n\n" . $output;
    }
    $args = shell_parameters();
    if (!is_dir(log_path())) {
        mkdir(log_path());
    }
    if ($style == 'red') {
        $log_file = isset($args['log']) ? $args['log'] : log_path() . '/log.txt';
        file_put_contents($log_file, $output, FILE_APPEND);
    }
    if ($style == 'red') {
        //echo "\x07\x07\x07\x07\x07\x07\x07\x07\x07";
        $output = "" . $output . "";
    } elseif ($style == 'yellow') {
        $output = "" . $output . "";
    } elseif ($style == 'green') {
        $output = "" . $output . "";
    } elseif ($style == 'title') {
        $output = "" . $output . "";
    }
    print $output;
}
function purge()
{
    $unix = new unix();
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
    $pidtime = "/etc/artica-postfix/pids/exec.suricata.hourly.purge.time";
    $pid = $unix->get_pid_from_file($pidfile);
    if ($unix->process_exists($pid, basename(__FILE__))) {
        $time = $unix->PROCCESS_TIME_MIN($pid);
        echo "Starting......: " . date("H:i:s") . " [INIT]: Already Artica task running PID {$pid} since {$time}mn\n";
        return;
    }
    @file_put_contents($pidfile, getmypid());
    if (system_is_overloaded()) {
        return;
    }
    $timeExec = $unix->file_time_min($pidtime);
    if ($timeExec < 1440) {
        return;
    }
    @unlink($pidtime);
    @file_put_contents($pidtime, time());
    $q = new postgres_sql();
    $sock = new sockets();
    $SuricataPurge = intval($sock->GET_INFO("SuricataPurge"));
    if ($SuricataPurge == 0) {
        $SuricataPurge = 15;
    }
    $q->QUERY_SQL("DELETE FROM suricata_events WHERE zdate < NOW() - INTERVAL '{$SuricataPurge} days'");
}
Example #11
0
 /**
  * @param string $router
  * @param array $env
  * @return UrlScript
  * @throws \RuntimeException
  */
 public function start($router, $env = array())
 {
     $this->slaughter();
     static $port;
     if ($port === NULL) {
         do {
             $port = rand(8000, 10000);
             if (isset($lock)) {
                 @fclose($lock);
             }
             $lock = fopen(dirname(TEMP_DIR) . '/http-server-' . $port . '.lock', 'w');
         } while (!flock($lock, LOCK_EX | LOCK_NB, $wouldBlock) || $wouldBlock);
     }
     $ini = NULL;
     if (($pid = getmypid()) && ($myprocess = `ps -ww -fp {$pid}`)) {
         $fullArgs = preg_split('~[ \\t]+~', explode("\n", $myprocess)[1], 8)[7];
         if (preg_match('~\\s\\-c\\s(?P<ini>[^ \\t]+)\\s~i', $fullArgs, $m)) {
             $ini = '-c ' . $m['ini'] . ' -n';
         }
     }
     $executable = new PhpExecutableFinder();
     $cmd = sprintf('%s %s -d register_argc_argv=on -t %s -S %s:%d %s', escapeshellcmd($executable->find()), $ini, escapeshellarg(dirname($router)), $ip = '127.0.0.1', $port, escapeshellarg($router));
     if (!is_resource($this->process = proc_open($cmd, self::$spec, $this->pipes, dirname($router), $env))) {
         throw new HttpServerException("Could not execute: `{$cmd}`");
     }
     sleep(1);
     // give him some time to boot up
     $status = proc_get_status($this->process);
     if (!$status['running']) {
         throw new HttpServerException("Failed to start php server: " . stream_get_contents($this->pipes[2]));
     }
     $this->url = new UrlScript('http://' . $ip . ':' . $port);
     return $this->getUrl();
 }
Example #12
0
 /**
  * @param string $destDir
  * @throws Exception on bogus files
  */
 public function extract($destDir)
 {
     $zip = $this->openArchive();
     // First pass: validate but don't save anything to disk.
     // Any errors will trip an exception.
     $this->traverseArchive($zip);
     // Second pass: now that we know we're good, actually extract!
     $tmpDir = $destDir . '.tmp' . getmypid();
     $this->traverseArchive($zip, $tmpDir);
     $zip->close();
     if (file_exists($destDir)) {
         $killDir = $tmpDir . '.old';
         $this->quiet();
         $ok = rename($destDir, $killDir);
         $this->loud();
         if (!$ok) {
             common_log(LOG_ERR, "Could not move old custom theme from {$destDir} to {$killDir}");
             // TRANS: Server exception thrown when saving an uploaded theme after decompressing it fails.
             throw new ServerException(_('Failed saving theme.'));
         }
     } else {
         $killDir = false;
     }
     $this->quiet();
     $ok = rename($tmpDir, $destDir);
     $this->loud();
     if (!$ok) {
         common_log(LOG_ERR, "Could not move saved theme from {$tmpDir} to {$destDir}");
         // TRANS: Server exception thrown when saving an uploaded theme after decompressing it fails.
         throw new ServerException(_('Failed saving theme.'));
     }
     if ($killDir) {
         $this->recursiveRmdir($killDir);
     }
 }
 /**
  *	ログを出力する
  *
  *	@access	public
  *	@param	int		$level		ログレベル(LOG_DEBUG, LOG_NOTICE...)
  *	@param	string	$message	ログメッセージ(+引数)
  */
 function log($level, $message)
 {
     if ($this->fp == null) {
         return;
     }
     $prefix = strftime('%Y/%m/%d %H:%M:%S ') . $this->ident;
     if ($this->option & LOG_PID) {
         $prefix .= sprintf('[%d]', getmypid());
     }
     $prefix .= sprintf('(%s): ', $this->_getLogLevelName($level));
     if ($this->option & (LOG_FUNCTION | LOG_POS)) {
         $tmp = "";
         $bt = $this->_getBacktrace();
         if ($bt && $this->option & LOG_FUNCTION && $bt['function']) {
             $tmp .= $bt['function'];
         }
         if ($bt && $this->option & LOG_POS && $bt['pos']) {
             $tmp .= $tmp ? sprintf('(%s)', $bt['pos']) : $bt['pos'];
         }
         if ($tmp) {
             $prefix .= $tmp . ": ";
         }
     }
     fwrite($this->fp, $prefix . $message . "\n");
     return $prefix . $message;
 }
Example #14
0
 function testUploadFile()
 {
     global $URL;
     print "starting DupUploadTest\n";
     for ($i = 0; $i < 2; $i++) {
         $loggedIn = $this->mybrowser->get($URL);
         $this->assertTrue($this->myassertText($loggedIn, '/Upload/'));
         $this->assertTrue($this->myassertText($loggedIn, '/From File/'));
         $page = $this->mybrowser->clickLink('From File');
         $this->assertTrue($this->myassertText($page, '/Upload a New File/'));
         $this->assertTrue($this->myassertText($page, '/Select the file to upload:/'));
         /* select Testing folder, filename based on pid */
         $id = $this->getFolderId('Basic-Testing', $page, 'folder');
         $this->assertTrue($this->mybrowser->setField('folder', $id));
         $this->assertTrue($this->mybrowser->setField('getfile', '/home/fosstester/licenses/Affero-v1.0'));
         $desc = 'File Affero-v1.0 uploaded by test UploadFileTest into Testing folder';
         $this->assertTrue($this->mybrowser->setField('description', "{$desc}"));
         $id = getmypid();
         $upload_name = 'TestUploadFile-' . "{$id}";
         $this->assertTrue($this->mybrowser->setField('name', $upload_name));
         /* we won't select any agents this time' */
         $page = $this->mybrowser->clickSubmit('Upload');
         $this->assertTrue($page);
         /* On the second try, we SHOULD see Upload added to job queue */
         if ($i == 1) {
             $this->assertTrue($this->myassertText($page, "/The file {$upload_name} has been uploaded/"), "FAIL! A Duplicate Upload was NOT created!\n" . "The phrase, The file {$upload_name} has been uploaded was NOT seen\n");
         } else {
             $this->assertFalse($this->myassertText($page, "/Upload failed/"), "FAIL! Upload Failed?\nPhrase 'Upload failed found\n");
         }
         //print "*********** Page after upload **************\n$page\n";
     }
 }
 /**
  * Return an instance of the Mandrill class.
  *
  * @return Mandrill Instance.
  */
 public static function getInstance()
 {
     // Detect when the PID of the current process has changed (from a fork, etc)
     // and force a reconnect to redis.
     $pid = getmypid();
     if (self::$pid !== $pid) {
         self::$mandrill = null;
         self::$pid = $pid;
     }
     if (!is_null(self::$mandrill)) {
         return self::$mandrill;
     }
     foreach (array_keys(self::$config) as $param) {
         if (Environment::get('mandrill.' . $param)) {
             self::$config[$param] = Environment::get('mandrill.' . $param);
         }
     }
     if (!self::$config['apikey']) {
         throw new Exception('missing Mandrill Configuration', 500);
     }
     try {
         self::$mandrill = new Mandrill(self::$config['apikey']);
     } catch (Exception $e) {
         return null;
     }
     return self::$mandrill;
 }
Example #16
0
 static function create($filename, $directory = false, $data = false, $atomic = false)
 {
     $filepath = $filename;
     if ($directory) {
         if (!file_exists($directory)) {
             eZDir::mkdir($directory, false, true);
             //                 eZDebugSetting::writeNotice( 'ezfile-create', "Created directory $directory", 'eZFile::create' );
         }
         $filepath = $directory . '/' . $filename;
     }
     // If atomic creation is needed we will use a temporary
     // file when writing the data, then rename it to the correct path.
     if ($atomic) {
         $realpath = $filepath;
         $dirname = dirname($filepath);
         if (strlen($dirname) != 0) {
             $dirname .= "/";
         }
         $filepath = $dirname . "ezfile-tmp." . md5($filepath . getmypid() . mt_rand());
     }
     $file = fopen($filepath, 'wb');
     if ($file) {
         //             eZDebugSetting::writeNotice( 'ezfile-create', "Created file $filepath", 'eZFile::create' );
         if ($data) {
             fwrite($file, $data);
         }
         fclose($file);
         if ($atomic) {
             eZFile::rename($filepath, $realpath);
         }
         return true;
     }
     //         eZDebugSetting::writeNotice( 'ezfile-create', "Failed creating file $filepath", 'eZFile::create' );
     return false;
 }
Example #17
0
 /**
  * Constructor.
  * 
  * Create new JsHttpRequest backend object and attach it
  * to script output buffer. As a result - script will always return
  * correct JavaScript code, even in case of fatal errors.
  */
 function JsHttpRequest($enc)
 {
     // QUERY_STRING is in form: PHPSESSID=<sid>&a=aaa&b=bbb&<id>
     // where <id> is request ID, <sid> - session ID (if present),
     // PHPSESSID - session parameter name (by default = "PHPSESSID").
     // Parse QUERY_STRING wrapper format.
     if (preg_match('/^(.*)(?:&|^)JsHttpRequest=(\\d+)-([^&]+)((?:&|$).*)$/s', $_SERVER['QUERY_STRING'], $m)) {
         $this->ID = $m[2];
         $this->LOADER = strtolower($m[3]);
         $_SERVER['QUERY_STRING'] = $m[1] . $m[4];
         unset($_GET['JsHttpRequest']);
         unset($_REQUEST['JsHttpRequest']);
     } else {
         $this->ID = 0;
         $this->LOADER = 'unknown';
     }
     // Start OB handling early.
     $this->_uniqHash = md5(microtime() . getmypid());
     ini_set('error_prepend_string', ini_get('error_prepend_string') . $this->_uniqHash);
     ini_set('error_append_string', ini_get('error_append_string') . $this->_uniqHash);
     ob_start(array(&$this, "_obHandler"));
     // Set up encoding.
     $this->setEncoding($enc);
     // Check if headers are already sent (see Content-Type library usage).
     // If true - generate debug message and exit.
     $file = $line = null;
     if (headers_sent($file, $line)) {
         trigger_error("HTTP headers are already sent" . ($line !== null ? " in {$file} on line {$line}" : "") . ". " . "Possibly you have extra spaces (or newlines) before first line of the script or any library. " . "Please note that Subsys_JsHttpRequest uses its own Content-Type header and fails if " . "this header cannot be set. See header() function documentation for details", E_USER_ERROR);
         exit;
     }
 }
Example #18
0
 /**
  * Return an instance of the Resque_Redis class instantiated for Resque.
  *
  * @return Resque_Redis Instance of Resque_Redis.
  */
 public static function redis()
 {
     // Detect when the PID of the current process has changed (from a fork, etc)
     // and force a reconnect to redis.
     $pid = getmypid();
     if (self::$pid !== $pid) {
         self::$redis = null;
         self::$pid = $pid;
     }
     if (!is_null(self::$redis)) {
         return self::$redis;
     }
     $server = self::$redisServer;
     if (empty($server)) {
         $server = 'localhost:6379';
     }
     if (is_array($server)) {
         require_once dirname(__FILE__) . '/Resque/RedisCluster.php';
         self::$redis = new Resque_RedisCluster($server);
     } else {
         if (strpos($server, 'unix:') === false) {
             list($host, $port) = explode(':', $server);
         } else {
             $host = $server;
             $port = null;
         }
         require_once dirname(__FILE__) . '/Resque/Redis.php';
         $redisInstance = new Resque_Redis($host, $port);
         $redisInstance->prefix(self::$namespace);
         self::$redis = $redisInstance;
     }
     self::$redis->select(self::$redisDatabase);
     return self::$redis;
 }
Example #19
0
 /**
  * Get Priority
  *
  * @param int $pid               If not specified, the pid of the current process is used.
  * @param int $processIdentifier One of PRIO_PGRP, PRIO_USER or PRIO_PROCESS.
  *
  * @return int The priority of the process or FALSE on error. A lower numerical value causes more favorable scheduling.
  */
 public function getPriority($pid = null, $processIdentifier = PRIO_PROCESS)
 {
     if (is_null($pid)) {
         $pid = getmypid();
     }
     return pcntl_getpriority($pid, $processIdentifier);
 }
Example #20
0
function applyAcls()
{
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
    $unix = new unix();
    if ($unix->process_exists(@file_get_contents("{$pidfile}"))) {
        echo "Already process exists\n";
        return;
    }
    @file_put_contents($pidfile, getmypid());
    $sql = "SELECT `directory` FROM acl_directories";
    $q = new mysql();
    $results = $q->QUERY_SQL($sql, 'artica_backup');
    if (!$q->ok) {
        if ($GLOBALS["VERBOSE"]) {
            echo $q->mysql_error . "\n";
            return;
        }
    }
    $count = mysql_num_rows($results);
    echo "Starting......: acls {$count} items\n";
    if ($count == 0) {
        return;
    }
    while ($ligne = mysql_fetch_array($results, MYSQL_ASSOC)) {
        ApplySingleAcls($ligne["directory"]);
    }
}
Example #21
0
 /**
  * 多进程处理任务
  * @param callback  $mission_func 子进程要进行的任务函数
  */
 public function dealMission($mission_func)
 {
     $this->_mission_func = $mission_func;
     for ($i = 0; $i < $this->_process_num; $i++) {
         $pid[] = pcntl_fork();
         if ($pid[$i] == 0) {
             //等于0时,是子进程
             $this->_func_obj->{$mission_func}($i + 1);
             //结束当前子进程,以防止生成僵尸进程
             if (function_exists("posix_kill")) {
                 posix_kill(getmypid(), SIGTERM);
             } else {
                 system('kill -9' . getmypid());
             }
             exit;
         } else {
             if ($pid > 0) {
                 //大于0时,是父进程,并且pid是产生的子进程的PID
                 //TODO 可以记录下子进程的pid,用pcntl_wait_pid()去等待程序并结束
                 pcntl_wait($status);
             } else {
                 throw new Exception('fork fail');
             }
         }
     }
 }
Example #22
0
 /**
  * Generate a random ID.
  */
 public function generate()
 {
     $pid = function_exists('zend_thread_id') ? zend_thread_id() : getmypid();
     /* Base64 can have /, +, and = characters. Restrict to URL-safe
      * characters. */
     return str_replace(array('/', '+', '='), array('-', '_', ''), base64_encode(pack('II', mt_rand(), crc32(php_uname('n'))) . pack('H*', uniqid() . sprintf('%04s', dechex($pid)))));
 }
Example #23
0
 protected function newLogId($plan = 'c')
 {
     $dt = microtime(true);
     list($s, $ms) = explode('.', $dt);
     $s = $s - 1435680000;
     //18446744073709551616
     //17------------------  18组服务器
     //--1234567890--------  时间戳
     //------------sss-----  毫秒
     //---------------12345  进程
     switch ($plan) {
         case 'a':
             //plan-a 180组服务器,30几年后溢出,(每个请求需要一个进程处理至少1个毫秒,)
             $this->plan = 'a';
             return sprintf("%03d%09d%03d%05d", \Sooh\Base\Ini::getInstance()->get('ServerId', 0), $s, substr($ms, 0, 3), getmypid());
         case 'b':
             //plan-b 18组服务器, 300年后溢出, (每个请求需要一个进程处理至少1个毫秒,)
             $this->plan = 'b';
             return sprintf("%02d%010d%03d%05d", \Sooh\Base\Ini::getInstance()->get('ServerId', 0), $s, substr($ms, 0, 3), getmypid());
         case 'c':
             //plan-c 18组服务器, 30年后溢出,  (每个请求需要一个进程处理至少0.1个毫秒,)
             $this->plan = 'c';
             return sprintf("%02d%09d%04d%05d", \Sooh\Base\Ini::getInstance()->get('ServerId', 0), $s, substr($ms, 0, 4), getmypid());
         default:
             throw new \Sooh\Base\ErrException('unknown support log-guid-generate');
     }
 }
Example #24
0
/**
 * performs a logging statement (verbose mode)
 * @param $msg string output to display
 * @return void
 */
function writelog($msg)
{
    if (defined('SNAPTEST_CLI_INTERFACE') && defined('SNAPTEST_VERBOSE_MODE') && SNAPTEST_VERBOSE_MODE) {
        $msg = "\n" . '[' . getmypid() . '] ' . date('Y-m-d H:i:s - ', time()) . $msg;
        file_put_contents(SNAPTEST_LOGFILE, $msg, FILE_APPEND);
    }
}
 /**
  * Inserts customer items.
  */
 public function migrate()
 {
     $this->msg('Adding customer performance data', 0);
     $context = $this->getContext();
     $customerManager = \Aimeos\MShop\Customer\Manager\Factory::createManager($context);
     $customerItem = $customerManager->createItem();
     $customerItem->setCode('demo-test');
     $customerItem->setLabel('Test demo unitperf user');
     $customerItem->setPassword(sha1(microtime(true) . getmypid() . rand()));
     $customerItem->setStatus(1);
     $addrItem = $customerItem->getPaymentAddress();
     $addrItem->setCompany('Test company');
     $addrItem->setVatID('DE999999999');
     $addrItem->setSalutation('mr');
     $addrItem->setFirstname('Testdemo');
     $addrItem->setLastname('Perfuser');
     $addrItem->setAddress1('Test street');
     $addrItem->setAddress2('1');
     $addrItem->setPostal('1000');
     $addrItem->setCity('Test city');
     $addrItem->setLanguageId('en');
     $addrItem->setCountryId('DE');
     $addrItem->setEmail('me@localhost');
     $customerManager->saveItem($customerItem);
     $this->status('done');
 }
Example #26
0
 public static function getLog()
 {
     if (!self::$log) {
         $path = PhabricatorEnv::getEnvConfig('log.ssh.path');
         $format = PhabricatorEnv::getEnvConfig('log.ssh.format');
         $format = nonempty($format, "[%D]\t%p\t%h\t%r\t%s\t%S\t%u\t%C\t%U\t%c\t%T\t%i\t%o");
         // NOTE: Path may be null. We still create the log, it just won't write
         // anywhere.
         $data = array('D' => date('r'), 'h' => php_uname('n'), 'p' => getmypid(), 'e' => time());
         $sudo_user = PhabricatorEnv::getEnvConfig('phd.user');
         if (strlen($sudo_user)) {
             $data['S'] = $sudo_user;
         }
         if (function_exists('posix_geteuid')) {
             $system_uid = posix_geteuid();
             $system_info = posix_getpwuid($system_uid);
             $data['s'] = idx($system_info, 'name');
         }
         $client = getenv('SSH_CLIENT');
         if (strlen($client)) {
             $remote_address = head(explode(' ', $client));
             $data['r'] = $remote_address;
         }
         $log = id(new PhutilDeferredLog($path, $format))->setFailQuietly(true)->setData($data);
         self::$log = $log;
     }
     return self::$log;
 }
Example #27
0
 /**
  * Uploads a XLS file with all attribute texts.
  *
  * @param \stdClass $params Object containing the properties
  */
 public function uploadFile(\stdClass $params)
 {
     $this->checkParams($params, array('site'));
     $this->setLocale($params->site);
     if (($fileinfo = reset($_FILES)) === false) {
         throw new \Aimeos\Controller\ExtJS\Exception('No file was uploaded');
     }
     $config = $this->getContext()->getConfig();
     /** controller/extjs/attribute/import/text/standard/enablecheck
      * Enables checking uploaded files if they are valid and not part of an attack
      *
      * This configuration option is for unit testing only! Please don't disable
      * the checks for uploaded files in production environments as this
      * would give attackers the possibility to infiltrate your installation!
      *
      * @param boolean True to enable, false to disable
      * @since 2014.03
      * @category Developer
      */
     if ($config->get('controller/extjs/attribute/import/text/standard/enablecheck', true)) {
         $this->checkFileUpload($fileinfo['tmp_name'], $fileinfo['error']);
     }
     $fileext = pathinfo($fileinfo['name'], PATHINFO_EXTENSION);
     $dest = md5($fileinfo['name'] . time() . getmypid()) . '.' . $fileext;
     $fs = $this->getContext()->getFilesystemManager()->get('fs-admin');
     $fs->writef($dest, $fileinfo['tmp_name']);
     $result = (object) array('site' => $params->site, 'items' => array((object) array('job.label' => 'Attribute text import: ' . $fileinfo['name'], 'job.method' => 'Attribute_Import_Text.importFile', 'job.parameter' => array('site' => $params->site, 'items' => $dest), 'job.status' => 1)));
     $jobController = \Aimeos\Controller\ExtJS\Admin\Job\Factory::createController($this->getContext());
     $jobController->saveItems($result);
     return array('items' => $dest, 'success' => true);
 }
 /**
  * Generates a URI based on a serial stored in the database.
  *
  * @access public
  * @author Jerome Bogaerts, <*****@*****.**>
  * @return string
  * @throws common_UriProviderException
  */
 public function provide()
 {
     $returnValue = (string) '';
     $modelUri = common_ext_NamespaceManager::singleton()->getLocalNamespace()->getUri();
     $uri = $modelUri . uniqid('i') . getmypid() . bin2hex(openssl_random_pseudo_bytes(8));
     return (string) $uri;
 }
function build()
{
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
    $unix = new unix();
    $sock = new sockets();
    $pid = $unix->get_pid_from_file($pidfile);
    if ($unix->process_exists($pid, basename(__FILE__))) {
        die;
    }
    $php = $unix->LOCATE_PHP5_BIN();
    @file_put_contents($pidfile, getmypid());
    progress("{get_system_informations}", 30);
    support_step1();
    progress("{APP_UFDBGUARD}", 40);
    $EnableUfdbGuard = intval($sock->EnableUfdbGuard());
    if ($EnableUfdbGuard == 1) {
        $ufdbguardd = $unix->find_program("ufdbguardd");
        if (is_file($ufdbguardd)) {
            shell_exec("{$php} /usr/share/artica-postfix/exec.squidguard.php --build --force --verbose >/usr/share/artica-postfix/ressources/support/build-ufdbguard.log 2>&1");
        }
    }
    progress("{get_all_logs}", 50);
    support_step2();
    progress("{get_all_logs}", 70);
    export_tables();
    progress("{compressing_package}", 90);
    support_step3();
    progress("{success}", 100);
}
Example #30
0
function xstart()
{
    $unix = new unix();
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . ".pid";
    $pidtime = "/etc/artica-postfix/pids/" . basename(__FILE__) . ".time";
    $pid = $unix->get_pid_from_file($pidfile);
    if ($unix->process_exists($pid, basename(__FILE__))) {
        return;
    }
    $TimeExec = $unix->file_time_min($pidtime);
    if ($TimeExec < 360) {
        return;
    }
    @unlink($pidtime);
    @file_put_contents($pidtime, time());
    @file_put_contents($pidfile, getmypid());
    $php5 = $unix->LOCATE_PHP5_BIN();
    $q = new mysql_squid_builder();
    $q->CreateCategoryUrisTable("malware");
    $COUNT1 = $q->COUNT_ROWS("categoryuris_malware");
    vxvault();
    malwareurls_joxeankoret();
    clean_mx_de();
    $COUNT2 = $q->COUNT_ROWS("categoryuris_malware");
    $URLS_ADDED = $COUNT2 - $COUNT1;
    if ($URLS_ADDED > 0) {
        system("{$php5} /usr/share/artica-postfix/exec.squidguard.php --compile-category malware");
        squid_admin_mysql(2, "{$URLS_ADDED} malware URLs added", null, __FILE__, __LINE__);
    }
}