PHP

[WordPress]独自設定画面で指定DBからデータ取得

functions.php

<?php
function my_menu()
{
    add_menu_page('独自設定画面','my menu','manage_options','my_menu','my_options_page','',58);
}
add_action('admin_menu', 'my_menu');

function my_options_page()
{
    $wpm = new ThisCaseModel();
    $wpdb = new wpdb('DBID','DBPW','DBNAME','DBHOST');

    $page = empty($_GET['_page']) ? 1 : $_GET['_page'];
    $sql = array();
    $sql[] = "SELECT u.id,u.name";
    $sql[] = "FROM users AS u";
    $sql[] = "LEFT JOIN others AS o ON u.id = o.user_id";
    $sql[] = "WHERE o.id IS NOT NULL";
    $sql[] = "ORDER BY u.id ASC";
    $sql[] = "LIMIT " . $wpm->get_sql_limit_value_by_page($page,20);
    $users = $wpdb->get_results(implode(" ",$sql));
    
    array_pop($sql);
    array_pop($sql);
    $sql[0] = "SELECT COUNT(*) AS count";
    $count = $wpdb->get_results(implode(" ",$sql));
    $page_info = $wpm->get_page_no_info($page,$count[0]->count,20);
    $page_numbers = $wpm->get_page_numbers_for_pager((int)$page_info['current'],(int)$page_info['last_page_no']);
    
    include TEMPLATEPATH . DIRECTORY_SEPARATOR . 'admin-my_menu.php';
}

admin-my_menu.php

<style>
    .users,.users th,.properties td{
        border-collapse: collapse;
        border:1px solid #ccc;
    }
    .users th,.users td{
        padding: 3px 5px;
    }
    .pager{
        display: flex;
    }
    .pager a{
        display: block;
        border:1px solid #ccc;
        margin-right: 5px;
        padding: 3px 10px;
    }
    .pager a:link{
        text-decoration: none;
    }
</style>
<div class="container">
    <h2>my menu</h2>
    <div>
        <div>件数:<?php echo $page_info['count'];?></div>
        <div><?php echo $page_info['current'];?>/<?php echo $page_info['last_page_no'];?></div>
    </div>
    <table class="users">
        <tr>
            <th>ID</th>
            <th>name</th>
        </tr>
        <?php foreach ($users as $user):?>
            <tr>
                <td><?php echo $wpm->esc_html($user->id);?></td>
                <td><?php echo $wpm->esc_html($user->name);?></td>
            </tr>
        <?php endforeach;?>
    </table>
    <div class="pager">
        <?php foreach ($page_numbers as $page_number):?>
            <?php if(empty($page_number)):?>
                …
            <?php else:?>
                <a href="<?php echo $wpm->get_url_by_current_url($page_number<2 ? array('exclude_keys'=>array('_page')) : array('exclude_keys'=>array('_page'),'add_values'=>array('_page'=>$page_number)));?>"><?php echo $page_number;?></a>
            <?php endif;?>
        <?php endforeach;?>
    </div>
</div>

[PHP]idiorm #1

require_once 'idiorm.php';
ORM::configure('mysql:host=localhost;dbname=dev_db');
ORM::configure('username', 'root');
ORM::configure('password', '');
ORM::configure('driver_options', [
    PDO::MYSQL_ATTR_INIT_COMMAND       => 'SET NAMES utf8',
    PDO::ATTR_EMULATE_PREPARES         => false,
    PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
]);
function echo_json($data)
{
    header("Content-Type: application/json; charset=utf-8");
    echo json_encode($data);
}
$words = mb_split('[\s, ]',addcslashes(trim($_POST['keywords']),'\_%'));
try{
    $orm = ORM::for_table('entries')->select('id')->where_equal('deleted','0')->order_by_asc('id');
    foreach ($words as $w) {
        $w = trim($w);
        if($w !== '')
            $orm->where_like('search', "%{$w}%");
    }
$recipes = $orm->find_many();
}catch (PDOException $e){
}
$result_data = array();
if(!empty($recipes)){
    foreach ($recipes as $recipe)
        $result_data[] = $recipe->html_id;
}
echo_json($result_data);
exit;

[PHP]remove_protocol

public function remove_protocol($url)
{
    return preg_replace('/^https?:\/\/[^\/]+/', '', $url);
}

[PHP]download_file

function download_file($filePath)
{
    header("Content-Disposition: inline; filename=\"" . basename($filePath) . "\"");
    header("Content-Length: " . filesize($filePath));
    header("Content-Type: application/octet-stream");
    readfile($filePath);
}

[PHP]get_image_rgb

public function get_image_rgb($image_path,$x=0,$y=0)
{
    if(!is_readable($image_path))
        return false;
    $im = imagecreatefrompng($image_path);
    $rgb = imagecolorat($im, $x, $y);
    $r = ($rgb >> 16) & 0xFF;
    $g = ($rgb >> 8) & 0xFF;
    $b = $rgb & 0xFF;
    return array(
        'r' => $r,
        'g' => $g,
        'b' => $b,
    );
}

[PHP]imagescale_output

public function imagescale_output($image_path,$save_path,$width,$height,$aspect_fill = true,$strict_size_on_aspect_fit = true,$space_color = array('r'=>255,'g'=>255,'b'=>255))
{
    if(!is_readable($image_path))
        return false;
    $o_img = $this->imagecreate($image_path);
    $o_w = imagesx($o_img);
    $o_h = imagesy($o_img);
    $w_ratio = $width / $o_w;
    $h_ratio = $height / $o_h;
    $ratio = $aspect_fill ? max($w_ratio,$h_ratio) : min($w_ratio,$h_ratio);
    $new_w = round($o_w * $ratio);
    $new_h = round($o_h * $ratio);
    if(function_exists('imagescale')){
        $new_img = imagescale($o_img,$new_w,$new_h);
    }else{
        $new_img = imagecreatetruecolor($new_w, $new_h);
        imagecopyresampled($new_img, $o_img, 0, 0, 0, 0, $new_w, $new_h, $o_w, $o_h);
    }
    
    $param = $aspect_fill ? array('x' => round(abs($width - $new_w) * 0.5), 'y' => round(abs($height - $new_h) * 0.5), 'width' => $width, 'height' => $height) : array('x' => 0, 'y' => 0, 'width' => $new_w, 'height' => $new_h);
    if(function_exists('imagecrop')) {
        $dest_img = imagecrop($new_img, $param);
    }else{
        $dest_img = imagecreatetruecolor($param['width'], $param['height']);
        imagecopy($dest_img, $new_img, 0, 0, $param['x'], $param['y'], $param['width'], $param['height']);
    }
    imagedestroy($new_img);
    if(!$aspect_fill && $strict_size_on_aspect_fit){
        $next_img = imagecreatetruecolor($width,$height);
        imagefill($next_img,0,0,empty($space_color) ? imagecolorat($dest_img,round($new_w*0.5),0) : imagecolorallocate($dest_img,$space_color['r'],$space_color['g'],$space_color['b']));
        imagecopy($next_img,$dest_img,round(abs($width - $new_w) * 0.5),round(abs($height - $new_h) * 0.5),0,0,$param['width'],$param['height']);
        $success = $this->imageoutput($next_img,$save_path);
        imagedestroy($o_img);
        imagedestroy($next_img);
        imagedestroy($dest_img);
    }else {
        $success = $this->imageoutput($dest_img, $save_path);
        imagedestroy($o_img);
        imagedestroy($dest_img);
    }
    return $success;
}

[PHP]copy_image_with_suffix

function copy_image_with_suffix($guid,$suffix)
{
    $upload_dir = $this->get_upload_dir();
    $o_image = dirname($upload_dir) . DIRECTORY_SEPARATOR . ltrim($guid,'/');
    $new_image = dirname($upload_dir)  . DIRECTORY_SEPARATOR . ltrim($this->add_suffix_to_filename($guid, $suffix),'/');
    if(!file_exists($o_image)) {
        $o_image = mb_convert_encoding($o_image, 'CP932', 'UTF-8');
        $new_image = mb_convert_encoding($new_image, 'CP932', 'UTF-8');
    }

    if (file_exists($new_image))
        unlink($new_image);

    $success = copy($o_image, $new_image);
    return $success;
}
public function add_suffix_to_filename($filename = '',$suffix = '')
{
    if(empty($filename))
        return '';
    return preg_replace('/\.(.{3,4})$/',"{$suffix}.$1",$filename);
}

[WordPress]delete_all_transient

public function delete_all_transient()
{
    global $wpdb;
    $sql = "DELETE FROM `{$wpdb->options}` WHERE `option_name` LIKE ('_transient_%');";
    $result = $wpdb->get_results($sql);
    $sql = "DELETE FROM `{$wpdb->options}` WHERE `option_name` LIKE ('_site_transient_%');";
    $result = $wpdb->get_results($sql);
}

[PHP]unzip

public function unzip($file,$to)
{
    $zip = new ZipArchive();
    $result = $zip->open($file);
    if($result === true){
        $result = $zip->extractTo($to);
        $zip->close();
    }
    return $result === true;
}

[CodeIgniter]get_table_names_by_dbname

$this->db->list_tables();

上記だとキャッシュから取得する。キャッシュを回避する場合下記を使用。

public function get_table_names_by_dbname($dbname)
{
    $names = array();
    $sql = "SHOW TABLES FROM {$dbname}";
    $query = $this->db->query($sql);
    foreach ($query->result_array() as $row)
    {
        if ( ! isset($key))
        {
            if (isset($row['table_name']))
            {
                $key = 'table_name';
            }
            elseif (isset($row['TABLE_NAME']))
            {
                $key = 'TABLE_NAME';
            }
            else
            {
                $key = array_keys($row);
                $key = array_shift($key);
            }
        }

        $names[] = $row[$key];
    }
    return $names;
}