Example #1
0
 public function getPair($record = null, $showEmpty = false)
 {
     if (!empty($this->setting)) {
         if ($this->setting[0] == 'getPair') {
             $where = $this->setting[4];
             if (!empty($where)) {
                 $where = json_decode($where, true);
                 foreach ($where as $k => $v) {
                     if ($v[0] == '{' && substr($v, -1) == '}') {
                         $v = substr($v, 1, -1);
                         $where[$k] = $record[$v];
                     }
                 }
             }
             $r = \Sooh\DB\Broker::getInstance($this->setting[1])->getPair($this->setting[2], $this->setting[3], $this->setting[4], $where);
         } else {
             throw new \ErrorException('unknown getPairMethod');
         }
     } else {
         $r = $this->arr;
     }
     if ($showEmpty && $this->captForEmpty) {
         $r[''] = $this->captForEmpty;
     }
     $this->pairVals = $r;
 }
Example #2
0
 /**
  * 
  * @param \Sooh\Base\Log\Data $logData
  */
 public function write($logData)
 {
     $resChg = $logData->resChanged;
     $arr = $logData->toArray();
     unset($arr['resChanged']);
     unset($arr['logGuid']);
     \Sooh\DB\Cases\LogStorage::$__YMD = \Sooh\Base\Time::getInstance()->YmdFull;
     \Sooh\DB\Cases\LogStorage::$__id_in_dbByObj = 'dbgrpForLog';
     \Sooh\DB\Cases\LogStorage::$__type = 'a';
     \Sooh\DB\Cases\LogStorage::$__nSplitedBy = $this->tbSplit;
     //\Sooh\DB\Cases\LogStorage::$__fields=array(.....);
     $tmp = \Sooh\DB\Cases\LogStorage::getCopy($logData->logGuid);
     foreach ($arr as $k => $v) {
         $tmp->setField($k, $v);
     }
     $ret = $tmp->writeLog();
     if ($ret) {
         $tbSub = str_replace('_a_', '_b_', $tmp->tbname());
         foreach ($resChg as $r) {
             $r['logGuid'] = $logData->logGuid;
             try {
                 \Sooh\DB\Broker::errorMarkSkip(\Sooh\DB\Error::tableNotExists);
                 $tmp->db()->addRecord($tbSub, $r);
             } catch (\ErrorException $e) {
                 if (\Sooh\DB\Broker::errorIs($e, \Sooh\DB\Error::tableNotExists)) {
                     $tmp->db()->ensureObj($tbSub, array('logGuid' => 'bigint unsigned not null  default 0', 'resName' => "varchar(36) not null default ''", 'resChg' => "int not null default 0", 'resNew' => "int not null default 0"));
                     $tmp->db()->addRecord($tbSub, $r);
                 } else {
                     error_log("write log failed:" . $e->getMessage() . "\n" . \Sooh\DB\Broker::lastCmd());
                 }
             }
         }
     }
 }
Example #3
0
 protected function getDB()
 {
     $dbid = 'default';
     //		$pre = \Sooh\Base\Ini::getInstance()->get('dbConf.'.$dbid);
     //		$pre = $pre['dbEnums']['default'];
     $pre = 'db_monitor';
     $this->tbname = $pre . '.tb_crond_log';
     return \Sooh\DB\Broker::getInstance($dbid);
 }
Example #4
0
 public function write($logData)
 {
     if ($this->rpc !== null) {
         return $this->rpc->initArgs(array('logData' => $logData))->send(__FUNCTION__);
     } else {
         $dt = \Sooh\Base\Time::getInstance();
         \Sooh\DB\Broker::getInstance()->addLog('db_monitor.tb_error_log', array('ymd' => $dt->YmdFull, 'hhiiss' => $dt->his, 'msg' => $logData));
         return 'done';
     }
 }
Example #5
0
 /**
  * 记录报表数据
  * | mainType | subType | ymd | rptdata | flg1 | flg2 | flg3 |
  * @param \Sooh\DB\Interfaces\All $db
  * @param int $ymd yyyymmdd
  * @param array $rptData
  * @param string $mainType
  * @param string $subType
  * @param array $flgs 标志位字段,不参与任何统计
  * @param array $conditionCanOverwrite 满足条件的才可以覆盖,null表示始终不能覆盖,空数组表示始终可以覆盖
  * @return boolean
  */
 public function save($db, $ymd, $rptData, $mainType, $subType, $flgs = array(), $conditionCanOverwrite = array())
 {
     $pkey = array('mainType' => $mainType, 'subType' => $subType, 'ymd' => $ymd);
     $fields = $flgs;
     if (!isset($fields['flg1'])) {
         $fields['flg1'] = 0;
     }
     if (!isset($fields['flg2'])) {
         $fields['flg2'] = 0;
     }
     if (!isset($fields['flg3'])) {
         $fields['flg3'] = 0;
     }
     $fields['rptdata'] = json_encode($rptData);
     $exists = $db->getOne($this->tbName, 'ymd', $pkey);
     if ($exists) {
         if (is_array($conditionCanOverwrite)) {
             if (empty($conditionCanOverwrite)) {
                 foreach ($pkey as $k => $v) {
                     $conditionCanOverwrite[$k] = $v;
                 }
                 $exists = $db->getOne($this->tbName, 'ymd', $conditionCanOverwrite);
                 if (!$exists) {
                     return false;
                 }
             }
             $db->updRecords($this->tbName, $fields, $pkey);
         } else {
             return false;
         }
     } else {
         try {
             \Sooh\DB\Broker::errorMarkSkip($v);
             foreach ($pkey as $k => $v) {
                 $fields[$k] = $v;
             }
             $db->addRecord($this->tbName, $fields);
         } catch (ErrorException $e) {
             if (\Sooh\DB\Broker::errorIs($e)) {
                 $this->save($db, $ymd, $mainType, $subType, $rptData);
             } else {
                 error_log($e->getMessage() . '#' . \Sooh\DB\Broker::lastCmd() . "\n" . $e->getTraceAsString());
                 return false;
             }
         }
     }
 }
Example #6
0
 public function writeLog()
 {
     try {
         \Sooh\DB\Broker::errorMarkSkip(\Sooh\DB\Error::tableNotExists);
         $this->update();
         return true;
     } catch (\Sooh\DB\Error $e) {
         if (\Sooh\DB\Broker::errorIs($e, \Sooh\DB\Error::tableNotExists)) {
             $this->createTable();
             $this->update();
             return true;
         } else {
             error_log("ErrorOnWriteLog:" . $e->getMessage() . "\n" . \Sooh\DB\Broker::lastCmd() . "\n" . $e->getTraceAsString());
             return false;
         }
     }
 }
Example #7
0
function var_log($var, $prefix = '')
{
    if (is_a($var, "\\Exception")) {
        $s = $var->__toString();
        if (strpos($s, '[Sooh_Base_Error]')) {
            if (class_exists('\\Sooh\\DB\\Broker', false)) {
                $sql = "\n" . \Sooh\DB\Broker::lastCmd() . "\n";
            } else {
                $sql = "\n";
            }
            error_log(str_replace('[Sooh_Base_Error]', $sql, $s));
        } else {
            error_log($prefix . $var->getMessage() . "\n" . $s);
        }
    } else {
        error_log($prefix . "\n" . var_export($var, true));
    }
}
Example #8
0
 /**
  * 实际保存到数据库的执行代码
  * @return int
  * @throws \ErrorException
  * @throws \Sooh\Base\ErrException 锁定了,又或诸如没什么要更改的确调用了save
  */
 protected function trySave()
 {
     $tbDisk = $this->tbname();
     $dbDisk = $this->db();
     if ($this->cacheWhenVerIDIs) {
         $tbCache = $this->tbname(true);
         $dbCache = $this->db(true);
     } else {
         $tbCache = null;
         $dbCache = null;
     }
     $class = get_called_class();
     if (empty($this->chged)) {
         throw new \ErrorException($class . ':nothing needs to do');
     }
     try {
         if ($this->lock && !$this->lock->lockedByThisProcess) {
             throw new \ErrorException("Can not update as record is locked");
         }
         if (!isset($this->r[$this->fieldName_verid])) {
             $verCurrent = array($this->fieldName_verid => 1);
             $fields = $this->fieldsForSqlUpds($this->chged);
             $pkeyBak = $dbDisk->kvoNew($tbDisk, $fields, $this->pkey, $verCurrent, $this->fieldAutoInc);
             $this->r[$this->fieldName_verid] = 1;
             foreach ($this->pkey as $k => $v) {
                 $this->r[$k] = $v;
             }
             $md5Key0 = md5(json_encode($this->pkey));
             $md5Key2 = md5(json_encode($pkeyBak));
             if ($md5Key0 !== $md5Key2) {
                 unset(self::$_copies[$class][$md5Key0]);
                 self::$_copies[$class][$md5Key2] = $this;
                 $this->pkey = $pkeyBak;
             }
             if ($this->cacheWhenVerIDIs > 0) {
                 $dbCache->kvoNew($tbCache, $fields, $this->pkey, $verCurrent, $this->fieldAutoInc);
             }
             return 1;
         } else {
             $verCurrent = array($this->fieldName_verid => $this->r[$this->fieldName_verid]);
             $whereForUpdate = $this->pkey;
             if ($this->lock) {
                 if (!$this->lock->lockedByThisProcess) {
                     throw new \Sooh\Base\ErrException(\Sooh\Base\ErrException::msgLocked);
                 } else {
                     $this->setField($this->fieldName_lockmsg, '');
                 }
             }
             //				else{
             //					$whereForUpdate[$this->fieldName_lockmsg]='';
             //				}
             if ($this->cacheWhenVerIDIs <= 1) {
                 if ($dbDisk->kvoFieldSupport()) {
                     $fields = $this->fieldsForSqlUpds($this->chged);
                     $_ret = $dbDisk->kvoUpdate($tbDisk, $fields, $whereForUpdate, $verCurrent);
                     $nextVerId = $fields[$this->fieldName_verid];
                 } else {
                     $fieldsAll = $this->fieldsForSqlUpds(array_keys($this->r));
                     $_ret = $dbDisk->kvoUpdate($tbDisk, $this->r, $whereForUpdate, $verCurrent);
                     $nextVerId = $fieldsAll[$this->fieldName_verid];
                 }
                 if ($this->cacheWhenVerIDIs) {
                     if ($dbCache->kvoFieldSupport()) {
                         if (empty($fields)) {
                             $fields = $this->fieldsForSqlUpds($this->chged);
                             $nextVerId = $fields[$this->fieldName_verid];
                         }
                         $dbCache->kvoUpdate($tbCache, $fields, $whereForUpdate, $verCurrent, true);
                     } else {
                         if (empty($fieldsAll)) {
                             $fieldsAll = $this->fieldsForSqlUpds(array_keys($this->r));
                             $nextVerId = $fieldsAll[$this->fieldName_verid];
                         }
                         $dbCache->kvoUpdate($tbCache, $fieldsAll, $whereForUpdate, $verCurrent, true);
                     }
                 }
                 $this->r[$this->fieldName_verid] = $nextVerId;
             } else {
                 if ($dbCache->kvoFieldSupport()) {
                     $fields = $this->fieldsForSqlUpds($this->chged);
                     $nextVerId = $fields[$this->fieldName_verid];
                     $_ret = $dbCache->kvoUpdate($tbCache, $fields, $whereForUpdate, $verCurrent);
                 } else {
                     $fieldsAll = $this->fieldsForSqlUpds(array_keys($this->r));
                     $nextVerId = $fieldsAll[$this->fieldName_verid];
                     $_ret = $dbCache->kvoUpdate($tbCache, $fieldsAll, $whereForUpdate, $verCurrent);
                 }
                 if ($this->r[$this->fieldName_verid] % $this->cacheWhenVerIDIs == 0) {
                     try {
                         if ($dbDisk->kvoFieldSupport()) {
                             if (empty($fields)) {
                                 $fields = $this->fieldsForSqlUpds($this->chged);
                                 $nextVerId = $fields[$this->fieldName_verid];
                             }
                             $_ret = $dbDisk->kvoUpdate($tbDisk, $fields, $whereForUpdate, $verCurrent, true);
                         } else {
                             if (empty($fieldsAll)) {
                                 $fieldsAll = $this->fieldsForSqlUpds(array_keys($this->r));
                                 $nextVerId = $fieldsAll[$this->fieldName_verid];
                             }
                             $_ret = $dbDisk->kvoUpdate($tbDisk, $fieldsAll, $whereForUpdate, $verCurrent, true);
                         }
                     } catch (\ErrorException $e) {
                         error_log("fatal error: {$class} : update disk failed after cache updated");
                         throw $e;
                     }
                 }
                 $this->r[$this->fieldName_verid] = $nextVerId;
             }
         }
         $this->lock = null;
         error_log("[KVObjV2 - save]" . implode("\n", \Sooh\DB\Broker::lastCmd(false)));
         return $_ret;
     } catch (\ErrorException $e) {
         //key duplicate -> add failed
         throw $e;
     }
 }
Example #9
0
 /**
  * 发放失败,收回
  * @param string $userIdentifier
  * @param string $logMsg 日志记录说明
  * @return bool
  */
 public function use_rollback($logMsg)
 {
     try {
         $log = \Prj\Data\ShopPointLog::getCopy($this->userIdentifier);
         $ret = $log->updateStatus($this->sn, \Prj\Data\ShopPointLog::status_cancel, $logMsg);
         if ($ret !== 1) {
             error_log("confirm shopPoint to {$this->userIdentifier} failed(none changed):" . \Sooh\DB\Broker::lastCmd() . "\n");
             return false;
         }
         $this->rs[$this->sn]['finalStatus'] = \Prj\Data\ShopPointLog::status_cancel;
         $this->_nleft -= $this->rs[$this->sn]['changed'];
         return true;
     } catch (\ErrorException $e) {
         error_log("confirm shopPoint to {$this->userIdentifier} failed:" . $e->getMessage() . "\n" . \Sooh\DB\Broker::lastCmd() . "\n" . $e->getTraceAsString());
         return false;
     }
 }
Example #10
0
 protected function _query($sql)
 {
     if ($sql == null) {
         if (empty($this->_lastCmd)) {
             throw new \Sooh\Base\ErrException('empty sql given');
         }
         $this->_lastCmd->dowhat = strtolower($this->_lastCmd->dowhat);
         switch ($this->_lastCmd->dowhat) {
             case 'insert':
                 $sql = 'insert into ' . $this->_lastCmd->tablenamefull . ' set ' . $this->_fmtField($this->_lastCmd->field);
                 break;
             case 'addlog':
                 $sql = 'insert delayed into ' . $this->_lastCmd->tablenamefull . ' set ' . $this->_fmtField($this->_lastCmd->field);
                 break;
             case 'insert':
                 $sql = 'insert into ' . $this->_lastCmd->tablenamefull . ' set ' . $this->_fmtField($this->_lastCmd->field);
                 break;
             case 'update':
                 $sql = 'update ' . $this->_lastCmd->tablenamefull . ' set ' . $this->_fmtField($this->_lastCmd->field);
                 break;
             case 'delete':
                 $sql = 'delete from ' . $this->_lastCmd->tablenamefull;
                 break;
             case 'select':
                 $sql = 'select ' . $this->_fmtField($this->_lastCmd->field) . ' from ' . $this->_lastCmd->tablenamefull;
                 break;
             default:
                 throw new \Sooh\Base\ErrException("unsupport sql cmd:" . $this->_lastCmd->dowhat);
         }
         if (!empty($this->_lastCmd->where)) {
             $sql .= ' ' . $this->_lastCmd->where;
         }
         if (!empty($this->_lastCmd->orderby)) {
             $arr = explode(' ', trim($this->_lastCmd->orderby));
             $mx = count($arr);
             $orderby = array();
             $groupby = array();
             for ($i = 0; $i < $mx; $i += 2) {
                 $k = $arr[$i];
                 $v = $arr[$i + 1];
                 switch ($k) {
                     case 'rsort':
                         $orderby[] = $v . ' desc';
                         break;
                     case 'sort':
                         $orderby[] = $v;
                         break;
                     case 'groupby':
                     case 'group':
                         $groupby[] = $v;
                         break;
                     default:
                         $err = new \Sooh\Base\ErrException('unsupport:' . $orderby);
                         throw $err;
                 }
             }
             if (!empty($groupby)) {
                 $sort_group .= ' group by ' . implode(',', $groupby);
             }
             if (!empty($orderby)) {
                 $sort_group .= ' order by ' . implode(',', $orderby);
             }
             $sql .= ' ' . $sort_group;
         }
         if ($this->_lastCmd->dowhat == 'select' && is_array($this->_lastCmd->fromAndSize) && $this->_lastCmd->fromAndSize[1] > 0) {
             $sql .= ' limit ' . $this->_lastCmd->fromAndSize[0] . ',' . $this->_lastCmd->fromAndSize[1];
         }
         $this->_lastCmd->resetForNext();
         $this->_lastCmd->strTrace = '[' . $this->_lastCmd->server . ']' . $sql;
     } else {
         if (is_string($sql)) {
             $this->_lastCmd->resetForNext();
             $this->_lastCmd->strTrace = '[' . $this->_lastCmd->server . ']' . $sql;
         } else {
             $err = new \Sooh\Base\ErrException('sql gived is not a string');
             error_log($err->getMessage() . "\n" . $err->getTraceAsString());
             throw $err;
         }
     }
     sooh_broker::pushCmd($this->_lastCmd);
     $skip = sooh_dbErr::$maskSkipTheseError;
     sooh_dbErr::$maskSkipTheseError = array();
     $rs = mysqli_query($this->_connection, $sql);
     $this->_chkErr($skip);
     return $rs;
 }
Example #11
0
 /**
  * 签到
  * @param boolean $withBonus 返回里是否带奖励物品列表
  * @param \Prj\Data\User $userOrAccountId accountId 或 \Prj\Data\User
  * @return array
  */
 public function doCheckIn($withBonus, $userOrAccountId)
 {
     if ($this->rpc !== null) {
         return $this->rpc->initArgs(array('withBonus' => $withBonus, 'userOrAccountId' => $userOrAccountId))->send(__FUNCTION__);
     } else {
         if (is_scalar($userOrAccountId)) {
             $userOrAccountId = \Prj\Data\User::getCopy($userOrAccountId);
         }
         $userOrAccountId->load();
         if ($userOrAccountId->exists() === false) {
             $userOrAccountId->setField(self::fieldUser, array());
             $userOrAccountId->update();
         }
         $this->decode($userOrAccountId->getField(self::fieldUser, true));
         if ($this->r['ymd'] == $this->today) {
             \Sooh\Base\Log\Data::getInstance()->ret = "checkin already";
             return $this->errFound(self::errTodayDone, 400, $withBonus);
         } elseif (sizeof($this->r['checked']) >= self::maxMonth) {
             \Sooh\Base\Log\Data::getInstance()->ret = 'checkin of this month:all done';
             return $this->errFound(self::errMonthDone, 400, $withBonus);
         }
         $accountId = $userOrAccountId->getAccountId();
         $idCheckThisTime = array_sum($this->r['checked']);
         $bonusThisTime = $this->getBonusList()[$idCheckThisTime];
         if (false === $userOrAccountId->lock('chkinBonus:' . http_build_query($bonusThisTime))) {
             \Sooh\Base\Log\Data::getInstance()->ret = "lock user for checkin failed";
             \Prj\Loger::alarm('[LockFailed] user-table on checkin' . \Sooh\DB\Broker::lastCmd());
             return $this->errFound(\Sooh\Base\ErrException::msgServerBusy, 500, $withBonus);
         }
         //\Lib\Items\Broker::iniForGiven('Voucher', array('iniDefaultForGive_a'=>60));// 如果有道具发放时有额外参数要设置(比如有效期不同)
         $givedThisTime = \Lib\Items\Broker::batchGive_pre($bonusThisTime, $accountId);
         if (sizeof($givedThisTime) == sizeof($bonusThisTime)) {
             if (\Lib\Items\Broker::batchGive_confirm($givedThisTime, $accountId)) {
                 try {
                     $this->r['checked'][$idCheckThisTime] = 1;
                     $this->r['bonusGot'][$idCheckThisTime] = $bonusThisTime;
                     $this->r['ymd'] = $this->today;
                     $userOrAccountId->setField(self::fieldUser, $this->r);
                     $userOrAccountId->update();
                     \Sooh\Base\Log\Data::getInstance()->ret = "done";
                     return $this->allDone(self::msgCheckinDone, $withBonus);
                 } catch (\ErrorException $errOnUpdate) {
                     \Prj\Loger::alarm('[CheckInFailed] on update user:'******'[GiveItemFailed] on checkin');
             \Sooh\Base\Log\Data::getInstance()->ret = "give item failed";
         } else {
             \Sooh\Base\Log\Data::getInstance()->ret = "update user failed";
         }
         if (\Lib\Items\Broker::batchGive_rollback('GiveItemFailedOnCheckin', $givedThisTime, $accountId)) {
             $userOrAccountId->unlock();
             return $this->errFound(\Sooh\Base\ErrException::msgServerBusy, 500, $withBonus);
         } else {
             return $this->errFound(\Sooh\Base\ErrException::msgServerBusy, 500, $withBonus);
         }
     }
 }
Example #12
0
 protected static function getDBAndTbNameById(&$tbnameToSet, $splitedId, $isCache = false)
 {
     $dbByObj = static::idFor_dbByObj_InConf($isCache);
     $ini = sooh_ini::getInstance();
     $dbId = $ini->get('dbByObj.' . $dbByObj);
     if (is_array($dbId)) {
         $i = $splitedId % (sizeof($dbId) - 1);
         $confIDStr = 'dbConf.' . $dbId[$i + 1];
     } elseif (!empty($dbId)) {
         $confIDStr = 'dbConf.' . $dbId;
     } else {
         $tmp = $ini->get('dbByObj.default');
         if (empty($tmp)) {
             $confIDStr = 'dbConf.default';
         } else {
             if (is_array($tmp)) {
                 $i = $splitedId % (sizeof($tmp) - 1);
                 $confIDStr = 'dbConf.' . $tmp[$i + 1];
             } else {
                 $confIDStr = 'dbConf.' . $tmp;
             }
         }
     }
     $conf = $ini->get($confIDStr);
     if (empty($conf)) {
         error_log('try find ' . $confIDStr . ' in dbConf failed for ' . $dbByObj);
         return null;
     }
     $db = sooh_dbBroker::getInstance($conf, $dbByObj);
     if (isset($conf['dbEnums'][$dbByObj])) {
         $dbname = $conf['dbEnums'][$dbByObj];
     } else {
         $dbname = $conf['dbEnums']['default'];
     }
     $tbnameToSet = $dbname . '.' . static::splitedTbName($splitedId, $isCache);
     return $db;
 }
Example #13
0
define("APP_PATH", dirname(__DIR__));
/* 指向public的上一级 */
if (!defined('SOOH_INDEX_FILE')) {
    define('SOOH_INDEX_FILE', 'index.php');
}
define('SOOH_ROUTE_VAR', '__');
error_log("-------------------------------------------------------tart:route=" . $_GET['__'] . " cmd=" . $_GET['cmd'] . " pid=" . getmypid());
include dirname(__DIR__) . '/conf/globals.php';
$ini = \Sooh\Base\Ini::getInstance();
$app = new Yaf_Application(APP_PATH . "/conf/application.ini");
$dispatcher = $app->getDispatcher();
if (!empty($reqeustReal)) {
    $dispatcher->setRequest($reqeustReal);
}
$view = \SoohYaf\SoohPlugin::initYafBySooh($dispatcher);
$dispatcher->returnResponse(TRUE);
try {
    $response = $app->run();
} catch (\ErrorException $e) {
    $view->assign('code', $e->getCode());
    $view->assign('msg', $e->getMessage());
    error_log("Error Caught at index.php:" . $e->getMessage() . "\n" . \Sooh\DB\Broker::lastCmd() . "\n" . $e->getTraceAsString() . "\n");
    $response = new Yaf_Response_Http();
    $response->setBody($view->render('ctrl/action.phtml'));
}
if ($ini->viewRenderType() === 'json') {
    header('Content-type: application/json');
}
$response->response();
\Sooh\Base\Ini::registerShutdown(null, null);
error_log("====================================================================end:route=" . $_GET['__'] . " cmd=" . $_GET['cmd'] . " pid=" . getmypid());
Example #14
0
 /**
  * 注册一个shutdown函数(一般是清理函数)
  * @param callback $callback array(obj,func), 'class::staticfunc',....
  * @param string $funcDesc function desc
  */
 public static function registerShutdown($callback, $funcDesc)
 {
     if ($callback === null) {
         foreach (self::$funcShutdown as $funcDesc => $func) {
             try {
                 if (is_array($func) || is_string($func)) {
                     call_user_func($func);
                 } else {
                     $func();
                 }
             } catch (\ErrorException $e) {
                 error_log('error shutdown:' . $funcDesc . " " . $e->getMessage() . "\n" . $e->getTraceAsString());
             }
         }
         if (class_exists("\\Sooh\\DB\\Broker", false)) {
             \Sooh\DB\Broker::free();
         }
     } else {
         self::$funcShutdown[$funcDesc] = $callback;
     }
 }
Example #15
0
 public function update($callback = null)
 {
     try {
         parent::update($callback);
     } catch (\Sooh\DB\Error $e) {
         if (\Sooh\DB\Broker::errorIs($e, \Sooh\DB\Error::tableNotExists)) {
             $this->createTable();
             parent::update($callback);
         } else {
             throw $e;
         }
     }
 }
Example #16
0
 /**
  * 账号登入, 失败抛出异常(密码错误,账号找不到等等)
  * @param $loginName
  * @param $cameFrom
  * @param $password
  * @param array $customArgs
  * @return mixed
  * @throws \ErrorException
  * @throws \Sooh\Base\ErrException
  * @throws array
  */
 public function login($loginName, $cameFrom, $password, $customArgs = ['contractId'])
 {
     if ($this->rpc !== null) {
         return $this->rpc->initArgs(['loginName' => $loginName, 'cameFrom' => $cameFrom, 'password' => $password, 'customArgs' => $customArgs])->send(__FUNCTION__);
     } else {
         $objLogin = \Sooh\DB\Cases\AccountAlias::getCopy($loginName, $cameFrom);
         $objLogin->load();
         if ($objLogin->exists()) {
             $accountId = $objLogin->getField('accountId');
             $this->setAccountStorage($accountId);
             $this->account->load();
             if ($this->account->exists()) {
                 $dt = \Sooh\Base\Time::getInstance();
                 $cmp = md5($password . $this->account->getField('passwdSalt'));
                 $loginFailed = $this->account->getField('loginFailed');
                 if ($loginFailed) {
                     $cd = new \Sooh\Base\CD($loginFailed, 750, 3600);
                     if ($cd->isRed()) {
                         throw new \Sooh\Base\ErrException(self::errAccountOrPasswordError);
                     }
                 } else {
                     $cd = new \Sooh\Base\CD(0, 750, 3600);
                 }
                 $ymdhForbidden = $this->account->getField('dtForbidden');
                 if ($ymdhForbidden) {
                     if ($dt->YmdH <= $ymdhForbidden) {
                         throw new \Sooh\Base\ErrException(self::errAccountLock, 404);
                     }
                 }
                 if ($cmp != $this->account->getField('passwd')) {
                     $cd->add(1);
                     $ret = new \Sooh\Base\ErrException(self::errAccountOrPasswordError, 404);
                 } else {
                     $nickname = $this->account->getField('nickname');
                     $ret = array('accountId' => $this->account->getField('accountId'), 'nickname' => $nickname);
                     if (!empty($customArgs)) {
                         if (is_string($customArgs)) {
                             $customArgs = explode(',', $customArgs);
                         }
                         foreach ($customArgs as $k) {
                             $ret[$k] = $this->account->getField('contractId');
                         }
                     }
                 }
                 $this->account->setField('lastIP', \Sooh\Base\Tools::remoteIP());
                 $this->account->setField('lastDt', $dt->timestamp());
                 $this->account->setField('loginFailed', $cd->toString());
                 try {
                     $this->account->update();
                 } catch (\ErrorException $ex) {
                     \Sooh\Base\Log\Data::error("error on update account when login:"******"\n" . \Sooh\DB\Broker::lastCmd() . "\n" . $ex->getTraceAsString());
                 }
                 if (is_array($ret)) {
                     return $ret;
                 } else {
                     throw $ret;
                 }
             } else {
                 throw new \Sooh\Base\ErrException(self::errAccountOrPasswordError, 400);
             }
         } else {
             throw new \Sooh\Base\ErrException(self::errAccountOrPasswordError, 400);
         }
     }
 }
Example #17
0
 /**
  * 删除过期日志
  * @param int $dayExpired (默认删除190天前)
  */
 public function remoreCrondLogExpired($dayExpired = 190)
 {
     $dt = \Sooh\Base\Time::getInstance()->getInstance()->timestamp(-$dayExpired);
     \Sooh\DB\Broker::getInstance($this->dbConfID)->delRecords($this->tbName, array('ymdh<' => date('YmdH', $dt)));
 }
Example #18
0
 /**
  * 
  * @param string $imei
  * @return int64 contractId
  */
 public static function getContractIdOfAndroid($imei)
 {
     $tmp = self::startAndroid($imei);
     try {
         \Sooh\DB\Broker::errorMarkSkip(\Sooh\DB\Error::tableNotExists);
         $pkey = $tmp->load();
         if ($pkey) {
             $dt = \Sooh\Base\Time::getInstance()->timestamp();
             if ($dt < $tmp->getField('expired')) {
                 $contractId = $tmp->getField('contractId');
                 try {
                     $tmp->update(array($tmp, 'markInstalled'));
                     return $contractId;
                 } catch (\ErrorException $e) {
                     error_log($e->getMessage() . "\n" . $e->getTraceAsString());
                     return 0;
                 }
             } else {
                 return 0;
             }
         } else {
             return 0;
         }
     } catch (\ErrorException $e) {
         if (\Sooh\DB\Broker::errorIs($e, \Sooh\DB\Error::tableNotExists)) {
             return 0;
         } else {
             error_log($e->getMessage() . "\n" . $e->getTraceAsString());
             return 0;
         }
     }
 }
Example #19
0
 protected function _query($sql)
 {
     if ($sql == null) {
         if (empty($this->_lastCmd)) {
             throw new \ErrorException('empty sql given');
         }
         $orderby = array();
         $groupby = array();
         if (!empty($this->_lastCmd->orderby)) {
             $arr = explode(' ', trim($this->_lastCmd->orderby));
             $mx = count($arr);
             for ($i = 0; $i < $mx; $i += 2) {
                 $k = $arr[$i];
                 $v = $arr[$i + 1];
                 switch ($k) {
                     case 'rsort':
                         $orderby[] = $v . ' desc';
                         break;
                     case 'sort':
                         $orderby[] = $v;
                         break;
                     case 'groupby':
                     case 'group':
                         $groupby[] = $v;
                         break;
                     default:
                         $err = new \ErrorException('unsupport:' . $orderby);
                         sooh_trace::exception($err);
                         throw $err;
                 }
             }
         }
         $this->_lastCmd->dowhat = strtolower($this->_lastCmd->dowhat);
         switch ($this->_lastCmd->dowhat) {
             case 'select':
                 $sql = 'select ';
                 if (is_array($this->_lastCmd->fromAndSize) && $this->_lastCmd->fromAndSize[1] > 0) {
                     $sql .= ' top ' . $this->_lastCmd->fromAndSize[1] . ' ';
                     if ($this->_lastCmd->fromAndSize[0] !== 0) {
                         if (is_array($this->_lastCmd->pkey) && sizeof($this->_lastCmd->pkey) > 1) {
                             throw new \ErrorException("multi-pkey not support in mssql for limit");
                         }
                         if (is_array($this->_lastCmd->pkey)) {
                             $pkey = key($this->_lastCmd->pkey);
                             if (is_int($pkey)) {
                                 $pkey = current($this->_lastCmd->pkey);
                             }
                         } else {
                             if (empty($this->_lastCmd->pkey)) {
                                 $pkey = 'Id';
                             } else {
                                 if (is_string($this->_lastCmd->pkey)) {
                                     $pkey = $this->_lastCmd->pkey;
                                 } else {
                                     throw new \ErrorException("invalid pkey  in mssql found for limit");
                                 }
                             }
                         }
                         $limit = "{$pkey} NOT IN (SELECT TOP {$this->_lastCmd->fromAndSize[0]} {$pkey} FROM {$this->_lastCmd->tablenamefull} __WHERE__";
                         if (!empty($orderby)) {
                             $limit .= ' order by ' . implode(',', $orderby);
                         }
                         $limit .= ")";
                         //throw new \ErrorException('todo: 获取并缓存主键');//SELECT TOP 10 * FROM sql WHERE ( code NOT IN (SELECT TOP 20 code FROM TestTable ORDER BY id))
                     }
                 }
                 $sql .= $this->_fmtField($this->_lastCmd->field) . ' from ' . $this->_lastCmd->tablenamefull;
                 break;
             case 'addlog':
             case 'insert':
                 $sql = 'insert into ' . $this->_lastCmd->tablenamefull;
                 $sql .= " (" . implode(',', array_keys($this->_lastCmd->field)) . ") ";
                 $sql .= "values (";
                 foreach ($this->_lastCmd->field as $k => $v) {
                     $sql .= $this->_safe($k, $v) . ',';
                 }
                 $sql = substr($sql, 0, -1) . ")";
                 break;
             case 'update':
                 //update FE_temp.dbo.tb_user set tb_user.timeLastBought = tb_bought.lastBought
                 ////	from FE_temp.dbo.tb_user left join FE_temp.dbo.tb_bought on tb_bought.userIdentifier=tb_user.userIdentifier
                 $sql = 'update ' . $this->_lastCmd->tablenamefull . ' set ' . $this->_fmtField($this->_lastCmd->field);
                 break;
             case 'delete':
                 $sql = 'delete from ' . $this->_lastCmd->tablenamefull;
                 break;
             default:
                 throw new \ErrorException('unsupport sql cmd:' . $this->_lastCmd->dowhat);
         }
         if (!empty($limit)) {
             if (!empty($this->_lastCmd->where)) {
                 $where = substr(trim($this->_lastCmd->where), 5);
                 $limit = str_replace('__WHERE__', ' where ' . $where, $limit);
                 $sql .= ' where (' . $where . ') and (' . $limit . ')';
             } else {
                 $sql .= ' where ' . ($limit = str_replace('__WHERE__', '', $limit));
             }
         } elseif (!empty($this->_lastCmd->where)) {
             $sql .= ' ' . $this->_lastCmd->where;
         }
         if (!empty($this->_lastCmd->orderby)) {
             if (!empty($groupby)) {
                 $sort_group .= ' group by ' . implode(',', $groupby);
             }
             if (!empty($orderby)) {
                 $sort_group .= ' order by ' . implode(',', $orderby);
             }
             $sql .= ' ' . $sort_group;
         }
         $this->_lastCmd->resetForNext();
         $this->_lastCmd->strTrace = '[' . $this->_lastCmd->server . ']' . $sql;
     } else {
         if (is_string($sql)) {
             $this->_lastCmd->resetForNext();
             $this->_lastCmd->strTrace = '[' . $this->_lastCmd->server . ']' . $sql;
         } else {
             $err = new \ErrorException('sql gived is not a string');
             error_log($err->getMessage() . "\n" . $err->getTraceAsString());
             throw $err;
         }
     }
     sooh_broker::pushCmd($this->_lastCmd);
     $skip = sooh_dbErr::$maskSkipTheseError;
     sooh_dbErr::$maskSkipTheseError = array();
     //throw new \ErrorException($sql);
     $rs = sqlsrv_query($this->_connection, $sql);
     $this->_chkErr($skip);
     return $rs;
 }
Example #20
0
 /**
  * 
  * @param string $type [idfa|imei|md5|mac]
  * @param string $sn
  * @param string $phone
  * @param string $userIdentifier
  * @param string $contractId
  * @param array $extraData
  * @return \PrjLib\DataDig\Log\Device
  */
 public static function ensureOne($type, $sn, $phone = null, $userIdentifier = null, $contractId = null, $extraData = null)
 {
     $dt = \Sooh\Base\Time::getInstance();
     $deviceId = self::guidMaker($type, $sn);
     $ddd = \Yaf_Dispatcher::getInstance()->getRequest();
     error_log("trace device->ensure(" . $ddd->getModuleName() . '/' . $ddd->getControllerName() . '/' . $ddd->getActionName() . ") " . $deviceId . "  phone:{$phone}  user:{$userIdentifier}");
     $sys = parent::getCopy(array('deviceId' => $deviceId));
     try {
         \Sooh\DB\Broker::errorMarkSkip(\Sooh\DB\Error::tableNotExists);
         $sys->load();
     } catch (\ErrorException $e) {
         if (\Sooh\DB\Broker::errorIs($e, \Sooh\DB\Error::tableNotExists)) {
             $sys->createTable();
         }
     }
     $fields = array('ip' => \Sooh\Base\Tools::remoteIP(), 'ymd' => $dt->YmdFull, 'hhiiss' => $dt->his);
     try {
         if ($sys->exists() === false) {
             foreach ($fields as $k => $v) {
                 $sys->setField($k, $v);
             }
             $sys->setField('phone', empty($phone) ? '0' : $phone);
             $sys->setField('userIdentifier', empty($userIdentifier) ? '' : $userIdentifier);
             $sys->setField('extraData', empty($extraData) ? '' : json_encode($extraData));
             $sys->setField('extraRet', '');
             $sys->setField('contractId', empty($contractId) ? '0' : $contractId);
             try {
                 \Sooh\DB\Broker::errorMarkSkip(\Sooh\DB\Error::duplicateKey);
                 $sys->update();
                 $sys->flgNewCreate = true;
                 return $sys;
             } catch (\ErrorException $e) {
                 $sys->reload();
                 if ($sys->exists() === false) {
                     error_log('error create new device log:' . $e->getMessage() . "\n" . $e->getTraceAsString());
                     return $sys;
                 }
             }
         }
         $oldPhone = $sys->getField('phone', true);
         $oldUser = $sys->getField('userIdentifier', true);
         $oldContractId = $sys->getField('contractId', true);
         if (!empty($phone) && !empty($oldPhone) && $phone != $oldPhone || !empty($oldUser) && !empty($userIdentifier) && $oldUser != $userIdentifier || !empty($oldContractId) && !empty($contractId) && $oldContractId != $contractId) {
             $extraDataOld = $sys->getField('extraData', true);
             $extraRetOld = $sys->getField('extraRet', true);
             $extraRetOld = is_scalar($extraRetOld) === false ? json_encode($extraRetOld) : $extraRetOld;
             \Sooh\DB\Broker::getInstance(\PrjLib\Tbname::db_rpt)->addRecord(\PrjLib\Tbname::tb_device_log, array('deviceId' => $deviceId, 'dtChange' => $dt->YmdFull . sprintf('%06d', $dt->his), 'phoneOld' => $oldPhone, 'userIdentifierOld' => $oldUser, 'extraDataOld' => is_scalar($extraDataOld) === false ? json_encode($extraDataOld) : $extraDataOld, 'extraRetOld' => $extraRetOld, 'contractIdOld' => $oldContractId, 'phoneNew' => $phone, 'userIdentifierNew' => $userIdentifier, 'extraDataNew' => empty($extraData) ? '' : json_encode($extraData), 'extraRetNew' => $extraRetOld, 'contractIdNew' => empty($contractId) ? '0' : $contractId, 'ipOld' => $sys->getField('ip', true), 'ipNew' => $fields['ip']));
         }
         foreach ($fields as $k => $v) {
             $sys->setField($k, $v);
         }
         if (!empty($extraData)) {
             $sys->setField('extraData', empty($extraData) ? '' : json_encode($extraData));
         }
         if (!empty($phone)) {
             $sys->setField('phone', $phone);
         }
         if (!empty($userIdentifier)) {
             $sys->setField('userIdentifier', $userIdentifier);
         }
         //$sys->setField('extraRet', '');
         if (!empty($contractId)) {
             $sys->setField('contractId', $contractId);
         }
         $sys->update();
         //var_log($sys->dump(),'======================log->filled for '.$sys->tbname());
         \Sooh\DB\Broker::errorMarkSkip(\Sooh\DB\Error::tableNotExists);
     } catch (\ErrorException $e) {
         error_log("error: on ensure-device:" . $e->getMessage() . "\n" . $e->getTraceAsString());
     }
     return $sys;
 }
Example #21
0
 /**
  * 循环遍历用的所有的数据库连接标识和表(不包括cache)
  * 回调函数接受两个参数:dbBroker和表名
  * @param type $callback_dbid_fulltbname
  */
 protected function loop($callback_dbid_fulltbname, $searchInCache = false)
 {
     $bak = $this->pkey_val;
     try {
         $numSplit = $this->numToSplit[0];
         if (is_callable($callback_dbid_fulltbname)) {
             for ($i = 0; $i < $numSplit; $i++) {
                 $this->pkey_val = $i;
                 $dbid = $this->_allHosts[$searchInCache ? 1 : 0][$i % $numSplit];
                 $tbname = $this->tbname($searchInCache);
                 $callback_dbid_fulltbname(\Sooh\DB\Broker::getInstance($dbid), $tbname);
             }
         } else {
             for ($i = 0; $i < $numSplit; $i++) {
                 $this->pkey_val = $i;
                 $dbid = $this->_allHosts[$searchInCache ? 1 : 0][$i % $numSplit];
                 $tbname = $this->tbname($searchInCache);
                 call_user_func($callback_dbid_fulltbname, \Sooh\DB\Broker::getInstance($dbid), $tbname);
             }
         }
     } catch (\ErrorException $e) {
         error_log("error found when " . get_called_class() . '->loop():' . $e->getMessage() . "\n" . $e->getTraceAsString());
     }
     $this->pkey_val = $bak;
 }
Example #22
0
 /**
  * 
  * @return \Soob\DB\Interfaces\All
  */
 protected function getDB($dbid)
 {
     return \Sooh\DB\Broker::getInstance($dbid);
 }
Example #23
0
 /**
  * 负责添加,更新逻辑以及表单页面控制
  * @return type
  */
 public function formAction()
 {
     $where = \Lib\Misc\DWZ::decodePkey($this->_request->get('_pkey_val'));
     $frm = \Sooh\Base\Form\Broker::getCopy('default')->init(\Sooh\Base\Tools::uri(), 'post', empty($where) ? \Sooh\Base\Form\Broker::type_c : \Sooh\Base\Form\Broker::type_u);
     //$frm->addItem('camefrom', form_def::factory('', 'local', form_def::constval));
     if (empty($where)) {
         $frm->addItem('loginname', form_def::factory('帐号', '', form_def::text))->addItem('nickname', form_def::factory('昵称', '', form_def::text));
         $frm->addItem('passwd', form_def::factory('初始密码', '', form_def::text));
         $this->_view->assign('FormOp', $op = '添加');
     } else {
         $frm->addItem('loginname', form_def::factory('帐号', '', form_def::constval))->addItem('nickname', form_def::factory('昵称', '', form_def::text));
         $this->_view->assign('FormOp', $op = '更新');
     }
     $frm->addItem('_pkey_val', '')->addItem('rights', form_def::factory('权限', '', array($this, 'renderTreeCheckbox')));
     //->initMore(new \Sooh\Base\Form\Options($this->optionsOfRights()))
     $frm->fillValues($this->getInputs());
     if ($frm->flgIsThisForm) {
         //submit
         try {
             if ($frm->type() == \Sooh\Base\Form\Broker::type_c) {
                 //add new manager
                 $fields = $frm->getFields();
                 if (is_array($fields['rights'])) {
                     $fields['rights'] = implode(',', $fields['rights']);
                 }
                 $acc = \Lib\Services\Manager::getInstance(null);
                 $acc->register($fields['loginname'], $fields['passwd'], $fields['camefrom'] = 'local', array('rights' => $fields['rights'], 'nickname' => $fields['nickname']));
                 $randPwd = $fields['passwd'];
             } else {
                 //update manager
                 $fields = $frm->getFields();
                 if (is_array($fields['rights'])) {
                     $fields['rights'] = implode(',', $fields['rights']);
                 }
                 //var_log($fields,'upd:');
                 unset($fields['camefrom']);
                 unset($fields['loginname']);
                 $manager = \Prj\Data\Manager::getCopy($where['loginname'], $where['camefrom']);
                 $manager->load();
                 foreach ($fields as $k => $v) {
                     $manager->setField($k, $v);
                 }
                 $manager->update();
                 $randPwd = null;
             }
             $this->closeAndReloadPage($this->tabname('index'));
             $this->returnOK($op . '成功' . ($randPwd ? ',密码:' . $randPwd : ''));
         } catch (\ErrorException $e) {
             if (\Sooh\DB\Broker::errorIs($e, \Sooh\DB\Error::duplicateKey)) {
                 $this->returnError($op . '失败:冲突,相关记录已经存在?');
             } else {
                 $this->returnError($op . '失败:' . $e->getMessage());
             }
         }
     } else {
         //show form
         if (!empty($where)) {
             $manager = \Prj\Data\Manager::getCopy($where['loginname'], $where['camefrom']);
             $manager->load();
             $fields = $manager->dump();
             $this->tmpVal = \Sooh\Base\Acl\Ctrl::_fromString($manager->getField('rights'));
             $ks = array_keys($frm->items);
             foreach ($ks as $k) {
                 if (isset($fields[$k]) && is_object($frm->items[$k])) {
                     $frm->item($k)->value = $fields[$k];
                 }
             }
             $frm->items['_pkey_val'] = \Lib\Misc\DWZ::encodePkey(array('camefrom' => $fields['camefrom'], 'loginname' => $fields['loginname']));
         } else {
             $fields = array();
             $this->tmpVal = array();
             //$frm->item('camefrom')->value='local';
         }
     }
 }
Example #24
0
 /**
  * 
  * @return \Soob\DB\Interfaces\All
  */
 protected function getDB()
 {
     return \Sooh\DB\Broker::getInstance($this->driver);
 }