【Linux】Neovimのインストールと設定(viでPHP+Laravel開発)

Neovim

Neovimのインストール
# dnf -y install neovim
プラグインマネージャのインストール
# curl -fLo ~/.local/share/nvim/site/autoload/plug.vim --create-dirs \
     https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
設定
# mkdir -p ~/.config/nvim
# vi ~/.config/nvim/init.vim
" ===== 基本設定 =====
set number
set relativenumber
set tabstop=4
set shiftwidth=4
set expandtab
set cursorline
syntax on

" ===== プラグイン =====
call plug#begin('~/.config/nvim/plugged')

Plug 'jwalton512/vim-blade'       " Bladeハイライト
Plug 'neoclide/coc.nvim', {'branch': 'release'}  " LSP補完
Plug 'dense-analysis/ale'         " 非同期Lint
Plug 'tpope/vim-fugitive'         " Git

call plug#end()

" ===== coc.nvim =====
let g:coc_global_extensions = ['coc-phpls']

" ===== ALE =====
let g:ale_linters = {'php': ['phpcs', 'phpstan']}
let g:ale_fixers = {'php': ['phpcbf']}
let g:ale_fix_on_save = 1

" ===== キーバインド =====
inoremap   pumvisible() ? "\" : "\"
inoremap   pumvisible() ? "\" : "\":wq
エイリアス設定
# echo "alias vi='nvim'" >> ~/.bashrc
# source ~/.bashrc
プラグインのインストール
# vi
:PlugInstall

【Wordpress】ワードプレスのブロックテーマTwentyTwentyThree(TT3)でのカスタムフィールドの使い方

カスタムフィールドを表示させる手順

・プラグインAdvanced Custom Fieldsをインストール
 フィールド名:comment でカスタムフィールドを設定
・プラグインMeta Field Blockをインストール
xxx.html編集
<!-- wp:mfb/meta-field-block {"fieldType":"acf","fieldName":"comment"} /-->

【Wordpress】ワードプレスのブロックテーマでアイキャッチ(サムネイル)一覧を表示させる

トップページなどでの画像サムネイル一覧表示

久々にワードプレスをいじったところ、”ブロックテーマ”なるものに置き換わりエディターも以前使っていたものはクラシックへ。theme.jsonって?
PHPをちょくせつ編集していたものが、テンプレートファイルxxx.htmlなどと置き換わり、
試行錯誤している最中、色々と沼る要素在り。
ホーム画面にサムネイル一覧を表示させるタグ
home.htmlなどを編集。
この場合はカスタム投稿タイプ”portfolio”を表示させる例。(一般的な投稿は”post”)
・
<ul class="portfolio">
<!-- wp:query {"queryId":1,"query":{"offset":0,"postType":"portfolio","categoryIds":[],"tagIds":[],"order":"desc","orderBy":"date","author":"","search":"","sticky":""}} -->
<!-- wp:post-template {"align":"wide"} -->
<li><!-- wp:post-featured-image {"isLink":true,"sizeSlug":"thumbnail"} /--></li>
<!-- /wp:post-template -->
<!-- /wp:query -->
</ul>
・

【Laravel】データーベースの特定のテーブルだけ修正、作り直したら外部キー制約でシーダーエラー

特定のテーブルだけマイグレート

テーブルの作り直し作業が発生したため、
マイグレーションファイルを修正後、マイグレートのやり直し。
マイグレーションの確認
$ php artisan migrate:status
+------+-------------------------------------------------------+-------+
| Ran? | Migration                                             | Batch |
+------+-------------------------------------------------------+-------+
| Yes  | 2019_12_14_000001_create_personal_access_tokens_table | 1     |
| Yes  | 2022_04_03_051357_create_areas_table                  | 1     |
| Yes  | 2022_04_03_051532_create_expeditions_table            | 1     |
| Yes  | 2022_04_03_071904_create_expedition_trigers           | 1     |
+------+-------------------------------------------------------+-------+
マイグレーションファイルの実行
$ php artisan migrate:refresh  --step=1 --path=/database/migrations/2022_04_03_071904_create_expedition_trigers.php
Rolling back: 2022_04_03_071904_create_expedition_trigers
Rolled back:  2022_04_03_071904_create_expedition_trigers (76.64ms)
Migrating: 2022_04_03_071904_create_expedition_trigers
Migrated:  2022_04_03_071904_create_expedition_trigers (211.42ms)

特定のテーブルだけシーダー

しかし、この後seedした結果
シーダーの実行
$ php artisan db:seed --class=ExpeditionTrigerSeeder
   Illuminate\Database\QueryException

  SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`kancolle`.`expedition_trigers`, CONSTRAINT `expedition_trigers_parent_exp_id_foreign` FOREIGN KEY (`parent_exp_id`) REFERENCES `expeditions` (`exp_id`)) (SQL: insert into `expedition_trigers` (`exp_id`, `parent_exp_id`) values (8, A2), (A1, A3), (A2, A3), (24, A4), (A4, A5), (B3, A6), (A5, A6), (B4, A7))

  at vendor/laravel/framework/src/Illuminate/Database/Connection.php:716
  ・
  ・
と出てしまう。 MySQLで作成したテーブルのSQLを見てみると。
> SHOW CREATE TABLE expedition_trigers;
+--------------------+-----
| Table              | Create Table                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
+--------------------+------------------
| expedition_trigers | CREATE TABLE `expedition_trigers` (
  `expedition_triger_id` int unsigned NOT NULL AUTO_INCREMENT,
  `parent_exp_id` varchar(10) COLLATE utf8mb4_unicode_ci NOT NULL,
  `exp_id` varchar(10) COLLATE utf8mb4_unicode_ci NOT NULL,
  `updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`expedition_triger_id`),
  KEY `expedition_trigers_parent_exp_id_foreign` (`parent_exp_id`),
  KEY `expedition_trigers_exp_id_foreign` (`exp_id`),
  CONSTRAINT `expedition_trigers_exp_id_foreign` FOREIGN KEY (`exp_id`) REFERENCES `expeditions` (`exp_id`),
  CONSTRAINT `expedition_trigers_parent_exp_id_foreign` FOREIGN KEY (`parent_exp_id`) REFERENCES `expeditions` (`exp_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci |
修正時に消した外部キーが追加されてしまっている。
既存のマイグレーションファイルを削除して作成し直す事で解決。
深くは考えずそういうものなのだという事で、、
テーブルはMYSQLで手動で削除。
マイグレーションファイルの作成
$ php artisan make:migration expedition_trigers
Created Migration: 2022_04_08_211941_expedition_trigers
マイグレーションファイルの実行
$ php artisan migrate:refresh --step=1 --path=/database/migrations/2022_04_08_211941_expedition_trigers.php
Migration not found: 2022_04_03_071904_create_expedition_trigers
Migrating: 2022_04_08_211941_expedition_trigers
Migrated:  2022_04_08_211941_expedition_trigers (31.00ms)
シーダーの実行
$ php artisan db:seed --class=ExpeditionTrigerSeeder
Database seeding completed successfully.

RockyLinuxでサーバー構築 - 1.環境設定

CentOS8が2021/12/31にサポート終了になりました。
CentOS7はまだ猶予がありそうですが、
代わりにRockyLinuxで環境を構築しました。
RockyLinuxインストール後の設定です。
インストールから始める方はこちらを参照↓
VMware+CentOS7で開発環境構築 - 1.インストール

SELinux停止

SELinuxが停止されているか確認
# getenforce
Disabled
停止されていなかったら停止しておく
# getenforce
Enforcing
# setenforce 0
# getenforce
Permissive
# vi /etc/sysconfig/selinux 
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
SELINUX=disabled
# SELINUXTYPE= can take one of these three values:
#     targeted - Targeted processes are protected,
#     minimum - Modification of targeted policy. Only selected processes are proo
tected.
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted
EnforcingSELinux有効
PermissiveSELinux無効。ポリシーに違反するアクセスがあった場合アクセスを許可する
DisableSELinux無効

rootになれるユーザの管理

wheelにrootになれるユーザhogehogeを追加
# usermod -G wheel hogehoge
#%PAM-1.0
auth            required        pam_env.so
auth            sufficient      pam_rootok.so
# Uncomment the following line to implicitly trust users in the "wheel" group.
#auth           sufficient      pam_wheel.so trust use_uid
# Uncomment the following line to require a user to be in the "wheel" group.
auth           required        pam_wheel.so use_uid ←コメント削除
auth            substack        system-auth
auth            include         postlogin
account         sufficient      pam_succeed_if.so uid = 0 use_uid quiet
account         include         system-auth
password        include         system-auth
session         include         system-auth
session         include         postlogin
session         optional        pam_xauth.so

root宛のメールを一般ユーザで受け取る

root宛をhogehogeに転送
# sed -i '/^root:/d' /etc/aliases
# echo "root: hogehoge" >> /etc/aliases
# newaliases
# newaliases
-bash: newaliases: command not found
と出た場合。Postfixがまだインストールされていないのでインストール後に。
# newaliases
newaliases: fatal: parameter inet_interfaces: no local interface found for ::1
と出た場合はPostfixが起動してないので起動させてから。

dnfリポジトリを日本サーバーに設定

AppStreamリポジトリファイルの修正
# vi /etc/yum.repos.d/Rocky-AppStream.repo
[appstream]
name=Rocky Linux $releasever - AppStream
#mirrorlist=https://mirrors.rockylinux.org/mirrorlist?arch=$basearch&repo=AppStream-$relea
sever
#baseurl=http://dl.rockylinux.org/$contentdir/$releasever/AppStream/$basearch/os/
baseurl=https://ftp.riken.jp/Linux/rocky/$releasever/AppStream/$basearch/os/
gpgcheck=1
enabled=1
countme=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rockyofficial
BaseOSリポジトリファイルの修正
# vi /etc/yum.repos.d/Rocky-BaseOS.repo
[baseos]
name=Rocky Linux $releasever - BaseOS
#mirrorlist=https://mirrors.rockylinux.org/mirrorlist?arch=$basearch&repo=BaseOS-$releasev
er
#baseurl=http://dl.rockylinux.org/$contentdir/$releasever/BaseOS/$basearch/os/
baseurl=https://ftp.riken.jp/Linux/rocky/$releasever/BaseOS/$basearch/os/
gpgcheck=1
enabled=1
countme=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rockyofficial
BaseOSリポジトリファイルの修正
# vi /etc/yum.repos.d/Rocky-Extras.repo
[extras]
name=Rocky Linux $releasever - Extras
#mirrorlist=https://mirrors.rockylinux.org/mirrorlist?arch=$basearch&repo=extras-$releasever
#baseurl=http://dl.rockylinux.org/$contentdir/$releasever/extras/$basearch/os/
baseurl=https://ftp.riken.jp/Linux/rocky/$releasever/extras/$basearch/os/
gpgcheck=1
enabled=1
countme=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rockyofficial:q

有効にしているリポジトリの確認
# grep 'enabled=1' /etc/yum.repos.d/*
/etc/yum.repos.d/Rocky-AppStream.repo:enabled=1
/etc/yum.repos.d/Rocky-BaseOS.repo:enabled=1
/etc/yum.repos.d/Rocky-Extras.repo:enabled=1

epelリポジトリの追加

epel-releaseインストール
# dnf -y install epel-release
リポジトリ修正
# vi /etc/yum.repos.d/epel.repo
[epel]
name=Extra Packages for Enterprise Linux $releasever - $basearch
# It is much more secure to use the metalink, but if you wish to use a local mirror
# place its address here.
#baseurl=https://download.example/pub/epel/$releasever/Everything/$basearch
metalink=https://mirrors.fedoraproject.org/metalink?repo=epel-$releasever&arch=$basearch&i
nfra=$infra&content=$contentdir
enabled=1
priority=10
gpgcheck=1
countme=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-8

elrepoリポジトリの追加

elrepo-releaseインストール
# dnf -y install elrepo-release
リポジトリ修正
#  vi /etc/yum.repos.d/elrepo.repo
[elrepo]
name=ELRepo.org Community Enterprise Linux Repository - el8
baseurl=http://elrepo.org/linux/elrepo/el8/$basearch/
        http://mirrors.coreix.net/elrepo/elrepo/el8/$basearch/
        http://mirror.rackspace.com/elrepo/elrepo/el8/$basearch/
        http://linux-mirrors.fnal.gov/linux/elrepo/elrepo/el8/$basearch/
mirrorlist=http://mirrors.elrepo.org/mirrors-elrepo.el8
enabled=1
priority=10
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-elrepo.org

remiリポジトリの追加

RockyLinuxのバージョン確認
# cat /etc/redhat-release
Rocky Linux release 8.5 (Green Obsidian)
remi-releaseインストール
#  dnf -y install https://rpms.remirepo.net/enterprise/remi-release-8.5.rpm
※自分の環境にあったrpmを使用する事。
リポジトリ修正
# vi /etc/yum.repos.d/remi-safe.repo
[remi-safe]
name=Safe Remi's RPM repository for Enterprise Linux 8 - $basearch
#baseurl=http://rpms.remirepo.net/enterprise/8/safe/$basearch/
#mirrorlist=https://rpms.remirepo.net/enterprise/8/safe/$basearch/httpsmirror
mirrorlist=http://cdn.remirepo.net/enterprise/8/safe/$basearch/mirror
enabled=1
priority=10
gpgcheck=1
repo_gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-remi.el8
# vi /etc/yum.repos.d/remi-modular.repo
[remi-modular]
name=Remi's Modular repository for Enterprise Linux 8 - $basearch
#baseurl=http://rpms.remirepo.net/enterprise/8/modular/$basearch/
#mirrorlist=https://rpms.remirepo.net/enterprise/8/modular/$basearch/httpsmirror
mirrorlist=http://cdn.remirepo.net/enterprise/8/modular/$basearch/mirror
enabled=1
priority=10
gpgcheck=1
repo_gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-remi.el8
有効にしているリポジトリの確認
# grep 'enabled=1' /etc/yum.repos.d/*
/etc/yum.repos.d/elrepo.repo:enabled=1
/etc/yum.repos.d/epel-modular.repo:enabled=1
/etc/yum.repos.d/epel.repo:enabled=1
/etc/yum.repos.d/remi-modular.repo:enabled=1
/etc/yum.repos.d/remi-safe.repo:enabled=1
/etc/yum.repos.d/Rocky-AppStream.repo:enabled=1
/etc/yum.repos.d/Rocky-BaseOS.repo:enabled=1
/etc/yum.repos.d/Rocky-Extras.repo:enabled=1
最新のパッケージに更新
# dnf -y upgrade

その他の初期設定

ホスト名の設定
# hostnamectl set-hostname kowloonet.net
自動アップデート
#  dnf -y install dnf-automatic
systemctl start dnf-automatic.timer
systemctl enable dnf-automatic.timer
開発ツールのインストール
# dnf -y groupinstall base "Development tools"
コンソール日本語化
# dnf -y install langpacks-ja glibc-langpack-ja
# localectl set-locale LANG=ja_JP.UTF-8
vimの設定
# echo "alias vi='vim'" >> /etc/profile
# source /etc/profile
# vi /etc/vimrc
下記を追加
set tabstop=2
set expandtab
set shiftwidth=2
set list
set whichwrap=b,s,[,],<,>
PERLのシンボリックリンク作成
# ln -s /usr/bin/perl /usr/local/bin/perl

不要なサービスの停止

サービス一覧
# systemctl list-units --type service
UNIT                                   LOAD   ACTIVE SUB     DESCRIPTION
auditd.service                         loaded active running Security Auditing Service
chronyd.service                        loaded active running NTP client/server
crond.service                          loaded active running Command Scheduler
dbus.service                           loaded active running D-Bus System Message Bus
dovecot.service                        loaded active running Dovecot IMAP/POP3 email server
dracut-shutdown.service                loaded active exited  Restore /run/initramfs on shutdown
firewalld.service                      loaded active running firewalld - dynamic firewall daemon
getty@tty1.service                     loaded active running Getty on tty1
httpd.service                          loaded active running The Apache HTTP Server
import-state.service                   loaded active exited  Import network configuration from initramfs
irqbalance.service                     loaded active running irqbalance daemon
kmod-static-nodes.service              loaded active exited  Create list of required static device nodes for the curre>
ldconfig.service                       loaded active exited  Rebuild Dynamic Linker Cache
lvm2-monitor.service                   loaded active exited  Monitoring of LVM2 mirrors, snapshots etc. using dmeventd>
mailman.service                        loaded active running GNU Mailing List Manager
NetworkManager-wait-online.service     loaded active exited  Network Manager Wait Online
NetworkManager.service                 loaded active running Network Manager
nis-domainname.service                 loaded active exited  Read and set NIS domainname from /etc/sysconfig/network
polkit.service                         loaded active running Authorization Manager
postfix.service                        loaded active running Postfix Mail Transport Agent
rsyslog.service                        loaded active running System Logging Service
saslauthd.service                      loaded active running SASL authentication daemon.
selinux-autorelabel-mark.service       loaded active exited  Mark the need to relabel after reboot
serial-getty@ttyS0.service             loaded active running Serial Getty on ttyS0
sshd.service                           loaded active running OpenSSH server daemon
sssd.service                           loaded active running System Security Services Daemon
systemd-fsck-root.service              loaded active exited  File System Check on Root Device
systemd-hwdb-update.service            loaded active exited  Rebuild Hardware Database
systemd-journal-catalog-update.service loaded active exited  Rebuild Journal Catalog
systemd-journal-flush.service          loaded active exited  Flush Journal to Persistent Storage
systemd-journald.service               loaded active running Journal Service
systemd-logind.service                 loaded active running Login Service
systemd-random-seed.service            loaded active exited  Load/Save Random Seed
systemd-remount-fs.service             loaded active exited  Remount Root and Kernel File Systems
systemd-sysctl.service                 loaded active exited  Apply Kernel Variables
systemd-sysusers.service               loaded active exited  Create System Users
systemd-tmpfiles-setup-dev.service     loaded active exited  Create Static Device Nodes in /dev
systemd-tmpfiles-setup.service         loaded active exited  Create Volatile Files and Directories
systemd-udev-trigger.service           loaded active exited  udev Coldplug all Devices
systemd-udevd.service                  loaded active running udev Kernel Device Manager
systemd-update-done.service            loaded active exited  Update is Completed
systemd-update-utmp.service            loaded active exited  Update UTMP about System Boot/Shutdown
systemd-user-sessions.service          loaded active exited  Permit User Sessions
tuned.service                          loaded active running Dynamic System Tuning Daemon
user-runtime-dir@0.service             loaded active exited  User runtime directory /run/user/0
user-runtime-dir@1000.service          loaded active exited  User runtime directory /run/user/1000
user@0.service                         loaded active running User Manager for UID 0
user@1000.service                      loaded active running User Manager for UID 1000
vsftpd.service                         loaded active running Vsftpd ftp daemon

LOAD   = Reflects whether the unit definition was properly loaded.
ACTIVE = The high-level unit activation state, i.e. generalization of SUB.
SUB    = The low-level unit activation state, values depend on unit type.

49 loaded units listed. Pass --all to see loaded but inactive units, too.
To show all installed unit files use 'systemctl list-unit-files'.
postfix,dovecot,httpd,sshd,vsftpd,mailmanは導入済み
不要なサービスはどれでしょうか。後回し。

【RockyLinux】mailmanの通し番号(シーケンス番号)をリセット・変更

mailmanの通し番号を指定した値に変更

CentOS8からRockyLinuxに変更し、環境を再構築。
今までの通し番号を引き継ぐ必要がでたため
シーケンス番号を49に変更する例。
リセットしたい場合は
m.post_id=1
コマンドからの変更
# /usr/lib/mailman/bin/withlist メーリングリスト名
Loading list メーリングリスト名 (unlocked)
The variable `m' is the dev MailList instance
>>> m.Lock()
>>> m.post_id
2.0
>>> m.post_id=49
>>> m.Save()
>>>
Unlocking (but not saving) list: メーリングリスト名
Finalizing

【Wordpress】ワードプレスでカスタム投稿記事をメールで送信(テキストメール編)

メール送信

ステータスが公開になったときにメールを送信する。
HTMLで記載された記事のタグと改行を削除。
改行が3個以上続くときは2個(最大1行の空白行)とする。
function.php
function sendmail_post_article($new_status, $old_status, $post) {
  $active_posttype = 'news';  // 記事のカテゴリ
  $mail_to = 'xxx@kowloonet.net';
  $mail_from_name = "小黒のtechメモ(仮)";
  $mail_from = 'yyy@kowloonet.net';
  $from = mb_encode_mimeheader($mail_from_name)." <$mail_from>";
  $mail_subject = '【NEWS】';
  $headers[] = 'Content-Type: text/html; charset=UTF-8';
  $headers[] = "From: ".$from;
  $headers[] = "Sender: ".$from;
  $headers[] = "Reply-To: ".$mail_from;
  $headers[] = "X-Sender: " . $mail_from;
  $headers[] = "X-Priority: 3";
  if ($new_status == 'publish' && $old_status != 'publish' && $post->post_type == $active_posttype) {
    /** HTML to txt **/
    $content = preg_replace('//i', "\n", $post->post_content);
    $content = strip_tags($content);
    $content = html_entity_decode($content);
    $content = preg_replace("/\r\n|\r|\n/us", "\n", $content);
    $content = preg_replace("/\n[^\S\n]+/us", "\n", $content);
    $content = trim(preg_replace("/(\r\n){3,}|\r{3,}|\n{3,}/us", "\n\n", $content));
     /**// HTML to txt **/
    $message .= $content."\n\n詳しくはこちら↓\n";
    $message .= get_permalink($post->ID)."\n\n\n";

    $attachments = [];  //添付ファイルがあれば
    wp_mail($mail_to, $mail_subject, $message, $headers, $attachments);
  }
}
add_action('transition_post_status','sendmail_post_article' , 10, 3)
エラーログを出力してデバック
error_log('$new_status: '.$new_status);
error_log('$post->post_type: '.$post->post_type);
error_log(print_r($post, true ));
wp-content/debug.log
に出力される。
エラーログの出力設定は割愛。

【PHP】フォームから送信した日本語が文字化け、php.iniの設定が反映されなかった件

mbstringを正しく設定しましょう

wordpressのContactForm7+Multi-Stepでフォームの確認画面を実装してみたところ文字化け、
もちろん送信されたメールの本文も文字化けし、じゃっかん沼った話。
php.iniの設定
# vi /etc/php.ini
mbstring.language = Japanese
mbstring.internal_encoding = UTF-8
mbstring.http_input = UTF-8
mbstring.http_output = UTF-8
mbstring.encoding_translation = Off
apache、 php-fpmの再起動
# systemctl restart httpd
# systemctl restart php-fpm
phpinfo()で確認。
php-fpmの再起動をしないと反映されないのですね。
古いシステムでなけれUTF-8に統一でmbstring.encoding_translation = Off
って事ですね。

【Wordpress】ワードプレスの開発環境・テスト環境構築 | サーバー移行手順

ワードプレスの開発環境を構築する手順。
サーバー移行する際も同じです。
ローカルに作成したい場合、Windows上であればVMWare等のバーチャルマシーンCentOS上に作ると良いでしょう。 サーバー移行に必要なものは、
  • Wordpressのファイル(フォルダ)
  • データベースのデータ(ダンプファイル)
の2点です。
wp-adminの管理者パスワードがわからない場合は、新たに設定可能です。
開発用なのでBASIC認証などで公開されない形にして、
簡単なパスワードに設定し直すのも良いでしょう。
移行前移行後
http://kowloonet.net/http://192.168.1.100/wordpress/

Wordpressのファイルを本番環境からダウンロード

サーバーから直接FTP等でダウンロードするのも良いですが、
コマンドが使える環境では、tar.gz に圧縮すると、サーバー間のファイル移動に好都合です。
フォルダ圧縮
# tar cvzf wordpress.tar.gz wordpress
wordpress/
wordpress/wp-config.php
wordpress/index.php
wordpress/license.txt
wordpress/readme.html
・
・
圧縮されたファイル wordpress.tar.gz が生成されますので、
こちらをFTP等でダウンロードします。
gzip形式で圧縮
 tar cvzf 圧縮後のファイル名.tar.gz ファイル名
gzip形式で解凍・展開
tar zxvf ファイル名.tar.gz
zip形式で圧縮
zip 圧縮後のファイル名.zip -r ファイル名
zip形式で解凍・展開
unzip ファイル名.zip
unzip ファイル名.zip -d 展開先ディレクトリ

データベースのエクスポート

wordpressで使用しているデータベース名を wp-config.php で確認。
コマンドが使える環境でない場合はmysqladminを利用してください。
ダンプファイル作成
# mysqldump -uユーザ名 -p  wordpress_db >  wordpress_db_dump.sql
wordpress_db_dump.sql が作成されますので、こちらもFTP等でダウンロード。

ファイルの展開と設定

ドキュメントルート /var/www/html/ 直下に展開します。
FTPなどでアップロードして配置してください。
ファイル展開
# cd /var/www/html/
# tar zxvf wordpress.tar.gz 
wordpress/
wordpress/wp-config.php
wordpress/index.php
wordpress/license.txt
・
・
ファイルの所有者変更
# chown -R apache:user wordpress/
所有者をapache
グループをuser
にしてuserでもファイルの書き込み変更を行えるようにします。
開発環境なので、パーミッションを
ディレクトリは775
ファイルは664
にしておきます。
ファイルのパーミッション変更
# find wordpress/  -type d -exec chmod 775 {} \;
# find wordpress/ -type f -exec chmod 664 {} \;
本番環境では下記のパーミッション変更も追加で実施
# chmod 606 ./wordpress/.htaccess
# chmod 404 ./wordpress/wp-config.php
※サーバー移転などでの本番環境のパーミッションはサイトルールに従ってください。
パーミッション確認
# cd wordpress/
# ls -la | awk 'NR>1{cmd="stat "$NF" -c %a";cmd|getline c;close(cmd);print c,$0}'
775 drwxrwxr-x  6 apache user  4096 Nov 20 11:53 .
755 drwxr-xr-x 12 user user  4096 Nov 20 11:00 ..
775 drwxrwxr-x  2 apache user  4096 Nov 18 18:24 img
664 -rw-rw-r--  1 apache user   420 Nov 18 13:10 index.php
664 -rw-rw-r--  1 apache user 19550 Nov 18 13:09 license.txt
664 -rw-rw-r--  1 apache user    68 Nov 18 13:10 php.ini
664 -rw-rw-r--  1 apache user  7447 Nov 18 13:09 readme.html
664 -rw-rw-r--  1 apache user  6919 Nov 18 13:09 wp-activate.php
775 drwxrwxr-x  9 apache user  4096 Nov 18 18:24 wp-admin
664 -rw-rw-r--  1 apache user   369 Nov 18 13:09 wp-blog-header.php
664 -rw-rw-r--  1 apache user  2340 Nov 18 13:09 wp-comments-post.php
664 -rw-rw-r--  1 apache user  4450 Nov 18 13:09 wp-config.php
664 -rw-rw-r--  1 apache user  3807 Nov 18 13:09 wp-config-sample.php
775 drwxrwxr-x  8 apache user  4096 Nov 18 18:24 wp-content
664 -rw-rw-r--  1 apache user  3847 Nov 18 13:09 wp-cron.php
775 drwxrwxr-x 20 apache user 12288 Nov 18 18:24 wp-includes
664 -rw-rw-r--  1 apache user  2502 Nov 18 13:09 wp-links-opml.php
664 -rw-rw-r--  1 apache user  3306 Nov 18 13:09 wp-load.php
664 -rw-rw-r--  1 apache user 39551 Nov 18 13:09 wp-login.php
664 -rw-rw-r--  1 apache user  8403 Nov 18 13:09 wp-mail.php
664 -rw-rw-r--  1 apache user 18962 Nov 18 13:09 wp-settings.php
664 -rw-rw-r--  1 apache user 31085 Nov 18 13:09 wp-signup.php
664 -rw-rw-r--  1 apache user  4764 Nov 18 13:09 wp-trackback.php
664 -rw-rw-r--  1 apache user  3068 Nov 18 13:09 xmlrpc.php

データベースの設定

データベース名、MySQLユーザ名は本番環境と同じである必要はありません。
ご都合に合わせて設定して下さい。今回は、
デーーベース名wordpress_db
MySQLユーザ名user
MySQLパスワード1234
データベースサーバーlocalhost
で設定。データベース名以外は本番のものから変更しておきました。
wp-config.phpの修正
# cd wordpress/
# vi wp-config.php
/** WordPress のためのデータベース名 */
define('DB_NAME', 'wordpress_db');

/** MySQL データベースのユーザー名 */
define('DB_USER', 'user');

/** MySQL データベースのパスワード */
define('DB_PASSWORD', '1234');

/** MySQL のホスト名 */
#define('DB_HOST', 'mysql.xxxxxxx.com');
define('DB_HOST', 'localhost');
・
・
/**
 * WordPress データベーステーブルの接頭辞
 *
 * それぞれにユニーク (一意) な接頭辞を与えることで一つのデータベースに複数の WordPress を
 * インストールすることができます。半角英数字と下線のみを使用してください。
 */
$table_prefix  = 'wp369041';
vi を使わずにテキストエディタで修正したものを配置しても同じです。
データベースの作製
# mysql -uuser -p
mysql>CREATE DATABASE wordpress_db;
データベースのインポート
# mysql -uuser -p1234 wordpress_db< wordpress_db_dump.sql
コマンドが使えない場合はmysqladminを利用して下さい。
今回は、本番URL
http://kowloonet.net/
を
http://192.168.1.100//wordpress/
でアクセスできるように変更します。
サイトURLが記載されている XXXoptions テーブルのカラム option_name の値 home と siteurl のカラム option_value の値を変更します。
XXXは wp-config.phpに記載されている $table_prefix の文字列になります。
テーブル名の変更が無い場合は「wp_」で、テーブル名は「wp_options」になります。
私の環境では「wp369041」でしたので、テーブル名は「wp369041options」になります。
サイトURL変更
mysql> USE wordpress_db
mysql> SELECT * FROM wp369041options WHERE option_name IN ('home','siteurl');
+-----------+-------------+-------------------------------+----------+
| option_id | option_name | option_value                  | autoload |
+-----------+-------------+-------------------------------+----------+
|         2 | home        | http://kowloonet.net/             | yes      |
|         1 | siteurl     | http://kowloonet.net/               | yes      |
+-----------+-------------+-------------------------------+----------+
2 rows in set (0.00 sec)

mysql> UPDATE wp369041options SET option_value = 'http://192.168.128.100/wordpress/'
 where option_name IN ('home','siteurl');
本番環境のwp-adminの管理者ユーザのパスワードは長くて複雑な場合が多々あるので、
簡易なものに変更しておきます。
パスワードが不明な場合もこちらの方法で再設定可能です。
管理者ユーザは XXXusers テーブルにあるので、
管理者ユーザの確認・パスワード変更
mysql> SELECT * FROM wp369041users;
で確認。
しかし、これだと管理者が誰かわからないので、「usermeta」テーブルも参照して、
mysql> SELECT u.user_login FROM wp369041users u, wp369041usermeta um WHERE u.ID = um.user_id AND um.meta_key LIKE '%capabilities' AND um.meta_value LIKE '%administrator%';
+------------+
| user_login |
+------------+
| admin     |
| user     |
+------------+
2 rows in set (0.00 sec)
ユーザ名「admin」のパスワードを「pass」に変更します。
パスワード変更
mysql>UPDATE wp369041users SET user_pass = MD5('pass')  WHERE user_login = 'admin';
必要があれば管理者のメールドレスも変更。
パスワード変更
mysql> update wp369041users set user_email = 'メールアドレス'  WHERE user_login = 'admin';
http://192.168.1.100//wordpress/
http://192.168.1.100//wordpress/wp-admin/
にアクセスして表示、動作できればOK。

Googleマテリアルアイコン - Material icons

Googleマテリアルアイコンの使用例

Google Material icons
HTML
<head>
・
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
・
</head>
<body>
・
<div class="search-box">
<input type="text" placeholder="遠征検索" v-model="keyword" class="encolle-global-search" />
</div>
・
</body>
※v-model はvue使用時の記述です。
CSS
.encolle-global-search{
display:inline-block;
width: 300px;
font-size: 1.2rem;
height: 30px;
line-height: 1;
box-sizing: border-box;
padding: 5px 4px 5px 28px;
color: #687c98;
border-radius: 5px;
font-weight: 700;
border: 1px solid #dcdfe6;
transition: border-color .4s cubic-bezier(0.65, 0.05, 0.36, 1);
}
.search-box{
position: relative;
display: inline-block;
}
.search-box::before{
content: '\e8b6';
font-family: 'Material Icons';
font-size: 24px;
color: #ccc;
font-family: 'Material Icons';
position: absolute;
top: 4px;
left: 4px;
}

LaravelでWEB開発 - PHPのtimezoneが反映されていなかった件

Laravel内でのPHPが吐き出す時間がJSTになっていなかったので、php.iniを確認してみたところ正しく設定されていて、Laravelの設定でUTCに変更されていた。

PHPのtimezone設定

php.ini の編集・確認
# vi /etc/php.ini
[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
date.timezone = "Asia/Tokyo"
timezone確認
# php -i | grep timezone
Default timezone => Asia/Tokyo
date.timezone => Asia/Tokyo => Asia/Tokyo

Laravelのtimezone設定

app.php 変更
$ vi config/app.php
    /*
    |--------------------------------------------------------------------------
    | Application Timezone
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default timezone for your application, which
    | will be used by the PHP date and date-time functions. We have gone
    | ahead and set this to a sensible default for you out of the box.
    |
    */

    'timezone' => 'Asia/Tokyo',

確認
$ php artisan tinker
Psy Shell v0.10.4 (PHP 7.4.8 ― cli) by Justin Hileman
>>> echo Carbon\Carbon::now();
2021-03-14 15:38:54
OK-

CentOS8でサーバー構築 - 12.不正アクセスブロック(fail2ban)

fail2banのインストール

インストール
# dnf -y install fail2ban

fail2banの設定

設定
# cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
# vi /etc/fail2ban/jail.local
# "bantime" is the number of seconds that a host is banned.
bantime  = 1d

# A host is banned if it has generated "maxretry" during the last "findtime"
# seconds.
findtime  = 1h

# "maxretry" is the number of failures before a host get banned.
maxretry = 3
・
・
# Destination email address used solely for the interpolations in
# jail.{conf,local,d/*} configuration files.
destemail = root

# Sender email address used solely for some actions
sender = root

# E-mail action. Since 0.8.1 Fail2Ban uses sendmail MTA for the
# mailing. Change mta configuration parameter to mail if you want to
# revert to conventional 'mail'.
mta = postfix
・
・
#
# Action shortcuts. To be used to define action parameter

# Default banning action (e.g. iptables, iptables-new,
# iptables-multiport, shorewall, etc) It is used to define
# action_* variables. Can be overridden globally or per
# section within jail.local file
#banaction = iptables-multiport
banaction = firewallcmd-ipset

#banaction_allports = iptables-allports
banaction_allports = firewallcmd-allports
・
・
#
# SSH servers
#

[sshd]
enabled = true
・
・
#
# HTTP servers
#

[apache-auth]
enable = true
・
・
[postfix]
enabled = true
・
・
[postfix-sasl]
enabled   = true
・
・
# dovecot defaults to logging to the mail syslog facility
# but can be set by syslog_facility in the dovecot configuration.
[dovecot]
enabled = true

fail2banの起動

起動
# systemctl start fail2ban
# systemctl enable fail2ban
設定を変更した時などクライアントリロード
#  fail2ban-client reload

fail2banの動作確認

sshd
# fail2ban-client status sshd
Status for the jail: sshd
|- Filter
|  |- Currently failed: 0
|  |- Total failed:     0
|  `- Journal matches:  _SYSTEMD_UNIT=sshd.service + _COMM=sshd
`- Actions
   |- Currently banned: 0
   |- Total banned:     0
   `- Banned IP list:
postfix-sasl
# fail2ban-client status postfix-sasl
Status for the jail: postfix-sasl
|- Filter
|  |- Currently failed: 16
|  |- Total failed:     505
|  `- Journal matches:  _SYSTEMD_UNIT=postfix.service
`- Actions
   |- Currently banned: 2
   |- Total banned:     2
   `- Banned IP list:   <BANされたIPアドレス>

その他

個別にBAN設定
# fail2ban-client -v set postfix-sasl banip xxx.xxx.xxx.0/24

CentOS8でサーバー構築 - 11.PHPでMemcached

DBへの接続は極力少なくして、キャッシュセッションはMemcachedを使いましょう。
って事でインストール。

Memcachedのインストール

Memcachedインストール
# dnf -y install memcached php-pecl-memcached
milter-manager_repos                                                                347  B/s | 819  B     00:02
milter-manager_repos-source                                                         446  B/s | 819  B     00:01
Dependencies resolved.
=====================================================
 Package                 Architecture    Version                        Repository             Size
======================================================
Installing:
 memcached           x86_64          1.5.9-3.el8           AppStream         132 k
 php-pecl-memcached      x86_64      3.1.5-1.el8.remi.7.4   remi-modular    96 k
Installing dependencies:
 fastlz        x86_64          0.1.0-0.12.20070619svnrev12.el8     epel        15 k
 libmemcached-libs       x86_64      1.0.18-15.el8          AppStream        137 k
 php-pecl-igbinary       x86_64      3.1.2-1.el8.remi.7.4       remi-modular      158 k
 php-pecl-msgpack        x86_64      2.1.0-1.el8.remi.7.4       remi-modular       65 k

Transaction Summary
=======================================================
Install  6 Packages
  epel、remiリポジトリを使用するので、使えるようにしておく事。

Memcachedの設定

Memcached設定
# vi /etc/sysconfig/memcached
PORT="11211"
USER="memcached"
MAXCONN="512"
CACHESIZE="64"
OPTIONS="-l 127.0.0.1"
phpのMemcached設定
# vi /etc/php.d/50-memcached.ini
;  Use memcache as a session handler
session.save_handler=memcached
;  Defines a comma separated list of server urls to use for session storage
session.save_path="localhost:11211"
# vi /etc/php.ini
[Session]
; Handler used to store/retrieve data.
; http://php.net/session.save-handler
;session.save_handler = files
memcached起動
# systemctl start memcached
# systemctl enable memcached
Created symlink /etc/systemd/system/multi-user.target.wants/memcached.service → /usr/lib/systemd/system/memcached.service.
Apache再起動
# systemctl restart httpd

Firewalledの設定

Firewalled設定
# firewall-cmd --add-port=11211/tcp --zone=public --permanent
# firewall-cmd --reload
下記の様なエラーが出て起動できず。
OPTIONS="-l 127.0.0.1"
と修正して解決。
systemctl status memcached
● memcached.service - memcached daemon
   Loaded: loaded (/usr/lib/systemd/system/memcached.service; enabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Fri 2020-07-17 09:30:49 JST; 2min 21s ago
  Process: 446015 ExecStart=/usr/bin/memcached -p ${PORT} -u ${USER} -m ${CACHESIZE} -c ${MAXCONN} $OPTIONS (code=e>
 Main PID: 446015 (code=exited, status=71)

Jul 17 09:30:49 kowloonet.net systemd[1]: Started memcached daemon.
Jul 17 09:30:49 kowloonet.net memcached[446015]: bind(): Cannot assign requested address
Jul 17 09:30:49 kowloonet.net memcached[446015]: failed to listen on TCP port 11211: Cannot assign requested address
Jul 17 09:30:49 kowloonet.net systemd[1]: memcached.service: Main process exited, code=exited, status=71/OSERR
Jul 17 09:30:49 kowloonet.net systemd[1]: memcached.service: Failed with result 'exit-code'.

LaravelでWEB開発 - 2.VueとjQueryの共存

<script>タグ内で jqueryを importし、 mounted() メソッドに処理を書けばOK。

Vueのンストール

Vueインストール
$ npm install vue
npm notice created a lockfile as package-lock.json. You should commit this file.
+ vue@2.6.11
added 1 package from 1 contributor and audited 1 package in 0.598s
found 0 vulnerabilities

jQueryのインポートと利用

.vueファイル修正
$ vi resources/js/components/Sample.vue
<table>の <thead>を固定させるスクリプトを jQueryで実装。
<template>
<div>
<p v-if="errored">{{ error }}</p>
<p v-if="loading">Loading...</p>
・
・
</div>
</template>
<script>
import $ from "jquery";
export default{
  data() {
    return {
      loading: true,
      errored: false,
      error: false,
  },
  mounted() {
    $(function () {
      var _window = $(window);
      $('.area1').css('color','red');
      var bottom;
        _window.on('scroll',function(){
          bottom = $('.vgt-global-search').height() + 50 + $('header').height();
          if(_window.scrollTop() > bottom){
            $('thead').css('position','fixed').css('top','0');
          }
          else{
            $('thead').css('position','static');
          }
        });
      _window.trigger('scroll');
    });
  }
};
</script>

CentOS8でサーバー構築 - 10.ApacheのDoS攻撃対策(mod_evasive)

mod_evasiveのインストール

2020/07/15現在、オフィシャルの CentOS8用のリポジトリに rpmは存在しないので、
同じカーネルの Fedora29のアーカイブページの rpmからネットワーク経由でインストールする。
Linuxカーネルを確認
# rpm -q kernel
kernel-4.18.0-147.3.1.el8_1.x86_64
kernel-4.18.0-147.8.1.el8_1.x86_64
kernel-4.18.0-193.6.3.el8_2.x86_64
  4.18なので、Fedora29(kernel4.18)のrpmでインストールする。
インストール
# rpm -ivh https://archives.fedoraproject.org/pub/archive/fedora/linux/updates/29/Everything/x86_64/Packages/m/mod_evasive-1.10.1-31.fc29.x86_64.rpm
インストール確認
# httpd -M | grep evasive
 evasive20_module (shared)

mod_evasiveの設定

mod_evasive.conf設定
# vi /etc/httpd/conf.d/mod_evasive.conf
# mod_evasive configuration
LoadModule evasive20_module modules/mod_evasive24.so

<IfModule mod_evasive24.c>
    # The hash table size defines the number of top-level nodes for each
    # child's hash table.  Increasing this number will provide faster
    # performance by decreasing the number of iterations required to get to the
    # record, but consume more memory for table space.  You should increase
    # this if you have a busy web server.  The value you specify will
    # automatically be tiered up to the next prime number in the primes list
    # (see mod_evasive.c for a list of primes used).
     DOSHashTableSize    3097

    # This is the threshhold for the number of requests for the same page (or
    # URI) per page interval.  Once the threshhold for that interval has been
    # exceeded, the IP address of the client will be added to the blocking
    # list.
     DOSPageCount        10

    # This is the threshhold for the total number of requests for any object by
    # the same client on the same listener per site interval.  Once the
    # threshhold for that interval has been exceeded, the IP address of the
    # client will be added to the blocking list.
     DOSSiteCount        5

    # The interval for the page count threshhold; defaults to 1 second
    # intervals.
     DOSPageInterval     2

    # The interval for the site count threshhold; defaults to 1 second
    # intervals.
     DOSSiteInterval     1

    # The blocking period is the amount of time (in seconds) that a client will
    # be blocked for if they are added to the blocking list.  During this time,
    # all subsequent requests from the client will result in a 403 (Forbidden)
    # and the timer being reset (e.g. another 10 seconds).  Since the timer is
    # reset for every subsequent request, it is not necessary to have a long
    # blocking period; in the event of a DoS attack, this timer will keep
    # getting reset.
     DOSBlockingPeriod   60

    # If this value is set, an email will be sent to the address specified
    # whenever an IP address becomes blacklisted.  A locking mechanism using
    # /tmp prevents continuous emails from being sent.
    #
    # NOTE: Requires /bin/mail (provided by mailx)
     DOSEmailNotify      "-s '[mod_evasive] Alert' メールアドレス"

    # If this value is set, the system command specified will be executed
    # whenever an IP address becomes blacklisted.  This is designed to enable
    # system calls to ip filter or other tools.  A locking mechanism using /tmp
    # prevents continuous system calls.  Use %s to denote the IP address of the
    # blacklisted IP.
    #DOSSystemCommand    "su - someuser -c '/sbin/... %s ...'"

    # Choose an alternative temp directory By default "/tmp" will be used for
    # locking mechanism, which opens some security issues if your system is
    # open to shell users.
    #
    #
    #   http://security.lss.hr/index.php?page=details&ID=LSS-2005-01-01
    #
    # In the event you have nonprivileged shell users, you'll want to create a
    # directory writable only to the user Apache is running as (usually root),
    # then set this in your httpd.conf.
    DOSLogDir           "/var/lock/mod_evasive"

    # You can use whitelists to disable the module for certain ranges of
    # IPs. Wildcards can be used on up to the last 3 octets if necessary.
    # Multiple DOSWhitelist commands may be used in the configuration.
    #DOSWhitelist   127.0.0.1
    #DOSWhitelist   192.168.0.*
</IfModule>
同じページに DOSPageInterval 秒に DOSPageCount 回のアクセスがあったらブラックリストへ。
同じサイトに DOSSiteInterval 秒に DOSSiteCount 回のアクセスがあったらブラックリストへ。
ブラックリストに登録された IPからは DOSBlockingPeriod 秒間 403を返す。
ロックファイル格納ディレクトリ作成
# mkdir /var/lock/mod_evasive
# chmod 777 /var/lock/mod_evasive
Apache再起動
# httpd -t
Syntax OK
# systemctl restart httpd

テストプログラムの実行

そのままでは BadRequest 400 が返ってくるので、test.plを修正。
私はPHPよりPerl歴の方が長いです・
test.pl修正
# vi /usr/share/doc/mod_evasive/test.pl
  print $SOCKET "GET /?$_ HTTP/1.0\r\n\r\n";
テスト実行
# perl /usr/share/doc/mod_evasive/test.pl
?
?
  Apacheの設定や環境によってはうまくいかないかもしれません。
  そんな時はブラウザでF5連打で試しましょう。
  成功すると、設定したアドレス宛に
To: -s '[mod_evasive] Alert' メールアドレス
Subject: HTTP BLACKLIST xxx.xxx.xxx.xxx

mod_evasive HTTP Blacklisted xxx.xxx.xxx.xxx

  とメールが届きます。

CentOS8でサーバー構築 - 9.mailmanのインストールと設定(Postfix)

メールホストkowloonet.net
URLホストadmin.kowloonet.net
URLhttps://admin.kowloonet.net/mailman/admin/
で設定します。

mailmanのインストール

mailmanインストール
# dnf -y install mailman

mailmanの設定

mm_cfg.pyの編集
# vi /etc/mailman/mm_cfg.py
DEFAULT_URL_HOST   = 'kowloonet.net'
DEFAULT_EMAIL_HOST = 'kowloonet.net'
Defaults.pyの編集
# vi /usr/lib/mailman/Mailman/Defaults.py
# Mailman needs to know about (at least) two fully-qualified domain names
# (fqdn); 1) the hostname used in your urls, and 2) the hostname used in email
# addresses for your domain.  For example, if people visit your Mailman system
# with "http://www.dom.ain/mailman" then your url fqdn is "www.dom.ain", and
# if people send mail to your system via "yourlist@dom.ain" then your email
# fqdn is "dom.ain".  DEFAULT_URL_HOST controls the former, and
# DEFAULT_EMAIL_HOST controls the latter.  Mailman also needs to know how to
# map from one to the other (this is especially important if you're running
# with virtual domains).  You use "add_virtualhost(urlfqdn, emailfqdn)" to add
# new mappings.
#
# If you don't need to change DEFAULT_EMAIL_HOST and DEFAULT_URL_HOST in your
# mm_cfg.py, then you're done; the default mapping is added automatically.  If
# however you change either variable in your mm_cfg.py, then be sure to also
# include the following:
#
#     add_virtualhost(DEFAULT_URL_HOST, DEFAULT_EMAIL_HOST)
#
# because otherwise the default mappings won't be correct.
DEFAULT_EMAIL_HOST = 'kowloonet.net'
DEFAULT_URL_HOST = 'admin.kowloonet.net'
DEFAULT_URL_PATTERN = 'https://%s/mailman/'
# MTA -- but then also see POSTFIX_STYLE_VIRTUAL_DOMAINS.
MTA = 'Postfix'
・
・
# The default language for this server.  Whenever we can't figure out the list
# context or user context, we'll fall back to using this language.  See
# LC_DESCRIPTIONS below for legal values.
DEFAULT_SERVER_LANGUAGE = 'ja'
・
・
# Set this variable to Yes to allow list owners to delete their own mailing
# lists.  You may not want to give them this power, in which case, setting
# this variable to No instead requires list removal to be done by the site
# administrator, via the command line script bin/rmlist.
OWNERS_CAN_DELETE_THEIR_OWN_LISTS = Yes
・
・
# These format strings will be expanded w.r.t. the dictionary for the
# mailing list instance.
DEFAULT_SUBJECT_PREFIX  = "[%(real_name)s: %%d] "

# What should happen to non-member posts which are do not match explicit
# non-member actions?
# 0 = Accept
# 1 = Hold
# 2 = Reject
# 3 = Discard
DEFAULT_GENERIC_NONMEMBER_ACTION = 0
・
・
# Mailman can be configured to "munge" Reply-To: headers for any passing
# messages.  One the one hand, there are a lot of good reasons not to munge
# Reply-To: but on the other, people really seem to want this feature.  See
# the help for reply_goes_to_list in the web UI for links discussing the
# issue.
# 0 - Reply-To: not munged
# 1 - Reply-To: set back to the list
# 2 - Reply-To: set to an explicit value (reply_to_address)
DEFAULT_REPLY_GOES_TO_LIST = 0
・
・
# SUBSCRIBE POLICY
# 0 - open list (only when ALLOW_OPEN_SUBSCRIBE is set to 1) **
# 1 - confirmation required for subscribes
# 2 - admin approval required for subscribes
# 3 - both confirmation and admin approval required
#
# ** please do not choose option 0 if you are not allowing open
# subscribes (next variable)
DEFAULT_SUBSCRIBE_POLICY = 2
・
・
 Are archives on or off by default?
DEFAULT_ARCHIVE = Off
・
・
# Will list be available in digested form?
DEFAULT_DIGESTABLE = No
エイリアス作成
# /usr/lib/mailman/bin/genaliases
管理者パスワード作成
# /usr/lib/mailman/bin/mmsitepass
管理用メーリングリスト作成
# /usr/lib/mailman/bin/newlist mailman
Enter the email of the person running the list: example@example.com
Initial mailman password:
Hit enter to notify mailman owner...
パーミッション修正
# /usr/lib/mailman/bin/check_perms -f
/etc/mailman/aliases bad group (has: root, expected mailman) (fixing)
/etc/mailman/adm.pw bad group (has: root, expected mailman) (fixing)
/usr/lib/mailman/Mailman/Defaults.pyc bad group (has: root, expected mailman) (fixing)
/usr/lib/mailman/Mailman/mm_cfg.pyc bad group (has: root, expected mailman) (fixing)
/var/log/mailman/error bad group (has: root, expected mailman) (fixing)
Problems found: 5
Re-run as mailman (or root) with -f flag to fix
# chown apache /etc/mailman/aliases
# chmod 664 /etc/mailman/aliases*
# chmod 2775 /etc/mailman
パーミッション修正確認
# /usr/lib/mailman/bin/check_perms
No problems found
mailman起動と自動起動設定
# systemctl enable --now mailman
# /usr/lib/mailman/bin/newlist mailman
Enter the email of the person running the list: example@example.com
Initial mailman password:
postalias: fatal: open /etc/mailman/aliases.db: Permission denied
Traceback (most recent call last):
  File "/usr/lib/mailman/bin/newlist", line 274, in 
    main()
  File "/usr/lib/mailman/bin/newlist", line 240, in main
    sys.modules[modname].create(mlist)
  File "/usr/lib/mailman/Mailman/MTA/Postfix.py", line 342, in create
    _update_maps()
  File "/usr/lib/mailman/Mailman/MTA/Postfix.py", line 78, in _update_maps
    raise RuntimeError, msg % (acmd, status, errstr)
RuntimeError: command failed: /usr/sbin/postalias /etc/mailman/aliases (status: 1, Operation not permitted)
などとエラーが出た場合は。
# /usr/lib/mailman/bin/check_perms -f
を実行してパーミッションを修正する。
管理者パスワードの変更
/usr/lib/mailman/bin/mmsitepass
メーリングリストの削除
# /usr/lib/mailman/bin/rmlist メーリングリスト名

Postfixの設定

mailman起動とサービス追加
# vi /etc/postfix/main.cf
#alias_maps = dbm:/etc/aliases
#alias_maps = hash:/etc/aliases
#alias_maps = hash:/etc/aliases, nis:mail.aliases
#alias_maps = netinfo:/aliases
alias_maps = hash:/etc/aliases, hash:/etc/mailman/aliases
・
・
#alias_database = dbm:/etc/aliases
#alias_database = dbm:/etc/mail/aliases
#alias_database = hash:/etc/aliases
#alias_database = hash:/etc/aliases, hash:/opt/majordomo/aliases
alias_database = hash:/etc/aliases, hash:/etc/mailman/aliases
postfix再起動
 # systemctl restart postfix

Apacheの設定

mailman.confや他の .confを状況に応じて修正後Apache再起動
mailman.conf
# cd /etc/httpd/conf.d/
# cp mailman.conf mailman.conf.org
# vi mailman.conf
Apache再起動
# httpd -t
Syntax OK
# systemctl restart httpd

ブラウザでアクセス

https://ホスト名/mailman/admin/
にアクセス。

【CentOS8】クローラ拒否設定(robots.txt .htaccess)

DocumentRoot /var/www/dev の場合

robots.txtでクローラ拒否

# vi /var/www/dev/robots.txt
User-Agent:*
Disallow:/

.htaccessでクローラ拒否

httpd.conf に記述してもOK。
# vi /var/www/dev/.htaccess
SetEnvIf User-Agent "Googlebot" ng_ua
SetEnvIf User-Agent "bingbot" ng_ua
order Allow,Deny
Allow from all
Deny from env=ng_ua

【CentOS8】Ruby2.7.1のインストール

dnfでもRubyはインストールできますが、2.5.5とバージョンが古いので、
rbenvを使って最新のRuby2.7.1をインストールします。
# dnf list avialable ruby
milter-manager_repos                                                                406  B/s | 819  B     00:02
milter-manager_repos-source                                                         400  B/s | 819  B     00:02
Available Packages
ruby.i686                               2.5.5-105.module_el8.1.0+214+9be47fd7                              AppStream
ruby.x86_64                             2.5.5-105.module_el8.1.0+214+9be47fd7                              AppStream

rbenvのインストール

CentOS8インストール時におおよそのもの、git、openssl-develなどはデフォルトで入っています。
こちらの環境で必要なものは readline-devel、nodejsでした。
必要なパッケージインストール
# yum -y install readline-devel nodejs
epelリポジトリが追加されていない場合は追加。
epelリポジトリの追加
# dnf -y install epel-release
rbenvをダウンロード
# git clone https://github.com/rbenv/rbenv.git ~/.rbenv
Pathなどを追加
# echo 'export PATH="~/.rbenv/bin:$PATH"' >> ~/.bash_profile
# echo 'eval "$(rbenv init -)"' >> ~/.bash_profile
# source ~/.bash_profile
rbenv intすると、下記のメッセージが。
# Load rbenv automatically by appending
# the following to ~/.bash_profile:

eval "$(rbenv init -)"
手動でやるな、自動でやれと。
rbenvバージョン確認
# rbenv -v
rbenv 1.1.2-30-gc879cb0

Rubyのインストール

Ruby最新バージョン確認
# rbenv install --list
2.5.8
2.6.6
2.7.1
jruby-9.2.11.1
maglev-1.0.0
mruby-2.1.1
rbx-5.0
truffleruby-20.1.0

Only latest stable releases for each Ruby implementation are shown.
Use 'rbenv install --list-all' to show all local versions.
Rubyインストール
# rbenv install 2.7.1
使用するRubyのバージョン指定
# rbenv global 2.7.1
# rbenv rehash
rbenvでバージョンを指定してやらないと下記のメッセージ。
# ruby -v
rbenv: ruby: command not found

The `ruby' command exists in these Ruby versions:
  2.7.1
Rubyバージョン確認
# ruby -v
ruby 2.7.1p83 (2020-03-31 revision a0c7c23c9c) [x86_64-linux]

【CentOS8】glib2.6インストール時に [meson.build:1814:2: ERROR: Dependency "mount" not found, tried pkgconfig]

# cd glib-2.60.7
# meson _build
・
・
Dependency mount found: NO (tried pkgconfig)

meson.build:1814:2: ERROR:  Dependency "mount" not found, tried pkgconfig
libmount-devel をインストールする事で解決。
# dnf -y install libmount-devel

CentOS8でサーバー構築 - 8.ファイアーウォール(Firewalld)

以前は iptablesで管理していましたが、CentOS7以降デフォルトで
Firewalldが使われることになったので、こちらを使う。
zoneは publicのみ設定します。

Firewalldの起動

現在起動していているか確認
# systemctl status firewalld
● firewalld.service - firewalld - dynamic firewall daemon
   Loaded: loaded (/usr/lib/systemd/system/firewalld.service; disabled; vendor preset: enabled)
   Active: inactive (dead)
     Docs: man:firewalld(1)
既にインストールされていているが起動していない。
firewall-cmdでも確認できる
# firewall-cmd --state
not running
パッケージが最新か確認
# dnf list firewalld
CentOS-8 - AppStream                                      448 kB/s | 4.3 kB     00:00
CentOS-8 - Base                                            87 kB/s | 3.9 kB     00:00
CentOS-8 - Extras                                         169 kB/s | 1.5 kB     00:00
CentOS-8 - PowerTools                                      21 kB/s | 4.3 kB     00:00
Extra Packages for Enterprise Linux Modular 8 - x86_64     15 kB/s | 8.1 kB     00:00
Extra Packages for Enterprise Linux 8 - x86_64             10 kB/s | 7.9 kB     00:00
Remi's Modular repository for Enterprise Linux 8 - x86_64 3.5 kB/s | 3.5 kB     00:00
Safe Remi's RPM repository for Enterprise Linux 8 - x86_6 3.1 kB/s | 3.0 kB     00:00
Installed Packages
firewalld.noarch                          0.7.0-5.el8_1.1                          @BaseOS
Available Packages
firewalld.noarch                          0.8.0-4.el8                              BaseOS
0.8が使えるようなのでupdate。dnfではupdateも使えるがupgradeが正しいオプション。
アップグレード
# dnf -y upgrade firewalld
起動
# systemctl start firewalld
起動したとたん、SSHの接続が切られました。事によってはデータセンターに行くパターンです。
設定サービスの確認
# firewall-cmd --zone=public --list-services
cockpit dhcpv6-client ssh
IPv6は使う予定が無いので dhcpv6-clientの通信を停止しておきます。
dhcpv6-client停止
# firewall-cmd --permanent --remove-service=dhcpv6-client
success
# firewall-cmd --reload
見慣れないcockpitはCentOS8の操作をWEB上からできるとか。
セキュリティ面を考慮しないとすぐには利用したくないので、こちらも一旦停止しておきます。
cockpit停止
# firewall-cmd --permanent --remove-service=cockpit
success
# firewall-cmd --reload
success
http https追加
# firewall-cmd --permanent --add-service=http
success
# firewall-cmd --permanent --add-service=https
success
# firewall-cmd --reload
success
確認
# firewall-cmd --zone=public --list-services
http https ssh
cockpitはデフォルトでインストールされていました。
# dnf list installed |grep cockpit
cockpit.x86_64                              196.3-1.el8                                @BaseOS
cockpit-bridge.x86_64                       196.3-1.el8                                @BaseOS
cockpit-packagekit.noarch                   197.3-1.el8                                @AppStream
cockpit-system.noarch                       196.3-1.el8                                @BaseOS
cockpit-ws.x86_64                           196.3-1.el8                                @BaseOS

メール関連のサービス追加

必要に応じて、smtp, smtps, pop3, pop3s, imap, imapsを追加。
# firewall-cmd --permanent --add-service=smtp
success
# firewall-cmd --permanent --add-service=smtps
success
# firewall-cmd --permanent --add-service=pop3
success
# firewall-cmd --permanent --add-service=pop3s
success
# firewall-cmd --reload
success

SSHのポートを変更対応

SSHのPortを12345に変更。
ssh.xmlコピー
# cp /usr/lib/firewalld/services/ssh.xml /etc/firewalld/services/ssh.xml
ssh.xm編集
# vi /etc/firewalld/services/ssh.xml
<?xml version="1.0" encoding="utf-8"?>
<service>
  <short>SSH</short>
  <description>Secure Shell (SSH) is a protocol for logging into and executing commands on remote machines. It provides secure encrypted communications. If you plan on accessing your machine remotely via SSH over a firewalled interface, enable this option. You need the openssh-server package installed for this option to be useful.</description>
  <port protocol="tcp" port="12345"/>
</service>
設定反映
# firewall-cmd --reload
success

FTPのポートを変更対応

FTPのPortを12345に変更。
PASV_PORT: 60100-60100
ftp.xmlコピー
# cp /usr/lib/firewalld/services/ftp.xml /etc/firewalld/services/ftp.xml
ftp.xml編集
# vi /etc/firewalld/services/ftp.xml
?xml version="1.0" encoding="utf-8"?>
<service>
  <short>FTP</short>
  <description>FTP is a protocol used for remote file transfer. If you plan to make your FTP server publicly available, enable this option. You need the vsftpd package installed for this option to be useful.</description>
  <port protocol="tcp" port="12345"/>
  <helper name="ftp"/>
</service>
追加されていない場合はftp追加
# firewall-cmd --permanent --add-service=ftp
success
PASVポート追加
# firewall-cmd --zone=public --permanent --add-port=60000-60100/tcp
success
設定反映
# firewall-cmd --reload
success
確認
# firewall-cmd --list-ports
60000-60100/tcp

コマンドまとめ

起動の確認
firewall-cmd --state
設定の確認
firewall-cmd --list-all
firewall-cmd --get-active-zone
firewall-cmd --zone=public --list-services
firewall-cmd --list-ports
サービスの追加
 firewall-cmd --permanent --add-service=ftp
サービスの削除
firewall-cmd --permanent --remove-service=ftp
設定反映
firewall-cmd --reload
特定のIPを拒否
firewall-cmd --zone=drop --permanent --add-source=46.38.148.0/22
lsofコマンドで現在使っているポートを確認
# lsof -i -nP
・
・
httpd      4176          apache    3u  IPv4  24324      0t0  TCP *:80 (LISTEN)
dovecot    8231            root   23u  IPv4 463784      0t0  TCP *:110 (LISTEN)
dovecot    8231            root   24u  IPv6 463785      0t0  TCP *:110 (LISTEN)
dovecot    8231            root   25u  IPv4 463786      0t0  TCP *:995 (LISTEN)
dovecot    8231            root   26u  IPv6 463787      0t0  TCP *:995 (LISTEN)
dovecot    8231            root   41u  IPv4 463832      0t0  TCP *:143 (LISTEN)
dovecot    8231            root   42u  IPv6 463833      0t0  TCP *:143 (LISTEN)
dovecot    8231            root   43u  IPv4 463834      0t0  TCP *:993 (LISTEN)
dovecot    8231            root   44u  IPv6 463835      0t0  TCP *:993 (LISTEN)
master     8346            root   16u  IPv4 467529      0t0  TCP *:25 (LISTEN)
master     8346            root   20u  IPv4 467532      0t0  TCP *:465 (LISTEN)
・
・