React continues to dominate the front-end landscape

“React continues to dominate the front-end landscape, and 2017 provided one of the most anticipated releases yet with version 16. It includes the fiber architecture which enables asynchronous UI rendering. This release also makes it much easier to manage unexpected application failures by providing error boundaries along with many other features.”

@TreyHuffine https://levelup.gitconnected.com/a-recap-of-front-end-development-in-2017-7072ce99e727

Alternative way monitoring Zabbix via PHP API

Purpose create this project

Display: alarms, warnings from Zabbix on PHP page. In this case I had to show some information about my services on independent web page.

Set enviroment for Zabbix PHP API

What you need to start:

  1. Zabbix API 2+ – doc: https://www.zabbix.com/documentation/, download: https://www.zabbix.com/download
  2. Apache 2.4+
  3. PHP 7+
  4. Bootstap 3+
  5. I have defined some alarms in Zabbix and I want to observe it in “application”. Just use https://github.com/confirm/PhpZabbixApi and https://www.zabbix.com/documentation/2.2/manual/api
  6. Fronted i use Bootstrap http://getbootstrap.com/javascript/#buttons and some additional lib’s https://datatables.net/extensions/index it is good effective way to make it simple an easy.
  7. Git (Btubucket, Github)

Work set

Zabbix PHP API

PhpZabbixApi is an open-source PHP class library to communicate with the Zabbix™ JSON-RPC API. Because PhpZabbixApi is generated directly from the origin Zabbix™ 2.0 PHP front-end source code / files, each real Zabbix™ JSON-RPC API method is implemented (hard-coded) directly as an own PHP method. This means PhpZabbixApi is IDE-friendly, because you’ve a PHP method for each API method, and there are no PHP magic functions or alike.

Bootstrap

Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile first projects on the web.

Source code on Bitbucket

<?php
/**
 * ZabbixAPI_class.php Copyright 2017 by Karol Preiskorn
 *
 * @version 18.03.2017 21:35:17 Karol Preiskorn Init
 * @version 19.03.2017 16:37:59 KPreiskorn ZabbixAPI_class.php Export to BB
 *
 */
require_once 'PhpZabbixApi-2.4.5/build/ZabbixApi.class.php';
include 'header.php';

use ZabbixApi\ZabbixApi;

/**
 *
 * @todo add LDAP via uptime
 *
 * @var string $uri
 *
 */

$uri = "http://zabixx";
$username = "user";
$password = "pass";

// set passwords and uri
include "passwords.php";

/**
 * poor print_r function
 *
 * @param unknown $val
 *
 */
function print_r2($val)
{
    echo '<pre>';
    print_r($val);
    echo '</pre>';
}

/**
 * Better print_r function
 */
function obsafe_print_r($var, $return = false, $html = true, $level = 0)
{
    $spaces = "";
    $space = $html ? " " : " ";
    $newline = $html ? "<br />" : "\n";
    for ($i = 1; $i <= 6; $i ++) {
        $spaces .= $space;
    }
    $tabs = $spaces;
    for ($i = 1; $i <= $level; $i ++) {
        $tabs .= $spaces;
    }
    if (is_array($var)) {
        $title = "Array";
    } elseif (is_object($var)) {
        $title = get_class($var) . " Object";
    }
    $output = "<b>" . $title . "</b>" . $newline . $newline;
    foreach ($var as $key => $value) {
        if (is_array($value) || is_object($value)) {
            $level ++;
            $value = obsafe_print_r($value, true, $html, $level);
            $level --;
        }
        $output .= $tabs . "[" . $key . "] => [" . $value . "]" . $newline;
    }
    if ($return)
        return $output;
    else
        echo "<pre>" . $output . "</pre>";
}

/**
 *
 * Generate bootstrap table with headers and coun of elements
 *
 * @param string $title
 * @param unknown $count
 * @param unknown $id
 */
function print_table_header($title, $count, $headers, $id)
{
    print('<div class="panel panel-default">' . "\n");
    print('<div class="panel-heading">' . $title . ' <a href="#"> <span class="badge">' . $count . '</span></a></div>' . "\n");
    print("<table id='" . $id . "' class='table table-striped table-bordered'>" . "\n");

    print("<thead><tr>" . "\n");
    foreach ($headers as $header) {
        print("<th>" . $header . "</th>" . "\n");
    }
    print("</tr>\n</thead>\n<tbody>" . "\n");
}

try {
    // connect to Zabbix API
    $api = new ZabbixApi($uri, $username, $password);

    // get all graphs
    $alerts = $api->alertGet();
    // print_r2 ( $graphs [0] );

    arsort($alerts);

    $headers = array(
        "Alert Id",
        "Event Id",
        "Date time",
        "Sent to",
        "Subject",
        "Message"
    );

    print_table_header('Alerts', count($alerts), $headers, 'alarms');

    // print all alerts
    foreach ($alerts as $alert) {
        if ($alert->sendto != "karol.preiskorn@t-mobile.pl") {
            if (strpos($alert->subject, "PROBLEM:") !== false) {
                $alerttype = "class='warning'";
            } else {
                $alerttype = "class='normal'";
            }
            if (preg_match("/Original event ID: ([0-9]{4,12})/", $alert->message, $regs)) {
                $eventid_org = "[link: <a href='#" . $regs[1] . "'>" . $regs[1] . "</a>]";
            } else {
                $eventid_org = "Not found Original event ID";
            }
            printf("<tr id='%s' %s><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>" . "\n", $alert->eventid, $alerttype, $alert->alertid, $alert->eventid, date("Y-m-d h:i", $alert->clock), $alert->sendto, $alert->subject, $alert->message . " " . $eventid_org);
        }
    }
    print("</tbody>\n</table>\n</div>\n");

    // get all graphs
    $graphs = $api->graphGet();
    $header_graph = array(
        "Graph Id",
        "Description"
    );
    print_table_header('Graph', count($graphs), $header_graph, 'graph');

    // print all graph IDs
    foreach ($graphs as $graph) {
        printf("<tr><td>%8d</td><td>%s</td></tr>\n", $graph->graphid, $graph->name);
    }
    print("</tbody>\n</table>\n</div>\n");

    print('<div class="panel-footer">

        <p>© T-Mobile Polska Company | OSS development powered by Karol Preiskorn | internal use</p>

      </div>');
    print("</div></body></html>"); // end of container

    // print "<h1>Alerts... agian in raw</h2>";
                                       // obsafe_print_r ( $alerts, FALSE, TRUE );
} catch (Exception $e) {
    // Exception in ZabbixApi catched
    echo $e->getMessage();
}
?>
<?php
/**
 *
 * HTML 5
 *
 */
?>
<!DOCTYPE html>
<html>
<head>
<title>Zabbix</title>

<link rel="stylesheet" type="text/css"
	href="https://cdn.datatables.net/v/bs-3.3.7/jq-2.2.4/dt-1.10.13/af-2.1.3/b-1.2.4/b-colvis-1.2.4/fh-3.1.2/kt-2.2.0/r-2.1.1/rr-1.2.0/sc-1.4.2/se-1.2.0/datatables.min.css" />
<script type="text/javascript"
	src="https://cdn.datatables.net/v/bs-3.3.7/jq-2.2.4/dt-1.10.13/af-2.1.3/b-1.2.4/b-colvis-1.2.4/fh-3.1.2/kt-2.2.0/r-2.1.1/rr-1.2.0/sc-1.4.2/se-1.2.0/datatables.min.js"></script>

<script>
$(document).ready(function() {
    $('#alarms').DataTable( {
        deferRender:    true,
        scrollY:        400,
        scrollCollapse: false,
        scroller:       false
    } );
} );


$(document).ready(function() {
	$('#graph').DataTable({
        deferRender:    true,
        scrollY:        400,
        scrollCollapse: false,
        scroller:       false
    } );
} );
</script>

</head>

<body>
	<div class="container">
		<div class="jumbotron">
			<h1>Zabbix Alarm monitoring</h1>
			<p>Aplikacja monitoruje alarmy z Zabbix.</p>

			<a class="btn btn-primary btn-lg"
				href="http://wrex/zabbix/zabbix.php?action=dashboard.view"
				role="button">Zabbix Dashboard</a> <a class="btn btn-lg"
				href="#alarms" role="button">Alarms</a> <a class="btn btn-lg"
				href="#graph" role="button">Graph</a> <a class="btn btn-lg"
				href="simple-json.php" role="button">Simple JSON</a>


			<button class="btn btn-primary" type="button" data-toggle="collapse"
				data-target="#collapseExample" aria-expanded="false"
				aria-controls="collapseExample">About</button>


			<div class="collapse" id="collapseExample">
				<div class="well">Aplikacja monitoruje alarmy z OSS Zabbix na
					serwerze wrex. Dost�p do API poprzez klas� PHP -> ZabbixApi. Opis
					API
					https://www.zabbix.com/documentation/2.2/manual/api/reference/history/get
				</div>
			</div>

		</div>
<?php

/**
 * Zabbix monitoring in PHP
 *
 * @author Karol Preiskorn
 *
 * @version 2017-04-16 KP init
 * @version 17.03.2017 14:47:16 Karol Preiskorn dodanie informacji na temat Alert�w
 * @version 17.03.2017 18:07:38 Karol Preiskorn - dodanie synchronizacji
 * @version 9 gru 2017 12:47:16 KPreiskorn simple-json.php add composer and manage password
 *
 *
 *
 * phpinfo ();
 *
 */
$uri = "http://zabixx";
$username = "user";
$password = "pass";

// set passwords and uri
include "passwords.php";
/**
 *
 * @param unknown $in
 * @param number $indent
 * @param string $from_array
 * @return string
 */
function json_readable_encode($in, $indent = 0, $from_array = true) {
	$_myself = __FUNCTION__;
	$_escape = function ($str) {
		return preg_replace ( "!([\b\t\n\r\f\"\\'])!", "\\\\\\1", $str );
	};

	$out = '';

	foreach ( $in as $key => $value ) {
		$out .= str_repeat ( "\t", $indent + 1 );
		$out .= "\"" . $_escape ( ( string ) $key ) . "\": ";

		if (is_object ( $value ) || is_array ( $value )) {
			$out .= "\n";
			$out .= $_myself ( $value, $indent + 1 );
		} elseif (is_bool ( $value )) {
			$out .= $value ? 'true' : 'false';
		} elseif (is_null ( $value )) {
			$out .= 'null';
		} elseif (is_string ( $value )) {
			$out .= "\"" . $_escape ( $value ) . "\"";
		} else {
			$out .= $value;
		}

		$out .= ",\n";
	}

	if (! empty ( $out )) {
		$out = substr ( $out, 0, - 2 );
	}

	$out = str_repeat ( "\t", $indent ) . "{\n" . $out;
	$out .= "\n" . str_repeat ( "\t", $indent ) . "}";

	return $out;
}

/**
 *
 * @param unknown $array
 */
function expand_arr($array) {
	foreach ( $array as $key => $value ) {
		if (is_array ( $value )) {
			echo "<i>" . $key . "</i>:<br>";
			expand_arr ( $value );
			echo "<br>\n";
		} else {
			echo "<i>" . $key . "</i>: " . $value . "<br>\n";
		}
	}
}
/**
 *
 * @param unknown $uri
 * @param unknown $data
 * @return mixed
 */
function json_request($uri, $data) {
	$json_data = json_encode ( $data );
	$c = curl_init ();
	curl_setopt ( $c, CURLOPT_URL, $uri );
	curl_setopt ( $c, CURLOPT_CUSTOMREQUEST, "POST" );
	curl_setopt ( $c, CURLOPT_RETURNTRANSFER, true );
	curl_setopt ( $c, CURLOPT_POST, $json_data );
	curl_setopt ( $c, CURLOPT_POSTFIELDS, $json_data );
	curl_setopt ( $c, CURLOPT_HTTPHEADER, array (
			'Content-Type: application/json',
			'Content-Length: ' . strlen ( $json_data )
	) );
	curl_setopt ( $c, CURLOPT_SSL_VERIFYPEER, false );
	$result = curl_exec ( $c );

	echo "<b>JSON Request:</b><br>\n";
	echo $json_data . "<br><br>\n";

	echo "<b>JSON Answer:</b><br>\n";
	echo $result . "<br><br>\n";

	/*
	 * echo "<b>CURL Debug Info:</b><br>\n";
	 * $debug = curl_getinfo ( $c );
	 * echo expand_arr ( $debug ) . "<br><hr>\n";
	 */

	return json_decode ( $result, true );
}
/**
 *
 * @param unknown $uri
 * @param unknown $username
 * @param unknown $password
 * @return unknown
 */
function zabbix_auth($uri, $username, $password) {
	$data = array (
			'jsonrpc' => "2.0",
			'method' => "user.login",
			'params' => array (
					'user' => $username,
					'password' => $password
			),
			'id' => "1"
	);
	$response = json_request ( $uri, $data );
	return $response ['result'];
}

/**
 *
 * @param unknown $uri
 * @param unknown $authtoken
 * @return unknown
 */
function zabbix_get_hostgroups($uri, $authtoken) {
	$data = array (
			'jsonrpc' => "2.0",
			'method' => "hostgroup.get",
			'params' => array (
					'output' => "extend",
					'sortfield' => "name"
			),
			'id' => "2",
			'auth' => $authtoken
	);
	$response = json_request ( $uri, $data );
	return $response ['result'];
}
/**
 *
 * @param unknown $uri
 * @param unknown $authtoken
 */
function zabbix_get_alert($uri, $authtoken) {
	$data = array (
			"jsonrpc" => "2.0",
			"method" => "alert.get",
			"params" => array (
					"output" => "extend",
					"actionids" => "3"
			),
			"auth" => $authtoken,
			"id" => 1
	);
	$response = json_request ( $uri, $data );
	return $response ['result'];
}

/**
 *
 * @var Ambiguous $authtoken
 */
print "<h1>Auth</h1>";
$authtoken = zabbix_auth ( $uri, $username, $password );

print "<h1>HostGrups</h1>";
expand_arr ( zabbix_get_hostgroups ( $uri, $authtoken ) );
print "<h2>json_readable_encode</h2>";
json_readable_encode ( zabbix_get_hostgroups ( $uri, $authtoken ) );
print "<h1>Alerts</h1>";
expand_arr ( zabbix_get_alert ( $uri, $authtoken ) );
?>

RegEx never endig story….

It is example of use RegEx to prepare SQL data for SELECT/UPDATE operation.

/^.*/gm

  1. ^ asserts position at start of a line
  2. .* matches any character (except for line terminators)
  3. * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
  4. Global pattern flags
    1. g modifier: global. All matches (don’t return after first match)
    2. m modifier: multi line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)

This example simple replace MBS to ,'MBS'. For example when you have many selected values SQL (in one column) and need convert it to running query.

Convert it to:

Very good tools for testing: https://regex101.com/ and here is this example: https://regex101.com/r/34repv/1

How its run?

Simple by Sublimetext, Notepad++ Find/Replace command

 

Regular Expressions Cheat Sheet

A regular expression specifies a set of strings that matches it. This cheat sheet is based off Python 3’s Regular Expressions (http://docs.python.org/3/library/re.html) but is designed for searches within Sublime Text.

Special Characters

\ Escapes special characters or signals a special sequence.
. Matches any single character except a newline.
^ Matches the start of the string.
$ Matches the end of the string.
* Greedily matches 0 or more repetitions of the preceding RE.
*? Matches 0 or more repetitions of the preceding RE.
+ Greedily matches 1 or more repetitions of the preceding RE.
+? Matches 1 or more repetitions of the preceding RE.
? Greedily matches 0 or 1 repetitions of the preceding RE.
?? Matches 0 or 1 repetitions of the preceding RE.
A|B Matches A, if A is unmatched then matches B, where A and B are arbitrary REs.
{m} Matches exactly m many repetitions of the previous RE.
{m,n} Greedily matches from m many to n many repetitions of the previous RE.
{m,n}? Matches m many to n many repetitions of the previous RE.

[…] Indicates a set of characters to match.

[amk] Matches ‘a’, ‘m’, or ‘k’.
[a-z] Matches ‘a’ through ‘z’.
[a-f0-7] Matches ‘a’ through ‘f’ or ‘0’ through ‘7’.
[a\-z] Matches ‘a’, ‘-‘, or ‘z’.
[a-] Matches ‘a’ or ‘-‘.
[-a] Matches ‘a’ or ‘-‘.
[(+*)] Matches ‘(‘, ‘+’, ‘*’, or ‘)’. [] matches special characters literally.
[\w] Matches the character class for ‘\w’. See character classes.
[^5] Matches anything other than ‘5’. ‘^’ forms the complementary set only as the first character in a set.
[]()] Matches ‘]’, ‘(‘, and ‘)’. ‘]’ is taken literally only as the first character in a set.
[()\]] Matches ‘]’, ‘(‘, and ‘)’.

(…) Matches the RE inside the parenthesis and assigns a new group.
(?P…) The RE matched is accessible by the group indicated by name.

(?…) Extension notation which changes a RE’s behavior. These do not assign a new group.
(?aiLmsux) Sets the corresponding flag to each letter. Does not work within Sublime Text.
(?:…) A non-capturing version of parenthesis. The matched substring cannot be retrieved later.
(?P=name) Matches the substring matched by the group named name.
(?#…) A comment, the contents are ignored.
(?=…) Lookahead assertion, the preceding RE only matches if this matches.
(?!…) Negative lookahead assertion, the preceding RE only matches if this doesn’t match.
(?<=…) Positive lookbehind assertion, the following RE will only match if preceded with this fixed length RE.
(?<!…) Negative lookbehind assertion, the following RE will only match if not preceded with this fixed length RE.
(?(id)true|false) If group id exists then uses the true RE, else use the false RE.

Character classes

\1 Matches the contents of the group labelled by the same number. Acceptable numbers are 1-99.
\A Matches at the start of the current string.
\b Matches the empty string at the beginning or end of a word. \b matches the boundary between \w and \W.
\B Matches the empty string not at the beginning or end of a word.
\d Matches any Unicode decimal digit, including 0-9.
\D Matches any Unicode non-decimal digit.
\s Matches any Unicode whitespace character, including ‘ ‘, \t, \n, \r, \f and \v.
\S Matches any Unicode non-whitespace character.
\w Matches any Unicode word character, including a-z, A-Z, and 0-9.
\W Matches any Unicode non-word character.
\Z Matches at the end of the string.

\a Matches the ASCII Bell ().
\f Matches the ASCII Formfeed ( ).
\n Matches the ASCII Linefeed.
\r Matches the ASCII Carriage Return ().
\t Matches the ASCII Horizontal Tab.
\v Matches the ASCII Vertical Tab ( ).

SublimeText 3 tips and customization

One of best text editor for Linux and W$ bellow some tips and usefully configuration

Regexp conversion to Wiki links

Conversion to Wiki links add [ before and ] after text.

Find what: (http.{2,})
Relpace to: [\1]

Polish letters

Polskie znaki diakrytyczne w Sublime Text 3 – dodanie wpisów do Key Bindings – User (na platformie Windows jest to plik Default (Windows).sublime-keymap):

Adding comma to each line using sublime text

To add comma to any line

  1. Select the lines you want to modify
  2. CTRL + SHIFT + L
  3. RIGHT_ARROW
  4. COMMA

Using ctrl + shift + L is how you can modify all selected lines. Very handy 🙂 Make batch edits with Multiple Selections.

Column Selection can be used to select a rectangular area of a file. Column selection doesn’t operate via a separate mode, instead it makes use of multiple selections.

You can use additive selections to select multiple blocks of text, or subtractive selections to remove a block.

‘Find What’: $ // matching all ends of your lines
‘Replace With’: , // replaces all line ends with a coma

Solve this problem

Links

  • https://www.shortcutfoo.com/blog/sublime-text-3-gifs-cheat-sheet/
  • https://forum.sublimetext.com/t/my-sublime-text-windows-cheat-sheet/8411

Source: Best of Sublime Text 3: Features, Plugins, and Settings | Scotch

Sublime Text 3 is an amazing piece of software. To start, it is a clean, functional, and fast code editor. Not only does it have incredible built in features (multi-edit and vim mode), but it has support for plugins, snippets, and many other things.

Source: Best of Sublime Text 3: Features, Plugins, and Settings | Scotch

Narzędzia to projektowania baz danych

GNU-GPL

Multiple versions/licenses (each has a “free” and a “not-free” version)

  • DBVisualizer
  • Toad http://www.toadsoft.com/

Not-free

  • Microsoft Visio – (If you already have it, it does work quite well)
  • DataStudio – 30 day trial http://www.aquafold.com
  • DBWrench – 30 day trial http://www.dbwrench.com/

ER diagram tool

  • http://druid.sf.net/
  • http://schemaspy.sourceforge.net/
  • http://uml.sourceforge.net/index.php

Proudly powered by WordPress | Theme: Baskerville 2 by Anders Noren.

Up ↑