PHP

[PHP]idiorm #8 save

$record = ORM::for_table($this->table_name)->where('id', $id)->find_one();
if(empty($record)){
    return false;
}
foreach ($data as $key => $value){
    $record->set($key,$value);
}
$result = $record->save();

[PHP]idiorm #7 raw_execute + AES_ENCRYPT

define('DB_ENCRYPT_KEY','aabbccddeeff');
require_once __DIR__ . '/idiorm.php';
ORM::configure('mysql:host=localhost;dbname=xxxx');
ORM::configure('username', 'yyy');
ORM::configure('password', 'zzz');
ORM::configure('driver_options', [
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
]);

$query = "INSERT INTO {$table_name}(`e_id`,`description`) VALUES(:e_id,AES_ENCRYPT(:description,'xxyyzz'))";
result = ORM::for_table('users')->raw_execute($query,['e_id'=>1,'description'=>'あいうえお']);

$query = "UPDATE {$table_name} SET `description`=AES_ENCRYPT(:description,'xxyyzz') WHERE `e_id` = :e_id";
result = ORM::for_table('users')->raw_execute($query,['e_id'=>1,'description'=>'あいうえお']);

[Laravel]AES_ENCRYPT

$result = DB::table('users')->insert([
                ['email' => \DB::raw("AES_ENCRYPT('{$xxx}',SHA2('".env('DB_ENCRYPT_KEY')."',512))"), 'token' => \DB::raw("AES_ENCRYPT('{$yyy}',SHA2('".env('DB_ENCRYPT_KEY')."',512))")]
            ]);

[Laravel]AES_DECRYPT

$record = DB::table('xxx')
            ->selectRaw("id,AES_DECRYPT(`yyy`,SHA2(:key1,512)) AS shop,AES_DECRYPT(`zzz`,SHA2(:key2,512)) AS token",['key1'=>env('DB_ENCRYPT_KEY'),'key2'=>env('DB_ENCRYPT_KEY')])
            ->whereRaw("AES_DECRYPT(`yyy`,SHA2(:key,512)) = :yyy", ['key'=>env('DB_ENCRYPT_KEY'),'yyy'=>$yyy])
            ->first();

[PHP]idiorm #6 select_expr + AES_DECRYPT

define('DB_ENCRYPT_KEY','aabbccddeeff');
require_once __DIR__ . '/idiorm.php';
ORM::configure('mysql:host=localhost;dbname=xxxx');
ORM::configure('username', 'yyy');
ORM::configure('password', 'zzz');
ORM::configure('driver_options', [
    PDO::MYSQL_ATTR_INIT_COMMAND       => 'SET NAMES utf8',
]);
$email = "xxxx@gmail.com";

ORM::configure('logging', true);
try{
    $orm = ORM::for_table('users')->select("id")->select_expr("AES_DECRYPT(`email`,'".DB_ENCRYPT_KEY."')","email")->select_expr("AES_DECRYPT(`name`,'".DB_ENCRYPT_KEY."')","name");
    $orm->where_raw("AES_DECRYPT(`email`,?) = ?",array(DB_ENCRYPT_KEY,$email));
    $record = $orm->find_one();
}catch (PDOException $e){
    return null;
}
echo "<pre>";
var_dump(ORM::get_last_query());
echo "</pre>";
if(!empty($record)) {
    echo "<pre>";
    echo $record->id;
    echo $record->email;
    echo $record->name;
    echo "</pre>";
}

[WordPress]アップロード画像の複数サイズ自動生成停止

下記実行

update wp_options set option_value='0' where option_name = 'thumbnail_size_w';
update wp_options set option_value='0' where option_name = 'thumbnail_size_h';
update wp_options set option_value='0' where option_name = 'medium_size_w';
update wp_options set option_value='0' where option_name = 'medium_size_h';
update wp_options set option_value='0' where option_name = 'large_size_w';
update wp_options set option_value='0' where option_name = 'large_size_h';
update wp_options set option_value='0' where option_name = 'medium_large_size_w';
update wp_options set option_value='0' where option_name = 'medium_large_size_h';

 
functions.phpに下記追加

function disable_image_sizes( $new_sizes ) {
    unset( $new_sizes['1536x1536'] );
    unset( $new_sizes['2048x2048'] );
    unset( $new_sizes['post-thumbnail'] );
    unset( $new_sizes['category-thumb'] );
    unset( $new_sizes['homepage-thumb'] );
    return $new_sizes;
}
add_filter( 'intermediate_image_sizes_advanced', 'disable_image_sizes' );

add_filter( 'big_image_size_threshold', '__return_false' );

[WordPress]get_post_by_post_name

public function get_post_by_post_name($post_name, $post_type = '', $post_status = 'publish')
{
    global $wpdb;
    $sql = array();
    $sql[] = "SELECT p.*";
    $sql[] = "FROM $wpdb->posts AS p";
    $sql[] = "WHERE p.post_name " . $this->__get_sql_for_in($post_name);
    if (!empty($post_type))
        $sql[] = "AND p.post_type = '$post_type'";
    if(!empty($post_status))
        $sql[] = "AND p.post_status = '$post_status'";
    $result = $wpdb->get_results(implode(' ', $sql));
    if (empty($result))
        return null;
    return is_array($post_name) ? $result : $result[0];
}
protected function __get_sql_for_in($values, $is_number = false)
{
    $quote    = $is_number ? "" : "'";
    $is_array = is_array($values);
    $not      = ($is_array && is_string($values[0]) && preg_match('/^.*\!=.+$/',$values[0])) || (!$is_array && is_string($values) && preg_match('/^.*\!=.+$/',$values));
    $in       = $not ? ' NOT IN' : ' IN';
    $eq       = $not ? '!=' : '=';
    if($is_array){
        foreach ($values as $i => $value) {
            $values[$i] = preg_replace('/^(\!=|=)/', '', esc_sql($value));
            $values[$i] = preg_replace('/^ /', '', esc_sql($value));
        }
    }else{
        $values = preg_replace('/^(\!=|=)/','',esc_sql($values));
        $values = preg_replace('/^ /','',esc_sql($values));
    }
    return $is_array && 1 < count($values) ? "{$in} ({$quote}" . implode("{$quote},{$quote}", $values) . "{$quote})" : ($is_array ? "{$eq} {$quote}{$values[0]}{$quote}" : "{$eq} {$quote}$values{$quote}");
}

[PHP]get_url_by_regex

public function get_url_by_regex($url = null,$replaces = null,$suffix = null)
{
    $tmp = explode('?',empty($url) ? $_SERVER['REQUEST_URI'] : $url);
    $url = 0<count($tmp) ? array_shift($tmp) : '';
    $tmp = 0<count($tmp) ? array_pop($tmp) : '';
    $tmp = explode('&',$tmp);
    for($i=0;$i<count($replaces);$i+=2){
        foreach ($tmp as $j => $q){
            $tmp[$j] = preg_replace($replaces[$i],$replaces[$i+1],$q);
        }
    }
    $tmp = array_diff($tmp,array(''));
    $is_empty = empty($tmp);
    return $url.($is_empty?'':'?'.implode('&',$tmp)) . (is_null($suffix)?'':($is_empty?'?':'&').preg_replace('/^[\?&]/','',$suffix));
}

[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