1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 |
/** * ホームページの内容を取ってくる / Fetch the contents of the webpage * * https://davidwalsh.name/curl-download */ function getHtml($url) { $timeout = 5; $user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_USERAGENT, $user_agent); $data = curl_exec($ch); curl_close($ch); // echo $data; return $data; } /** * html 文字列から タイトルとアーティクルを探して返す / Find and return title and article from html string */ private function getTitleAndArticleFromHtmlString($html) { // echo '<textarea>'.$html.'</textarea>'; $array = $this->parseHtmlToArray($html); list($k, $article) = $this->getValueByArrayKey('article', null, $array); // print_r($article); list($k, $title) = $this->getValueByArrayKey('h1', null, $article); // print_r($title); list($k, $body) = $this->getValueByArrayKey('div', array('key' => 'id', 'value' => 'entryBody'), $article); // print_r($body); return array('title' => strip_tags($this->arrayToHtml($title)), 'article' => $this->arrayToHtml($body)); } /** * html array から指定された tag, attribute を持つ配列を探して返す * * @param $searchKey: search target tag of html * @param $attribute null or array(key =>, value =>): search target attribute of html tag * @param $array: html array by simplexml_load_string */ private function getValueByArrayKey($searchKey, $attribute, $array) { foreach ($array as $key => $value) { if (preg_match('/^[0-9]+$/', $key)) { $key = 'div'; } if (strcmp($key, $searchKey) == 0) { if (is_array($attribute)) { if (is_array($value) && array_key_exists('@attributes', $value) && array_key_exists($attribute['key'], $value['@attributes']) && strcmp($value['@attributes'][$attribute['key']], $attribute['value']) == 0) { // echo ' key1: '.$key. 'a: '.$value['@attributes'][$attribute['key']]; return array(true, $value); } } else { // echo ' key2: '.$key; return array(true, $value); } } if (is_array($value)) { list($k, $v) = $this->getValueByArrayKey($searchKey, $attribute, $value); if ($k) { //echo ' key3: '.$key; return array(true, $v); } } } return array(false, null); } /** * html をパースして array に変換して返す / Parse html, convert it to an array and return */ private function parseHtmlToArray($html) { $domDocument = new DOMDocument(); @$domDocument->loadHTML($html); // エラー出力抑制 @ // Warning: DOMDocument::loadHTML(): Unexpected end tag : ... $xmlString = $domDocument->saveXML(); $xmlObject = simplexml_load_string($xmlString); // $xmlObject = simplexml_load_string($html); // var_dump($xmlObject); $array = json_decode(json_encode($xmlObject), true); // Object to Array return $array; } /** * simplexml_load_string でパースした html array を html 文字列に変換して返す / Convert html array to html string and return, the html array was parsed by simplexml_load_string and converted to array. * * 自己閉じタグには非対応 / Not supported for self closing tags. */ private function arrayToHtml($a) { $html = ''; foreach ($a as $key => $value) { if (strcmp($key, '@attributes') == 0) { continue; } else if (preg_match('/^[0-9]+$/', $key)) { $key = 'div'; } $html .= '<'.$key; if (is_array($value)) { if (array_key_exists('@attributes', $value)) { $attr = $this->attributeArrayToString($value['@attributes']); $html .= ' '.$attr.'>'; unset($value['@attributes']); } else { $html .= '>'; } $html .= $this->arrayToHtml($value); } else { $html .= '>'.$value; } $html .= '</'.$key.'>'; } return $html; } /** * simplexml_load_string でパースした html タグのアトリビュートの配列を文字列にして返す * * 値はダブルコーテーションで囲まれる */ private function attributeArrayToString($a) { $attr = ''; foreach ($a as $keyA => $valueA) { $attr .= ' '.$keyA.'="'.$valueA.'"'; } return $attr; } |
This way is temporary support to Gutenberg for Metabox in a WordPress classic plugin
クラシックなプラグインでメタボックスを使用していたら保存ができなくなったので暫定的な対処をしてみた。Gutenberg 4.1.1, WordPress 5.1 alpha
1 2 3 4 5 6 7 8 9 10 11 |
<?php // the-plugin.php // Using classic MetaBox and Gutenberg, save and update error Unhandled promise rejection... if ($_GET['action'] === 'edit' && $_GET['post'] && $_GET['classic-editor'] && $_GET['meta_box']) { header("HTTP/1.1 200 OK"); // your code exit(0); } // plugin code... |
spinner is moving…
Tried crypt AES Mode CFB with Python, JavaScript and PHP, data cross each other / AES でデーターを相互に暗号化・復号化するテスト
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
#!/usr/bin/python3 # -*- coding:utf-8 -*- # # pip install PyCrypto # pip3 install PyCrypto # # See: https://stackoverflow.com/questions/46346371/convert-openssl-aes-in-php-to-python-aes import base64 from Crypto.Cipher import AES from Crypto import Random import re, random # echo test | openssl aes-256-cbc -e -base64 encryption_encoded_key = 'U2FsdGVkX19nm8SCCdOk1RytPaIUvb2+Z7w+JfarEYo=' end_of_data_mark = b'<EOD>' def aes_encrypt(data): try: global encryption_encoded_key, end_of_data_mark data += end_of_data_mark.decode() # Align data length data = data + padding(data) encryption_key = base64.b64decode(encryption_encoded_key) iv = Random.new().read(AES.block_size) cipher = AES.new(encryption_key, AES.MODE_CFB, iv, segment_size=128) # Encrypt the data using AES 256 encryption in CBC mode using our encryption key and initialization vector. encrypted = cipher.encrypt(data) return base64.b64encode(encrypted).decode(), base64.b64encode(iv).decode() except Exception as e: raise Exception(str(e)) def aes_decrypt(data, iv): try: global encryption_encoded_key, end_of_data_mark encryption_key = base64.b64decode(encryption_encoded_key) iv = base64.b64decode(iv) cipher = AES.new(encryption_key, AES.MODE_CFB, iv, segment_size=128) encrypted_data = base64.b64decode(data) # Align data length encrypted_data = encrypted_data + padding(encrypted_data).encode() return cipher.decrypt(encrypted_data).split(end_of_data_mark)[0].decode() except Exception as e: raise Exception(str(e)) def padding(data): try: size = len(data) i = int(size / AES.block_size) j = AES.block_size * i if j < size: j += AES.block_size return "".ljust(j - size, "\x00") except Exception as e: raise Exception(str(e)) if __name__ == '__main__': # 12345678123456781234567812345678 data = 'Hello world!' data, iv = aes_encrypt(data) print("data = %s" % data) print("iv = %s" % iv) data = aes_decrypt(data, iv) print("data = %s" % data) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
/* See: https://code.google.com/archive/p/crypto-js/ https://code.google.com/archive/p/crypto-js/downloads https://stackoverflow.com/questions/14958103/how-to-decrypt-message-with-cryptojs-aes-i-have-a-working-ruby-example https://gist.github.com/marcoslin/8026990 http://sct9.blog85.fc2.com/blog-entry-62.html https://fisproject.jp/2015/01/crypto-js-pycrypto-compatible/ */ var encryption_encoded_key = 'U2FsdGVkX19nm8SCCdOk1RytPaIUvb2+Z7w+JfarEYo='; var end_of_data_mark = '<EOD>'; function aes_encrypt(data) { var key = CryptoJS.enc.Base64.parse(encryption_encoded_key).toString(); var key_hex = CryptoJS.enc.Hex.parse(key); var iv_base64 = iv(); var iv_string = CryptoJS.enc.Base64.parse(iv_base64).toString(); var iv_hex = CryptoJS.enc.Hex.parse(iv_string); data += end_of_data_mark; var result = CryptoJS.AES.encrypt(data, key_hex, { iv: iv_hex, mode: CryptoJS.mode.CFB, padding: CryptoJS.pad.NoPadding, }); return Array(result.toString(), iv_base64); } function aes_decrypt(data, iv_base64) { var key = CryptoJS.enc.Base64.parse(encryption_encoded_key).toString(); var key_hex = CryptoJS.enc.Hex.parse(key); var iv_string = CryptoJS.enc.Base64.parse(iv_base64).toString(); var iv_hex = CryptoJS.enc.Hex.parse(iv_string); var cipher = CryptoJS.lib.CipherParams.create({ ciphertext: CryptoJS.enc.Base64.parse(data), }); var result = CryptoJS.AES.decrypt(cipher, key_hex, { iv: iv_hex, mode: CryptoJS.mode.CFB, padding: CryptoJS.pad.NoPadding, }); result = result.toString(CryptoJS.enc.Utf8).split(end_of_data_mark, 1)[0]; return result; } function iv() { var rawStr = CryptoJS.lib.WordArray.random(128 / 16); var wordArray = CryptoJS.enc.Utf8.parse(rawStr); var base64 = CryptoJS.enc.Base64.stringify(wordArray); return base64; } (function () { var data = 'Hello world!'; var e = aes_encrypt(data); var data = e[0]; var iv = e[1]; console.log('data = ' + data); console.log('iv = ' + iv); var d = aes_decrypt(data, iv); console.log('data = ' + d); })(); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>CryptoJS AES 256 mode-cfb</title> <script src="./components/core.js"></script> <script src="./components/md5.js"></script> <script src="./components/enc-base64.js"></script> <script src="./components/evpkdf.js"></script> <script src="./components/cipher-core.js"></script> <script src="./components/aes.js"></script> <script src="./components/mode-cfb.js"></script> <script src="./components/pad-nopadding.js"></script> <script src="test.js"></script> </head> <body> </body> </html> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
<?php /* * https://stackoverflow.com/questions/46346371/convert-openssl-aes-in-php-to-python-aes */ $encryption_encoded_key = 'U2FsdGVkX19nm8SCCdOk1RytPaIUvb2+Z7w+JfarEYo='; $end_of_data_mark = '<EOD>'; function aes_encrypt($data) { global $encryption_encoded_key, $end_of_data_mark; try { $data .= $end_of_data_mark; $encryption_key = base64_decode($encryption_encoded_key); $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cfb')); $encrypted = openssl_encrypt($data, 'aes-256-cfb', $encryption_key, 1, $iv); return Array(base64_encode($encrypted), base64_encode($iv)); } catch (Exception $e) { throw new Exception($e->getMessage()); } } function aes_decrypt($data, $iv) { global $encryption_encoded_key, $end_of_data_mark; try { $encryption_key = base64_decode($encryption_encoded_key); $encrypted_data = base64_decode($data); $iv = base64_decode($iv); return explode($end_of_data_mark, openssl_decrypt($encrypted_data, 'aes-256-cfb', $encryption_key, 1, $iv), 2)[0]; } catch (Exception $e) { throw new Exception($e->getMessage()); } } $data = 'Hello world!'; list($data, $iv) = aes_encrypt($data); echo "data = $data\n"; echo "iv = $iv\n"; $data = aes_decrypt($data, $iv); echo "data = $data\n"; |
Socket sync communication test between PHP7 and Python3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
#!/usr/bin/python3 # -*- coding:utf-8 -*- import socket, select, json TOKEN = '1234567' HOST = '127.0.0.1' PORT = 50009 SOCKET_TIMEOUT = 3 # seconds BACKLOG = 10 BUFSIZE = 4096 # See: http://memo.saitodev.com/home/python_network_programing/ def initSocket(): server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) readfds = set([server_sock]) try: server_sock.bind((HOST, PORT)) server_sock.listen(BACKLOG) while True: rready, wready, xready = select.select(readfds, [], []) for sock in rready: if sock is server_sock: # fd = sock.fileno() # print("fd: %d" % fd) sock.settimeout(SOCKET_TIMEOUT) conn, address = server_sock.accept() readfds.add(conn) else: buffer = sock.recv(BUFSIZE) if len(buffer) == 0: sock.close() readfds.remove(sock) else: ret = getSendValue(command(buffer)) sock.send(ret) # sock.close() readfds.remove(sock) except Exception as e: print("Exception: " + str(e)) finally: for sock in readfds: sock.close() server_sock.close() # @param buffer receive buffer data # @return dict def command(buffer): try: data = getReceiveValue(buffer) print("Receive: ", data) if 'token' not in data or data['token'] != TOKEN: msg = "token error." print(msg) return {"message": msg} if 'command' not in data: msg = "Receive message is failed, key 'command' not found." print(msg) return {"message": msg} cmd = data['command'] return {"Receive command": cmd} except Exception as e: return {"exception": str(e)} def getReceiveValue(buffer): return json.JSONDecoder().decode(buffer.decode('utf-8').strip()) def getSendValue(value): if not (isinstance(value, list) or isinstance(value, dict) or isinstance(value, tuple)): value = {value} return bytes(json.JSONEncoder().encode(value), 'utf-8') def main(): print("Backend start") while True: initSocket() print("Escape main loop...") if __name__ == '__main__': main() |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
<?php $sendMessage = array( 'cmd' => 'commandA', ); $result = commBackend($sendMessage); print_r($result); function commBackend($sendMessage) { $sendMessage['token'] = '1234567'; $address = '127.0.0.1'; $service_port = 50009; $timeout_sec = 3; // sec $timeout = time() + $timeout_sec; try { $fp = fsockopen($address, $service_port); if (!$fp) { throw new Exception('Cannot communicate Backend.'); } // non blocking, need to timeout. stream_set_blocking($fp ,0); stream_set_timeout($fp, $timeout_sec); fwrite($fp, json_encode($sendMessage)); $contents = ''; do { if ($timeout - time() <= 0) { $timeout = -1; break; } // echo '.'; $contents .= fread($fp, 8192); } while (!feof($fp)); $info = stream_get_meta_data($fp); // print_r($info); fclose($fp); if ($info['timed_out'] || $timeout === -1) { throw new Exception('Communication with the backend timed out.'); } // echo $contents; $res = json_decode($contents); // json string to object // print_r($res); return $res; } catch (Exception $e) { echo $e->getMessage(); throw new Exception($e->getMessage()); } } |
Execute command with PHP and read/write STDOUT, STDERR and STDIN; tested PHP7 and PHP5
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 |
<?php // Execute command with PHP and read/write STDOUT, STDERR and STDIN $cmd = array( 'cwd' => '/home/user/Desktop', 'cmd' => '/home/user/Desktop/test.sh arg1 arg2 arg3', // 実行するコマンドのための環境変数の配列。 現在の PHP プロセスと同じ環境変数を使用する場合は NULL を指定します。 'env' => NULL, 'stdout' => '', 'stderr' => '', 'stdin' => array( '[\r\n]ABC[\r\n]' => "Yes\n", '[\r\n]DEF[\r\n]' => "No\n", ), ); try { $result = exec_cmd($cmd); print_r($result); } catch (Exception $e) { echo $e->getMessage(); } /** * See: http://php.net/manual/ja/function.proc-open.php * https://stackoverflow.com/questions/16351302/reading-from-stdin-pipe-when-using-proc-open * http://ishijima.blog97.fc2.com/blog-entry-68.html */ function exec_cmd($cmd, $timeout_sec = 3) { $timeout = time() + $timeout_sec; // sec $descriptorspec = array( 0 => array("pipe", "r"), // stdin read by child process 1 => array('pipe', 'w'), // stdout write by child process 2 => array('pipe', 'w') // stderr write by child process ); $pipes = NULL; $proc = proc_open($cmd['cmd'], $descriptorspec, $pipes, $cmd['cwd'], $cmd['env']); if (!is_resource($proc)) { return false; } // print_r($pipes); // non blocking, need to timeout. stream_set_blocking($pipes[0] ,0); stream_set_blocking($pipes[1] ,0); stream_set_blocking($pipes[2] ,0); $stdin_key = key($cmd['stdin']); $stdin_val = array_shift($cmd['stdin']); $match_string = ''; $close = function($proc, $pipes) { foreach ($pipes as &$pipe) { if ($pipe) { fclose($pipe); } } unset($pipes); return proc_close($proc); }; // now, poll for child termination while (true) { // echo 'while '; // detect if the child has terminated - the php way $status = proc_get_status($proc); // check return value if ($status === FALSE) { $close($proc, $pipes); throw new Exception ("Failed to obtain status information for ".$status['pid']); } if ($timeout - time() <= 0) { $close($proc, $pipes); throw new Exception ("Timeout ".$status['pid']); } if ($status['running'] === FALSE) { $cmd['exitcode'] = $status['exitcode']; $cmd['proc_close'] = $close($proc, $pipes); // print_r($cmd); return $cmd; } // read from child stdout and stderr // avoid *forever* blocking through using a time out (50000usec) foreach (array(1, 2) as $desc) { // echo 'foreach '; // check stdout for data $read = array($pipes[$desc]); $write = NULL; $except = NULL; $tv = 0; $utv = 50000; // microsecond $n = stream_select($read, $write, $except, $tv, $utv); if ($n == 0) { continue; } do { // echo 'do '; $data = fread($pipes[$desc], 8092); // fwrite(STDOUT, $data); if ($desc == 1) { $cmd['stdout'] .= $data; $match_string .= $data; } else { $cmd['stderr'] .= $data; } if ($stdin_key) { if (preg_match('/('.$stdin_key.')(.*)$/', $match_string, $matches)) { // echo '-- matches --'; // print_r($matches); $match_string = $matches[count($matches) - 1]; // Behind the matched part fwrite($pipes[0], $stdin_val); $stdin_key = key($cmd['stdin']); $stdin_val = array_shift($cmd['stdin']); } } } while (strlen($data) > 0); } // foreach stdout and stderr } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#!/bin/sh # test.sh pwd echo $* echo '123,' echo 'error-123,' >&2 echo '456,' echo 'error-456,' >&2 echo 'ABC' read -p "fool? (y/N): " yn echo $yn echo '789,' echo 'error-789,' >&2 echo 'DEF' read -p "cool? (y/N): " yn echo $yn echo '101112,' echo 'error-101112,' >&2 |