sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function read($session_id)
{
foreach ($this->getHandlers() as $handler) {
if ($data = $handler->read($session_id)) {
return $data;
}
}
return '';
} | @param string $session_id
@return string | entailment |
public static function init($key = null)
{
$instance = Injector::inst()->get(__CLASS__);
if (empty($key)) {
user_error(
'HybridSession::init() was not given a $key. Disabling cookie-based storage',
E_USER_WARNING
);
} else {
$instance->setKey($key);
}
session_set_save_handler($instance, true);
self::$enabled = true;
} | Register the session handler as the default
@param string $key Desired session key | entailment |
public function boot()
{
if ($this->isLumen() === false) {
$this->publishes([
__DIR__ . '/../../config/hashids.php' => config_path('hashids.php'),
]);
// Add 'Assets' facade alias
AliasLoader::getInstance()->alias('Hashids', 'Torann\Hashids\Facade');
}
} | Bootstrap the application events.
@return void | entailment |
public function register()
{
$this->app->bind('hashids', function ($app) {
$config = $app->config->get('hashids');
return new Hashids(
array_get($config, 'salt'),
array_get($config, 'length', 0),
array_get($config, 'alphabet')
);
});
} | Register the service provider.
@return void | entailment |
public function setIpinfoConfig($token = null, $debug = false)
{
$this->ipinfo->__construct(compact('token', 'debug'));
return $this;
} | Set token for Ipinfo if exists.
@access public
@param string $token (default: null)
@param bool $debug (default: false) | entailment |
public function getInfo()
{
$this->hostIpinfo();
$this->clientIpinfo();
$this->getServerInfoSoftware();
$this->serverInfoHardware();
$this->uptime();
$this->databaseInfo();
return $this->results;
} | Get all info.
@access public
@return array | entailment |
protected function databaseInfo()
{
$pdo = $this->database->getConnection()->getPdo();
$version = $this->ifExists($pdo->getAttribute(PDO::ATTR_SERVER_VERSION));
$driver = $this->ifExists($pdo->getAttribute(PDO::ATTR_DRIVER_NAME));
$driver = $this->ifExists((! empty($this->databases[$driver]) ? $this->databases[$driver] : null));
$this->results['database'] = compact('driver', 'version');
return $this;
} | Get database info.
@access protected | entailment |
protected function hostIpinfo()
{
$ipinfo = $this->ipinfo->getYourOwnIpDetails()->getProperties();
$this->results['host'] = $ipinfo;
return $this;
} | Parse host info.
@access protected | entailment |
protected function clientIpinfo()
{
$ip = $this->request->getClientIp();
$ipinfo = $this->ipinfo->getFullIpDetails($ip)->getProperties();
$this->results['client'] = $ipinfo;
return $this;
} | Parse client info.
@access protected | entailment |
protected function getCPUString($cpus = [])
{
if (empty($cpus)) {
return '';
}
$cpuStrings = [];
foreach ($cpus as $cpu) {
$model = $cpu['Model'];
$model = str_replace('(R)', '®', $model);
$model = str_replace('(TM)', '™', $model);
array_push($cpuStrings, $model);
}
$cpuStrings = array_unique($cpuStrings);
return trim(implode(' / ', $cpuStrings));
} | Get CPU string.
@access protected
@param array $cpus (default: array())
@return string | entailment |
protected function getDiskSpace($mounts = [])
{
$total = $free = 0;
if (empty($mounts)) {
return compact('total', 'free');
}
foreach ($mounts as $mount) {
$total += $mount['size'];
$free += $mount['free'];
}
return compact('total', 'free');
} | Get disk space string.
@access protected
@param array $mounts (default: array())
@return string | entailment |
protected function serverInfoSoftware()
{
$linfo = $this->linfo->getParser();
$os = $this->ifExists($linfo->getOS());
$kernel = $this->ifExists($linfo->getKernel());
$arc = $this->ifExists($linfo->getCPUArchitecture());
$webserver = $this->ifExists($linfo->getWebService());
$php = $this->ifExists($linfo->getPhpVersion());
$distro = '';
if (method_exists($linfo, 'getDistro')) {
$distro = $this->getDistroString(
$this->ifExists($linfo->getDistro())
);
}
$this->results['server']['software'] = compact(
'os', 'distro', 'kernel', 'arc', 'webserver', 'php'
);
return $this;
} | Parse server software.
@access protected | entailment |
protected function serverInfoHardware()
{
$linfo = $this->linfo->getParser();
$CPUs = $this->ifExists($linfo->getCPU());
$cpu = $this->getCPUString($CPUs);
$cpu_count = count($CPUs);
$model = $this->ifExists($linfo->getModel());
$virtualization = $this->getVirtualizationString(
$this->ifExists($linfo->getVirtualization())
);
$memory = $this->ifExists($linfo->getRam());
$ram = [
'total' => (int) $this->ifExists($memory['total']),
'free' => (int) $this->ifExists($memory['free']),
];
$swap = [
'total' => (int) $this->ifExists($memory['swapTotal']),
'free' => (int) $this->ifExists($memory['swapFree']),
];
$disk = $this->getDiskSpace($linfo->getMounts());
$this->results['server']['hardware'] = compact(
'cpu', 'cpu_count', 'model', 'virtualization', 'ram', 'swap', 'disk'
);
return $this;
} | Parse server hardware.
@access protected | entailment |
protected function uptime()
{
$linfo = $this->linfo->getParser();
$uptime = $booted_at = null;
$systemUptime = $this->ifExists($linfo->getUpTime());
if (! empty($systemUptime['text'])) {
$uptime = $systemUptime['text'];
}
if (! empty($systemUptime['bootedTimestamp'])) {
$booted_at = date('Y-m-d H:i:s', $systemUptime['bootedTimestamp']);
}
$this->results['server']['uptime'] = compact(
'uptime', 'booted_at'
);
return $this;
} | Parse uptime.
@access protected | entailment |
protected function resolveDispositionHeaderFilename($filename)
{
$userAgent = $this->request->headers->get('User-Agent');
if (preg_match('#MSIE|Safari|Konqueror#', $userAgent)) {
return "filename=".rawurlencode($filename);
}
return "filename*=UTF-8''".rawurlencode($filename);
} | Algorithm inspired by phpBB3 | entailment |
protected function getCrypto($session_id)
{
$key = $this->getKey();
if (!$key) {
return null;
}
if (!$this->crypto || $this->crypto->getSalt() != $session_id) {
$this->crypto = Injector::inst()->create(CryptoHandler::class, $key, $session_id);
}
return $this->crypto;
} | Get the cryptography store for the specified session
@param string $session_id
@return HybridSessionStore_Crypto | entailment |
public function encrypt($cleartext)
{
$iv = mcrypt_create_iv($this->ivSize, MCRYPT_DEV_URANDOM);
$enc = mcrypt_encrypt(
MCRYPT_RIJNDAEL_256,
$this->saltedKey,
$cleartext,
MCRYPT_MODE_CBC,
$iv
);
$hash = hash_hmac('sha256', $enc, $this->saltedKey);
return base64_encode($iv.$hash.$enc);
} | Encrypt and then sign some cleartext
@param $cleartext - The cleartext to encrypt and sign
@return string - The encrypted-and-signed message as base64 ASCII. | entailment |
public function decrypt($data)
{
$data = base64_decode($data);
$iv = substr($data, 0, $this->ivSize);
$hash = substr($data, $this->ivSize, 64);
$enc = substr($data, $this->ivSize + 64);
$cleartext = rtrim(mcrypt_decrypt(
MCRYPT_RIJNDAEL_256,
$this->saltedKey,
$enc,
MCRYPT_MODE_CBC,
$iv
), "\x00");
// Needs to be after decrypt so it always runs, to avoid timing attack
$gen_hash = hash_hmac('sha256', $enc, $this->saltedKey);
if ($gen_hash == $hash) {
return $cleartext;
}
return false;
} | Check the signature on an encrypted-and-signed message, and if valid
decrypt the content
@param $data - The encrypted-and-signed message as base64 ASCII
@return bool|string - The decrypted cleartext or false if signature failed | entailment |
public static function authenticateWithToken($token) {
$pkeyResource = openssl_pkey_new(array(
"digest_alg" => "sha256",
"private_key_bits" => 2048
));
openssl_pkey_export($pkeyResource, $generatedPrivateKey);
$pkeyResourceDetails = openssl_pkey_get_details($pkeyResource);
$generatedPublicKey = $pkeyResourceDetails["key"];
$requestResult = Request::post("/g_business/v1/authentication_keys", array(
"body" => array(
"public_key" => $generatedPublicKey,
"token" => $token
)
));
self::$privateKey = $generatedPrivateKey;
self::$publicKey = $generatedPublicKey;
self::$keyId = $requestResult->key_id;
$returnClass = new ApiAuthentication();
$returnClass->privateKey = $generatedPrivateKey;
$returnClass->publicKey = $generatedPublicKey;
$returnClass->keyId = $requestResult->key_id;
return $returnClass;
} | Generate new keys and authenticate with token
@param string $token | entailment |
public static function setEnv($value) {
self::$env = $value;
if ($value == "production") {
self::$authservicesUrl = "https://authservices.satispay.com";
} else {
self::$authservicesUrl = "https://".$value.".authservices.satispay.com";
}
} | Set env
@param string $value | entailment |
public static function get($path, $options = array()) {
$requestOptions = array(
"path" => $path,
"method" => "GET"
);
if (!empty($options["sign"])) {
$requestOptions["sign"] = $options["sign"];
}
return self::request($requestOptions);
} | GET request
@param string $path
@param array $options | entailment |
public static function post($path, $options = array()) {
$requestOptions = array(
"path" => $path,
"method" => "POST",
"body" => $options["body"]
);
if (!empty($options["sign"])) {
$requestOptions["sign"] = $options["sign"];
}
return self::request($requestOptions);
} | POST request
@param string $path
@param array $options | entailment |
public static function put($path, $options = array()) {
$requestOptions = array(
"path" => $path,
"method" => "PUT",
"body" => $options["body"]
);
if (!empty($options["sign"])) {
$requestOptions["sign"] = $options["sign"];
}
return self::request($requestOptions);
} | PUT request
@param string $path
@param array $options | entailment |
public static function patch($path, $options = array()) {
$requestOptions = array(
"path" => $path,
"method" => "PATCH",
"body" => $options["body"]
);
if (!empty($options["sign"])) {
$requestOptions["sign"] = $options["sign"];
}
return self::request($requestOptions);
} | PATCH request
@param string $path
@param array $options | entailment |
private static function signRequest($options = array()) {
$headers = array();
$authorizationHeader = "";
$privateKey = Api::getPrivateKey();
$keyId = Api::getKeyId();
$securityBearer = Api::getSecurityBearer();
if (!empty($privateKey) && !empty($keyId)) {
$date = date("r");
array_push($headers, "Date: ".$date);
$signature = "(request-target): ".strtolower($options["method"])." ".$options["path"]."\n";
$signature .= "host: ".str_replace("https://", "", Api::getAuthservicesUrl())."\n";
if (!empty($options["body"])) {
$digest = base64_encode(hash("sha256", $options["body"], true));
array_push($headers, "Digest: SHA-256=".$digest);
$signature .= "content-type: application/json\n";
$signature .= "content-length: ".strlen($options["body"])."\n";
$signature .= "digest: SHA-256=$digest\n";
}
$signature .= "date: $date";
openssl_sign($signature, $signedSignature, $privateKey, OPENSSL_ALGO_SHA256);
$base64SignedSignature = base64_encode($signedSignature);
$signatureHeaders = "(request-target) host date";
if (!empty($options["body"])) {
$signatureHeaders = "(request-target) host content-type content-length digest date";
}
$authorizationHeader = "Signature keyId=\"$keyId\", algorithm=\"rsa-sha256\", headers=\"$signatureHeaders\", signature=\"$base64SignedSignature\"";
} else if (!empty($securityBearer)) {
$authorizationHeader = "Bearer $securityBearer";
}
if (!empty($authorizationHeader)) {
array_push($headers, "Authorization: $authorizationHeader");
}
return array(
"headers" => $headers
);
} | Sign request
@param array $options | entailment |
private static function request($options = array()) {
$body = "";
$headers = array(
"Accept: application/json",
"User-Agent: ".self::$userAgentName."/".Api::getVersion()
);
$method = "GET";
if (!empty($options["method"])) {
$method = $options["method"];
}
if (!empty($options["body"])) {
array_push($headers, "Content-Type: application/json");
$body = json_encode($options["body"]);
array_push($headers, "Content-Length: ".strlen($body));
}
$sign = false;
if (!empty($options["sign"])) {
$sign = $options["sign"];
}
if ($sign) {
$signResult = self::signRequest(array(
"body" => $body,
"method" => $method,
"path" => $options["path"]
));
$headers = array_merge($headers, $signResult["headers"]);
}
$curlResult = self::curl(array(
"url" => Api::getAuthservicesUrl().$options["path"],
"method" => $method,
"body" => $body,
"headers" => $headers
));
if (!empty($curlResult["errorCode"]) && !empty($curlResult["errorMessage"])) {
throw new \Exception($curlResult["errorMessage"], $curlResult["errorCode"]);
}
$isResponseOk = true;
if ($curlResult["status"] < 200 || $curlResult["status"] > 299) {
$isResponseOk = false;
}
$responseData = json_decode($curlResult["body"]);
if (!$isResponseOk) {
if (!empty($responseData->message) && !empty($responseData->code) && !empty($responseData->wlt)) {
throw new \Exception($responseData->message.", request id: ".$responseData->wlt, $responseData->code);
} else {
throw new \Exception("HTTP status is not 2xx");
}
}
return $responseData;
} | Execute request
@param array $options | entailment |
private static function curl($options = array()) {
$curlOptions = array();
$curl = curl_init();
$curlOptions[CURLOPT_URL] = $options["url"];
$curlOptions[CURLOPT_RETURNTRANSFER] = true;
if ($options["method"] != "GET") {
if ($options["method"] != "POST") {
$curlOptions[CURLOPT_CUSTOMREQUEST] = $options["method"];
}
$curlOptions[CURLOPT_POSTFIELDS] = $options["body"];
$curlOptions[CURLOPT_POST] = true;
} else {
$curlOptions[CURLOPT_HTTPGET] = true;
}
if (Api::getEnv() == "test") {
$curlOptions[CURLOPT_VERBOSE] = true;
$curlOptions[CURLOPT_SSL_VERIFYHOST] = false;
$curlOptions[CURLOPT_SSL_VERIFYPEER] = false;
}
$curlOptions[CURLOPT_HTTPHEADER] = $options["headers"];
curl_setopt_array($curl, $curlOptions);
$responseJson = curl_exec($curl);
$responseStatus = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$curlErrorCode = curl_errno($curl);
$curlErrorMessage = curl_error($curl);
curl_close($curl);
return array(
"body" => $responseJson,
"status" => $responseStatus,
"errorCode" => $curlErrorCode,
"errorMessage" => $curlErrorMessage
);
} | Curl request
@param array $options | entailment |
public function register()
{
$this->app->singleton('larinfo', function ($app) {
$larinfo = new Larinfo(new Ipinfo(), new Request(), new Linfo(), new Manager());
$token = config('services.ipinfo.token');
if (! empty($token)) {
return $larinfo->setIpinfoConfig($token);
}
$larinfo->setDatabaseConfig(config('database.connections.'.config('database.default')));
return $larinfo;
});
} | Register the application services. | entailment |
protected function url($path, array $parameters = null)
{
$query = [
'client_id' => $this->client_key,
'redirect_uri' => $this->redirect_uri,
'response_type' => 'code'
];
if ($parameters)
$query = array_merge($query, $parameters);
$query = http_build_query($query);
return sprintf('%s%s?%s', self::API_HOST, $path, $query);
} | Make URLs for user browser navigation.
@param string $path
@param array $parameters
@return string | entailment |
public function post($path, array $parameters, $authorization = false)
{
$query = [];
if ($authorization)
$query = [
'client_id' => $this->client_key,
'client_secret' => $this->client_secret,
'redirect_uri' => $this->redirect_uri,
'grant_type' => 'authorization_code',
];
if ($parameters)
$query = array_merge($query, $parameters);
try {
$response = $this->client->request('POST', $path, [
'form_params' => $query,
'timeout' => self::TIMEOUT
]);
return $this->toArray($response);
}
catch (ClientException $e) {
return $this->toArray($e->getResponse());
}
} | Make POST calls to the API
@param string $path
@param boolean $authorization [Use access token query params]
@param array $parameters [Optional query parameters]
@return Array | entailment |
public function get($path, array $parameters)
{
try {
$response = $this->client->request('GET', $path, [
'query' => $parameters
]);
return $this->toArray($response);
}
catch (ClientException $e) {
return $this->toArray($e->getResponse());
}
} | Make GET calls to the API
@param string $path
@param array $parameters [Query parameters]
@return Array | entailment |
public function handle(Dispatcher $events, ManagerRegistry $registry)
{
$class = $this->argument('model');
$em = $registry->getManagerForClass($class);
$repository = $em->getRepository($class);
if (!$repository instanceof SearchableRepository) {
$repository = new SearchableRepository(
$em,
$em->getClassMetadata($class),
$this->getLaravel()->make(EngineManager::class)
);
}
$events->listen(ModelsImported::class, function ($event) use ($class) {
$this->line(sprintf(
'<comment>Imported %d [%s] models up to ID: %s</comment>',
$event->models->count(),
$class,
$event->models->last()->getKey()
));
});
$repository->makeAllSearchable();
$events->forget(ModelsImported::class);
$this->info('All [' . $class . '] records have been imported.');
} | Execute the console command.
@param \Illuminate\Contracts\Events\Dispatcher $events
@param ManagerRegistry $registry | entailment |
public function run( )
{
@set_time_limit( 600 );
\System::loadLanguageFile('tl_backupdb'); // Modultexte laden
$user = \BackendUser::getInstance(); // Backend-User
$filename = \Environment::get('host'); // Dateiname = Domainname
if( isset($GLOBALS['TL_CONFIG']['websiteTitle']) ) $filename = $GLOBALS['TL_CONFIG']['websiteTitle']; // IF( Exiat WbsiteTitle ) Dateiname für Template-Dateien
$filename = \StringUtil::generateAlias( $filename ); // Dateiname = Alias für Template-Dateien
$arrExclude = Array ( // Diese Datenbank-Tabellen gehören nicht in ein WS-Template
'tl_cache',
'tl_cron',
'tl_lock',
'tl_log',
'tl_runonce',
'tl_search',
'tl_search_index',
'tl_session',
'tl_undo',
'tl_version'
);
$arrResults = array();
$headertext = "#================================================================================\r\n";
$headertext .= "# Website-Template : " . $filename . ".sql\r\n";
$headertext .= BackupDbCommon::getHeaderInfo( false, 'Saved by User : ' . $user->username . ' (' . $user->name . ')' );
//--- Zielverzeichnis für Website-Templates ---
$zielVerz = 'templates';
if( isset( $GLOBALS['BACKUPDB']['WsTemplatePath'] ) && is_dir(TL_ROOT . '/' . trim($GLOBALS['BACKUPDB']['WsTemplatePath'], '/')) ) {
$zielVerz = trim($GLOBALS['BACKUPDB']['WsTemplatePath'], '/');
}
if( isset( $GLOBALS['TL_CONFIG']['WsTemplatePath'] ) && is_dir(TL_ROOT . '/' . trim($GLOBALS['TL_CONFIG']['WsTemplatePath'], '/')) && (trim($GLOBALS['TL_CONFIG']['WsTemplatePath']) != '') ) {
$zielVerz = trim($GLOBALS['TL_CONFIG']['WsTemplatePath'], '/');
}
$tempdir = '/system/tmp/'; // temporäre Datei anlegen, dann wird das vorige Template nur überschrieben, wenn die runtime ausreicht
$fileSQL = $filename . '.sql'; // Datenbank-Datei
$fileTXT = $filename . '.txt'; // Info-Datei
$fileSTR = $filename . '.structure'; // Struktur-Datei
$datei = new \File( $tempdir . $fileSQL );
$datei->write( $headertext );
$datei->write( 'SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";' . "\r\n"
. "\r\n"
. "/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\r\n"
. "/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\r\n"
. "/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\r\n"
. "/*!40101 SET NAMES utf8 */;\r\n" );
$arrSavedDB = array( 'tl_' ); // Default, Verhalten wie in den Vorversionen von BackupDB
if( isset( $GLOBALS['TL_CONFIG']['backupdb_saveddb'] ) && (trim($GLOBALS['TL_CONFIG']['backupdb_saveddb']) != '') ) {
$arrSavedDB = trimsplit( ',', strtolower($GLOBALS['TL_CONFIG']['backupdb_saveddb']) );
}
$arrBlacklist = BackupDbCommon::get_blacklist( );
$sqlarray = BackupDbCommon::getFromDB( );
$arrEntries = array( );
if( count($sqlarray) == 0 ) {
$datei->write( "\r\nNo tables found in database." );
}
else {
foreach( array_keys($sqlarray) as $table ) {
if( in_array( $table, $arrExclude ) ) continue; // Exclude-Tabellen überspringen
if( in_array( $table, $arrBlacklist ) ) continue; // Blacklisten-Tabellen überspringen
$found = false;
for( $i=0; $i<count($arrSavedDB); $i++ ) {
if( (strlen($arrSavedDB[$i]) <= strlen($table)) && ($arrSavedDB[$i] === substr($table, 0, strlen($arrSavedDB[$i]))) ) {
$found = true;
}
}
if( !$found ) continue; // nur die angegebenen Datentabellen sichern
$arrEntries[] = BackupDbCommon::get_table_content( $table, $datei, true ); // Dateninhalte in Datei schreiben
}
}
$arrResults['entries'] = $arrEntries;
$datei->write( "\r\n# --- End of Backup ---\r\n" ); // Endekennung
$datei->close();
$datei = new \File( $tempdir . $fileSTR ); // Strukturdatei öffnen
$datei->write( BackupDbCommon::getHeaderInfo( true, 'Saved by User : ' . $user->username . ' (' . $user->name . ')' ));
$sqlarray = BackupDbCommon::getFromDB( );
if( count($sqlarray) == 0 ) {
$datei->write( 'No tables found in database.' );
}
else {
foreach( array_keys($sqlarray) as $table ) {
$datei->write( BackupDbCommon::get_table_structure($table, $sqlarray[$table]) );
}
}
$datei->write( "\r\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\r\n"
."/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\r\n"
."/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;\r\n"
."\r\n# --- End of Backup ---\r\n" ); // Endekennung
$datei->close();
$datei = new \File( $tempdir . $fileTXT ); // Textdatei öffnen
$datei->write( $headertext );
$datei->close();
//--- alte Dateien löschen, neue ans Ziel verschieben ---
if( file_exists(TL_ROOT . '/' . $zielVerz . '/' . $fileSQL) ) { // Delete old files if exist
unlink(TL_ROOT . '/' . $zielVerz . '/' . $fileSQL);
}
if( file_exists(TL_ROOT . '/' . $zielVerz . '/' . $fileSTR) ) {
unlink(TL_ROOT . '/' . $zielVerz . '/' . $fileSTR);
}
if( file_exists(TL_ROOT . '/' . $zielVerz . '/' . $fileTXT) ) {
unlink(TL_ROOT . '/' . $zielVerz . '/' . $fileTXT);
}
rename( TL_ROOT . $tempdir . $fileSQL, TL_ROOT . '/' . $zielVerz . '/' . $fileSQL ); // Move new files
rename( TL_ROOT . $tempdir . $fileSTR, TL_ROOT . '/' . $zielVerz . '/' . $fileSTR );
rename( TL_ROOT . $tempdir . $fileTXT, TL_ROOT . '/' . $zielVerz . '/' . $fileTXT );
//--- Ergebnisausgabe ---
$arrResults['header']['text'] = $GLOBALS['TL_LANG']['tl_backupdb']['tplhead'];
$arrResults['entry']['text'] = array( $GLOBALS['TL_LANG']['tl_backupdb']['tplentry'], $GLOBALS['TL_LANG']['tl_backupdb']['tplentriesd'] );
$arrResults['footer']['result'] = $GLOBALS['TL_LANG']['tl_backupdb']['tplresult'];
$arrResults['footer']['legend'] = $GLOBALS['TL_LANG']['tl_backupdb']['tpllegend'];
$arrResults['footer']['fileSQL'] = '/' . $zielVerz . '/' . $fileSQL;
$arrResults['footer']['fileTXT'] = '/' . $zielVerz . '/' . $fileTXT;
$arrResults['footer']['fileSTR'] = '/' . $zielVerz . '/' . $fileSTR;
$arrResults['footer']['text'] = $GLOBALS['TL_LANG']['tl_backupdb']['tplfooter'];
$arrResults['footer']['button'] = $GLOBALS['TL_LANG']['tl_backupdb']['tplbutton'];
return $arrResults;
} | ------------------------- | entailment |
public function run( )
{
@set_time_limit( 600 );
$user = \BackendUser::getInstance();
$filepath = $GLOBALS['TL_CONFIG']['uploadPath'] . '/AutoBackupDB';
$pfad = TL_ROOT . '/' . $filepath;
if( file_exists( $pfad . '/' . BACKUPDB_RUN_LAST ) ) {
unlink( $pfad . '/' . BACKUPDB_RUN_LAST ); // LastRun-Datei löschen
}
//--- Datei-Extension festlegen ---
$ext = '';
if( isset( $GLOBALS['TL_CONFIG']['backupdb_zip'] ) && ($GLOBALS['TL_CONFIG']['backupdb_zip'] == true) ) {
$ext = '.zip';
}
$tmpdatei = new \File( $filepath . '/Database_' . $GLOBALS['TL_CONFIG']['dbDatabase'] . '_' . date('Y-m-d') . '_' . date('His') . '.sql' ); // temporäre Datei erstellen
$tmpdatei->write( BackupDbCommon::getHeaderInfo( true, 'Saved by User : ' . $user->username . ' (' . $user->name . ')' ) );
$arrBlacklist = BackupDbCommon::get_blacklist( );
$sqlarray = BackupDbCommon::getFromDB( );
if( count($sqlarray) == 0 ) {
$tmpdatei->write( 'No tables found in database.' );
}
else {
foreach( array_keys($sqlarray) as $table ) {
$tmpdatei->write( BackupDbCommon::get_table_structure( $table, $sqlarray[$table] ) );
if( in_array( $table, $arrBlacklist ) ) continue; // Blacklisten-Tabellen speichern nur Struktur, keine Daten -> continue
BackupDbCommon::get_table_content( $table, $tmpdatei ); // Dateninhalte ausgeben
}
}
$tmpdatei->write( "\r\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\r\n"
. "/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\r\n"
. "/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;\r\n"
. "\r\n# --- End of Backup ---\r\n" ); // Endekennung
$tmpdatei->close();
//--- Wenn Komprimierung gewünscht, ZIP erstellen ---
if( $ext === '.zip' ) {
$objZip = new \ZipWriter( $filepath . '/' . $tmpdatei->basename . '.zip' );
$objZip->addFile( $filepath . '/' . $tmpdatei->name, $tmpdatei->name );
$objZip->addFile( 'composer.json' );
$objZip->addFile( 'composer.lock' );
$objZip->addString( BackupDbCommon::get_symlinks(), 'restoreSymlinks.php', time() ); // Symlink-Recovery
$objZip->close();
}
// Timestamp-Datei erstellen
$datei = new \File( $GLOBALS['TL_CONFIG']['uploadPath'] . '/AutoBackupDB/' . BACKUPDB_RUN_LAST );
$datei->write( date($GLOBALS['TL_CONFIG']['datimFormat']) );
$datei->close();
// Update the hash of the target folder
$objFile = \Dbafs::addResource( $GLOBALS['TL_CONFIG']['uploadPath'] . '/AutoBackupDB/' . BACKUPDB_RUN_LAST ); // Datei in der Dateiverwaltung eintragen
\Dbafs::updateFolderHashes($strUploadFolder);
//=== Ausgabe der temporären Datei ===
header( 'Pragma: public' );
header( 'Expires: 0' );
header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
header( 'Cache-Control: private', false );
header( 'Content-type: application/octet-stream' );
header( 'Content-disposition: attachment; filename=' . $tmpdatei->name . $ext );
header( 'Content-Transfer-Encoding: binary' );
echo file_get_contents( $pfad . '/' . $tmpdatei->name . $ext ); // Ausgabe als Download
$tmpdatei->delete( );
if( $ext === '.zip' ) {
unlink( $pfad . '/' . $tmpdatei->name . $ext ); // ZIP-Datei löschen
}
} | ------------------------- | entailment |
public function makeAllSearchable()
{
$this->chunk(100, function (Collection $models) {
$models = $models->map(function (Searchable $model) {
$model->setSearchableAs($this->searchableAs());
$model->setClassMetaData($this->getClassMetadata());
return $model;
});
$this->searchableUsing()->update($models);
event(new ModelsImported($models));
});
} | Make all searchable | entailment |
public static function getHeaderInfo( $sql_mode, $savedby = 'Saved by Cron' )
{
$objDB = \Database::getInstance();
$instExt = array();
$bundles = array();
$result = "#================================================================================\r\n"
. "# Contao-Website : " . (isset($GLOBALS['TL_CONFIG']['websiteTitle']) ? $GLOBALS['TL_CONFIG']['websiteTitle'] : \Environment::get('host')) . "\r\n"
. "# Contao-Database : " . $GLOBALS['TL_CONFIG']['dbDatabase'] . "\r\n"
. "# " . $savedby . "\r\n"
. "# Time stamp : " . date( "Y-m-d" ) . " at " . date( "H:i:s" ) . "\r\n"
. "#\r\n"
. "# Contao Extension : BackupDbBundle, Version " . BACKUPDB_VERSION . '.' . BACKUPDB_BUILD . "\r\n"
. "# Copyright : Softleister (www.softleister.de)\r\n"
. "# Licence : LGPL\r\n"
. "#\r\n"
. "# Visit https://github.com/do-while/contao-BackupDB for more information\r\n"
. "#\r\n"
//--- Installierte Pakete auflisten ---
. "#-----------------------------------------------------\r\n"
. "# If you save the backup in ZIP file, a file restoreSymlinks.php\r\n"
. "# is also in the ZIP. See the file for more information\r\n"
. "#-----------------------------------------------------\r\n"
. "# Contao Version " . VERSION . "." . BUILD . "\r\n"
. "# The following packages must be installed:\r\n"
. "#\r\n";
//--- installierte Pakete ---
$rootDir = \System::getContainer()->getParameter('kernel.project_dir'); // TL_ROOT
$objComposerPackages = new ComposerPackages($rootDir);
if (true === $objComposerPackages->parseComposerJson() &&
true === $objComposerPackages->parseComposerLock()
)
{
// $bundles: array('name' => 'version')
$bundles = $objComposerPackages->getPackages(self::$arrExclude);
}
ksort( $bundles ); // sortieren nach name (key)
if( empty( $bundles ) ) {
$result .= "# == none ==\r\n";
}
else {
foreach( $bundles as $ext => $ver )
$result .= "# - $ext : $ver\r\n";
}
$result .= "#\r\n"
. "#================================================================================\r\n"
. "\r\n";
if( $sql_mode ) {
$result .= 'SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";' . "\r\n"
. 'SET time_zone = "+00:00";' . "\r\n"
. "\r\n"
. "/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\r\n"
. "/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\r\n"
. "/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\r\n"
. "/*!40101 SET NAMES utf8 */;\r\n";
}
return $result;
} | --------------------------------------- | entailment |
public static function getFromDB( )
{
$result = array();
$objDB = \Database::getInstance( );
$tables = $objDB->listTables( null, true );
if( empty($tables) ) {
return $result;
}
foreach( $tables as $table ) {
$keys = array();
$fields = $objDB->listFields($table, true);
foreach( $fields as $field ) {
$name = $field['name'];
$field['name'] = '`' . $field['name'] . '`';
if( in_array(strtolower($field['type']), array('text', 'tinytext', 'mediumtext', 'longtext')) && isset($fields[$name]) ) {
$keys[$name] = 'FULLTEXT ';
}
//--- Tabellenspalten definieren ---
if( $field['type'] != 'index' ) {
unset($field['index']);
// Field type
if( isset($field['length']) && ($field['length'] != '') ) {
$field['type'] .= '(' . $field['length'] . ((isset($field['precision']) && $field['precision'] != '') ? ',' . $field['precision'] : '') . ')';
unset( $field['length'] );
unset( $field['precision'] );
}
// Variant collation
if( ($field['collation'] != '') && ($field['collation'] != $GLOBALS['TL_CONFIG']['dbCollation']) ) {
$field['collation'] = 'COLLATE ' . $field['collation'];
}
else {
unset( $field['collation'] );
}
// Default values
if( in_array(strtolower($field['type']), array('text', 'tinytext', 'mediumtext', 'longtext', 'blob', 'tinyblob', 'mediumblob', 'longblob')) || stristr($field['extra'], 'auto_increment') || ($field['default'] === null) || (strtolower($field['null']) == 'null') ) {
unset( $field['default'] );
}
// Date/time constants (see #5089)
else if( in_array(strtolower($field['default']), array('current_date', 'current_time', 'current_timestamp')) ) {
$field['default'] = "default " . $field['default'];
}
// Everything else
else {
$field['default'] = "default '" . $field['default'] . "'";
}
unset( $field['origtype'] );
$result[$table]['TABLE_FIELDS'][$name] = trim( implode( ' ', $field ) );
}
//--- Index-Einträge ---
if( isset($field['index']) && !empty($field['index_fields']) ) {
$index_fields = '`' . implode( '`, `', $field['index_fields'] ) . '`';
$index_fields = str_replace(array('(', ')`'), array('`(', ')'), $index_fields );
switch( $field['index'] ) {
case 'UNIQUE': if( $name == 'PRIMARY' ) {
$result[$table]['TABLE_CREATE_DEFINITIONS'][$name] = 'PRIMARY KEY ('.$index_fields.')';
}
else {
$result[$table]['TABLE_CREATE_DEFINITIONS'][$name] = 'UNIQUE KEY `'.$name.'` ('.$index_fields.')';
}
break;
default: $result[$table]['TABLE_CREATE_DEFINITIONS'][$name] = (isset($keys[$name]) ? $keys[$name] : '') . 'KEY `'.$name.'` ('.$index_fields.')';
break;
}
unset( $field['index_fields'] );
unset( $field['index'] );
}
}
}
// Table status
$objStatus = $objDB->execute( 'SHOW TABLE STATUS' );
while( $zeile = $objStatus->fetchAssoc() ) {
$result[$zeile['Name']]['TABLE_OPTIONS'] = ' ENGINE=' . $zeile['Engine'] . ' DEFAULT CHARSET=' . substr($zeile['Collation'], 0, strpos($zeile['Collation'],"_"));
if( $zeile['Auto_increment'] != '' ) {
$result[$zeile['Name']]['TABLE_OPTIONS'] .= ' AUTO_INCREMENT=' . $zeile['Auto_increment'];
}
}
return $result;
} | ------------------------------------------------ | entailment |
public static function get_table_structure( $table, $tablespec )
{
$result = "\r\n"
. "#---------------------------------------------------------\r\n"
. "# Table structure for table '$table'\r\n"
. "#---------------------------------------------------------\r\n";
$result .= "CREATE TABLE `" . $table . "` (\n " . implode(",\n ", $tablespec['TABLE_FIELDS']) . (count($tablespec['TABLE_CREATE_DEFINITIONS']) ? ',' : '') . "\n";
if( is_array( $tablespec['TABLE_CREATE_DEFINITIONS'] ) ) { // Bugfix 29.3.2009 Softleister
$result .= " " . implode( ",\n ", $tablespec['TABLE_CREATE_DEFINITIONS'] ) . "\n";
}
$result .= ")" . $tablespec['TABLE_OPTIONS'] . ";\r\n\r\n";
return $result;
} | --------------------------------------- | entailment |
public static function get_table_content( $table, $datei=NULL, $sitetemplate=false )
{
$objDB = \Database::getInstance();
$objData = $objDB->executeUncached( "SELECT * FROM $table" );
$fields = $objDB->listFields( $table ); // Liste der Felder lesen
$fieldlist = '';
$arrEntry = array( );
if( $sitetemplate ) {
$fieldlist = ' (';
foreach( $fields as $field ) {
if( $field['type'] != 'index' ) {
$fieldlist .= '`' . $field['name'] . '`, ';
}
}
$fieldlist = substr( $fieldlist, 0, -2 ) . ')'; // letztes ", " abschneiden
$arrEntry = array( $table, $objData->numRows );
}
$noentries = $objData->numRows ? '' : ' - no entries';
if( $datei == NULL ) {
echo "\r\n"
. "#\r\n"
. "# Dumping data for table '$table'" . $noentries . "\r\n"
. "#\r\n\r\n";
}
else {
$datei->write( "\r\n"
. "#\r\n"
. "# Dumping data for table '$table'" . $noentries . "\r\n"
. "#\r\n\r\n" );
}
while( $row = $objData->fetchRow() ) {
$insert_data = 'INSERT INTO `' . $table . '`' . $fieldlist . ' VALUES (';
$i = 0; // Fields[0]['type']
foreach( $row as $field_data ) {
if( !isset( $field_data ) ) {
$insert_data .= " NULL,";
}
else if( $field_data != "" ) {
switch( strtolower($fields[$i]['type']) ) {
case 'blob':
case 'binary':
case 'varbinary':
case 'tinyblob':
case 'mediumblob':
case 'longblob': $insert_data .= " 0x"; // Auftackt für HEX-Darstellung
$insert_data .= bin2hex($field_data);
$insert_data .= ","; // Abschuß
break;
case 'smallint':
case 'int': $insert_data .= " $field_data,";
break;
case 'text':
case 'mediumtext': if( strpos( $field_data, "'" ) != false ) { // ist im Text ein Hochkomma vorhanden, wird der Text in HEX-Darstellung gesichert
$insert_data .= " 0x" . bin2hex($field_data) . ",";
break;
}
// else: weiter mit default
default: $insert_data .= " '" . str_replace( array("\\", "'", "\r", "\n"), array("\\\\", "\\'", "\\r", "\\n"), $field_data )."',";
break;
}
}
else
$insert_data .= " '',";
$i++; // Next Field
}
$insert_data = trim( $insert_data, ',' );
$insert_data .= " )";
if( $datei == NULL ) {
echo "$insert_data;\r\n"; // Zeile ausgeben
}
else {
$datei->write( "$insert_data;\r\n" );
}
}
return $arrEntry;
} | ------------------------------------------------ | entailment |
public static function get_blacklist( )
{
$arrBlacklist = array(); // Default: alle Datentabellen werden gesichert
if( isset( $GLOBALS['TL_CONFIG']['backupdb_blacklist'] ) && (trim($GLOBALS['TL_CONFIG']['backupdb_blacklist']) != '') ) {
$arrBlacklist = trimsplit(',', strtolower($GLOBALS['TL_CONFIG']['backupdb_blacklist']));
}
return $arrBlacklist;
} | ------------------------------------------------ | entailment |
public static function get_symlinks( )
{
Self::$arrSymlinks = array(); // leeres Array
$url = TL_ROOT . '/';
Self::iterateDir( $url ); // Symlinks suchen
asort( Self::$arrSymlinks ); // alphabetisch sortieren
$links = array();
foreach( Self::$arrSymlinks as $link ) {
$links[] = Self::getLinkData( $link );
}
$script = "<?php\n\n"
. "// This file is part of a backup, included in the zip archive.\n"
. "// Place the restoreSymlinks.php in the web directory of your\n"
. "// contao 4 and call http://domain.tld/restoreSymlinks.php\n"
. "// After running script clear symfony-cache, e.g. with Contao Manager\n\n"
. '$arrSymlinks = unserialize(\'' . serialize( $links ) . "');\n\n"
. "// Check current position\n"
. 'if( !is_dir( "../web" ) || !file_exists( "./app.php" ) ) {' . "\n"
. "\t" . 'die( "The file is not in the correct directory" );' . "\n"
. "}\n\n"
. "// detect OS\n"
. '$windows = strtoupper(substr(PHP_OS, 0, 3)) === "WIN"; // Windows or not' . "\n\n"
. "// get absolute path to contao\n"
. '$rootpath = getcwd();' . "\n"
. '$rootpath = substr( $rootpath, 0 , strlen($rootpath) - 3 );' . "\n\n"
. "// Restore the symlinks\n"
. '$errors = 0;' . "\n"
. '$counter = 0;' . "\n"
. 'foreach( $arrSymlinks as $link ) {' . "\n"
. "\t// get linkpath\n"
. "\t" . '$l = $rootpath . $link["link"]; // absolute address of symlink' . "\n"
. "\t" . 'if( $windows ) $l = str_replace( "/", "\\\\", $l ); // for windows change slashes' . "\n\n"
. "\t// get targetpath\n"
. "\t" . 'if( $windows ) {' ."\n"
. "\t\t" . '$t = str_replace( "/", "\\\\", $rootpath . $link["target"] );' . "\n"
. "\t}\n"
. "\telse {\n"
. "\t\t" . '$t = $link["target"];' . "\n"
. "\t\t" . 'for( $i = 0; $i < $link["depth"]; $i++ ) {' . "\n"
. "\t\t\t" . '$t = "../" . $t;' . "\n"
. "\t\t}\n"
. "\t}\n\n"
. "\t// check if link seem to be a directory\n"
. "\t" . 'if( file_exists( $l ) && !is_link( $l ) ) {' . "\n"
. "\t\t" . 'rename( $l, $l . ".removed" ); // rename directory or file' . "\n"
. "\t}\n\n"
. "\t// no action, if link is a symlink\n"
. "\t" . 'if( is_link( $l ) ) continue;' . "\n\n"
. "\t// set new symlink\n"
. "\t" . '$counter++;' . "\n"
. "\t" . 'if( !symlink( $t, $l ) ) {' . "\n"
. "\t\t" . 'echo "Symlink failed: " . $l . "<br>";' . "\n"
. "\t\t" . '$errors++;' . "\n"
. "\t}\n"
. "}\n\n"
. 'echo "Program terminated with " . $errors . " errors, " . $counter . " new symlinks<br><br>PLEASE DELETE THE SCRIPT FROM THE DIRECTORY NOW!<br>CLEAR THE SYMFONY-CACHE, e.g. with Contao Manager<br>";' . "\n\n";
return $script;
} | ------------------------------------------------ | entailment |
public static function iterateDir( $startPath )
{
foreach( new \DirectoryIterator( $startPath ) as $objItem ) {
if( $objItem->isLink( ) ) {
Self::$arrSymlinks[] = $objItem->getPath( ) . '/' . $objItem->getFilename( );
continue;
}
if($objItem->isDir( ) ) {
if( !$objItem->isDot( ) ) Self::iterateDir( $objItem->getPathname(), $arrResult );
continue;
}
if( $objItem->isLink() ) Self::$arrSymlinks[] = $objItem->getPath( ) . '/' . $objItem->getFilename( );
}
return;
} | ------------------------------------------------ | entailment |
public static function getLinkData( $link )
{
$root = str_replace('\\', '/', TL_ROOT) . '/';
$sym = substr( str_replace('\\', '/', $link), strlen($root) );
$target = str_replace('\\', '/', readlink( $link ) );
if( substr($target, 0, strlen($root)) === $root ) { // absolute path
$target = substr($target, strlen($root));
$depth = count(explode('/', $sym)) - 1;
}
else { // relative path
$depth = 0;
while( substr($target, 0, 3) === '../' ) {
$target = substr($target, 3);
$depth++;
}
}
return array( 'link'=>$sym, 'target'=>trim($target, '/'), 'depth'=>$depth );
} | ------------------------------------------------ | entailment |
protected function compile()
{
\System::loadLanguageFile('tl_backupdb');
switch( \Input::get('act') ) {
case 'backup': BackupDbRun::run( );
die( ); // Beenden, da Download rausgegangen ist
case 'webtemplate': $objTemplate = new \BackendTemplate('be_backupdb_wstpl');
$this->Template = $objTemplate;
$this->Template->arrResults = BackupWsTemplate::run( );
$this->Template->back = 'contao/main.php?do=BackupDB&ref' . TL_REFERER_ID;
$this->Template->backupdb_version = 'BackupDB Version ' . BACKUPDB_VERSION . '.' . BACKUPDB_BUILD;
return;
}
//--- Zielverzeichnis für Website-Templates ---
$zielVerz = 'templates';
if( isset( $GLOBALS['BACKUPDB']['WsTemplatePath'] ) && is_dir(TL_ROOT.'/'.trim($GLOBALS['BACKUPDB']['WsTemplatePath'], '/')) ) {
$zielVerz = trim($GLOBALS['BACKUPDB']['WsTemplatePath'], '/');
}
if( isset( $GLOBALS['TL_CONFIG']['WsTemplatePath'] ) && is_dir(TL_ROOT.'/'.trim($GLOBALS['TL_CONFIG']['WsTemplatePath'], '/')) && (trim($GLOBALS['TL_CONFIG']['WsTemplatePath']) != '') ) {
$zielVerz = trim($GLOBALS['TL_CONFIG']['WsTemplatePath'], '/');
}
$filename = \Environment::get('host'); // Dateiname = Domainname
if( isset($GLOBALS['TL_CONFIG']['websiteTitle']) ) $filename = $GLOBALS['TL_CONFIG']['websiteTitle']; // IF( Exiat WbsiteTitle ) Dateiname für Template-Dateien
$filename = \StringUtil::generateAlias( $filename ); // Dateiname = Alias für Template-Dateien
$this->Template->ws_template_sqlfile = $zielVerz.'/' . $filename . '.sql';
$this->Template->ws_template_txtfile = $zielVerz.'/' . $filename . '.txt';
$this->Template->ws_template_strfile = $zielVerz.'/' . $filename . '.structure';
$this->Template->settingslink = $settingslink = 'contao/main.php?do=settings&ref=' . TL_REFERER_ID;
$this->Template->cronlink = $cronlink = 'contao/main.php?do=cron&ref=' . TL_REFERER_ID;
$this->Template->backuplink = 'contao/main.php?do=BackupDB&act=backup&rt=' . REQUEST_TOKEN . '&ref=' . TL_REFERER_ID;
$this->Template->webtemplatelink = 'contao/main.php?do=BackupDB&act=webtemplate&rt=' . REQUEST_TOKEN . '&ref=' . TL_REFERER_ID;
$this->Template->database = $GLOBALS['TL_CONFIG']['dbDatabase'];
$this->Template->texte = array(
'download' => $GLOBALS['TL_LANG']['tl_backupdb']['download'],
'startdownload' => $GLOBALS['TL_LANG']['tl_backupdb']['startdownload'],
'database' => $GLOBALS['TL_LANG']['tl_backupdb']['database'] . ': ',
'backupdesc' => $GLOBALS['TL_LANG']['tl_backupdb']['backupdesc'],
'backupsetup' => sprintf( $GLOBALS['TL_LANG']['tl_backupdb']['backupsetup'], $settingslink ),
'backuplast' => $GLOBALS['TL_LANG']['tl_backupdb']['backuplast'] . ': ',
'croninfo' => $GLOBALS['TL_LANG']['tl_backupdb']['croninfo'],
'cronsetup' => sprintf( $GLOBALS['TL_LANG']['tl_backupdb']['cronsetup'], $cronlink ),
'cronlast' => $GLOBALS['TL_LANG']['tl_backupdb']['cronlast'] . ': ',
'maketpl' => $GLOBALS['TL_LANG']['tl_backupdb']['maketpl'],
'tpldesc' => $GLOBALS['TL_LANG']['tl_backupdb']['tpldesc'],
'tplfiles' => $GLOBALS['TL_LANG']['tl_backupdb']['tplfiles'] . ':',
'tplnobackup' => $GLOBALS['TL_LANG']['tl_backupdb']['tplnobackup'],
'tplwarning' => $GLOBALS['TL_LANG']['tl_backupdb']['tplwarning']
);
//--- CRON Erweiterung einbeziehen, wenn vorhanden ---
$this->Template->ws_cron = $this->checkCronExt(); // übergibt 0 (kein Cron), 1 (Cron ohne Job), 2 (Cron, Job inaktiv) oder 3 (Cron, Job aktiv)
if( ($this->Input->get('op') == 'cron') && ($this->checkCron() == 1) ) {
$sql = "INSERT INTO `tl_cron` "
."(`id`, `tstamp`, `lastrun`, `nextrun`, `scheduled`, `title`, `job`, `t_minute`, `t_hour`, `t_dom`, `t_month`, `t_dow`, `runonce`, `enabled`, `logging`) "
."VALUES ( 0, " . time() . ", 0, 0, 0, 'AutoBackupDB', 'system/modules/BackupDB/AutoBackupDB.php', '0', '2', '*', '*', '*', '', '', '1')";
$this->Database->execute( $sql ); // inaktiven Cronjob eintragen
$this->reload();
}
//--- Letzte Backups ---
$pfad = TL_ROOT . '/' . $GLOBALS['TL_CONFIG']['uploadPath'] . '/AutoBackupDB/';
$this->Template->lastrun = file_exists($pfad . BACKUPDB_RUN_LAST) ? file_get_contents($pfad . BACKUPDB_RUN_LAST) : '--.--.---- --:--';
$this->Template->lastcron = file_exists($pfad . BACKUPDB_CRON_LAST) ? file_get_contents($pfad . BACKUPDB_CRON_LAST) : '--.--.---- --:--';
//--- Footer ---
$this->Template->backupdb_icons = 'Icons from <a href="https://icons8.com" target="_blank">Icons8</a> (<a href="https://creativecommons.org/licenses/by-nd/3.0/" target="_blank">CC BY-ND 3.0</a>)';
$this->Template->backupdb_version = '<a href="https://github.com/do-while/contao-BackupDB" target="_blank">BackupDB Version ' . BACKUPDB_VERSION . '.' . BACKUPDB_BUILD . '</a>';
} | Function compile | entailment |
public function checkCronExt( )
{
$result = 0; // kein Cron
$objDB = \Database::getInstance();
if( $objDB->tableExists('tl_crontab') ) {
$result = 1; // Cron vorhanden, kein Job
$objJob = $objDB->execute("SELECT * FROM tl_crontab WHERE job='system/modules/BackupDB/public/AutoBackupDB.php' LIMIT 1");
if( $objJob->next() ) { // IF( Job vorhanden )
$result = $objJob->enabled ? 3 : 2; // Job AKTIV(3) oder Job INAKTIV(2)
}
}
return $result;
} | Function check cron job | entailment |
public function configureServers(array $servers): array
{
return array_map(
static function ($item) {
if ($item['basic']) {
$item['basic'] = base64_encode($item['basic']);
}
return $item;
},
$servers
);
} | Returns servers list with hash for basic auth computed if provided. | entailment |
public function AutoBackupAction()
{
$this->container->get('contao.framework')->initialize();
$controller = new \Softleister\BackupDB\AutoBackupDb();
return $controller->run();
} | Renders the alerts content.
@return Response
@Route("/autobackup", name="backupdb_autobackup") | entailment |
public function cacheAction(Request $request)
{
$parameters = $request->get('parameters', []);
if ($request->get('token') !== $this->computeHash($parameters)) {
throw new AccessDeniedHttpException('Invalid token');
}
$subRequest = Request::create('', 'get', $parameters, $request->cookies->all(), [], $request->server->all());
$controller = $this->resolver->getController($subRequest);
$subRequest->attributes->add(['_controller' => $parameters['controller']]);
$subRequest->attributes->add($parameters['parameters']);
$arguments = $this->argumentResolver->getArguments($subRequest, $controller);
return \call_user_func_array($controller, $arguments);
} | @throws AccessDeniedHttpException
@return mixed | entailment |
public function run( )
{
// Spamming-Schutz
if( \Config::get('backupdb_var') != '' ) {
if( \Input::get( \Config::get('backupdb_var') ) === NULL ) {
die( 'You cannot access this file directly!' ); // Variable nicht vorhanden => NULL
} // Variable leer => ''
}
@set_time_limit( 600 );
//--- alten Zeitstempel löschen ---
$pfad = TL_ROOT . '/' . $GLOBALS['TL_CONFIG']['uploadPath'] . '/AutoBackupDB';
if( file_exists( $pfad . '/' . BACKUPDB_CRON_LAST ) ) {
unlink( $pfad . '/' . BACKUPDB_CRON_LAST ); // LastRun-Datei löschen
}
$result = 'Starting BackupDB ...<br>';
//--- Datei-Extension festlegen ---
$ext = '.sql';
if( isset( $GLOBALS['TL_CONFIG']['backupdb_zip'] ) && ($GLOBALS['TL_CONFIG']['backupdb_zip'] == true) ) {
$ext = '.zip';
}
//--- alte Backups aufrutschen --- Anzahl einstellbar 29.3.2009 Softleister, über localconfig 07.05.2011
$anzBackup = 3;
if( isset( $GLOBALS['BACKUPDB']['AutoBackupCount'] ) && is_int($GLOBALS['BACKUPDB']['AutoBackupCount']) ) {
$anzBackup = $GLOBALS['BACKUPDB']['AutoBackupCount'];
}
if( isset( $GLOBALS['TL_CONFIG']['AutoBackupCount'] ) && is_int($GLOBALS['TL_CONFIG']['AutoBackupCount']) ) {
$anzBackup = $GLOBALS['TL_CONFIG']['AutoBackupCount'];
}
if( file_exists( $pfad . '/AutoBackupDB-' . $anzBackup . $ext ) ) {
unlink( $pfad . '/AutoBackupDB-' . $anzBackup . $ext );
}
for( ; $anzBackup > 1; $anzBackup-- ) {
if( file_exists( $pfad . '/AutoBackupDB-' . ($anzBackup-1) . $ext ) ) {
rename( $pfad . '/AutoBackupDB-' . ($anzBackup-1) . $ext, $pfad . '/AutoBackupDB-' . $anzBackup . $ext );
}
}
//--- wenn alte Backupdatei existiert: löschen ---
if( file_exists( $pfad . '/AutoBackupDB-1.sql' ) ) {
unlink( $pfad . '/AutoBackupDB-1.sql' );
}
//--- neue Datei AutoBackupDB-1.sql ---
$datei = new \File( $GLOBALS['TL_CONFIG']['uploadPath'] . '/AutoBackupDB/AutoBackupDB-1.sql' );
$from = defined( 'DIRECT_CALL' ) ? 'Saved : by direct call from IP ' . $this->Environment->ip : 'Saved by Cron';
$datei->write( BackupDbCommon::getHeaderInfo( true, $from ) );
$arrBlacklist = BackupDbCommon::get_blacklist( );
$sqlarray = BackupDbCommon::getFromDB( );
if( count($sqlarray) == 0 ) {
$datei->write( 'No tables found in database.' );
}
else {
foreach( array_keys($sqlarray) as $table ) {
$datei->write( BackupDbCommon::get_table_structure( $table, $sqlarray[$table] ) );
if( in_array( $table, $arrBlacklist ) ) continue; // Blacklisten-Tabellen speichern nur Struktur, keine Daten -> continue
BackupDbCommon::get_table_content( $table, $datei ); // Dateninhalte in Datei schreiben
}
}
$datei->write( "\r\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\r\n"
. "/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\r\n"
. "/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;\r\n"
. "\r\n# --- End of Backup ---\r\n" ); // Endekennung
$datei->close();
$result .= 'End of Backup<br>';
//--- Wenn Komprimierung gewünscht, ZIP erstellen ---
if( $ext === '.zip' ) {
$objZip = new \ZipWriter( $GLOBALS['TL_CONFIG']['uploadPath'] . '/AutoBackupDB/AutoBackupDB-1.zip' );
$objZip->addFile( $GLOBALS['TL_CONFIG']['uploadPath'] . '/AutoBackupDB/AutoBackupDB-1.sql', 'AutoBackupDB-1.sql' );
$objZip->addFile( 'composer.json' );
$objZip->addFile( 'composer.lock' );
$objZip->addString( BackupDbCommon::get_symlinks(), 'restoreSymlinks.php', time() ); // Symlink-Recovery
$objZip->close();
unlink( $pfad . '/AutoBackupDB-1.sql' );
}
$objFile = \Dbafs::addResource( $GLOBALS['TL_CONFIG']['uploadPath'] . '/AutoBackupDB/AutoBackupDB-1' . $ext ); // Datei in der Dateiverwaltung eintragen
//--- Mail-Benachrichtigung ---
if( isset( $GLOBALS['TL_CONFIG']['backupdb_sendmail'] ) && ($GLOBALS['TL_CONFIG']['backupdb_sendmail'] == true) ) {
$objEmail = new \Email();
$objEmail->from = $GLOBALS['TL_CONFIG']['adminEmail'];
$objEmail->subject = 'AutoBackupDB ' . \Environment::get('host');
$objEmail->text = BackupDbCommon::getHeaderInfo( false, $from );
if( isset( $GLOBALS['TL_CONFIG']['backupdb_attmail'] ) && ($GLOBALS['TL_CONFIG']['backupdb_attmail'] == true) ) {
$objEmail->attachFile( $pfad . '/AutoBackupDB-1' . $ext, 'application/octet-stream' );
}
$objEmail->sendTo( $GLOBALS['TL_CONFIG']['adminEmail'] );
}
$datei = new \File( $GLOBALS['TL_CONFIG']['uploadPath'] . '/AutoBackupDB/' . BACKUPDB_CRON_LAST );
$datei->write( date($GLOBALS['TL_CONFIG']['datimFormat']) );
$datei->close();
// Update the hash of the target folder
$objFile = \Dbafs::addResource( $GLOBALS['TL_CONFIG']['uploadPath'] . '/AutoBackupDB/' . BACKUPDB_CRON_LAST ); // Datei in der Dateiverwaltung eintragen
\Dbafs::updateFolderHashes( $GLOBALS['TL_CONFIG']['uploadPath'] . '/AutoBackupDB/' );
return new Response( $result );
} | ------------------------- | entailment |
public function enqueue(Task $task): \Generator
{
if (!$this->context->isRunning()) {
throw new StatusError('The worker has not been started.');
}
if ($this->shutdown) {
throw new StatusError('The worker has been shut down.');
}
// If the worker is currently busy, store the task in a busy queue.
if (null !== $this->active) {
$delayed = new Delayed();
$this->busyQueue->enqueue($delayed);
yield $delayed;
}
$this->active = new Coroutine($this->send($task));
try {
$result = yield $this->active;
} catch (\Throwable $exception) {
$this->kill();
throw new WorkerException('Sending the task to the worker failed.', $exception);
} finally {
$this->active = null;
}
// We're no longer busy at the moment, so dequeue a waiting task.
if (!$this->busyQueue->isEmpty()) {
$this->busyQueue->dequeue()->resolve();
}
if ($result instanceof TaskFailure) {
throw $result->getException();
}
return $result;
} | {@inheritdoc} | entailment |
private function send(Task $task): \Generator
{
yield from $this->context->send($task);
return yield from $this->context->receive();
} | @coroutine
@param \Icicle\Concurrent\Worker\Task $task
@return \Generator
@resolve mixed | entailment |
public function shutdown(): \Generator
{
if (!$this->context->isRunning() || $this->shutdown) {
throw new StatusError('The worker is not running.');
}
$this->shutdown = true;
// Cancel any waiting tasks.
$this->cancelPending();
// If a task is currently running, wait for it to finish.
if (null !== $this->active) {
try {
yield $this->active;
} catch (\Throwable $exception) {
// Ignore failure in this context.
}
}
yield from $this->context->send(0);
return yield from $this->context->join();
} | {@inheritdoc} | entailment |
private function cancelPending()
{
if (!$this->busyQueue->isEmpty()) {
$exception = new WorkerException('Worker was shut down.');
do {
$this->busyQueue->dequeue()->cancel($exception);
} while (!$this->busyQueue->isEmpty());
}
} | Cancels all pending tasks. | entailment |
public function start()
{
$this->process->start();
$this->channel = new ChannelledStream($this->process->getStdOut(), $this->process->getStdIn());
} | {@inheritdoc} | entailment |
public function receive(): \Generator
{
if (null === $this->channel) {
throw new StatusError('The process has not been started.');
}
$data = yield from $this->channel->receive();
if ($data instanceof ExitStatus) {
$data = $data->getResult();
throw new SynchronizationError(sprintf(
'Thread unexpectedly exited with result of type: %s',
is_object($data) ? get_class($data) : gettype($data)
));
}
return $data;
} | {@inheritdoc} | entailment |
protected function writeProgress($progress)
{
if($this->debug) {
return parent::writeProgress($progress);
}
$this->scoreboard->score($progress);
} | {@inheritdoc} | entailment |
protected function printHeader()
{
if (!$this->debug) {
if (!$this->scoreboard->isRunning()) {
$this->scoreboard->start();
}
$this->scoreboard->stop();
}
parent::printHeader();
} | {@inheritdoc} | entailment |
public function addFailure(Test $test, AssertionFailedError $e, $time)
{
if ($this->debug) {
return parent::addFailure($test, $e, $time);
}
$this->writeProgress('fail');
$this->lastTestFailed = TRUE;
} | {@inheritdoc} | entailment |
public function setPriority(float $priority): float
{
if ($priority < 0 || $priority > 1) {
throw new InvalidArgumentError('Priority value must be between 0.0 and 1.0.');
}
$nice = round(19 - ($priority * 39));
if (!pcntl_setpriority($nice, $this->pid, PRIO_PROCESS)) {
throw new ForkException('Failed to set the fork\'s priority.');
}
} | Sets the fork's scheduling priority as a percentage.
Note that on many systems, only the superuser can increase the priority of a process.
@param float $priority A priority value between 0 and 1.
@throws InvalidArgumentError If the given priority is an invalid value.
@throws ForkException If the operation failed.
@see Fork::getPriority() | entailment |
public function start()
{
if (0 !== $this->oid) {
throw new StatusError('The context has already been started.');
}
list($parent, $child) = Stream\pair();
switch ($pid = pcntl_fork()) {
case -1: // Failure
throw new ForkException('Could not fork process!');
case 0: // Child
// @codeCoverageIgnoreStart
// Create a new event loop in the fork.
Loop\loop($loop = Loop\create(false));
$channel = new ChannelledStream($pipe = new DuplexPipe($parent));
fclose($child);
$coroutine = new Coroutine($this->execute($channel));
$coroutine->done();
try {
$loop->run();
$code = 0;
} catch (\Throwable $exception) {
$code = 1;
}
$pipe->close();
exit($code);
// @codeCoverageIgnoreEnd
default: // Parent
$this->pid = $pid;
$this->oid = posix_getpid();
$this->channel = new ChannelledStream($this->pipe = new DuplexPipe($child));
fclose($parent);
}
} | Starts the context execution.
@throws \Icicle\Concurrent\Exception\ForkException If forking fails.
@throws \Icicle\Stream\Exception\FailureException If creating a socket pair fails. | entailment |
private function execute(Channel $channel): \Generator
{
try {
if ($this->function instanceof \Closure) {
$function = $this->function->bindTo($channel, Channel::class);
}
if (empty($function)) {
$function = $this->function;
}
$result = new ExitSuccess(yield $function(...$this->args));
} catch (\Throwable $exception) {
$result = new ExitFailure($exception);
}
// Attempt to return the result.
try {
try {
return yield from $channel->send($result);
} catch (SerializationException $exception) {
// Serializing the result failed. Send the reason why.
return yield from $channel->send(new ExitFailure($exception));
}
} catch (ChannelException $exception) {
// The result was not sendable! The parent context must have died or killed the context.
return 0;
}
} | @coroutine
This method is run only on the child.
@param \Icicle\Concurrent\Sync\Channel $channel
@return \Generator
@codeCoverageIgnore Only executed in the child. | entailment |
public function kill()
{
if ($this->isRunning()) {
// Forcefully kill the process using SIGKILL.
posix_kill($this->pid, SIGKILL);
}
if (null !== $this->pipe && $this->pipe->isOpen()) {
$this->pipe->close();
}
// "Detach" from the process and let it die asynchronously.
$this->pid = 0;
$this->channel = null;
} | {@inheritdoc} | entailment |
public function signal(int $signo)
{
if (0 === $this->pid) {
throw new StatusError('The fork has not been started or has already finished.');
}
posix_kill($this->pid, (int) $signo);
} | @param int $signo
@throws \Icicle\Concurrent\Exception\StatusError | entailment |
public function join(): \Generator
{
if (null === $this->channel) {
throw new StatusError('The fork has not been started or has already finished.');
}
try {
$response = yield from $this->channel->receive();
if (!$response instanceof ExitStatus) {
throw new SynchronizationError(sprintf(
'Did not receive an exit status from fork. Instead received data of type %s',
is_object($response) ? get_class($response) : gettype($response)
));
}
return $response->getResult();
} finally {
$this->kill();
}
} | @coroutine
Gets a promise that resolves when the context ends and joins with the
parent context.
@return \Generator
@resolve mixed Resolved with the return or resolution value of the context once it has completed execution.
@throws \Icicle\Concurrent\Exception\StatusError Thrown if the context has not been started.
@throws \Icicle\Concurrent\Exception\SynchronizationError Thrown if an exit status object is not received. | entailment |
public function send($data): \Generator
{
if (null === $this->channel) {
throw new StatusError('The fork has not been started or has already finished.');
}
if ($data instanceof ExitStatus) {
throw new InvalidArgumentError('Cannot send exit status objects.');
}
return yield from $this->channel->send($data);
} | {@inheritdoc} | entailment |
private function init($maxLocks, $permissions)
{
$maxLocks = (int) $maxLocks;
if ($maxLocks < 1) {
$maxLocks = 1;
}
$this->key = abs(crc32(spl_object_hash($this)));
$this->maxLocks = $maxLocks;
$this->queue = msg_get_queue($this->key, $permissions);
if (!$this->queue) {
throw new SemaphoreException('Failed to create the semaphore.');
}
// Fill the semaphore with locks.
while (--$maxLocks >= 0) {
$this->release();
}
} | @param int $maxLocks The maximum number of locks that can be acquired from the semaphore.
@param int $permissions Permissions to access the semaphore.
@throws SemaphoreException If the semaphore could not be created due to an internal error. | entailment |
public function acquire(): \Generator
{
do {
// Attempt to acquire a lock from the semaphore.
if (@msg_receive($this->queue, 0, $type, 1, $chr, false, MSG_IPC_NOWAIT, $errno)) {
// A free lock was found, so resolve with a lock object that can
// be used to release the lock.
return new Lock(function (Lock $lock) {
$this->release();
});
}
// Check for unusual errors.
if ($errno !== MSG_ENOMSG) {
throw new SemaphoreException('Failed to acquire a lock.');
}
} while (yield from Coroutine\sleep(self::LATENCY_TIMEOUT));
} | {@inheritdoc} | entailment |
public function free()
{
if (is_resource($this->queue) && msg_queue_exists($this->key)) {
if (!msg_remove_queue($this->queue)) {
throw new SemaphoreException('Failed to free the semaphore.');
}
$this->queue = null;
}
} | Removes the semaphore if it still exists.
@throws SemaphoreException If the operation failed. | entailment |
public function unserialize($serialized)
{
// Get the semaphore key and attempt to re-connect to the semaphore in memory.
list($this->key, $this->maxLocks) = unserialize($serialized);
if (msg_queue_exists($this->key)) {
$this->queue = msg_get_queue($this->key);
}
} | Unserializes a serialized semaphore.
@param string $serialized The serialized semaphore. | entailment |
protected function release()
{
// Call send in non-blocking mode. If the call fails because the queue
// is full, then the number of locks configured is too large.
if (!@msg_send($this->queue, 1, "\0", false, false, $errno)) {
if ($errno === MSG_EAGAIN) {
throw new SemaphoreException('The semaphore size is larger than the system allows.');
}
throw new SemaphoreException('Failed to release the lock.');
}
} | Releases a lock from the semaphore.
@throws SemaphoreException If the operation failed. | entailment |
public function send($data): \Generator
{
// Serialize the data to send into the channel.
try {
$serialized = serialize($data);
} catch (\Throwable $exception) {
throw new SerializationException(
'The given data cannot be sent because it is not serializable.', $exception
);
}
$length = strlen($serialized);
try {
yield from $this->write->write(pack('CL', 0, $length) . $serialized);
} catch (\Throwable $exception) {
throw new ChannelException('Sending on the channel failed. Did the context die?', $exception);
}
return $length;
} | {@inheritdoc} | entailment |
public function receive(): \Generator
{
// Read the message length first to determine how much needs to be read from the stream.
$length = self::HEADER_LENGTH;
$buffer = '';
$remaining = $length;
try {
do {
$buffer .= yield from $this->read->read($remaining);
} while ($remaining = $length - strlen($buffer));
$data = unpack('Cprefix/Llength', $buffer);
if (0 !== $data['prefix']) {
throw new ChannelException('Invalid header received.');
}
$buffer = '';
$remaining = $length = $data['length'];
do {
$buffer .= yield from $this->read->read($remaining);
} while ($remaining = $length - strlen($buffer));
} catch (\Throwable $exception) {
throw new ChannelException('Reading from the channel failed. Did the context die?', $exception);
}
set_error_handler($this->errorHandler);
// Attempt to unserialize the received data.
try {
$data = unserialize($buffer);
} catch (\Throwable $exception) {
throw new SerializationException('Exception thrown when unserializing data.', $exception);
} finally {
restore_error_handler();
}
return $data;
} | {@inheritdoc} | entailment |
public function start()
{
if (0 !== $this->oid) {
throw new StatusError('The thread has already been started.');
}
$this->oid = getmypid();
list($channel, $this->socket) = Stream\pair();
$this->thread = new Internal\Thread($this->socket, $this->function, $this->args);
if (!$this->thread->start(PTHREADS_INHERIT_INI | PTHREADS_INHERIT_FUNCTIONS | PTHREADS_INHERIT_CLASSES)) {
throw new ThreadException('Failed to start the thread.');
}
$this->channel = new ChannelledStream($this->pipe = new DuplexPipe($channel));
} | Spawns the thread and begins the thread's execution.
@throws \Icicle\Concurrent\Exception\StatusError If the thread has already been started.
@throws \Icicle\Concurrent\Exception\ThreadException If starting the thread was unsuccessful.
@throws \Icicle\Stream\Exception\FailureException If creating a socket pair fails. | entailment |
public function kill()
{
if (null !== $this->thread) {
try {
if ($this->thread->isRunning() && !$this->thread->kill()) {
throw new ThreadException('Could not kill thread.');
}
} finally {
$this->close();
}
}
} | Immediately kills the context.
@throws ThreadException If killing the thread was unsuccessful. | entailment |
private function close()
{
if (null !== $this->pipe && $this->pipe->isOpen()) {
$this->pipe->close();
}
if (is_resource($this->socket)) {
fclose($this->socket);
}
$this->thread = null;
$this->channel = null;
} | Closes channel and socket if still open. | entailment |
public function join(): \Generator
{
if (null === $this->channel || null === $this->thread) {
throw new StatusError('The thread has not been started or has already finished.');
}
try {
$response = yield from $this->channel->receive();
if (!$response instanceof ExitStatus) {
throw new SynchronizationError('Did not receive an exit status from thread.');
}
$result = $response->getResult();
$this->thread->join();
} catch (\Throwable $exception) {
$this->kill();
throw $exception;
}
$this->close();
return $result;
} | @coroutine
Gets a promise that resolves when the context ends and joins with the
parent context.
@return \Generator
@resolve mixed Resolved with the return or resolution value of the context once it has completed execution.
@throws StatusError Thrown if the context has not been started.
@throws SynchronizationError Thrown if an exit status object is not received. | entailment |
public function getException()
{
return new TaskException(
sprintf('Uncaught exception in worker of type "%s" with message "%s"', $this->type, $this->message),
$this->code,
$this->trace
);
} | {@inheritdoc} | entailment |
public function isFreed(): bool
{
// If we are no longer connected to the memory segment, check if it has
// been invalidated.
if ($this->handle !== null) {
$this->handleMovedMemory();
$header = $this->getHeader();
return $header['state'] === static::STATE_FREED;
}
return true;
} | Checks if the object has been freed.
Note that this does not check if the object has been destroyed; it only
checks if this handle has freed its reference to the object.
@return bool True if the object is freed, otherwise false. | entailment |
public function unwrap()
{
if ($this->isFreed()) {
throw new SharedMemoryException('The object has already been freed.');
}
$header = $this->getHeader();
// Make sure the header is in a valid state and format.
if ($header['state'] !== self::STATE_ALLOCATED || $header['size'] <= 0) {
throw new SharedMemoryException('Shared object memory is corrupt.');
}
// Read the actual value data from memory and unserialize it.
$data = $this->memGet(self::MEM_DATA_OFFSET, $header['size']);
return unserialize($data);
} | {@inheritdoc} | entailment |
protected function wrap($value)
{
if ($this->isFreed()) {
throw new SharedMemoryException('The object has already been freed.');
}
$serialized = serialize($value);
$size = strlen($serialized);
$header = $this->getHeader();
/* If we run out of space, we need to allocate a new shared memory
segment that is larger than the current one. To coordinate with other
processes, we will leave a message in the old segment that the segment
has moved and along with the new key. The old segment will be discarded
automatically after all other processes notice the change and close
the old handle.
*/
if (shmop_size($this->handle) < $size + self::MEM_DATA_OFFSET) {
$this->key = $this->key < 0xffffffff ? $this->key + 1 : mt_rand(0x10, 0xfffffffe);
$this->setHeader(self::STATE_MOVED, $this->key, 0);
$this->memDelete();
shmop_close($this->handle);
$this->memOpen($this->key, 'n', $header['permissions'], $size * 2);
}
// Rewrite the header and the serialized value to memory.
$this->setHeader(self::STATE_ALLOCATED, $size, $header['permissions']);
$this->memSet(self::MEM_DATA_OFFSET, $serialized);
} | If the value requires more memory to store than currently allocated, a
new shared memory segment will be allocated with a larger size to store
the value in. The previous memory segment will be cleaned up and marked
for deletion. Other processes and threads will be notified of the new
memory segment on the next read attempt. Once all running processes and
threads disconnect from the old segment, it will be freed by the OS. | entailment |
public function synchronized(callable $callback): \Generator
{
/** @var \Icicle\Concurrent\Sync\Lock $lock */
$lock = yield from $this->semaphore->acquire();
try {
$value = $this->unwrap();
$result = yield $callback($value);
$this->wrap(null === $result ? $value : $result);
} finally {
$lock->release();
}
return $result;
} | {@inheritdoc} | entailment |
public function free()
{
if (!$this->isFreed()) {
// Invalidate the memory block by setting its state to FREED.
$this->setHeader(static::STATE_FREED, 0, 0);
// Request the block to be deleted, then close our local handle.
$this->memDelete();
shmop_close($this->handle);
$this->handle = null;
$this->semaphore->free();
}
} | Frees the shared object from memory.
The memory containing the shared value will be invalidated. When all
process disconnect from the object, the shared memory block will be
destroyed by the OS.
Calling `free()` on an object already freed will have no effect. | entailment |
public function unserialize($serialized)
{
list($this->key, $this->semaphore) = unserialize($serialized);
$this->memOpen($this->key, 'w', 0, 0);
} | Unserializes the local object handle.
@param string $serialized The serialized object handle. | entailment |
private function handleMovedMemory()
{
// Read from the memory block and handle moved blocks until we find the
// correct block.
while (true) {
$header = $this->getHeader();
// If the state is STATE_MOVED, the memory is stale and has been moved
// to a new location. Move handle and try to read again.
if ($header['state'] !== self::STATE_MOVED) {
break;
}
shmop_close($this->handle);
$this->key = $header['size'];
$this->memOpen($this->key, 'w', 0, 0);
}
} | Updates the current memory segment handle, handling any moves made on the
data. | entailment |
private function setHeader(int $state, int $size, int $permissions)
{
$header = pack('CLS', $state, $size, $permissions);
$this->memSet(0, $header);
} | Sets the header data for the current memory segment.
@param int $state An object state.
@param int $size The size of the stored data, or other value.
@param int $permissions The permissions mask on the memory segment. | entailment |
private function memOpen(int $key, string $mode, int $permissions, int $size)
{
$this->handle = @shmop_open($key, $mode, $permissions, $size);
if ($this->handle === false) {
throw new SharedMemoryException('Failed to create shared memory block.');
}
} | Opens a shared memory handle.
@param int $key The shared memory key.
@param string $mode The mode to open the shared memory in.
@param int $permissions Process permissions on the shared memory.
@param int $size The size to crate the shared memory in bytes. | entailment |
public function acquire(): \Generator
{
// Try to create the lock file. If the file already exists, someone else
// has the lock, so set an asynchronous timer and try again.
while (($handle = @fopen($this->fileName, 'x')) === false) {
yield from Coroutine\sleep(self::LATENCY_TIMEOUT);
}
// Return a lock object that can be used to release the lock on the mutex.
$lock = new Lock(function (Lock $lock) {
$this->release();
});
fclose($handle);
return $lock;
} | {@inheritdoc} | entailment |
private function close($resource)
{
if (is_resource($resource)) {
fclose($resource);
}
if (is_resource($this->process)) {
proc_close($this->process);
$this->process = null;
}
$this->stdin->close();
} | Closes the stream resource provided, the open process handle, and stdin.
@param resource $resource | entailment |
public function join(): \Generator
{
if (null === $this->delayed) {
throw new StatusError('The process has not been started.');
}
$this->poll->listen();
try {
return yield $this->delayed;
} finally {
$this->stdout->close();
$this->stderr->close();
}
} | @coroutine
@return \Generator
@throws \Icicle\Concurrent\Exception\StatusError If the process has not been started. | entailment |
public function kill()
{
if (is_resource($this->process)) {
// Forcefully kill the process using SIGKILL.
proc_terminate($this->process, 9);
// "Detach" from the process and let it die asynchronously.
$this->process = null;
}
} | {@inheritdoc} | entailment |
public function signal(int $signo)
{
if (!$this->isRunning()) {
throw new StatusError('The process is not running.');
}
proc_terminate($this->process, (int) $signo);
} | Sends the given signal to the process.
@param int $signo Signal number to send to process.
@throws \Icicle\Concurrent\Exception\StatusError If the process is not running. | entailment |
public function get(string $key)
{
if (isset($this->ttl[$key]) && 0 !== $this->ttl[$key]) {
$this->expire[$key] = time() + $this->ttl[$key];
$this->queue->insert($key, -$this->expire[$key]);
}
return isset($this->data[$key]) ? $this->data[$key] : null;
} | @param string $key
@return mixed|null Returns null if the key does not exist. | entailment |
public function clear()
{
$this->data = [];
$this->expire = [];
$this->ttl = [];
$this->timer->stop();
$this->queue = new \SplPriorityQueue();
} | Removes all values. | entailment |
private function init(int $locks)
{
$locks = (int) $locks;
if ($locks < 1) {
$locks = 1;
}
$this->semaphore = new Internal\Semaphore($locks);
$this->maxLocks = $locks;
} | Initializes the semaphore with a given number of locks.
@param int $locks | entailment |
public function release()
{
if ($this->released) {
throw new LockAlreadyReleasedError('The lock has already been released!');
}
// Invoke the releaser function given to us by the synchronization source
// to release the lock.
($this->releaser)($this);
$this->released = true;
} | Releases the lock.
@throws LockAlreadyReleasedError If the lock was already released. | entailment |
public function run()
{
/* First thing we need to do is re-initialize the class autoloader. If
* we don't do this first, any object of a class that was loaded after
* the thread started will just be garbage data and unserializable
* values (like resources) will be lost. This happens even with
* thread-safe objects.
*/
foreach (get_declared_classes() as $className) {
if (strpos($className, 'ComposerAutoloaderInit') === 0) {
// Calling getLoader() will register the class loader for us
$className::getLoader();
break;
}
}
Loop\loop($loop = Loop\create(false)); // Disable signals in thread.
// At this point, the thread environment has been prepared so begin using the thread.
try {
$channel = new ChannelledStream(new DuplexPipe($this->socket, false));
} catch (\Throwable $exception) {
return; // Parent has destroyed Thread object, so just exit.
}
$coroutine = new Coroutine($this->execute($channel));
$coroutine->done();
$timer = $loop->timer(self::KILL_CHECK_FREQUENCY, true, function () use ($loop) {
if ($this->killed) {
$loop->stop();
}
});
$timer->unreference();
$loop->run();
} | Runs the thread code and the initialized function.
@codeCoverageIgnore Only executed in thread. | entailment |
public function start()
{
if ($this->isRunning()) {
throw new StatusError('The worker pool has already been started.');
}
// Start up the pool with the minimum number of workers.
$count = $this->minSize;
while (--$count >= 0) {
$worker = $this->createWorker();
$this->idleWorkers->enqueue($worker);
}
$this->running = true;
} | Starts the worker pool execution.
When the worker pool starts up, the minimum number of workers will be created. This adds some overhead to
starting the pool, but allows for greater performance during runtime. | entailment |
public function enqueue(Task $task): \Generator
{
$worker = $this->get();
return yield from $worker->enqueue($task);
} | Enqueues a task to be executed by the worker pool.
@coroutine
@param Task $task The task to enqueue.
@return \Generator
@resolve mixed The return value of the task.
@throws \Icicle\Concurrent\Exception\StatusError If the pool has not been started.
@throws \Icicle\Concurrent\Exception\TaskException If the task throws an exception. | entailment |
public function shutdown(): \Generator
{
if (!$this->isRunning()) {
throw new StatusError('The pool is not running.');
}
$this->running = false;
$shutdowns = [];
foreach ($this->workers as $worker) {
if ($worker->isRunning()) {
$shutdowns[] = new Coroutine($worker->shutdown());
}
}
return yield Awaitable\reduce($shutdowns, function ($carry, $value) {
return $carry ?: $value;
}, 0);
} | Shuts down the pool and all workers in it.
@coroutine
@return \Generator
@throws \Icicle\Concurrent\Exception\StatusError If the pool has not been started. | entailment |
public function kill()
{
$this->running = false;
foreach ($this->workers as $worker) {
$worker->kill();
}
} | Kills all workers in the pool and halts the worker pool. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.