* @copyright Copyright(c) 2010 BlueArt Co.,Ltd. All Rights Reserved. * @license BlueArt Co.,Ltd. ------------------------------------------------------------------------*/ /** * 共通で利用する処理を記述したファイルを呼び出す */ require_once('Common.php'); /** * ログを管理するクラスを呼び出す */ require_once('LogTrace.php'); /** * フレームワークを処理するクラスを呼び出す */ require_once('FrameWork.php'); /** * 権限を管理するクラスを呼び出す */ require_once('AuthMgr.php'); /** * データベースを制御するクラスを呼び出す */ require_once('Zend/Db.php'); require_once 'Zend/Cache.php'; /** * データ検証を行うクラスを呼び出す */ require_once('ValidateMgr.php'); /** * CSV処理クラスを呼び出す */ require_once('Csv.php'); class AbstructModel { /** * インスタンス化したモデルのリスト */ static protected $_objModelList; /** * @var array データベースオブジェクトを格納したリスト */ static protected $_db_list = array(); /** * @var object 入力データ */ static protected $_input = array(); /** * @var object フレームワークを管理するオブジェクト */ protected $_fw; /** * @var string モデルクラス名のフォーマット */ protected $_name_format = '{$model}'; /** * @var string モデルクラス名 */ protected $_name; /** * @var string 設定ファイルのセクションキー、データベース情報を指す */ protected $_db_key = ''; /** * @var object システム設定情報を保持するオブジェクト */ protected $_config; /** * @var object ログ管理オブジェクト */ protected $_log; /** * @var object 権限を管理するオブジェクト */ protected $_auth; /** * @var object データベースを制御する Zend_Db オブジェクト */ protected $_db; /** * @var string 操作対象とするテーブルの名前 */ protected $_table = ''; /** * @var string 最後に処理したレコードのID */ protected $_last_id = ''; /** * @var object モデル項目の各名前を格納した連想配列 */ protected $_arrParamName = array(); /** * @var boolean データ処理を許可するかどうか */ protected $_lock = false; /** * @var array 1件データをキャッシュする配列 */ static protected $_get_item = array(); /** * @var array 全件データをキャッシュする配列 */ static protected $_get_item_all = array(); /**---------------------------------------------------------------------- * コンストラクタ ------------------------------------------------------------------------*/ public function __construct() { $this->init(); } /**---------------------------------------------------------------------- * 初期化 ------------------------------------------------------------------------*/ public function init() { add_include_path(dirname(__FILE__)); self::$_get_item = array(); self::$_get_item_all = array(); $this->_fw = new FrameWork(); $this->_config = $this->_fw->get_config(); $this->_auth = new AuthMgr($this->_config, $this->_config['config_file']['auth']); $this->_log = new LogTrace($this->_config, get_class($this)); $this->_log->start('__construct'); $this->_db = $this->getDb($this->_db_key); // テーブル名生成 /** * C-Unit 2011-11-02 * Translation * Don't check TranslateCls */ //if ('AbstructModel' != get_class($this)) { if ('AbstructModel' != get_class($this) && 'TranslateCls' != get_class($this)) { if (false !== strpos($this->_name_format, '{$model}')) { // モデルクラス名から抜き出し list($prefix, $suffix) = explode('{$model}', $this->_name_format); $name = substr(get_class($this), strlen($prefix), strlen(get_class($this)) - strlen($prefix) - strlen($suffix)); $name = strtolower($name); } else { // そのまま使用 $name = $this->_name_format; } $this->_name = $name; $this->_table = $this->_config[$this->_db_key]['prefix'] . $this->_name; } else { $this->_table = ''; } $this->_log->end(); } /** * This function return the content of configure file * */ public function getConfig() { return $this->_config; } /**---------------------------------------------------------------------- * 入力データの登録 * @param object $input 入力データ ------------------------------------------------------------------------*/ public function setInput($input) { self::$_input = $input; } /**---------------------------------------------------------------------- * データベースから指定IDのレコードを1件取得する * @param string $id 対象レコードの主キー * @return array 指定データの連想配列 ------------------------------------------------------------------------*/ public function get($id) { if ('' == $this->_table || empty($this->_db)) { return array(); } // キャッシュ if (isset(self::$_get_item[$id])) { return self::$_get_item[$id]; } $this->_log->start('get'); // 取得メイン $data = $this->_get_main($id); if (0 !== count($data)) { // 加工処理呼び出し $data = $this->_get_process($data); } // キャッシュに登録 self::$_get_item[$id] = $data; // 最後に処理した識別番号 $this->_last_id = $id; $this->_log->end(); return $data; } /**---------------------------------------------------------------------- * データベースから指定IDのレコードを1件取得する(メイン) * @param string $id 対象レコードの主キー * @return array 指定データの連想配列 ------------------------------------------------------------------------*/ protected function _get_main($id) { $data = $this->query_fetch('select * from `' . $this->_table . '` where `id`="' . $id . '"'); if (empty($data)) { $data = array(); } return $data; } public function getDataById($id,$item = null){ if($item == null ) { $item = '*'; } $data = $this->query_fetch('select '.$item.' from `' . $this->_table . '` where `id`="' . $id . '"'); if (empty($data)) { $data = array(); } return $data; } /**---------------------------------------------------------------------- * データベースから指定IDのレコードを1件取得する(メイン) * @param string $id 対象レコードの主キー * @return array 指定データの連想配列 ------------------------------------------------------------------------*/ protected function get_where($where) { $data = $this->query_fetch('select * from `' . $this->_table . '` where ' . $where . ''); if (empty($data)) { $data = array(); } return $data; } /**---------------------------------------------------------------------- * 取得したデータを加工する * @param object $data 加工するデータを格納した連想配列 * @return object 加工したデータを格納した連想配列 ------------------------------------------------------------------------*/ protected function _get_process($data) { return $data; } /**---------------------------------------------------------------------- * データベースの指定テーブルから全レコードを取得する * @return array 全レコードのリスト ------------------------------------------------------------------------*/ public function getAll() { if ('' == $this->_table || empty($this->_db)) { return array(); } // キャッシュ if (isset(self::$_get_item_all[$this->_name])) { return self::$_get_item_all[$this->_name]; } $this->_log->start('getAll'); // 全取得メイン $list = $this->_getAll_main(); // 加工処理呼び出し foreach ($list as $i => $data) { $list[$i] = $this->_get_process($data); } // キャッシュに登録 self::$_get_item_all[$this->_name] = $list; $this->_log->end(); return $list; } /**---------------------------------------------------------------------- * データベースの指定テーブルから全レコードを取得する(メイン) * @return array 全レコードのリスト ------------------------------------------------------------------------*/ protected function _getAll_main($orderBy = null) { if($orderBy == null){ $orderBy = '`date_update`'; } $list = $this->query_fetch_all('select * from `' . $this->_table . '` order by '.$orderBy.'desc'); return $list; } /**---------------------------------------------------------------------- * データベースを検索する * @param string $query where 以降のSQL文 * @param string $sort 検索結果を表示する際の並び変えに使用される項目 * @return array 検索結果レコードのリスト ------------------------------------------------------------------------*/ public function search($query, $sort = '', $strLimit = '') { if ('' == $this->_table || empty($this->_db)) { return array(); } $this->_log->start('search'); if ('' != $query) { // 検索 $strSql = 'select * from `' . $this->_table . '` where ' . $query . ' '; if(empty($sort) == false && $sort != '') { $strSql .= "order by `".$sort."` ASC" ; } $strSql .= $strLimit; $list = $this->query_fetch_all($strSql); // 加工処理呼び出し foreach ($list as $i => $data) { /* * C-Unit 2011-12-06 start * #6105 * seach dynamic string 2 byte */ $strData = ''; if(isset($list[$i]['data'])== true){ $strData= $list[$i]['data']; } $list[$i] = $this->_get_process($data); $list[$i]['search_data'] = $strData; /* * C-Unit 2011-12-06 del end */ } // 更新日順 //$list = vsort($list, array($sort => SORT_ASC)); } else { $list = array(); } $this->_log->end(); return $list; } /**---------------------------------------------------------------------- * レコードを1件登録する * @param object $model 登録するレコードを格納した連想配列 * @return integer 処理結果コード ------------------------------------------------------------------------*/ public function set($model) { if (true == $this->_lock) { return DB_LOCK_NG; } if ('' == $this->_table || empty($this->_db)) { return DB_INIT_NG; } $this->_log->start('set'); $model['id_account'] = $model['id_account']; if (isset($model['id']) && '' !== $model['id']) { $objData = $this->get($model['id']); if (0 == count($objData)) { $model['id'] = ''; } } // Remove the field id_html because it's an auto-increment field (PRIMARY KEY) unset($model['id_html']); if (!isset($model['id']) || '' === $model['id']) { $this->_log->debug('set-before'); $this->_log->debug($model); $model = $this->_set_process($model); $this->_log->debug('set-after'); $this->_log->debug($model); $model['id'] = uniqid32(); $model['date_create'] = date('Y-m-d H:i:s'); $model['date_update'] = date('Y-m-d H:i:s'); $this->_last_id = $model['id']; /* * C-Unit 2011-11-17 strart * #5661 * Add date_update edit */ unset($model['action_update']); /* * C-Unit 2011-11-17 strart */ $this->_log->info('db-insert'); $this->_log->info($this->_table); ob_start(); $log = ob_get_clean(); $this->_log->info($log); $intInsertCount = $this->_db->insert($this->_table, $model); if($this->_table== $this->_config['db_cms']['prefix'].'news') { $strLink = $this->_config['path']['user_cms_lancelot'].'/siteuser/newsdetail/user_id/'.str_replace('user/id_','',$this->_config['path']['user_site_create']).'/id/'.$model['id']; $strLink = $this->_config['path']['root_public'].str_replace('//', '/', '/' . $strLink); $model['data'] = str_replace('@url',$strLink,$model['data']); $intUpdateCount = $this->_db->update($this->_table, $model, '`id`="' . $model['id'] . '"'); } if (0 < $intInsertCount) { $result = DB_INSERT_OK; } else { $result = DB_INSERT_NG; } $this->_log->info('count:' . $intInsertCount); } else { $this->_last_id = $model['id']; unset($model['id']); /* * C-Unit 2011-11-17 strart * #5661 * Add date_update edit */ if(isset($model['action_update']) == 'true'){ if($model['action_update'] == 'true'){ unset($model['action_update']); if (!isset($model['date_update']) || '' == $model['date_update']) { $model['date_update'] = date('Y-m-d H:i:s'); } } } /* * C-Unit 2011-11-17 strart */ $result = $this->set_where($model, '`id`="' . $this->_last_id . '"'); // キャッシュを削除 if (isset(self::$_get_item[$this->_last_id])) { unset(self::$_get_item[$this->_last_id]); } if (isset(self::$_get_item_all[$this->_name])) { unset(self::$_get_item_all[$this->_name]); } } $this->_log->end(); return $result; } /**---------------------------------------------------------------------- * レコードを更新する * @param object $model 登録するレコードを格納した連想配列 * @param string $where 登録レコードの検索条件 * @return integer 処理結果コード ------------------------------------------------------------------------*/ public function set_where($model, $where) { $this->_log->start('set_where'); // Remove the field id_html because it's an auto-increment field (PRIMARY KEY) unset($model['id_html']); $model = $this->_set_process($model); if (!empty($model['date_update'])) { $model['date_update'] = date('Y-m-d H:i:s'); } if (isset($model['id'])) { $this->_last_id = $model['id']; unset($model['id']); } $this->_log->info('db-update[' . $this->_last_id . ']'); ob_start(); $log = ob_get_clean(); $this->_log->info($log); if($this->_table== $this->_config['db_cms']['prefix'].'news') { $replace = array('=','"'); $strId = str_replace("`","/",$where); $strId = str_replace($replace,"",$strId); $strLink = $this->_config['path']['user_cms_lancelot'].'/siteuser/newsdetail/user_id/'.str_replace('user/id_','',$this->_config['path']['user_site_create']).$strId; $strLink = $this->_config['path']['root_public'].str_replace('//', '/', '/' . $strLink); $model['data'] = str_replace('@url',$strLink,$model['data']); $intUpdateCount = $this->_db->update($this->_table, $model, '`id`="' . $model['id'] . '"'); } $intUpdateCount = $this->_db->update($this->_table, $model, $where); if (0 < $intUpdateCount) { $result = DB_UPDATE_OK; } else { $result = DB_UPDATE_NG; } $this->_log->info('count:' . $intUpdateCount); $this->_log->end(); return $result; } /**---------------------------------------------------------------------- * 登録するレコードを加工する * @param object $model 登録するデータ * @return object 加工したデータ ------------------------------------------------------------------------*/ protected function _set_process($model) { return $model; } /**---------------------------------------------------------------------- * レコードを1件削除する * @param string $id 対象レコードの主キー * @return integer 処理結果コード ------------------------------------------------------------------------*/ public function del($id) { if (true == $this->_lock) { return DB_LOCK_NG; } // 消そうとしている対象は存在するか? $arrData = $this->query_fetch('select * from ' . $this->_table . ' where `id`="' . $id . '"'); if (0 == count($arrData)) { return DB_DELETE_OK; } $result = $this->del_where('`id`="' . $id . '"'); $this->_last_id = $id; return $result; } /**---------------------------------------------------------------------- * レコードを1件削除する * @param string $id 対象レコードの主キー * @return integer 処理結果コード ------------------------------------------------------------------------*/ public function del_where($where) { if ('' == $this->_table || empty($this->_db)) { return DB_INIT_NG; } // 消そうとしている対象は存在するか? $arrData = $this->query_fetch_all('select * from ' . $this->_table . ' where ' . $where); if (0 == count($arrData)) { return DB_DELETE_OK; } $intDeleteCount = $this->_db->delete($this->_table, $where); if (0 < $intDeleteCount) { $result = DB_DELETE_OK; } else { $result = DB_DELETE_NG; $this->_log->error('delete ng[' . $where . ']'); } return $result; } /**---------------------------------------------------------------------- * レコードを全て削除する * @return integer 処理結果コード ------------------------------------------------------------------------*/ public function delAll() { if ('' == $this->_table || empty($this->_db)) { return DB_DELETE_NG; } $this->_log->start('delAll'); $this->_db->delete($this->_table, '1=1'); //$this->_db->query('truncate table ' . $this->_table . ';'); $result = DB_DELETE_OK; $this->_log->end(); return $result; } /**---------------------------------------------------------------------- * レコードを複製する * @param string $id 対象レコードの主キー * @return integer 処理結果コード ------------------------------------------------------------------------*/ public function cpy($id) { if (true == $this->_lock) { return DB_LOCK_NG; } if ('' == $this->_table || empty($this->_db)) { return DB_INIT_NG; } $this->_log->start('cpy'); // 加工前のデータを取得 $model = $this->get($id); if (0 != count($model)) { $model = $this->_cpy_update($model); unset($model['id']); // Remove the field id_html because it's an auto-increment field unset($model['id_html']); $result = $this->set($model); if (DB_INSERT_OK == $result) { $result = DB_COPY_OK; } else { $result = DB_COPY_NG; } } else { $result = DB_COPY_NG; } $this->_log->end(); return $result; } /**---------------------------------------------------------------------- * データを検証する * @param object $model 処理対象とするモデルデータ * @param string $validate_name 処理対象とするモデルデータ * @return array 検証結果のエラーを格納した配列 ------------------------------------------------------------------------*/ public function check($model, $validate_name = null) { $this->_log->start('check'); if (null == $validate_name) { $validate_name = $this->_name; } $objValidate = new ValidateMgr(); $result = $objValidate->isValid($model, $this->_config['config_file']['validate'], $validate_name); // 検証結果のエラーを作成 if (false == $result) { $arrError = $objValidate->getMessage( array( 'name' => $this->_arrParamName, ) ); } else { $arrError = array(); } $this->_log->end(); return $arrError; } /**---------------------------------------------------------------------- * データベースのデータをCSVとして取得する ------------------------------------------------------------------------*/ public function csvget() { $this->_log->start('csvget'); $objDataList = $this->getAll(); /* * C-Unit 2011-11-22 strart * #5840 * download CSV in search item and check page */ $count = 10; $page = 1; $page = self::$_input['search_page']; $objPageDataList = array_chunk($objDataList ,$count); $objDataList = $objPageDataList[$page-1]; /* * C-Unit 2011-11-22 end */ foreach ($objDataList as $i => $objData) { $objDataList[$i] = $this->_data2csv($objData); } $objCsv = new Csv(); $strCsv = $objCsv->create($objDataList, $this->_csvHeader, true); $this->_log->end(); return $strCsv; } /**---------------------------------------------------------------------- * データベース用データをCSVデータに変換する * @param object $objData データベース用データ * @return object $objData CSVデータ ------------------------------------------------------------------------*/ protected function _data2csv($objData) { return $objData; } /**---------------------------------------------------------------------- * CSVをデータベースのデータとして登録する * @param string $strFileName CSVファイル名 ------------------------------------------------------------------------*/ public function csvset($strFileName) { if ('' == $this->_table || empty($this->_db)) { return DB_DELETE_NG; } $this->_log->start('csvset'); // CSV取得 $objCsv = new Csv(); $arrCsv = $objCsv->load($strFileName); if (!is_array($arrCsv)) { $this->_log->end(); return $arrCsv; } // 連想配列のリストに変換 $this->_log->debug($arrCsv); $objDataList = $objCsv->convert($arrCsv, $this->_csvHeader); // データベース登録 foreach ($objDataList as $i => $objData) { $objData = $this->_csv2data($objData); if (isset($objData['id']) && '' != $objData['id']) { $objData_old = $this->query_fetch('select * from ' . $this->_table . ' where `id`="' . $objData['id'] . '"'); foreach ($objData as $key => $val) { $objData_old[$key] = $val; } $objData = $objData_old; } if (null !== $objData) { $this->set($objData); } else { $this->_log->error('登録失敗[' . ($i + 1) . ']行目'); } } $result = FILE_CSV_SET_OK; $this->_log->end(); return $result; } /**---------------------------------------------------------------------- * CSVデータをデータベース用データに変換する * @param object $objData CSVデータ * @return object $objData データベース用データ ------------------------------------------------------------------------*/ protected function _csv2data($objData) { return $objData; } /**---------------------------------------------------------------------- * 複製対象のレコードを更新する * @param object $model 複製するレコードを格納した連想配列 * @param object $uniq_list 一意な値とするキーとフォーマットの組を格納した連想配列 * 指定するとテーブル内で一意な値となるように複製する * @return object 更新後の複製レコードを格納した連想配列 ------------------------------------------------------------------------*/ protected function _cpy_update($model, $uniq_list = array()) { return $model; } /**---------------------------------------------------------------------- * データベースオブジェクトを取得する * @param string $db_key 設定ファイルのセクションキー、データベース情報を指す * @return object データベースオブジェクト ------------------------------------------------------------------------*/ public function getDb($db_key = null, $config = null) { if (null === $db_key) { $db_key = $this->_db_key; } if ('' == $db_key) { return null; } if (!isset(self::$_db_list[$db_key]) || $config != null) { $this->_log->start('getDb'); if($config != null){ $config_db = $config[$db_key]; } else{ $config_db = $this->_config[$db_key]; } $db = Zend_Db::factory($config_db['driver'], $config_db); $db->getConnection()->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true); if (false !== strpos(strtolower($this->_config['encode']['database']), 'euc')) { $encode = 'ujis'; } else { $encode = $this->_config['encode']['database']; $encode = str_replace('-', '', $encode); } $db->query('set names "' . $encode . '"'); $db->setFetchMode(Zend_Db::FETCH_ASSOC); self::$_db_list[$db_key] = $db; $this->_log->end(); } return self::$_db_list[$db_key]; } /**---------------------------------------------------------------------- * テーブル名を取得する * @return string テーブル名 ------------------------------------------------------------------------*/ public function get_table() { return $this->_table; } /**---------------------------------------------------------------------- * 最後に処理したレコードのIDを取得する * @return string レコードID ------------------------------------------------------------------------*/ public function get_last_id() { return $this->_last_id; } /**---------------------------------------------------------------------- * モデルオブジェクトを作成する * @param string $name モデルの名前 * @param object $input 入力データ * @return object モデルオブジェクト ------------------------------------------------------------------------*/ public function createObject($name) { // モデル名 $model_name = $this->_fw->getMvcFileName('model', $name); // キャッシュを返す if (isset(self::$_objModelList[$model_name])) { return self::$_objModelList[$model_name]; } // モデルファイル名 $objPath = new PathMgr($this->_config); $userSession = new Zend_Session_Namespace('userinfo'); if(!isset($userSession -> user_site)){ $strModelFile = $objPath->get('mvc', 'model') . '/' . $model_name . '.php'; } else { $strModelFile = $objPath->get('mvc', 'model_user') . '/' . $model_name . '.php'; } // モデル作成 if (is_file($strModelFile)) { require_once($strModelFile); eval('$objModel = new ' . $model_name . '();'); } else { $objModel = new AbstructModel(); } self::$_objModelList[$model_name] = $objModel; return $objModel; } /**---------------------------------------------------------------------- * 一意になるように名前を付けて複製する * @param object $model 複製するデータ * @param array $key_list チェック対象とする名前を指すキーを格納した配列 * @param string $first 複製番号の前に置くテキスト * @param string $last 複製番号の後に置くテキスト * @return array 複製されたデータ ------------------------------------------------------------------------*/ protected function _copy_uniq_model($model, $key_list, $first = '[', $last = ']') { $arrData = $this->getAll(); foreach ($key_list as $key) { $index = 2; if (false !== strpos($model[$key], $first)) { $value = explode($first, $model[$key]); $name_index = array_splice($value, count($value) - 1, 1); $name_index = substr($name_index[0], 0, strpos($last, $name_index[0])); $value = implode($value); if (false !== $name_index && is_numeric($name_index)) { $model[$key] = $value; $index = (int)$name_index; } } $value = $model[$key] . $first . $index . $last; $arrData = vsort($arrData, array($key => SORT_ASC)); for ($i = 0; $i < count($arrData); $i ++) { if ($value == $arrData[$i][$key]) { $index ++; $value = $model[$key] . $first . $index . $last; $i = 0; } } $model[$key] = $value; } return $model; } /**---------------------------------------------------------------------- * データをロックする ------------------------------------------------------------------------*/ public function lock() { $this->_lock = true; } /**---------------------------------------------------------------------- * データをアンロックする ------------------------------------------------------------------------*/ public function unlock() { $this->_lock = false; } /**---------------------------------------------------------------------- * SQL文を実行し、1行取得する * @param string $query 実行するSQL文 * @return object SQL実行結果 ------------------------------------------------------------------------*/ public function query_fetch($query) { $result = $this->_db->query($query); $objData = $result->fetch(); $result->closeCursor(); return $objData; } /**---------------------------------------------------------------------- * SQL文を実行し、全ての行を取得する * @param string $query 実行するSQL文 * @return array SQL実行結果 ------------------------------------------------------------------------*/ public function query_fetch_all($query) { $result = $this->_db->query($query); $arrData = $result->fetchAll(); return $arrData; } /**---------------------------------------------------------------------- * Retrieve the last id value ------------------------------------------------------------------------*/ public function getLastId() { return $this->_last_id; } }