blog system

CREATE TABLE post (
	no SERIAL,
	title TEXT,
	content TEXT,
	time TIMESTAMP
);
CREATE TABLE comment (
	no SERIAL,
	post_no INT,
	name TEXT,
	content TEXT,
	time TIMESTAMP
);
INSERT INTO post(no,title,content) VALUES(1,'記事1タイトル','記事1の内容です。');
INSERT INTO post(no,title,content) VALUES(2,'記事2タイトル','記事2の内容です。');
INSERT INTO comment(no,post_no,name,content) VALUES(1,1,'たろう','記事1へのコメントです。');
INSERT INTO comment(no,post_no,name,content) VALUES(2,1,'はなこ','記事1へのコメントです。');

css

body {
  background-color:#f77;
  font-size: 14px;
  font-family: Helvetica,Arial, sans-serif;
}
a:link, a:visited {color: #a00;}
a:hover {color: #fca;}
p {
  margin: 0;
  padding: 0;
}
h1 {
  margin: 10px 0;
  padding: 0;
  color: white;
  font-size: 32px;
  text-align: center;
}
h2 {
  margin: 0 -20px 10px -20px;
  padding: 5px 10px;
  background-color: #379;
  color: white;
  font-size: 18px;
}
h3 {
  margin: 0 -15px 10px -15px;
  padding: 5px 10px;
  background-color: #a55;
  color: white;
  font-size: 14px;
}
.post {
  width: 500px;
  margin: 0 auto 15px auto;
  padding: 0 20px 20px 20px;
  background-color: #fb0;
}
.comment {
  margin: 10px 0;
  padding: 0 15px 15px 15px;
  background-color: #da7;
}
.comment_link {
  text-align: right;
}
<!DOCTYPE>
<html>
<head>
    <meta charset="utf-8">
    <title>special blog</title>
    <link rel="stylesheet" href="blog.css">
</head>
<body>
  <h1>Special Blog</h1>
  <div class="post">
    <h2>記事1のタイトルです</h2>
    <p>記事1の本文です。<br>
      記事1の本文です。<br>
    </p>
    <div class="comment">
      <h3>通りすがり1</h3>
      <p>
        記事1へのコメントです。<br>
        記事1へのコメントです。<br>
      </p>
    </div>
    <div class="comment">
      <h3>通りすがり2</h3>
      <p>
        記事1へのコメントです。
      </p>
    </div>
    <p class="comment_link">
      投稿日:2016/12/19
      <a href="#">コメント</a>
    </p>
  </div>
</body>
</html>

index

<?php
  $pdo = new PDO("mysql:dbname=test", "root");
  $st = $pdo->query("SELECT * FROM post ORDER BY no DESC");
  $posts = $st->fetchAll();
  for ($i = 0; $i < count($posts); $i++) {
    $st = $pdo->query("SELECT * FROM comment WHERE post_no={$posts[$i]['no']} ORDER BY no DESC");
    $posts[$i]['comments'] = $st->fetchAll();
  }
  require 't_index.php';
?>

t_index.php

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Special Blog</title>
<link rel="stylesheet" href="blog.css">
</head>
<body>
<h1>Special Blog</h1>
<?php foreach ($posts as $post) { ?>
  <div class="post">
    <h2><?php echo $post&#91;'title'&#93; ?></h2>
    <p><?php echo nl2br($post&#91;'content'&#93;) ?></p>
    <?php foreach ($post&#91;'comments'&#93; as $comment) { ?>
      <div class="comment">
        <h3><?php echo $comment&#91;'name'&#93; ?></h3>
        <p><?php echo nl2br($comment&#91;'content'&#93;) ?></p>
      </div>
    <?php } ?>
    <p class="commment_link">
      投稿日:<?php echo $post&#91;'time'&#93; ?> 
      <a href="comment.php?no=<?php echo $post&#91;'no'&#93; ?>">コメント</a>
    </p>
  </div>
<?php } ?>
</body>
</html>

post

<?php
  $error = $title = $content = '';
  if (@$_POST&#91;'submit'&#93;){
    $title = $_POST&#91;'title'&#93;;
    $content = $_POST&#91;'content'&#93;;
    if (!$title) $error .= 'タイトルがありません。<br>';
    if (mb_strlen($title) > 80) $error .= 'タイトルが長すぎます。<br>';
    if (!$content) $error .= '本文がありません。<br>';
    if (!$error) {
      $pdo = new PDO("mysql:dbname=test", "root");
      $stmt = $pdo->query("INSERT INTO post(title,content) VALUES('$title','$content')");
      header('Location: index.php');
      exit();
    }
  }
require 't_post.php';
?>

post_t.php

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>記事投稿| Special Blog</title>
  <link rel="stylesheet" href="blog.css">
</head>
<body>
  <form method="post" action="post.php">
    <div class="post">
      <h2>記事投稿</h2>
      <p>題名</p>
      <p><input type="text" name="title" size="40" value="<?php echo $title ?>"></p>
      <p>本文</p>
      <p><textarea name="content" rows="8" cols="40"><?php echo $content ?></textarea></p>
      <p><input name="submit" type="submit" value="投稿"></p>
      <p><?php echo $error ?></p>
    </div>
  </form>
</body>
</html>

comment

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>コメント投稿 | Special Blog</title>
<link rel="stylesheet" href="blog.css">
</head>
<body>
<form method="post" action="comment.php">
  <div class="post">
    <h2>コメント投稿</h2>
    <p>お名前</p>
    <p><input type="text" name="name" size="40" value="<?php echo $name ?>"></p>
    <p>コメント</p>
    <p><textarea name="content" rows="8" cols="40"><?php echo $content ?></textarea></p>
    <p>
      <input type="hidden" name="post_no" value="<?php echo $post_no ?>">
      <input name="submit" type="submit" value="投稿">
    </p>
    <p><?php echo $error ?></p>
  </div>
</form>
</body>
</html>

comment_t

<?php
  $post_no = $error = $name = $content = '';
  if (@$_POST&#91;'submit'&#93;) {
    $post_no = strip_tags($_POST&#91;'post_no'&#93;);
    $name = strip_tags($_POST&#91;'name'&#93;);
    $content = strip_tags($_POST&#91;'content'&#93;);
    if (!$name) $error .= '名前がありません。<br>';
    if (!$content) $error .= 'コメントがありません。<br>';
    if (!$error) {
      $pdo = new PDO("mysql:dbname=test", "root");
      $st = $pdo->prepare("INSERT INTO comment(post_no,name,content) VALUES(?,?,?)");
      $st->execute(array($post_no, $name, $content));
      header('Location: index.php');
      exit();
    }
  } else {
    $post_no = strip_tags($_GET['no']);
  }
  require 't_comment.php';
?>

crontab

setting

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=""
HOME=/

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name command to be executed

* * * * * /user/bin/php /home/vagrant/hoge/index.php

php Jaccard

<?php

 /**
 * $item_ids => 商品IDの配列[1,2,3,4,5]の配列
 */

 foreach($item_ids as $item_id1){
   $base = $Redis->lRange('Viewer:Item' . $item_id1, 0, 999);
   if (count($base) === 0){
     continue;
   }
   foreach ($item_ids as $item_id2){
     if ($item_id1 === $item_id2){
       continue;
     }
     $target = $Redis->lRange('Viewer:Item:' . $item_id2, 0, 999);
     if (count($target) === 0){
       continue;
     }

     #ジャッカード指数を計算
     $join = floatval(count(array_unique(array_merge($base, $target))));
     $intersect = floatval(count(array_intersect($base, $target)));
     if ($intersect == 0 || $join == 0){
       continue;
     }
     $jaccard = $intersect / $join;

     $redis->zAdd('Jaccard:Item:' . $item_id1, $jaccard, $item_id2);

   }
 }
<?
/**
* $item_id => 商品id
* $user_id => ユーザid
*/
$Redis->lRem('Viewer:Item' . $item_id, $user_id);
$Redis->lPush('Viewer:Item' . $item_id, $user_id);
$Redis->lTrim('Viewer:Item' . $item_id, 0, 999);
<?php
 $Redis->zRevRange('Jaccard:Item:' . $item_id, 0, -1);

php redis

%e7%84%a1%e9%a1%8c

redisがインストールされた状態

git clone git://github.com/nicolasff/phpredis.git
cd phpredis
phpize
./configure
make
make install

php iniにextension=redis.soを追加。

[vagrant@localhost rss11]$ sudo vi /etc/php.ini
[vagrant@localhost rss11]$ php -m | grep redis
redis

phpでredis操作

<?php
$redis = new Redis();
$redis->connect("127.0.0.1",6379);

// PINGで確認する
echo $redis->ping();

set

<?php
$redis = new Redis();
$redis->connect("127.0.0.1",6379);

// PINGで確認する
echo $redis->set('hoge', 'huga');

$value = $redis->get('hoge');

echo $value;

php rss

<?php
$num = 5;//RSS取得件数

$rssUrl=array(
  'http://x6xo.hatenablog.com/rss',//サイトURL
);

//magpierss
require_once('./magpierss-master/rss_fetch.inc');
define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');//encode
define('MAGPIE_CACHE_AGE','30');//cache

foreach($rssUrl as $no => $rss_url){
  if($rss_url != ''){
    //urlからRSSを取得
    $rss = @fetch_rss($rss_url);
      if($rss != NULL){
        for ($i=0; $i<count($rss->items); $i++){
          $rss->items[$i]["site_title"] = $rss->channel["title"];
          $rss->items[$i]["site_link"] = $rss->channel["link"];
        }
        // itemsを格納
        $rssItemsArray[] = $rss->items;
      }
  }
}

$concatArray = array();
if (is_array($rssItemsArray)) {
    for($i=0;$i<count($rssItemsArray);$i++){
    $concatArray = array_merge($concatArray,$rssItemsArray&#91;$i&#93;);//配列を統合する
  }

    foreach ($concatArray as $no => $values) {

        //RSSの種類によって日付を取得
        if($values['published']){$date = $values['published'];}
        elseif($values['created']){$date = $values['created'];}
        elseif($values['pubdate']){$date = $values['pubdate'];}
        elseif($values['dc']['date']){$date = $values['dc']['date'];}
        $date=date("Y-m-d H:i:s",strtotime($date));

        //Filter
        $nowtime = date("Y-m-d H:i:s",strtotime( "now" ));//現在時刻の取得
        if($date > $nowtime){//未来記事の排除
        }elseif(preg_match("/AD/", $values["title"])){//広告記事の排除
        }elseif(preg_match("/PR/", $values["title"])){
        }else{

            //値の定義
            $title=$values["title"];
            $link=$values["link"];
            $site_title=$values["site_title"];
            $site_link=$values["site_link"];

            //記事ごとに必要な項目を抽出
            $rssArray[]=array($date, $title, $link, $site_title, $site_link);
        }//
    }//

    //ソート
    function cmp($a, $b) {
        if ($a[0] == $b[0]) return 0;
        return ($a[0] > $b[0]) ? -1 : 1;
    }
    if($rssArray) { usort($rssArray, 'cmp'); }
    if(count($rssArray) > $num){$count=$num;}
    else{$count=count($rssArray);}

    for ($i=0; $i<$count; $i++) {
        $date=date("Y-m-d H:i:s",strtotime($rssArray&#91;$i&#93;&#91;0&#93;));
        $title=$rssArray&#91;$i&#93;&#91;1&#93;;
        $link=$rssArray&#91;$i&#93;&#91;2&#93;;
        $site_title=$rssArray&#91;$i&#93;&#91;3&#93;;
        $site_link=$rssArray&#91;$i&#93;&#91;4&#93;;
        $datelink = "<div>$date";
      $titlelink = "<a href='$link'>$title</a>";
      $site_titlelink = "<a href='$site_link'>[$site_title]</a></div>";
      echo "$datelink$titlelink$site_titlelink</div>";//(確認用)
    }
}
?>

mysql

create table rss(
	id int not null auto_increment primary key,
	title varchar(255),
	link varchar(255),
	site_title varchar(64),
	site_link varchar(64),
	date datetime
);

MagpieRSS

<?php
//RSS
$rssUrl = array(
  'http://blog.livedoor.jp/news4vip2/index.rdf',//ニュー速クオリティ
  'http://himasoku.com/index.rdf',
  'http://kanasoku.info/index.rdf',
  'http://workingnews.blog117.fc.com/?xml',
  'http://blog.livedoor.jp/dgnplus/index.rdf',
  'http://majikichi.com/index.rdf',
);

//MagpieRSS
require_once('./magpierss-master/rss_fetch.inc');
define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
define('MAGPIE_CACHE_ON', false);

//配列編集
foreach ($rssUrl as $no => $rss_url){
  $rss = @fetch_rss($rss_url);
  if ($rss != NULL){
    for ($i=0; $i<count($rss->items); $i++){
      $rss->items[$i]["site_title"] = $rss->channel["title"];
      $rss->items[$i]["site_link"] = $rss->channel["link"];
    }
    $rssItemsArray[] = $rss->items;
  }
}
$contactArray = array();
for($i=0;$i<count($rssItemsArray);$i++){
$contactArray = array_merge($contactArray,$rssItemsArray&#91;$i&#93;);}
foreach ($contactArray as $no => $values){

//RSSの種類によって日付を取得
if($values['published']){$date = $values['published'];}
elseif($values['dc']['date']){$date = $values['dc']['date'];}
elseif($values['pubdate']){$date = $values['pubdate'];}
$date=date("Y-m-d H:i:s",strtotime($date));

//Filter
$nowtime = date("Y-m-d h:i:s", strtotime("now"));
if ($date > $nowtime){
} elseif(preg_match("/AD/", $values["title"])){
} elseif(preg_match("/PR/", $values["title"])){
} else {

// 値の定義
$title=$values["title"];
$link=$values["link"];
$site_title=$value["site_title"];
$site_link=$values["site_link"];

// 画像取得
$content=$values["content"]["encoded"];
preg_match('/<img.*>/i', $content, $img_all);
if(empty($img_all[0])){
  $content = $values['description'];
  preg_match('/<img.*>/i', $content, $img_all);
}
preg_match('/http.*?(\.gif|\.png|\.jpg|\.jpeg$|\.bmp)/i', $img_all[0], $gazo);
if(empty($gazo[0])){$gazo = "http://azaz.clouver.jp/antenna/noimage.png";}
else{$gazo = $gazo[0];}

//配列
$rssArray[]=array($date,$title, $link, $site_title, $site_link, $gazo);
}
}

$num = 50;
if(count($rssArray)>$num){$count=$num;}else{$count=count($rssArray);}
rsort($rssArray);

//HTML整形
for($i=0; $i<$count; $i++){
  $date=date("m/d H:i", strtotime($rssArray&#91;$i&#93;&#91;0&#93;));
  $title=$rssArray&#91;$i&#93;&#91;1&#93;;
  $link=$rssArray&#91;$i&#93;&#91;2&#93;;
  $site_title=$rssArray&#91;$i&#93;&#91;3&#93;;
  $site_link=$rssArray&#91;$i&#93;&#91;4&#93;;
  $gazo=$rssArray&#91;$i&#93;&#91;5&#93;;
    $datelink = "<div class='date'>$date</div>";
    $gazolink = "<a target='_blank' href='$link'><div class='trim'><img src='$gazo' /></div></a>";
    $titlelink = "<div class='title'><a href='$link'>$title</a></div>";
    $site_titlelink = "<div class='site_title'><a href='$site_link'>$date - [$site_title]</a></div>";
    echo "<article>$gazolink$titlelink$site_titlelink</article>";
}

?>

rss from fnn news

%e7%84%a1%e9%a1%8c

<?php
$xml = simplexml_load_file('http://rss.fnn-news.com/fnn_news.xml');
echo "<ul>";
foreach($xml->channel->item as $entry){
  $entrydate = date ("Y.m.d",strtotime ($entry->pubDate));
  echo "<li>$entrydate<a href='$entry->link'>$entry->title</a></li>";
}
echo "</ul>";
?>

画像付き
reference:preg_match
Perform a regular expression match

<?php
$xml = simplexml_load_file('http://rss.fnn-news.com/fnn_news.xml');

foreach($xml->channel->item as $entry){
echo "<article>";

// sitelink
$site_title = $xml->channel->title;
$site_link = $xml->channel->link;
$site_titlelink = "<a href='$site_link'>$site_title</a>";
echo $site_titlelink;

// date
$date = date ("Y.m.d",strtotime($entry->pubDate));
echo $date;

//article link
$titlelink = "<a href='$entry->link'>$entry->title</a>";
echo $titlelink;

// picture
preg_match('/<img.*>/i', $entry->description, $entryimg);
echo $entryimg[0];

echo "</article>";
}
?>

xml connect with MySQL

<?php 

$database = "nameofthedatabase"
$dbconnect = mysql_pconnect(localhost, dbuser, dbpassword);
mysql_select_db($database, $dbconnect);
$query = "select link, headline, description from 'headlines' limit 15";
$result = mysql_query($query, $dbconnect);

while ($line = mysql_fetch_assoc($result))
  {
    $result&#91;&#93; = $line;
  }
$now = date("D, d M Y H:i:s T");

$output = "<?xml version=\"1.0\"?>
        <rss version=\"2.0\">
          <channel>
            <title>Our Demo RSS</title>
            <link>http://wwww.tracypeterson.com/RSS/RSS.php</link>
            <description>A TEST RSS</description>
            <language>en-us</language>
            <pubDate>$now</pubDate>
            <docs>http://someurl.com</docs>
            <managingEditor>yo@youremail.com<managingEditor>
            <webMaster>you@youremail.com</webMaster>
          ";
foreach ($return as $line)
{
  $output .= "<item><title>".htmlentities($line['headline'])."</title>
              <link>".htmlentities($line['link'])."</link>

  <description>".htmlentities(strip_tags($line['description']))."</description>
      </item>";
}
$output .= "</channel></rss>";
echo $output;
?>
<?php
// ヘッダーを出力する
header("Content-type: text/xml;charset=utf-8");
echo '<?xml version="1.0" encoding="UTF-8"?>';

// サイト情報を書き込む
echo '
<rss version="2.0">
<channel>
<title>hogehogeオレオレRSS</title>
<link>http://google.com</link>
<description>Facebookのgraph api, cake php, javascriptなどの記事を更新していきます。</description>
<category>php, graph api, facebook, cakephp</category>
<generator>@DAI199</generator>
<webMaster>@DAI199</webMaster>
';

// 記事の内容を更新
for(ループさせる)
{
echo '
<item>
<title>Test'.$i.'</title>
<link>http://google.com</link>
<description>TestTest</description>
<author>@DAI199</author>
<category>php</category>
</item>
';
}

echo '
</channel>
</rss>
';
?>

make a xml file4

<?php
 // ライブラリの読み込み
 require_once './Feed.php';

 // 取得するフィードのurl指定
 $url = "http://www.lesson5.info/?feed=rss2" ;

 // インスタンスの作成
 $feed = new Feed;

 // RSS読み込み
 $rss = $feed->loadRss( $url );

 // HTML表示用
 $html = '';
 $sitename = $rss->title ;

foreach( $rss->item as $item )
{
  // 各エントリーの処理
  $title = $item->title; //タイトル
  $link = $item->link ; //リンク

  // 日付の取得(unix timestamp)
  foreach( array( "pubDate", "date_timestamp", "dc:date", "published", "issued" ) as $time )
  {
    if ( isset( $item->{ $time }) && !empty( $item->{ time }))
    {
      $timestamp = ( is_int( $item->{ $time })) ? $item->{ $time }: strtotime( $item->{ $time });
      break ;
    }
  }

  //仮に日付が取得できなかったら現在時刻
  if( !isset( $timestamp ))
  {
    $timestamp = time();
  }
  $html .= '<dt><a href="' . $link . '" traget="_blank">' . $title . '</a>(' . date( "Y/m/d" , $timestamp).')</dt></dd>' . $sitename .'</dd>';
}
?>

<dl>
  <?php echo $html ?>
</dl>
<?php
 // ライブラリの読み込み
 require_once './Feed.php';

 // キャッシュの設定
 Feed::$cacheDir = './temp';
 Feed::$cacheExpire = '1 hours';

 // html表示用
 $html = '';

 // 表示最大件数
 $maxview = 5;

 // 取得するフィードのurl指定
 $urls = array(
   "http://www.lesson5.info/?feed=rss2",
   "http://www.lesson5.info/?feed=rss2",
   "http://www.lesson5.info/?feed=rss2",
   "http://www.lesson5.info/?feed=rss2",
   "http://www.lesson5.info/?feed=rss2",
   "http://www.lesson5.info/?feed=rss2"
 );

 // 各rssをまとめた配列
 $entrylist = array();

 for ($i = 0; $i < count($urls); $i++){
   $url = $urls&#91;$i&#93;;

 // インスタンスの作成
 $feed = new Feed;

 // RSS読み込み
 $rss = Feed::loadRss($url);

 for ($entry = 0; $entry < 1; $entry++){
   $sitename = $rss->title;
   $sitelink = $rss->link;
   $item = $rss->item[$entry];
   // 各エントリーの処理
   $title = $item->title ;
   $link = $item->link ;
   $timestamp = strtotime($item->pubDate);
   // 配列に
   $entrylist[$i]['sitename'] = $sitename;
   $entrylist[$i]['sitelink'] = $sitelink;
   $entrylist[$i]['title'] = $title;
   $entrylist[$i]['link'] = $link;
   $entrylist[$i]['timestamp'] = $timestamp;
 }
 }

 // 日付でソート
 foreach ((array)$entrylist as $key => $value){
   $sort[$key] = $value['timestamp'];
 }
 array_multisort($sort, SORT_DESC, $entrylist);

 if ( count($entrylist) > $maxview ){
   $entrynum = $maxview;
 } else {
   $entrynum = count($entrylist);
 }
 for ($i = 0; $i < $entrynum; $i++){
   $html .= '<dt><a href="' . $entrylist&#91;$i&#93;&#91;'link'&#93; . '" target="_blank">' . $entrylist[$i]['title'] . '</a> (' . date( "Y/m/d" , $entrylist[$i]['timestamp'] ) . ')</dt><dd><a href="' . $entrylist&#91;$i&#93;&#91;'sitelink'&#93; . '" target="_blank">' . $entrylist[$i]['sitename'] . '</a></dd>' ;
 }
?>

<dl>
  <?php echo $html ?>
</dl>