文章を解析して#を付与して返却。

2024.03.04

Logging

おはようございます、文章を解析して#を付与して返却…Qiitaの丸コピです
SNSでの使用することを考えて作りました。文章を解析して名詞と形容詞の文字の先頭に#を付与して返却します😌。

レンタルサーバーでは動きませんがawsやgcp,vpsなどでは動く作りになっています。
作った経緯はこういうサービスが無かったので作りました?。

因みにexecの脆弱性が気になるところですので対応が必要かもです🙇。

※phpやPythonのインストールはご自身で行ってください。

#前処理 mecab-python3バージョンは1.0.8です
sudo apt-get install mecab libmecab-dev mecab-ipadic-utf8
sudo pip install mecab-python3
pip install unidic-lite
<?php
class sharpPost
{
    /**
     * mecab.pyを使って文章を解析(名詞と形容詞を取り出す)
     * @param $posstData
     * @return array|null
     */
    public function analysis($postData)
    {
        if(!$postData)return null;
        $word = null;
        exec('python py/mecab.py "'.strip_tags(htmlentities($postData)).'"',$output);// 2>&1
        if(is_array($output)){
            foreach($output as $val){
                $analysisWord = explode("\t",$val);
                if(isset($analysisWord[1]) && preg_match('/(名詞|形容詞)/',$analysisWord[1])){
                    $word[] = $analysisWord[0];
                    $word = array_unique($word);
                }
            }
        }
        return $word;
    }
    
    /**
     * 文字列を置き換える処理
     * @param $postData
     * @param $word|null
     * @return string
     */
    public function replacePostData($postData='',$word=null)
    {
        if(is_array($word)){
            foreach($word as $val){
                $postData = preg_replace("/({$val})/u"," #{$val} ",$postData);
            }
        }
        return $postData;
    }
}
$textData = '単なる自分が使いたい機能です、無かったので作ってみただけです。';
$sharpPost = new sharpPost();
$word = $sharpPost->analysis($textData);
print(($sharpPost->replacePostData($textData,$word)).PHP_EOL);
import MeCab
import sys
args = sys.argv
if(args[1]):
    tagger = MeCab.Tagger()
    print(tagger.parse(args[1]))

タグ

analysis, args, argv if, AWS, exec, explode, foreach, htmlentities, isset, PARAM, preg_match, preg_replace, print, qiita, quot, replacePostData, return, sharpPost, tagger, tagger.parse,

何かの役に立つ#bluesky

2024.01.29

Logging

おはようございます、QiitaにblueSkyのプロフィールURLからRSSを抽出するコードを書きました。先日、blueSkyにRSS機能を追加したという記事を読んだので、その日のうちに対応した形になります。

特に難しいコードでもないので、コメントは一切書いていませんが、それなりに役に立つと信じてリリースしました、ソースの改修などを行って頂けて構いませんが出来ればQiitaもしくはこちらの記事にリンクを貼っていただけたら幸いです。

PHP環境は8.2になっていますが、PHP7系でも動くソースコードなので安心してご使用いただけるかと思います。使用にあたって最終行はコメントアウトを行ってください、url変数も自分にあったurlに変えていただければと思います。

<?php
class blueSkyRss{
    public $rss = null;
    /**
     * __construct
     * @param $url
     * @return void
     */
    public function __construct($url)
    {
        try {
            $html = file_get_contents($url);
            preg_match('/https:\/\/bsky\.app\/profile\/did.*\/rss/',$html,$matches);
            if($rssUrl = $matches[0]){
                $feed = simplexml_load_file($rssUrl);
                $this->rss = $feed;    
            }
        } catch (\Throwable $th) {
            //throw $th;
        }
    }
    /**
     * getRss
     * @return object
     */
    public function getRss():object
    {
        $response = [];
        if(isset($this->rss->channel)){
            $cnt = 0;
            foreach($this->rss->channel->item as $item){
                $response[$cnt]['link']    = $item->link;
                $response[$cnt]['comment']   = $item->description;
                $response[$cnt]['date'] = $item->pubDate;
                $cnt++;
            }
        }
        return (object)$response;
    }
}
$url = 'https://bsky.app/profile/xxxxxxx.bsky.social';
//var_dump((new blueSkyRss($url))->getRss());

明日へ続く。

タグ

bluesky, catch, cnt, construct, description, did, foreach, getRss, isset, lt, object, PARAM, preg_match, pubDate, qiita, return, RSS, throw, Throwable, try,

TwitterとMastodonに同時配信するツールを作成

2023.07.08

Logging

おはようございます。先日、Twitter民がAPI制限で表示がされない問題が起きていた時に、TwitterとMastodonに同時配信するツールを作っていました。普通につぶやくのは前にコードを作っていましたので、それを流用して簡単に出来るなぁなどと思いながら作っていたら画像も添付した状態でつぶやきたいという欲が出てきて沼にハマりました。

Twitterの方は画像添付のつぶやきも簡単にできたものの、Mastodonで沼にハマりました。PHPにはcurlのメソッドがあります、これを使用してAPIに指示を出す感じです。ドキュメントにはヘッダーとともに必須項目を送信すればトゥート(つぶやける)できるよと記載されていたのだけど、実際はユーザーエージェントの値も送信しないと上手く動作しない仕様になっていました。

これはちょっと酷くない?と思いながら数時間悩み、その後、パラメーターの文字化けするという問題に沼にハマりここで数分悩んでいました。結局、全て自己解決したのですが調べても生成AIを頼っても答えが出ない場合は、今までの自分の知識や経験がある方が優位だなって感じました。

トイウコトデ、Qiitaでも掲載したのですがこちらでも解決策を記載します。

<?php
class Mastodon
{
    const host = "mstdn.jp";
    const endpoint1  = "/api/v1/statuses";
    const endpoint2  = "/api/v1/media";

    public function toot($text){
        $data = array('file' => new CURLFile("/var/www/html/t_m/image.png", 'image/png', "image.png"));
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://" . self::host . self::endpoint2);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['User-Agent: ' . $_SERVER['HTTP_USER_AGENT'], 'Content-Type: multipart/form-data', 'Authorization: Bearer ' . MSTDN_ACCESSTOKEN]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $response =   json_decode(@curl_exec($ch));
        curl_close($ch);
        if (isset($response->id)) {
            $postdata = [
                "visibility" => "public",
                "media_ids" => [$response->id],
                "status" => strip_tags($text),
            ];
            $data = json_encode($postdata);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "https://" . self::host . self::endpoint1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['User-Agent: ' . $_SERVER['HTTP_USER_AGENT'], 'Content-Type: application/json', 'Authorization: Bearer ' . MSTDN_ACCESSTOKEN]);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            $response =  @curl_exec($ch);
            curl_close($ch);
        }
    }
}

タグ

'User-Agent', API, application, array, Authorization, Bearer, Content-type, curl, false, isset, json_decode, mastodon, multipart, qiita, quot, Twitter, VERIFYHOST, トイウコトデ, トゥート, ユーザーエージェント,

Twitter API V2では画像ツイートが出来ないと流れてきたので対処方法

2023.06.02

Logging

おはようございます。先日、Twitter API V2では画像ツイートが出来ないと流れてきたので対処方法を載せときます。Qiitaにも掲載していますが、こちらでも記載します。コードはいつまで使用出来るかは不明ですね、イーロン・マスクのサジカゲンで無料プランでは出来なくなる可能性を秘めています。今のところ、使用できるコードです。PHP8系では動きますがPHP7系は:mixedの部分を退けてあげないと動かないかもです。因みにPythonのサンプルコードが公式にはあったような気がします。

<?php

require_once "tw-config-v2.php";
require_once "vendor/autoload.php";

use Abraham\TwitterOAuth\TwitterOAuth;

class tw
{
    public $connection = null;
    public $media = null;
    public function __construct()
    {
        $this->connection = new TwitterOAuth(APIKEY, APISECRET, ACCESSTOKEN, ACCESSTOKENSECRET);
    }

    /**
     * イメージのエンドポイントを取得する v1.1 そのうち廃止されそう。
     * @param $imageName
     * @return boolean
     */
    public function getImage($imageName = null): bool
    {
        if (empty($imageName)) {
            return false;
        }
        $this->media = $this->connection->upload('media/upload', ['media' => "/var/www/html/tw/tmp/images/$imageName"]);
        return true;
    }

    /**
     * イメージ付きでツイート。
     * @param $text
     * @return mixed
     */
    public function tweet($text = null): mixed
    {
        if (!empty($text) && isset($this->media->media_id_string)) {
            $param = [
                'text' => $text,
                'media' => [
                    'media_ids' => [
                        $this->media->media_id_string
                    ]
                ]
            ];
            $this->connection->setApiVersion('2');
            return $this->connection->post('tweets', $param, true);
        }
        return false;
    }
}

if($argv[0]){
    $tw = new tw();
    if($tw->getImage("php2023.png"))
    {
        $tw->tweet("これはテストです");
    }    
}

タグ

argv, bool, connection, construct, empty, getImage, isset, media', mixed, PARAM, qiita, quot, quot;vendor, return, tmp, tw, Tweet, use AbrahamTwitterOAuthTwitterOAuth, イーロン, サジカゲン,

ワードプレスの自動タグ生成するプラグイン再開発。 #wp #tag

2022.12.12

Logging

おはようございます、今年もあと半分とちょっとですね、月曜日のたわわ☕。

さて、今日はワードプレスの自動タグ生成するプラグイン再開発しましたってお話です、この自動タグを生成するツールは以前、作っていたのですがYahoo!APIのバージョンアップに伴い使用出来なくなっていました。その為、プラグインを更新しV2対応をこの度、行ったって話です。もともと日本語記事のタグ自動生成するものは存在していたのですが、それがエラーで使用出来なくなり自分で開発したのが今に至っています。

プラグインをダウンロードして使いたい方は、zipファイルを解凍し解凍したフォルダをサーバーのプラグイン置き場にアップロードすることにより使用出来るようになります。尚、前手順としてYahoo!APIのアプリケーションIDの取得を行う必要があります。

プラグインをダウンロードしたくないという方のためにソースコードを一部貼っときます。

        if (isset($appid)) {
            $endpoint = "https://jlp.yahooapis.jp/KeyphraseService/V2/extract";
            $headers = [
                "Content-Type: application/json",
                "User-Agent: Yahoo AppID: ".$appid,
            ]; 
            $param = [
                "id"=> time(),
                "jsonrpc" => "2.0",
                "method" => "jlp.keyphraseservice.extract",
                "params" => [
                    "q"=>preg_replace("/https?:([a-zA-Z0-9|\/|_|\-|%|@|\*|\.|\?|&|=]){0,}/m","",$content)
                    ]
                ];

                $curl=curl_init($endpoint);
                curl_setopt($curl,CURLOPT_POST, TRUE);
                curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
                curl_setopt($curl,CURLOPT_POSTFIELDS, json_encode($param));
                curl_setopt($curl,CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($curl,CURLOPT_SSL_VERIFYHOST, FALSE);
                curl_setopt($curl,CURLOPT_RETURNTRANSFER, TRUE);
                
                $response =  json_decode(curl_exec($curl));


            if (isset($response->result->phrases)) {
                foreach ($response->result->phrases as $keys=>$word) {
                    if ($word->text) {
                        $tags[] = $word->text;
                    }
                    if (is_array($tags)) {
                        wp_set_post_tags($post_id, implode(",", array_unique($tags)), false);
                    }
                }
            }
        }

タグ

application, false, foreach, gt, headers, implode, isset, jlp, json_decode, json_encode, keys, PARAM, phrases, quot, quot;User-Agent, response, result, Text, true, VERIFYHOST,

google NewsをRSSで取得してjsonで返却するPHPプログラム

2018.12.22

Logging

<?php
//$_POST["sh"]...検索キーワード 
if ($_POST["sh"]) {
	$sh = urlencode(@xss_defence($_POST["sh"]));
	$res = simplexml_load_file("https://news.google.com/news/rss/headlines/section/q/$sh/?ned=jp&hl=ja&gl=JP");
	rss($res);
}
function rss(object $obj = null):void
{
	if (isset($obj->channel->item)) {
		if ($obj->channel->item) {
			$cnt = 0;
			foreach ($obj->channel->item as $item) {
				$result[$cnt]["title"] = (string)$item->title;
				$result[$cnt]["link"] = (string)$item->link;
				$result[$cnt]["pubDate"] = (string)$item->pubDate;
				$result[$cnt]["description"] = (string)$item->description;
				$result[$cnt]["source"] = (string)$item->source;
				$cnt++;
			}
		}
	}
	echo json_encode($result);
}

function xss_defence(mixed $val):mixed
{

    if(!isset($val))return false;
    if(is_array($val)){
        foreach ($val as $key => $value) {
            # code...
            $val[$key] = strip_tags($value);
            $val[$key] = htmlentities($val[$key],ENT_QUOTES);
        }
    }else{
        $val = strip_tags($val);
        $val = htmlentities($val,ENT_QUOTES);
    }
    return $val;
}

google NewsをRSSで取得してjsonで返却するPHPプログラムです。
ご自由にご使用ください。

タグ

0, channel-, cnt, com, defence, file, foreach, function, gl, Google, gt, headlines, hl, https, if, isset, item, ja, jp, json, load, lt, ned, News, null, obj, object, php, POST, quot, res, RSS, section, sh, simplexml, urlencode, void, xss, キーワード, プログラム, 取得, 検索, 返却,