ÿØÿà JFIF ` ` ÿþ
Server : Apache System : Linux ruga7-004.fmcity.com 3.10.0-1160.119.1.el7.x86_64 #1 SMP Tue Jun 4 14:43:51 UTC 2024 x86_64 User : tkt_travelbus ( 1137) PHP Version : 7.0.0p1 Disable Function : mysql_pconnect Directory : /tkt_travelbus/www/Lib/ |
Upload File : |
<?php /** * DataObject Class */ class DataObject { const WRITE_DB = 'WRITE'; // master const READ_DB = 'READ'; // slaves var $DB; var $id; var $dsn = array(); var $charset; var $table; var $fields = '*'; var $PK = array(); var $recordType = 0; var $record = array(); var $validate = array(); var $invalidate = array(); var $_sql; var $where; var $search; /** * constructor * * @param string $dsn DSN string * @param string $charset specify database charset * @return void */ function DataObject($dsn = '', $charset = '') { if ($dsn && is_string($dsn)) { $this->dsn = array( DataObject::WRITE_DB => getConf($dsn), DataObject::READ_DB => getConf($dsn) ); } elseif ( $dsn && is_array($dsn) && $dsn['write'] && $dsn['read'] ){ $this->dsn = array( DataObject::WRITE_DB => getConf($dsn['write']), // master DataObject::READ_DB => getConf($dsn['read']) // slave ); } else { if ( getConf('dsn.default') && getConf('dsn.read') ){ $this->dsn = array( DataObject::WRITE_DB => getConf('dsn.default'), // or getConf('dsn.write') or getConf('dsn.master') DataObject::READ_DB => getConf('dsn.read') // or getConf('dsn.slave') ); }else{ $this->dsn = array( DataObject::WRITE_DB => getConf('dsn.default'), DataObject::READ_DB => getConf('dsn.default') ); } } if ($charset) { $this->charset = $charset; } else { $this->charset = getConf('site.charset'); } $this->charset = str_replace('-', '', $this->charset); $scheme = substr($this->dsn[DataObject::WRITE_DB], 0, strpos($this->dsn[DataObject::WRITE_DB], '://')); if (!$scheme) { $this->error('데이터베이스 설정 오류입니다.'); } $className = 'DB_' . strtolower($scheme); $this->DB = new $className($this->dsn, $this->charset, getConf('debug.db'), getConf('debug.log.dberror')); $this->DB->setCacheDir(getConf('dir.dbcache')); $this->search = array(); // debug if (getConf('debug.db')) { $this->setDebug(); } } // 조건절 지정(ListManager) - lsh : 2008-10-15 function initWhere() { $this->search = array(); if (isset($this->where)) { unset($this->where); } } function setWhere($where) { $this->where = $where; } function addWhere($where) { $this->search[] = $where; } function addSearch($field, $keyword="__blank", $cond="like", $type=1) { if($keyword == "__blank") $this->addWhere($field); elseif($keyword != null && $keyword != "") { list($tablename, $fieldname) = explode(".", $field, 2); if ( !$fieldname ) { $str = sprintf("`%s` %s", mysql_real_escape_string(trim($tablename,'`')), $cond); }else{ $str = sprintf("`%s`.`%s` %s", mysql_real_escape_string(trim($tablename,'`')), mysql_real_escape_string(trim($fieldname,'`')), $cond); } if($type == 0) $str .= mysql_real_escape_string($keyword); elseif($type == 2) $str .= "'%" . mysql_real_escape_string($keyword) . "%'"; elseif($type == 3) $str .= "'" . mysql_real_escape_string($keyword) . "%'"; else $str .= "'" . mysql_real_escape_string($keyword) . "'"; $this->search[] = $str; } } function getWhereQuery() { if(!isset($this->where)) { if(count($this->search)) $where = implode(" AND ", $this->search); else $where = ""; } else { $where = $this->where; } return $where; } /** * 모델객체 생성함수 * model object factory * * @param string $model DBO class id * @param string $dsn * @return object */ function factory($model, $dsn = '') { static $__instance; // singleton if (!isset($__instance[$model])) { $className = 'DBO_' . $model; $__instance[$model] = new $className($dsn); //if ($__instance[$model]->table && $__instance[$model]->DB) { // $__instance[$model]->DB->setTable($__instance[$model]->table); //} } return $__instance[$model]; } /** * 디버깅 모드 설정 * set debug flag * * @param boolean $flag * @return void */ function setDebug($flag = true) { $this->DB->setDebug($flag); } function setTargetConnection() { } /** * 테이블 지정 * set table and PK * * @param string $table * @param string $PK primary key name * @return */ function setTable($table, $PK = null) { $old = array($this->table, $this->PK); if (is_array($table)) { $PK = $table[1]; $table = $table[0]; } $this->table = $table; $this->DB->setTable($table); $this->fields = '*'; if (is_array($PK)) { $this->PK = $PK; } else if ($PK) { $this->PK = array($PK=>1); } else { $this->PK = array(); } return $old; } /** * 테이블 조인 초기화 * init table join (clean old join table) * * @return void */ function initJoin() { $this->DB->initJoin(); } /** * 테이블 조인 * add join table * * @param string $table * @param string $joinType * @param string $on join condition for ON clause * @return void */ function addJoin($table, $joinType, $on) { $this->DB->addJoin($table, $joinType, $on); } /** * 쿼리 실행 및 데이터 반환 (cakePHP 인터페이스) * execute select query and return fetched data * * @param string $sql * @return array */ function query($sql, $targetDb = NULL) { return $this->DB->data($sql, '', $targetDb); } /** * 쿼리 실행 (cakePHP 인터페이스) * execute query and return query resource * * @param string $sql * @return resource */ function execute($sql, $targetDb = NULL) { return $this->DB->query($sql, $targetDb); } /** * 필드 지정 - 2008-08-27 현재 get() 함수에서만 사용됨 * set select fields for get() * * @param string $value * @return void */ function setFields($value) { $this->fields = $value; } /** * 칼럼 데이타 반환 * get datum from record by column name * * @param string $name * @return mixed */ function getCol($name) { if (isset($this->record[$name])) { return $this->record[$name]; } else { return null; } } /** * 칼럼 데이타 지정 * set column datum to record * * @param string $name * @param mixed $value * @return void */ function setCol($name, $value) { $this->record[$name] = $value; } /** * 칼럼 데이타 지정 혹은 반환 * set or get column datum on condition value is exists or not * * @param string $name * @param mixed $value * @return */ function item($name, $value = null) { if (func_num_args() == 1) { return $this->getCol($name); } else { $this->setCol($name, $value); return true; } } /** * 레코드 등록 * insert record to current table * * @param array $record * @return resource */ function insert($record = null) { if (is_array($record)) { $this->record = array_merge($this->record, $record); } if (!$this->record) { $this->error('입력할 데이타가 없습니다.'); } $this->DB->setTable($this->table); $result = $this->DB->insert($this->record, true); $this->record = array(); return $result; } /** * 레코드 수정 * update record to current table using PK or where clause * * 참고 : PK만 지정하여 사용하는 경우($isWhere == false)에는 $record에 포함된 PK 칼럼은 unset됨 * * @param array $record * @param mixed $id * @param boolean $isWhere if true $id is not PK but where clause * @return */ function update($record = null, $id = null, $isWhere = false) { if (is_array($record)) { $this->record = array_merge($this->record, $record); } if (!$this->record) { $this->error('수정할 데이타가 없습니다.'); } // where if ($isWhere) { $where = $id; } else { if ($id) { $this->id = $id; } if (!$this->id) { $this->error('기본키가 지정되지 않았습니다.'); } $where = $this->_getPrimaryWhere($this->id); // unset primary key foreach ($this->PK as $field => $type) { unset($this->record[$field]); } } $this->DB->setTable($this->table); $result = $this->DB->update($this->record, $where, true); $this->record = array(); return $result; } /** * 레코드 저장(등록/수정) (cakePHP 인터페이스) * update or insert record to current table on condition $this->id is set or not * * @param array $data * @return resource */ function save($data) { //데이타가 없을 경우 에러 if (!$data || !is_array($data)) { $this->error('저장할 데이타가 없습니다.'); } foreach ($data as $key => $value) { $this->item($key, $value); } //유효성 검사 if (!$this->isValid()) { $this->error('저장할 데이타가 유효하지 않습니다.'); } //입력, 수정을 분리 $result = NULL; if ($this->id) { $result = $this->update(); } else { $result = $this->insert(); } return $result; } /** * 레코드 삭제 (cakePHP 인터페이스) * delete record from current table using PK or where clause * * 참고 : PK가 여러개일 때는 배열로 사용한다. * * @param mixed $id * @param boolean $isWhere if true $id is not PK but where clause * @return resource */ function del($id = null, $isWhere = false) { if ($isWhere) { $where = $id; } else { if (!$id) { $id = $this->id; } if (!$id) { $this->error('기본키가 지정되어 있지 않습니다.'); } $where = $this->_getPrimaryWhere($id); } return $this->DB->delete($where); } /** * 레코드 삭제 * delete record from current table using PK * alias of del() * 참고 : PK가 여러개일 때는 delete(array(id1, id2, id2 ...)) 처럼 개별 인수로 사용한다. * * @param * @return */ function delete() { $args = func_get_args(); if ($args) { return call_user_func_array(array(&$this, 'del'), $args); //return $this->del($args); } else { return $this->del(); } } /** * 특정 필드 저장 (cakePHP 인터페이스) * save column datum to current table * * @param string $name * @param mixed $value * @return resource */ function saveField($name, $value) { $this->DB->setTable($this->table); return $this->update(array($name => $value)); } /** * 특정 필드값 가져오기 (cakePHP 인터페이스) * get column datum from current table * * @param string $name column name * @param string $where * @param string $order * @param string $targetDb * @return mixed */ function field($name, $where, $order = null, $targetDb = NULL) { $sql = 'SELECT ' . $name . ' FROM ' . $this->table . ' WHERE ' . $where; if ($order) { $sql .= ' ORDER BY ' . $order; } $sql .= ' LIMIT 1'; return $this->DB->result($sql, 0, 0, $targetDb); } /** * 조건에 부합한 레코드 가져오기 (cakePHP 인터페이스) * select one record from current table using where clause * * @param string $where * @param string $fields * @param string $order * @param string $group * @param string $targetDb * @return array */ function find($where, $fields = '*', $order = '', $group = '', $targetDb = NULL) { return $this->DB->select($where, $fields, 1, $order, $group, $targetDb); } /** * 조건에 부합한 모든 레코드 가져오기 (cakePHP 인터페이스) * select records from current table using where clause * * @param string $where * @param string $fields * @param string $order * @param int $limit * @param string $group * @param string $targetDb * @return array */ function findAll($where, $fields = '*', $order = '', $limit = '', $group = '', $targetDb = NULL) { if ($limit === 1 || $limit === "1") { $data = $this->DB->select($where, $fields, $limit, $order, $group, $targetDb); if ($data) { $data = array($data); } return $data; } else { return $this->DB->select($where, $fields, $limit, $order, $group, $targetDb); } } /** * 조건에 부합한 레코드 갯수 가져오기 (cakePHP 인터페이스) * select count from current table using where caluse * * @param string $where * @param string $field * @param string $targetDb * @return int */ function findCount($where = null, $field = '*', $targetDb = NULL) { return $this->DB->getCount($where, $field, FALSE, $targetDb); } /** * 특정 레코드 가져오기 (cakePHP 인터페이스) * select one record from current table using PK * * 참고 : PK가 여러개일 때는 배열로 사용한다. * * @param string $fields * @param mixed $id * @return array */ function read($fields = '*', $id = null, $targetDb = NULL) { if ($id) { $this->id = $id; } if (!$this->id) { $this->error('기본키가 지정되지 않았습니다.'); } $where = $this->_getPrimaryWhere($this->id); return $this->DB->select($where, $fields, 1, '', '', $targetDb); } /** * 특정 레코드 가져오기 * select one record from current table using PK * * 참고 : PK가 여러개일 때는 get(id1, id2, id2 ...) 처럼 개별 인수로 사용한다. * * @param mixed $id * @return array */ function get() { $args = func_get_args(); if ($args) { return $this->read($this->fields, $args); } else { return $this->read(); } } /** * 카운트 필드 수정 * update count column by value (increase or decrease) * * @param string $where * @param string $field * @param int $value * @return resource */ function updateCount($where, $field, $value = 1) { if (is_array($field)) { $tmp = array(); foreach ($field as $k=>$v) { if (intval($v) < 0) { $tmp[] = $k . '=' . $k . $v; } else { $tmp[] = $k . '=' . $k . '+' . $v; } } $set = implode(', ', $tmp); } else { if (intval($value) < 0) { $set = $field . '=' . $field . $value; } else { $set = $field . '=' . $field . '+' . $value; } } $sql = 'UPDATE ' . $this->table . ' SET ' . $set . ' WHERE ' . $where; return $this->DB->query($sql); } /** * 마지막 등록 아이디 반환 * get last insert id * * @return mixed */ function getInsertId($new = false) { return $this->DB->getInsertId($new); } /** * 에러메시지 디버깅 * trigger error * * @param string $msg * @param boolean $force * @return void */ function error($msg, $force=FALSE) { if ( is_object($this->DB) && method_exists($this->DB, 'error') ){ $this->DB->error($msg, $force); }else{ trigger_error($msg, E_USER_ERROR); } } /** * 에러스택에서 1개 얻어오기 * * @return string */ function popError() { if ( is_object($this->DB) ){ if ( count($this->DB->errorStack)>0 ){ return array_pop($this->DB->errorStack); } } return NULL; } /** * 에러스택에 쌓인 에러가 존재하는가? * * @return boolean */ function hasError() { if ( is_object($this->DB) ){ if ( count($this->DB->errorStack)>0 ){ return TRUE; } } return FALSE; } /** * 실행 쿼리 반환 * get last executed query * * @return string */ function getSQL() { return $this->DB->getQuery(); } /////////////////////////////////////////////////////////////////////////////////////////////////// // extend /** * 리스트매니저 객채 반환 * get instance of ListManager class inherited * * @return object */ function getListManager() { $obj = new ListManager($this->DB); $obj->setTable($this->table); return $obj; } /** * 2차 배열을 루프용 데이터로 변환 * format array for loop * * @param array $data * @param string $formatter function name for formatting * @return array */ function getLoopData($data, $formatter) { for ($i=0, $ci=count($data); $i<$ci; $i++) { $data[$i]['__idx'] = $i; } if (function_exists($formatter)) { array_walk($data, $formatter); } return $data; } /** * 프라이머리키에 해당하는 조건문 생성 * make where using PK * * @access private * @param mixed $id * @return string */ function _getPrimaryWhere($id) { if (empty($id)) { $id = array(-1); } if (!is_array($id)) { $id = explode(',', $id); } $query = array(); $i = 0; foreach ($this->PK as $field => $type) { if (!isset($id[$i])) { $id[$i] = -1; } if ($type == 1) { $query[] = $field . ' = \'' . trim($id[$i]) . '\''; } else { $query[] = $field . ' = ' . trim($id[$i]); } $i++; } return implode(' AND ', $query); } /** * 데이타 유효성 검사 * validate record using PREG RegExp pattern * * @return boolean */ function isValid() { $valid = true; foreach ($this->validate as $field => $pattern) { if (!preg_match($pattern, $this->record[$field])) { $this->inValidate[] = $field; $valid = false; } } return $valid; } /** * set callback function * * @param string $callback * @param string $tablename * @param string $read_or_write read|write * @return boolean */ function setCallback($callback, $read_or_write, $table=NULL) { return $this->DB->setCallback($callback, $read_or_write, $table); } /** * get callback function * @param string $read_or_write read|write * @param string $tablename(optional) * * @return string */ function getCallback($read_or_write, $table=NULL) { return $this->DB->getCallback($read_or_write, $table); } /** * reset callback function * @param string $read_or_write read|write * @param string $tablename(optional) * * @return string */ function resetCallback($read_or_write, $table=NULL) { return $this->DB->resetCallback($read_or_write, $table); } /** * 트랜잭션 상태반환 * return transaction status * * @access public * @return boolean */ function transStatus() { return $this->DB->transStatus(); } /** * 트랜잭션 사용여부 * set transaction enabling * * @access public * @param boolean $transEnable * @return NULL */ function transEnable( $transEnable ) { $this->DB->transEnable( $transEnable ); } /** * 트랜잭션 완료가 안되어있는가? * need to transaction complete * * @access public * @return boolean */ function needToTransComplete() { return $this->DB->needToTransComplete(); } /** * 트랜잭션 시작 * transaction begin * * @access public * @return boolean */ function transBegin() { //$this->_trans_status = TRUE; return $this->DB->transBegin(); } /** * 트랜잭션 커밋 * transaction commit * * @access public * @return boolean */ function transCommit() { return $this->DB->transCommit(); } /** * 트랜잭션 롤백 * transaction rollback * * @access public * @return boolean */ function transRollback() { return $this->DB->transRollback(); } /** * 자동처리 트랜잭션 완료 * transaction start * * @access public * @param callable $callbackOrForceChangeTransStatus * @param mixed params(optional) * @return boolean */ function transComplete($callbackOrForceChangeTransStatus=NULL) { if ( $callbackOrForceChangeTransStatus!=NULL && is_callable($callbackOrForceChangeTransStatus) ){ $args = func_get_args(); array_shift($args); //첫번째 인자를 제거한다 $callback_trans_status = call_user_func_array($callbackOrForceChangeTransStatus, $args); return $this->DB->transComplete($callback_trans_status); }else{ return $this->DB->transComplete($callbackOrForceChangeTransStatus); } } }