PHP

[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

[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;
}

[WordPress]ACF Pro Wysiwyg用関数

public function is_empty_wysiwyg_content($content)
{
    $content = $this->get_string_from_wysiwyg_content($content);
    return $content === '';
}
public function get_wysiwyg_content($content)
{
    return apply_filters('acf_the_content',$content);
}
public function get_string_from_wysiwyg_content($_content)
{
    $is_empty = trim(preg_replace('/<[^>]+?>/','',$_content)) == ' ';
    if($is_empty)
        return '';
    return trim(html_entity_decode(preg_replace('/<[^>]+?>/','',$_content)));
}

[WordPress]タクソノミー、タームから記事数取得

public function get_posts_count_by_taxonomy_slug($taxonomy, $term = '')
{
    global $wpdb;
    $sql = array();
    $sql[] = "SELECT";
    $sql[] = "COUNT(tr.object_id) AS count";
    $sql[] = "FROM $wpdb->term_relationships AS tr";
    $sql[] = "LEFT JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id";
    $sql[] = "LEFT JOIN $wpdb->terms AS t ON tt.term_id = t.term_id";
    $sql[] = "LEFT JOIN $wpdb->posts AS p ON tr.object_id = p.ID";
    $sql[] = "WHERE p.post_status = 'publish'";
    if (!empty($term))
        $sql[] = "AND t.slug ='$term'";
    $sql[] = "AND tt.taxonomy = '$taxonomy'";
    if (empty($term))
        $sql[] = "GROUP BY tr.object_id";

    $posts = $wpdb->get_results(implode(' ', $sql));
    return empty($posts) ? 0 : $posts[0]->count;
}

[WordPress][プラグイン]WordPress Popular Posts

プラグインWordPress Popular Postsによって閲覧数が保存されている時
指定投稿タイプの記事IDを閲覧数の多い順に取得する

public function get_post_ids_order_by_views_wppp($post_type = 'post', $param = array())
{
    $param = array_merge(
        array(
            'posts_per_page' => 5,
            'range' => '1 MONTH',
            'return_posts' => false,
        ),
        $param
    );
    global $wpdb;
    $now = current_time('mysql');
    $interval = "";
    switch ($param['range']) {
        case "yesterday":
            $interval = "1 DAY";
            break;
        case "daily":
            $interval = "1 DAY";
            break;
        case "weekly":
            $interval = "1 WEEK";
            break;
        case "monthly":
            $interval = "1 MONTH";
            break;
        default:
            $interval = $param['range'];
            break;
    }
    $sql[] = "SELECT postid AS ID,SUM(pageviews) AS views,p.post_type";
    $sql[] = "FROM {$wpdb->prefix}popularpostssummary AS pps";
    $sql[] = "LEFT JOIN $wpdb->posts AS p ON pps.postid = p.ID";
    $sql[] = "WHERE view_datetime > DATE_SUB('{$now}', INTERVAL $interval)";
    $sql[] = "AND p.post_type " . (is_array($post_type) ? "IN ('" . implode("','", $post_type) . "')" : "= '$post_type'");
    $sql[] = "AND p.post_status = 'publish'";
    if (!empty($param['post_id'])) {
        $sql[] = "AND postid " . (is_array($param['post_id']) ? "IN (" . implode(",", $param['post_id']) . ")" : "= {$param['post_id']}");
    }
    if (!empty($param['not_post_id'])) {
        $sql[] = "AND postid " . (is_array($param['not_post_id']) ? "NOT IN (" . implode(",", $param['not_post_id']) . ")" : "!= {$param['not_post_id']}");
    }
    $sql[] = "GROUP BY postid";
    $sql[] = "ORDER BY views DESC";
    if (!empty($param['ppp'])) {
        $sql[] = "LIMIT 0,{$param['ppp']}";
    }elseif (!empty($param['posts_per_page'])) {
        $sql[] = "LIMIT 0,{$param['posts_per_page']}";
    }
    $posts = $wpdb->get_results(implode(' ', $sql));
    if ($param['return_posts'])
        return $posts;
    $ids = array();
    foreach ($posts as $post) {
        $ids[] = $post->ID;
    }
    return $ids;
}

[PHP]idiorm #4 raw_query

try{
    $sql = "SELECT * FROM shops WHERE name LIKE ? OR name LIKE ?";
    $words = array("%銀座%","%御徒町%");
    $items = ORM::for_table('shops')->raw_query($sql,$words)->find_array();
}catch (PDOException $e){
    return null;
}
return $items;

[PHP]idiorm #3 select_expr

$this->init_pgsql();
try{
    $orm = ORM::for_table('users')->select_expr("DISTINCT CONCAT(team,'_',job)","tj")->select('team')->select('job');
    $orm->where_in('team',$teams);
    $records = $orm->find_array();
}catch (PDOException $e){
    return null;
}
return $records;

[WordPress]Gutenberg下のプレビューURL変更

/**
 * Gutenbergによる投稿プレビューのURL(プレビュー生成中からのリダイレクト先)を変更する
 * WordPress 5.3.2で動作確認
 * @param $response
 * @return array
 */
function my_rest_pre_echo_response($response)
{
    if(!is_user_logged_in())
        return;
    if($response['status'] === 'draft'){
        $response['link'] = '任意のURL';
    }
    return $response;
}
add_filter( 'rest_pre_echo_response', 'my_rest_pre_echo_response', 100 );

[PHP]idiorm #2 join

public function init_pgsql()
{
if($this->_init_pgsql)return;
$this->_init_pgsql = true;
ORM::configure(‘pgsql:host=’.PDB_HOST.’;port=’.PDB_PORT.’;dbname=’.PDB_DB.’;’);
ORM::configure(‘username’, PDB_ID);
ORM::configure(‘password’, PDB_PW);
}
public function get_data_by_id($id)
{
$this->init_pgsql();
try{
$orm = ORM::for_table(‘wp_posts’)->join(‘wp_postmeta’, array(‘wp_posts.ID’, ‘=’, ‘wp_postmeta.post_id’))->select(‘*’)->where_equal(‘wp_posts.ID’,$id)->limit(1);
$data = $orm->find_array();
}catch (PDOException $e){
return null;
}
return empty($data) ? null : $data;
}