[SSH]SSHトンネル@WinSCP

SFTP
xxx.xxx.xxx.xxx
22
ID:xxxxxx
PW:yyyyyy
・設定
-トンネル
チェック:SSHトンネルを経由して接続する
nnn.nnn.nnn.nnn 50001
ID:mmmmmm
PW:pppppp
ローカルトンネルポート 自動選択
秘密鍵 id_rsa.ppk
-SSH 認証
チェック エージェントの転送を許可する
秘密鍵 filename.ppk

[PHP]CSV出力@メモリ節約

$csvfile = date('YmdHis') . ".csv";
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $csvfile);
$fp = fopen('php://output','w');
stream_filter_append($fp, 'convert.iconv.UTF-8/CP932', STREAM_FILTER_WRITE);
fputcsv($fp, array('A','B','C'));
fclose($fp);

[PHP,Ruby]Instagram Graph API

PHP

<?php
function echo_json_by_filename($filename)
{
    header("Content-Type: application/json; charset=utf-8");
    if(is_readable($filename)) {
        readfile($filename);
    }else{
        echo '{data:[]}';
    }
}
$businessID          = '111111';
$hashTagID           = '17843677603040508';//パスタ
$targetInstaUsername = isset($_GET['u']) ? $_GET['u'] : '';
$targetFileNo        = isset($_GET['no']) ? $_GET['no'] : '';
$apiBaseUrl          = 'https://graph.facebook.com/v5.0/';
$accessToken         = 'abcdefg';
$urlForHashTag       = "{$apiBaseUrl}{$hashTagID}/recent_media?user_id={$businessID}&fields=id,media_type,media_url,permalink,like_count,comments_count&limit=50&access_token={$accessToken}";
$urlForUsername      = "{$apiBaseUrl}{$businessID}?fields=business_discovery.username({$targetInstaUsername}){id,followers_count,media_count,ig_id,media{caption,permalink,username,media_url,media_type,like_count,comments_count,timestamp,id}}&access_token={$accessToken}";
$urls                = array($urlForHashTag,$urlForUsername);
$nos                 = array_keys($urls);
$filename            = dirname(__FILE__) . "/insta{$targetFileNo}.json";
if(empty($targetInstaUsername) || !is_numeric($targetFileNo) || !in_array($targetFileNo,$nos)){
    echo_json_by_filename($filename);
    exit;
}
if(file_exists($filename)){
    $t = filemtime($filename);
    if($t === false || abs($t - time()) < 60){
        echo_json_by_filename($filename);
        exit;
    }
    if(unlink($filename) === false){
        echo_json_by_filename($filename);
        exit;
    }
}
$data = file_get_contents($urls[$targetFileNo]);
file_put_contents($filename,$data);
header("Content-Type: application/json; charset=utf-8");
echo $data;

Ruby

#!/Ruby23-x64/bin/ruby
# coding: utf-8
ENV['SSL_CERT_FILE'] = File.expand_path('/cert/cacert.pem')
require "cgi"
require "net/https"
require "uri"
require "date"
def echo_json_by_filename(filename)
	puts "Content-Type: application/json; charset=utf-8\n\n"
    if File.exist?(filename) then
        File.open(filename, "r") do |f|
          puts f.read
        end
    else
        puts "{data:[]}"
    end
end
cgi = CGI.new
businessID          = "111111"
hashTagID           = "17843677603040508"#パスタ
targetInstaUsername = cgi["u"]
targetFileNo        = cgi["no"]
apiBaseUrl          = "https://graph.facebook.com/v5.0/"
accessToken         = "abcdefg"
urlForHashTag       = apiBaseUrl + hashTagID + "/recent_media?user_id="+businessID+"&fields=id,media_type,media_url,permalink,like_count,comments_count&limit=50&access_token=" + accessToken
urlForUsername      = apiBaseUrl + businessID + "?fields=business_discovery.username("+targetInstaUsername+"){id,followers_count,media_count,ig_id,media{caption,permalink,username,media_url,media_type,like_count,comments_count,timestamp,id}}&access_token=" + accessToken
filename            = "./insta"+targetFileNo+".json"
if targetInstaUsername.empty? || targetFileNo.empty? then
	echo_json_by_filename(filename)
	exit
end
if File.exist?(filename) then
	gap = DateTime.now.to_time - File.mtime(filename)
	if gap < 60 then
		echo_json_by_filename(filename)
		exit
	end
	File.delete(filename)
end
uri = URI.parse urlForUsername
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
req = Net::HTTP::Get.new uri.request_uri
res = http.request req
file = File.open(filename,"w")
file.puts(res.body)
puts "Content-Type: application/json; charset=utf-8\n\n"
puts res.body
exit

[WordPress]wp_head不要タグ削除

remove_action( 'wp_head', 'wp_resource_hints', 2 );
remove_action( 'wp_head', 'rest_output_link_wp_head', 10, 0 );
remove_action( 'wp_head', 'feed_links_extra', 3);
remove_action( 'wp_head', 'wp_generator');
remove_action( 'wp_head', 'rsd_link' );
remove_action( 'wp_head', 'wlwmanifest_link' );
remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'wp_head', 'wp_print_styles', 8 );

[Apache].htaccessクエリ置換

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} (^|.*&)id=100($|[^0-9])(.*)
RewriteRule ^search.*$ http://%{HTTP_HOST}%{REQUEST_URI}?%1id=200%2%3 [R=301,L]
</IfModule>

id=100をid=200に置換してリダイレクト
id以外のクエリはそのまま

[WordPress]メニュー削除

function remove_noneed_menus()
{
    global $menu;
    global $submenu;

    unset($menu[5]);  // 投稿
    //unset($menu[20]);  // 固定ページ
    unset($menu[25]);  // コメント
}
add_action('admin_menu', 'remove_noneed_menus');

[WordPress]テンプレ切替

function add_user_rewrite_rules()
{
    add_rewrite_rule("^post_type1/?$", "index.php?post_type=post_type1&mode=archive", 'top');
    add_rewrite_rule("^post_type1/article/([^\/]+)/?$", 'index.php?post_type=post_type1&name=$matches[1]&mode=single', 'top');
    add_rewrite_rule("^post_type2/?$", "index.php?post_type=post_type2&mode=archive", 'top');
    add_rewrite_rule("^post_type2/(\d+)/?$", 'index.php?post_type=post_type2&p=$matches[1]&mode=single', 'top');
}
add_action('init', 'add_user_rewrite_rules');

function add_user_routes_query_vars($query_vars)
{
    $query_vars[] = 'mode';
    $query_vars[] = 'param';
    return $query_vars;
}
add_filter('query_vars', 'add_user_routes_query_vars');

/**
 * is_single,is_archiveの返値が確定する前に処理
 * @param $query
 */
function my_parse_request($query)
{
    if(is_admin())
        return;
    
    if($query->query_vars['post_type'] === 'post_type1') {
        $query->query_vars['posts_per_page'] = 10;
    }else if($query->query_vars['post_type'] === 'post_type2') {
        $query->query_vars['posts_per_page'] = 20;
    }else if($query->query_vars['post_type'] === 'post_type3'){
    }
}
add_action( 'parse_request', 'my_parse_request');

function my_pre_get_posts( $query )
{
    if ( is_admin() || ! $query->is_main_query() ){
        return;
    }
    if($query->query['post_type'] === 'post_type1') {
        if (!empty($_GET['api'])) {
            if(!empty($_GET['count']) && preg_match('/^\d+$/',$_GET['count'])){
                $query->set('posts_per_page',$_GET['count']);
            }else{
                $query->set('posts_per_page',3);
            }
        }
    }else if($query->query['post_type'] === 'post_type2') {
        if (!empty($_GET['api'])) {
            if (isset($_GET['cate'])) {
                $tax_query[] = array(
                    'taxonomy' => 'tax_type',
                    'terms'    => array($_GET['cate']),
                    'field'    => 'slug',
                    'operator' => 'IN');
                $query->set('tax_query', array('relation' => 'OR', $tax_query));
            }
            if(!empty($_GET['count']) && preg_match('/^\d+$/',$_GET['count'])){
                $query->set('posts_per_page',$_GET['count']);
            }else{
                $query->set('posts_per_page',3);
            }
        }else if (isset($query->query['param'])) {
            $tax_query[] = array(
                'taxonomy' => 'tax_type',
                'terms'    => array($query->query['param']),
                'field'    => 'slug',
                'operator' => 'IN');
            $query->set('tax_query', array('relation' => 'OR', $tax_query));
        }
    }
}
add_action('pre_get_posts','my_pre_get_posts');

/**
 * テンプレートファイル切替
 * @param $template
 * @return mixed
 */
function my_template_include($template)
{
    global $wp_query;
    if($wp_query->query['post_type'] === 'post_type1' && isset($wp_query->query['mode']) && $wp_query->query['mode'] === 'top') {
        $bn = basename($template);
        return preg_replace("/{$bn}$/","index-post_type1.php",$template);
        
    }else if($wp_query->query['post_type'] === 'post_type2' && isset($wp_query->query['mode']) && $wp_query->query['mode'] === 'top'){
        $bn = basename($template);
        return preg_replace("/{$bn}$/","archive-post_type2.php",$template);

    }else if($wp_query->query['post_type'] === 'post_type3'){
        if($wp_query->query['mode'] === 'single'){
            $bn = basename($template);
            return preg_replace("/{$bn}$/","single-post_type3.php",$template);
        }
    }
    return $template;
}
add_filter('template_include','my_template_include');


[WordPress]wp_enqueue_script

function my_original_option()
{
    add_menu_page('オリジナルメニュー','オリジナルメニュー','manage_options','my_option','my_option','',30);
}
add_action('admin_menu', 'my_original_option');

function my_option()
{
    include TEMPLATEPATH . DIRECTORY_SEPARATOR . 'my_option.php';
}
function my_register_scripts()
{
    if(is_admin() && !empty($_GET['page']) && $_GET['page']==='my_option') {
        $keyname = 'my_option';
        $result = wp_register_script($keyname, get_template_directory_uri() . '/scripts/admin-custom.js', array('jquery', 'jquery-ui-sortable'));
        wp_enqueue_script($keyname);
    }
}
add_action('init', 'my_register_scripts');

[PHP]idiorm #5 raw_execute

public function get_std_by_array($arr,$include_keys = null)
{
    $tmp = new stdClass();
    foreach ($arr as $key => $v){
        if(empty($include_keys) || (!empty($include_keys) && in_array($key,$include_keys)))
            $tmp->$key = $v;
    }
    return $tmp;
}
public function get_datas
{
$sql = array();
$sql[] = "SELECT * FROM wp_posts";
$this->init_pgsql();
try{
    $res = ORM::raw_execute(implode(" ",$sql));
    $statement = ORM::get_last_statement();
    $rows = array();
    $results = array();
    while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
        $results[] = $this->get_std_by_array($row);
    }
}catch (PDOException $e){
}
return empty($results) ? null : $results;
}

[PostgreSQL]カラム名、カラムコメント取得

SELECT
psat.relname AS TABLE_NAME,pa.attname AS COLUMN_NAME,pd.description AS COLUMN_COMMENT
FROM
pg_stat_all_tables AS psat,pg_description AS pd,pg_attribute AS pa
WHERE
psat.schemaname = (SELECT schemaname FROM pg_stat_user_tables WHERE relname = 'テーブル名') AND psat.relname = 'テーブル名' AND psat.relid = pd.objoid AND pd.objsubid <> 0 AND pd.objoid = pa.attrelid AND pd.objsubid = pa.attnum
ORDER BY pd.objsubid