var n = Number(69.9900 * 2 * 1.1).toFixed(2); console.log(n * 100); // 15397.999999999998 console.log(n * 10 * 10); // 15398
...今まで知らんかった。恥ずかしい。
var n = Number(69.9900 * 2 * 1.1).toFixed(2); console.log(n * 100); // 15397.999999999998 console.log(n * 10 * 10); // 15398
カテゴリページで wp_nav_menu() を呼ぶとなぜかデフォルトのナビが呼び出される。
見たところカテゴリページで wp_nav_menu() を単純に呼ぶと post_type が上書きされて nav_menu_item で無くなってるのが原因の模様。
対処法は以下の通り。
<?php
if(is_category()):
$wp_query = NULL;
$wp_query = new WP_Query(array('post_type'=>'post','page'));
endif;
wp_nav_menu($args);
?>
jQuery(function() {
jQuery('.rotate div').hide();
jQuery('.rotate div:first').show();
setInterval(function() {
jQuery('.rotate div:first-child').fadeOut().hide().next('div').fadeIn().end().appendTo('.rotate');
}, 10000);
});
UPDATE wp_posts SET guid=REPLACE(guid, 'http://古いドメイン名', 'http://新しいドメイン名'); UPDATE wp_posts SET post_content=REPLACE(post_content, 'http://古いドメイン名', 'http://新しいドメイン名');
MagentoのチェックアウトはウェブサイトのBase Currencyでしかチェックアウトできないようになっています。
そのためアメリカのユーザが米ドル(USD)で、日本のユーザが日本円(JPY)でチェックアウトできるようにするには、Paypalプラグインを使用するか、サイトを複数作成する方法が一般的です。
このページは複数のウェブサイトを作成し、それぞれに通貨を設定する方法を記載しています。
www.example.com (JPY, 日本語)
www.example.com/en/ (USD, 英語)
Name: English Root
Is Active: Yes
Include in Navigation Menu: Yes / No
Name: English
Code: en
Website: (2)で作成したウェブサイト
Name: Main Website
Root Category: (1)で作成したルートカテゴリ
Store: (3)で作成したストア
Name: English View
Code: en
Status: Enabled
$mageRunCode = isset($_SERVER['MAGE_RUN_CODE']) ? $_SERVER['MAGE_RUN_CODE'] : ''; $mageRunType = isset($_SERVER['MAGE_RUN_TYPE']) ? $_SERVER['MAGE_RUN_TYPE'] : 'store';以下のように変更。
$mageRunCode = isset($_SERVER['MAGE_RUN_CODE']) ? $_SERVER['MAGE_RUN_CODE'] : 'en'; $mageRunType = isset($_SERVER['MAGE_RUN_TYPE']) ? $_SERVER['MAGE_RUN_TYPE'] : 'website';
1~6までが複数のウェブサイト作成。
7,8でウェブサイトごとに別々のBase Currencyを設定することで複数の通貨での支払いが可能になります。
<?php echo date_default_timezone_get(); ?>タイムゾーンの設定
<?php date_default_timezone_set('Asia/Tokyo'); ?>
サポートされるタイムゾーンのリスト<?php
echo date('Y年n月j日'); // 2013年2月8日
echo date('Y-m-d H:i:s'); // 2013-02-08 11:28:04
echo date('F jS, l'); // February 8th, Friday
?>
<?php
echo date('H:i:s'); // 11:28:04
echo date('g:ia'); // 11:28am
?>
<?php
echo time();
echo date('U');
echo mktime(date('H'),date('i'),date('s'),date('m'),date('d'),date('Y'));
echo strtotime('now');
?>
<?php var_dump(getdate()); // array // 'seconds' => int 20 // 'minutes' => int 29 // 'hours' => int 11 // 'mday' => int 8 // 'wday' => int 5 // 'mon' => int 2 // 'year' => int 2013 // 'yday' => int 38 // 'weekday' => string 'Friday' (length=6) // 'month' => string 'February' (length=8) // 0 => int 1360276160 ?>月の日数
<?php echo date('t'); ?> // 28
うるう年判定
<?php echo date('L'); ?> // 0 or 1
年始から何日目か
<?php echo date('z日目'); ?>
<?php
echo date('Y年n月j日 H時i分s秒', mktime(date('H') - 4,date('i'),date('s') - 2,date('m'),date('d') - 9,date('Y')));
echo date('Y年n月j日 H時i分s秒', strtotime("-1 week -2 days -4 hours -2 seconds"));
?>
第17週目の日曜日
<?php echo date("Y年n月j日", strtotime("2013-W17-0"));
// 0=日曜日, 1=月曜日, 2=火曜日, 3=水曜日, 4=木曜日, 5=金曜日, 6=土曜日
?>
年始から123日目の日付
<?php
echo date("Y年n月j日", mktime(0, 0, 0, 1, 1+123, 2013));
echo date("Y年n月j日", strtotime("+123 days", strtotime('2013-01-01')));
?>
オブジェクト関係マッピング(英: Object-relational mapping、O/RM、ORM)とは、データベースとオブジェクト指向プログラミング言語の間の非互換なデータを変換するプログラミング技法である。オブジェクト関連マッピングとも呼ぶ。実際には、オブジェクト指向言語から使える「仮想」オブジェクトデータベースを構築する手法である。
(引用元:オブジェクト関係マッピング)
CREATE TABLE sample ( id int(11) NOT NULL AUTO_INCREMENT, field1 varchar(255) COLLATE utf8_unicode_ci NOT NULL, field2 varchar(255) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
<?php
/**
* Object-relational mapping (ORM) file generator
*
* Generate folloing files
* /modles/--database table name--.php
* /models/basemodels/base--database table name--.php
*/
function generate_models()
{
$ci =& get_instance();
$tables = $ci->db->list_tables();
foreach($tables as $table)
{
$res = $ci->db->query('DESCRIBE `'.$table.'`');
$primary = FALSE;
$data = '<?php // '.$table.' table mapping'.PHP_EOL;
$data .= 'class Base'.ucfirst($table).' extends MY_Model'.PHP_EOL;
$data .= '{'.PHP_EOL;
foreach($res->result() as $row)
{
$data .= "\tvar $".$row->Field.";".PHP_EOL;
if($row->Key == 'PRI')
$primary = $row->Field;
}
if($primary)
$data .= "\t"."var \$primary = '".$primary."';".PHP_EOL;
else
$data .= "\t"."var \$primary = FALSE;".PHP_EOL;
$data .= "".PHP_EOL;
$data .= "\tfunction __construct(\$table=null)".PHP_EOL;
$data .= "\t{".PHP_EOL;
$data .= "\t\tparent::__construct(\$table);".PHP_EOL;
$data .= "\t}".PHP_EOL;
$data .= '}';
$base_model_path = CSTPATH.'models/BaseModels/';
if( ! file_exists($base_model_path)) mkdir($base_model_path);
// generate base model files
file_put_contents($base_model_path.'Base'.ucfirst($table).EXT, $data);
// check general model files
if( ! file_exists(CSTPATH.'models/'.$table.EXT))
{
$data = '<?php'.PHP_EOL;
$data .= 'class '.ucfirst($table).' extends Base'.ucfirst($table).PHP_EOL;
$data .= '{'.PHP_EOL;
$data .= '}'.PHP_EOL;
file_put_contents(CSTPATH.'models/'.$table.EXT, $data);
}
}
}<?php
class MY_Model extends CI_Model
{
var $table;
function __construct($table=null)
{
$this->table = ($table) ? $table : get_called_class();
log_message('debug', ucfirst($this->table) . " Class Initialized");
}
/**
* find by primary key
*
* @param mixed $id
* @return class object or FALSE
*/
public function find($pk)
{
$ci =& get_instance();
$ci->db->where($this->primary, $pk);
$q = $ci->db->get($this->table);
if($q->num_rows())
{
$array = $q->row_array();
foreach($array as $key => $value)
{
$this->$key = $value;
}
// return object
return $this;
}
else return FALSE;
}
public function save()
{
$ci =& get_instance();
$primary = $this->primary;
$table = $this->table;
// temporary unset values to run query
unset($this->primary);
unset($this->table);
if($where = $this->$primary)
{ // update row
$ci->db->where($primary, $where);
$ci->db->update($table, $this);
}
else
{ // insert new row
$ci->db->set($this);
$ci->db->insert($table);
}
// re-set value and return obj
$this->primary = $primary;
$this->table = $table;
return $this;
}
}<?php
class MY_Loader extends CI_Loader
{
/**
* Model Loader
*
* This function lets users load and instantiate models.
*
* @access public
* @param string the name of the class
* @param string name for the model
* @param bool database connection
* @return void
*/
function model($model, $name = '', $db_conn = FALSE)
{
if (is_array($model))
{
foreach ($model as $babe)
{
$this->model($babe);
}
return;
}
if ($model == '')
{
return;
}
$path = '';
// Is the model in a sub-folder? If so, parse out the filename and path.
if (($last_slash = strrpos($model, '/')) !== FALSE)
{
// The path is in front of the last slash
$path = substr($model, 0, $last_slash + 1);
// And the model name behind it
$model = substr($model, $last_slash + 1);
}
if ($name == '')
{
$name = $model;
}
if (in_array($name, $this->_ci_models, TRUE))
{
return;
}
$CI =& get_instance();
if (isset($CI->$name))
{
show_error('The model name you are loading is the name of a resource that is already being used: '.$name);
}
$model = strtolower($model);
foreach ($this->_ci_model_paths as $mod_path)
{
if ( ! file_exists($mod_path.'models/'.$path.$model.EXT))
{
continue;
}
if ($db_conn !== FALSE AND ! class_exists('DB'))
{
if ($db_conn === TRUE)
{
$db_conn = '';
}
$CI->load->database($db_conn, FALSE, TRUE);
}
if ( ! class_exists('Model'))
{
load_class('Model', 'core');
}
if(file_exists($mod_path.'models/BaseModels/'.'Base'.ucfirst($model).EXT))
{
require_once($mod_path.'models/BaseModels/'.'Base'.ucfirst($model).EXT);
}
require_once($mod_path.'models/'.$path.$model.EXT);
$class = ucfirst($model);
$CI->$name = new $class($model);
$this->_ci_models[] = $name;
return;
}
// couldn't find the model
show_error('Unable to locate the model you have specified: '.$model);
}
}
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends MY_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* @see http://codeigniter.com/user_guide/general/urls.html
*/
public function index()
{
$this->load->view('welcome_message');
}
public function generate()
{
$this->load->database();
$this->load->helper('orm');
$this->load->helper('url');
generate_models();
redirect('/');
}
public function insert()
{
$this->load->database();
$this->load->model('sample');
$sample = $this->sample;
// set data
$sample->field1 = 'aaaaa';
$sample->field2 = 'bbbb';
// insert
$sample->save();
}
public function update()
{
$this->load->database();
$this->load->model('sample');
// retrieve data by id = 1
$sample = $this->sample->find(1);
// set data
$sample->field1 = 'cccc';
$sample->field2 = 'bbbb';
// update
$sample->save();
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
レスポンシブ・ウェブデザインは、CSS3のメディアクエリを使用して見た目を変更するWEB ページの構築手法です。つまり、デバイスに関わらず共通の1つのHTMLを用意し、CSS メディアクエリを使用して、そのページを表示する画面サイズからデバイスを判断しCSSを選択し、そのデザインを変更します。
(引用元:Google がお勧めするスマートフォンに最適化されたウェブサイトの構築方法)
レスポンシブWebデザインはあくまでマルチデバイス対応の一手法です。導入ありきで話を進めてしまうと、誰も幸せにならない結果となりかねません。
サイトの目的やターゲットユーザーから必要とされる要件を洗い出し、見込まれる効果とコストを他の手法と比較した上で、導入を検討していくべきと考えています。
(引用元:レスポンシブWebデザインのメリット/デメリットをできるだけ中立的に検証してみた)
$('ul').each(function(){
var rep = 0;
$(this).children().each(function(){
var itemHeight = parseInt($(this).height());
if(itemHeight > rep){
rep = itemHeight;
}
});
$(this).children().css({height:(rep)});
});
こんな感じ(で合ってるはず)。jQuery(function($) {
$(window).load(function() {
$('ul#sample').each(function(){
var rep = 0;
$(this).children().each(function(){
var itemHeight = parseInt($(this).height());
if(itemHeight > rep){
rep = itemHeight;
}
});
$(this).children().css({height:(rep)});
});
});
});
これはローカル環境だとページロードが早かったから表面化しなかった問題。<?php
/**
* @property DB_active_record $db
* @property DB_forge $dbforge
* @property Benchmark $benchmark
* @property Calendar $calendar
* @property Cart $cart
* @property Config $config
* @property Controller $controller
* @property Email $email
* @property Encrypt $encrypt
* @property Exceptions $exceptions
* @property Form_validation $form_validation
* @property Ftp $ftp
* @property Hooks $hooks
* @property Image_lib $image_lib
* @property Input $input
* @property Language $language
* @property Loader $load
* @property Log $log
* @property Model $model
* @property Output $output
* @property Pagination $pagination
* @property Parser $parser
* @property Profiler $profiler
* @property Router $router
* @property Session $session
* @property Sha1 $sha1
* @property Table $table
* @property Trackback $trackback
* @property Typography $typography
* @property Unit_test $unit_test
* @property Upload $upload
* @property URI $uri
* @property User_agent $agent
* @property Validation $validation
* @property Xmlrpc $xmlrpc
* @property Xmlrpcs $xmlrpcs
* @property Zip $zip
*
* その他のライブラリ、モデルなどを以下に追加。
*
*/
class MY_Controller extends Controller
{
function __construct()
{
parent::__construct();
}
}
<?php
class Classname extends MY_Controller
{
function __construct()
{
parent::__construct();
}
}
app/design/frontend/--your theme--/default/layout/contacts.xml
<contacts_index_index translate="label">
...
<reference name="breadcrumbs">
<action method="addCrumb">
<crumbName>Home</crumbName>
<crumbInfo>
<label>Home</label>
<title>Home</title>
<link>/</link>
</crumbInfo>
</action>
<action method="addCrumb">
<crumbName>Contacts</crumbName>
<crumbInfo>
<label>Contact Us</label>
<title>Contact Us</title>
</crumbInfo>
</action>
</reference>
...
</contacts_index_index>
ハードコードではあるけど、一応追加は完了。
特別、ダイナミックにパンくずリストを生成する必要がない限りはこれで対応できるはず。
まず、WindowsにPythonをインストールします。
前述のとおりPHPなのになぜかPython用の文書生成アプリを使ってるので、Windowsには標準装備されてないPythonのインストールからやらないといけない。
Pythonを既にインストールしてる人はこの手順をスキップしてください。
Pythonバージョン2系をダウンロード。
3系はダメ(だそうです)。
Windows用のインストーラをダウンロードした場合はそのままインストール。
必須ではないですが、インストールが完了したら環境変数にPythonのパスを追加しておくと便利です。
環境変数への登録(XP)
コントロールパネル→システム→詳細設定→環境変数
Pathを選択してPythonのパスを追加。
eg) C:\Python27\;C:\Python27\Scripts;
登録が終わったらコマンドプロンプトで python と入力すれば確認できます。
ez_setup.pyをダウンロード、コマンドラインで python ez_setup.py と入力すると勝手にインストールしてくれます(以下同文)。
コマンドラインで easy_install sphinx と入力。
コマンドラインで sphinx-quickstart と入力すると会話形式の設定画面が表示されます。
基本的にEnterで進んで行って問題ないです。わかる人は変更してください。
'Project Name', 'Version Number','Author'が必須項目なので適当に。
コマンドラインで easy_install sphinxcontrib-phpdomain と入力。
Gitでコピーしたファイルの中に user_guide_src というフォルダがあるので、コマンドプロンプトで移動します。
さらにその中に cilexer があるので移動。
python setup.py install と入力。
インストールが終わったら pygmentize -L | more と入力して以下の記述があるか確認します。あればインストール完了。
* ci, codeigniter:
CodeIgniter (filenames *.html, *.css, *.php, *.xml, *.static)
上述 user_guide_src フォルダの中に source フォルダがあるので今度はこちらに移動。
make html と入力すると _build フォルダが作成されます。更にその中に doctrees, html とフォルダが作成され、そのうち html が作成されたユーザガイドです。
この html フォルダをコピー(もしくはカット)して Codeigniter のトップに貼り付け user_guide とフォルダ名を変更すれば完了。
<?php
class Setting extends Controller
{
function __construct()
{
parent::__construct();
if( ! _s('admin')) redirect();
}
function index()
{
$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
$this->form_validation->set_rules('name',_l('SHOP_NAME'),'required|trim|xss_clean');
$this->form_validation->set_rules('url',_l('SHOP_URL'),'required|trim|xss_clean');
$this->form_validation->set_rules('title',_l('PAGE_TITLE'),'trim|xss_clean');
$this->form_validation->set_rules('keywords',_l('PAGE_KEYWORDS'),'trim|xss_clean');
$this->form_validation->set_rules('desc',_l('PAGE_DESCRIPTION'),'trim|xss_clean');
if($this->form_validation->run())
{
$data['i'] = $this->input->post();
$config_data = $this->load->view('setting/config_template', $data, TRUE);
file_put_contents(EXTPATH.'config/'.((defined('ENVIRONMENT'))?ENVIRONMENT:'').'/setting.php', $config_data);
setMessage('success', _l('SUCCESS_UPDATE_SETTING'));
redirect('setting');
}
$data['setting'] = $this->config->item('setting');
$data['breadcrumbs'] = array(_l('HOME')=>'', _l('SETTINGS')=>'settings');
$data['h1'] = _l('SETTINGS_SHOP');
$this->layout->view('setting/shop', $data);
}
}
<?php echo '<?php'.PHP_EOL; ?>
/*
* Setting Updated: <?php echo date('Y-m-d H:i:s').PHP_EOL; ?>
*/
$config['site_name'] = '<?php echo $i['name']; ?>';
$config['site_url'] = '<?php echo $i['url']; ?>';
$config['page_title'] = '<?php echo $i['title']; ?>';
$config['page_keywords'] = '<?php echo $i['keywords']; ?>';
$config['page_desc'] = '<?php echo $i['desc']; ?>';
日本人が起業したfluxflexはGithubと連動する安くて簡単なクラウド・ホスティング・サービスを目指す(だいぶ亀ですが・・・)現在作成中のショッピングカートをどこかでデモさせてもらえないかと探していたら、タイミングよくTechCrunchに記事が掲載されていたので試してみました。
http://jp.techcrunch.com/archives/20110817github-integrated-fluxflex-aims-at-making-cloud-hosting-easier-and-cheaper/
$config['uri_protocol'] = 'REQUEST_URI';
RewriteEngine on RewriteBase / RewriteCond $1 !^(index\.php|robots\.txt|favicon\.ico) RewriteRule ^(.*)$ /index.php?/-- default controller --$1 [L]そして最後にRewriteRuleにCodeigniterのdefault_controllerを指定して動作させることができました。
未定義のクラス/インターフェイスを使用しようとした時に 自動的にコールされる __autoload 関数を定義することができます。 この関数をコールすることにより、 スクリプトエンジンは、PHPがエラーで止まる前にクラスをロードする最後の チャンスを与えます。これを使ってモデルを呼べれば楽なんですよね。そうすると
引用元:php.net
$this->load->model('model-name');
$this->model-name->function();という書き方から以下のように普通のPHP5の書き方に変えられる。$model = new Model-name; $model->function();
6 CodeIgniter Hacks for the Mastersほうほう、config/config.phpの最後に__autoload()を入れるとな。
http://net.tutsplus.com/tutorials/php/6-codeigniter-hacks-for-the-masters/
function __autoload($class)
{
log_message('debug', 'Trying to load class: '.$class);
if(file_exists(EXTPATH."models/".strtolower($class).EXT))
{
include_once(EXTPATH."models/".strtolower($class).EXT);
}
}spl_autoload_register — 指定した関数を __autoload() の実装として登録するサンプルヘルパ: spl_autoload_helper.php
http://nz.php.net/manual/ja/function.spl-autoload-register.php
引用元:php.net
<?php
/**
* SAMPLE SPL Autoload Helper
* ファイル名、メソッド名は適宜修正してください。
*/
function sample_loader($class)
{
if(file_exists(APPPATH."models/".strtolower($class).EXT))
{
log_message('debug', 'Load '.$class.' models in php5 style');
include_once(APPPATH."models/".strtolower($class).EXT);
}
}
spl_autoload_register('sample_loader');上記ではモデルだけ追加してますが、ライブラリもヘルパも追加することが可能です。<?php
class User extends Controller
{
function __construct()
{
parent::__construct();
if( ! _s('admin')) redirect();
$this->load->model('users_model', 'usersdb');
}
function index()
{
$this->accounts();
}
function accounts($page=0)
{
$this->form_validation->set_rules('delete', '', 'isArray');
if($this->form_validation->run())
{
$this->usersdb->delete_array($this->input->post('delete'));
}
$data['breadcrumbs'] = array(_l('HOME')=>'', _l('USERLIST')=>'user');
$data['h1'] = _l('USERLIST');
$data['all'] = $this->usersdb->all($page);
$this->layout->view('user/accounts', $data);
}
function create()
{
$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
$this->form_validation->set_rules('email',_l('EMAIL'),'required|valid_email|email_exist');
$this->form_validation->set_rules('firstname',_l('FIRSTNAME'),'required|min_length[2]');
$this->form_validation->set_rules('lastname',_l('LASTNAME'),'required|min_length[2]');
$this->form_validation->set_rules('passwd',_l('PASSWORD'),'required|min_length[6]|matches[passwdconf]');
if($this->form_validation->run())
{ // insert into db
$data = array(
'email' => $this->input->post('email'),
'password' => $this->input->post('passwd'),
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post('lastname'),
'status' => $this->input->post('status')
);
$this->usersdb->newuser($data);
redirect('user');
}
$data['breadcrumbs'] = array(_l('HOME')=>'', _l('USERLIST')=>'user', _l('CREATE_USER')=>'user/create');
$data['h1'] = _l('CREATE_USER');
$this->layout->view('user/create', $data);
}
function edit($id)
{ // just in case
if($user = $this->usersdb->byId($id))
{
$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
$this->form_validation->set_rules('email',_l('EMAIL'),'required|valid_email|email_exist['.$id.']');
$this->form_validation->set_rules('firstname',_l('FIRSTNAME'),'required|min_length[2]');
$this->form_validation->set_rules('lastname',_l('LASTNAME'),'required|min_length[2]');
if($this->input->post('passwd')) $this->form_validation->set_rules('passwd',_l('PASSWORD'),'required|min_length[6]|matches[passwdconf]');
if($this->form_validation->run())
{ // update user info
$data['email'] = $this->input->post('email');
$data['firstname'] = $this->input->post('firstname');
$data['lastname'] = $this->input->post('lastname');
$data['status'] = $this->input->post('status');
if($this->input->post('passwd')) $data['password'] = $this->input->post('password');
$this->usersdb->update($user, $data);
redirect('user');
}
$data['breadcrumbs'] = array(_l('HOME')=>'', _l('USERLIST')=>'user', _l('EDIT_USER')=>'user/edit');
$data['h1'] = _l('EDIT_USER');
$data['user'] = $user;
$this->layout->view('user/edit', $data);
}
else redirect();
}
}function newuser($data)
{
$data['hash'] = $this->auth->_generate_hash();
$data['password'] = $this->auth->_encode($data['password'], $data['hash']);
$this->db->insert($this->table, $data);
setMessage('success', _l('SUCCESS_CREATE_USER'));
}
function update($obj, $data)
{
if(array_key_exists('password', $data)) $data['password'] = $this->auth->_encode($data['password'], $obj->hash);
$this->db->where('id', $obj->id);
$this->db->update($this->table, $data);
setMessage('success', _l('SUCCESS_UPDATE_USER'));
}
ユーザ追加用とアップデート用のメソッドを追加。<?php
class MY_Form_validation extends Form_validation
{
function __construct()
{
parent::__construct();
}
function email_exist($email, $id=FALSE)
{
$this->CI->form_validation->set_message('email_exist', $this->CI->lang->line('in_use'));
$this->CI->load->model('users_model', 'usersdb');
return ($this->CI->usersdb->exist($email, $id)) ? FALSE : TRUE;
}
function isArray($arr)
{
$this->CI->form_validation->set_message('isArray', $this->CI->lang->line('is_array'));
return (is_array($arr) && count($arr) > 0) ? TRUE : FALSE;
}
}<div class="buttons">
<button onclick="javascript:location.href = '<?php echo base_url('user/create'); ?>';"><?php echo _l('CREATE_USER'); ?></button>
<button onclick="confirmDelSelected();"><?php echo _l('DELETE_SELECTED'); ?></button>
</div>
<?php echo form_open(uri_string()); ?>
<?php if($all): ?>
<table class="list">
<tr>
<th><input type="checkbox" onclick="applyToAll(this);" /></th>
<th><?php echo _l('FULLNAME'); ?></th>
<th><?php echo _l('EMAIL'); ?></th>
<?php /* <th><?php echo _l('ROLE'); ?></th> */ ?>
<th><?php echo _l('STATUS'); ?></th>
<th><?php echo _l('ACTION'); ?></th>
</tr>
<?php foreach($all as $a): ?>
<tr>
<td><input type="checkbox" name="delete[]" value="<?php echo $a->id; ?>"<?php if($a->id==1): ?> disabled="disabled"<?php endif; ?>></td>
<td><?php echo $a->firstname.' '.$a->lastname; ?></td>
<td><?php echo $a->email; ?></td>
<?php /* <td><?php echo $a->role; ?></td> */ ?>
<td><?php echo ($a->status) ? _l('ACTIVE') : _l('INACTIVE') ; ?></td>
<td>
<a href="<?php echo base_url('user/edit/'.$a->id); ?>"><?php echo _l('EDIT'); ?></a>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
<?php echo form_close(); ?>
<script type="text/javascript">
function confirmDelSelected() {
var c = 0;
$(":checkbox").each(function(){
if($(this).attr('checked')) c++;
})
if(c > 0) {
if(confirm("<?php echo _l('CONFIRM_DELETE_SELECTED'); ?>")) $('form').submit();
}
else { alert("<?php echo _l('ALERT_PLZ_SELECT'); ?>"); }
}
</script><?php echo form_open(uri_string()); ?>
<input type="button" value="<?php echo _l('CANCEL'); ?>" onclick="javascript:location.href = '<?php echo base_url('user'); ?>';" tabindex="9" />
<h2><?php echo _l('USER_DETAILS'); ?></h2>
<dl class="horizontal">
<dt><?php echo _l('EMAIL'); ?></dt>
<dd><input class="field" id="email" type="email" name="email" value="<?php echo set_value('email'); ?>" tabindex="1" /><?php echo form_error('email'); ?></dd>
<dt><?php echo _l('LASTNAME'); ?></dt>
<dd><input class="field" id="lastname" type="text" name="lastname" value="<?php echo set_value('lastname'); ?>" tabindex="2" /><?php echo form_error('lastname'); ?></dd>
<dt><?php echo _l('FIRSTNAME'); ?></dt>
<dd><input class="field" id="firstname" type="text" name="firstname" value="<?php echo set_value('firstname'); ?>" tabindex="3" /><?php echo form_error('firstname'); ?></dd>
<dt><?php echo _l('PASSWORD'); ?></dt>
<dd><input class="field" id="passwd" type="password" name="passwd" value="" tabindex="4" /><?php echo form_error('passwd'); ?></dd>
<dt><?php echo _l('PASSWORDCONF'); ?></dt>
<dd><input class="field" id="passwdconf" type="password" name="passwdconf" value="" tabindex="5" /></dd>
<dt><?php echo _l('STATUS'); ?></dt>
<dd>
<select name="status" class="field" tabindex="6">
<option value="1"><?php echo _l('ACTIVE'); ?></option>
<option value="0"><?php echo _l('INACTIVE'); ?></option>
</select>
</dd>
<dd><input type="submit" value="<?php echo _l('SAVE'); ?>" onclick="return check(['email','lastname','firstname','passwd','passwdconf']);" tabindex="7" /> <input type="reset" value="<?php echo _l('RESET'); ?>" tabindex="8" /></dd>
</dl>
<?php echo form_close(); ?><?php echo form_open(uri_string()); ?>
<input type="button" value="<?php echo _l('CANCEL'); ?>" onclick="javascript:location.href = '<?php echo base_url('user'); ?>';" tabindex="9" />
<h2><?php echo _l('USER_DETAILS'); ?></h2>
<dl class="horizontal">
<dt><?php echo _l('EMAIL'); ?></dt>
<dd><input class="field" id="email" type="email" name="email" value="<?php echo $user->email; ?>" tabindex="1" /><?php echo form_error('email'); ?></dd>
<dt><?php echo _l('LASTNAME'); ?></dt>
<dd><input class="field" id="lastname" type="text" name="lastname" value="<?php echo $user->lastname; ?>" tabindex="2" /><?php echo form_error('lastname'); ?></dd>
<dt><?php echo _l('FIRSTNAME'); ?></dt>
<dd><input class="field" id="firstname" type="text" name="firstname" value="<?php echo $user->firstname; ?>" tabindex="3" /><?php echo form_error('firstname'); ?></dd>
<dt><?php echo _l('PASSWORD'); ?></dt>
<dd><input class="field" id="passwd" type="password" name="passwd" value="" tabindex="4" /><?php echo form_error('passwd'); ?></dd>
<dt><?php echo _l('PASSWORDCONF'); ?></dt>
<dd><input class="field" id="passwdconf" type="password" name="passwdconf" value="" tabindex="5" /></dd>
<dt><?php echo _l('STATUS'); ?></dt>
<dd>
<select name="status" class="field" tabindex="6">
<option value="1"<?php if($user->status==1): ?> selected="selected"<?php endif; ?>><?php echo _l('ACTIVE'); ?></option>
<option value="0"<?php if($user->status==0): ?> selected="selected"<?php endif; ?>><?php echo _l('INACTIVE'); ?></option>
</select>
</dd>
<dd><input type="submit" value="<?php echo _l('SAVE'); ?>" onclick="return check(['email','lastname','firstname']);" tabindex="7" /> <input type="reset" value="<?php echo _l('RESET'); ?>" tabindex="8" /></dd>
</dl>
<?php echo form_close(); ?><?php
function breadcrumb($array)
{
$count = count($array); $i = 1;
$html = '<div id="breadcrumb"><ul>';
foreach($array as $k=>$v)
{
$class = (empty($v)) ? ' class="home"' : '';
if($i != $count)
$html .= '<li><a href="'.base_url($v).'"'.$class.'>'.$k.'</a></li>';
else // no link for the last one
$html .= '<li class="last"><span>'.$k.'</span></li>';
$i++;
}
$html .= '</ul></div>';
return $html;
}<?php
class User extends Controller
{
function __construct()
{
parent::__construct();
if( ! _s('admin')) redirect();
}
function index()
{
$this->accounts();
}
function accounts($page=0)
{
$data['breadcrumbs'] = array(_l('HOME')=>'', _l('USERLIST')=>'admin/user');
$this->layout->view('user/accounts', $data);
}
}<?php if(isset($breadcrumbs) && is_array($breadcrumbs)) echo breadcrumb($breadcrumbs); ?>
CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `email` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `firstname` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `lastname` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `status` tinyint(4) NOT NULL, `role` int(11) NOT NULL, `hash` varchar(32) COLLATE utf8_unicode_ci NOT NULL, `lastlogin` timestamp NULL DEFAULT NULL, `updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ;
<?php
class Auth
{
var $_error;
public function __construct()
{
$this->ci =& get_instance();
}
function error()
{
return $this->_error;
}
function login($email, $passwd, $target='customer')
{
if($target === 'user')
{ // load user model
$this->ci->load->model('users_model','usersdb');
// check if exists
if($user = $this->ci->usersdb->exist($email))
{ // retrieve user hash & matching up with entered password
if($this->_encode($passwd, $user->hash) === $user->password)
{ // update last login
$this->ci->usersdb->lastlogin($user->id);
// set admin session
$this->ci->session->set_userdata('admin',TRUE);
return TRUE;
}
else $this->_error = _l('error_wrong_combination');
}
else $this->_error = _l('error_not_exist');
}
return FALSE;
}
private function _encode($passwd, $hash)
{
/* 暗号化スクリプト */
return $passwd;
}
}<?php
class Users_model extends Model
{
var $table = 'users';
function __construct()
{
parent::__construct();
}
function exist($email)
{
$q = $this->db->get_where($this->table, array('email'=>$email));
return ($q->num_rows() == 1) ? $q->row() : FALSE;
}
function lastlogin($id)
{
$this->db->where('id',$id);
$this->db->update($this->table, array('lastlogin'=>date('Y-m-d H:i:s')));
}
}INSERT INTO `users` (`id`, `email`, `password`, `firstname`, `lastname`, `status`, `role`, `hash`, `lastlogin`, `updated`) VALUES (1, 'test@test.com', '723e66f900dcb555d089050c80455331feb2b7ca', 'firstname', 'lastname', 0, 0, '5898e88516d636dbd3571c7d24550f67', '2011-08-04 10:49:04', '2011-08-04 10:49:04');
$autoload['libraries'] = array('Auth','database','Form_validation','Session');<?php
class Login extends Controller
{
function __construct()
{
parent::__construct();
if(_s('admin')) redirect();
}
function index()
{
$this->form_validation->set_rules('email',_l('EMAIL'),'required|trim|valid_email');
$this->form_validation->set_rules('password', _l('PASSWORD'), 'required|trim');
if($this->form_validation->run())
{
$login = $this->auth->login($this->input->post('email'), $this->input->post('password'), 'user');
if($login) redirect();
else $data['error'] = $this->auth->error();
}
else $data['error'] = validation_errors();
$data['css'] = array('login');
$data['page_title'] = _l('CONTROLPANEL');
$this->layout->view('login', $data);
}
}<?php echo form_open(uri_string()); ?>
<div>
<h1><?php echo _l('CONTROLPANEL'); ?></h1>
<p><?php echo _l('MSG_LOGIN'); ?></p>
<dl>
<dt><?php echo _l('EMAIL'); ?></dt>
<dd><input type="email" name="email" value="<?php echo set_value('email'); ?>" /></dd>
<dt><?php echo _l('PASSWORD'); ?></dt>
<dd><input type="password" name="password" value="" /></dd>
<dd><input type="submit" value="<?php echo _l('LOGIN'); ?>"></dd>
<?php if(isset($error)): ?><dd><?php echo $error; ?></dd><?php endif; ?>
</dl>
</div>
<?php echo form_close(); ?><?php
define('EXT', '.php');
define('FCPATH', __FILE__);
$pathinfo = pathinfo(FCPATH);
define('SELF', $pathinfo['basename']);
define('ROOT',realpath($pathinfo['dirname'].'/../').'/');
unset($pathinfo);
define('SYSPATH', ROOT.'system/');
define('EXTPATH', ROOT.'extension/');
define('APPPATH', ROOT.'admin/application/');
$f=pathinfo(__FILE__, PATHINFO_BASENAME);
if (!is_dir(SYSPATH)) exit("Your system folder path does not appear to be set correctly. Please open the following file and correct this: ".$f);
if (!is_dir(APPPATH)) exit("Your application folder path does not appear to be set correctly. Please open the following file and correct this: ".$f);
if (!is_dir(EXTPATH)) exit("Your extension folder path does not appear to be set correctly. Please open the following file and correct this: ".$f);
define('ENVIRONMENT', 'development');
if (defined('ENVIRONMENT'))
{
switch (ENVIRONMENT)
{
case 'development':
error_reporting(E_ALL);
break;
case 'testing':
case 'production':
error_reporting(0);
break;
default:
exit('The application environment is not set correctly.');
}
}
require(SYSPATH.'core/Bootstrap'.EXT);define('ADMIN', FALSE);define('ADMIN', TRUE);if(! ADMIN) $load->set_view_path(TEMPATH.$template.'/');
<?php
class Home extends Controller
{
function index()
{
$this->layout->view('home');
}
}this is admin directory - <?php echo __FILE__; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Admin Template</title>
</head>
<body>
<?php echo $contents; ?>
<p><br />Page rendered in {elapsed_time} seconds</p>
</body>
</html>