Пример #1
0
 public function user()
 {
     $_DCOOKIE = array();
     $this->cookiepre = $this->cookiepre . substr(md5($this->cookiepath . '|' . $this->cookiedomain), 0, 4) . '_';
     $prelength = strlen($this->cookiepre);
     foreach ($_COOKIE as $key => $val) {
         if (substr($key, 0, $prelength) == $this->cookiepre) {
             $_DCOOKIE[substr($key, $prelength)] = Lua::clean($val);
         }
     }
     unset($prelength);
     if (isset($_DCOOKIE['auth'])) {
         $authkey = md5($this->authkey . $_SERVER['HTTP_USER_AGENT']);
         $auth = Lua::clean(explode("\t", $this->authcode($_DCOOKIE['auth'], 'DECODE', $authkey)));
         list($discuz_pw, $discuz_uid) = empty($auth) || count($auth) < 2 ? array('', '') : $auth;
         if ($discuz_uid) {
             Doo::db()->reconnect('X15');
             $query = "select u.uid,u.username,u.password,p.gender from pre_common_member u left join pre_common_member_profile p on p.uid=u.uid where u.uid='{$discuz_uid}'";
             $query = str_replace('pre_', $this->tablepre, $query);
             $user = Lua::get_one($query);
             Doo::db()->reconnect('dev');
             if (!empty($user) && $user['password'] == $discuz_pw) {
                 unset($user['password']);
                 return $user;
             }
         }
     }
     return array();
 }
Пример #2
0
 public function programa()
 {
     Doo::loadModel('CtEventos');
     $this->data['eventos'] = Doo::db()->find('CtEventos', array('asc' => 'hora'));
     $this->data['slug'] = 'programa';
     $this->renderc('eventos', $this->data);
 }
 protected function _fetchTableDefinition($table)
 {
     $fullTableDefinition = Doo::db()->fetchAll('DESCRIBE ' . $table);
     $tableDefinition = array();
     foreach ($fullTableDefinition as $columnDefinition) {
         $fieldName = $columnDefinition['Field'];
         $type = strtolower($columnDefinition['Type']);
         $size = null;
         if (strpos($type, '(') !== false) {
             $size = substr($type, strpos($type, '(') + 1, -1);
             $type = substr($type, 0, strpos($type, '('));
             if ($type != 'char' && $type != 'varchar') {
                 $size = null;
             }
         }
         $require = $columnDefinition['Null'] == 'YES' ? false : true;
         $default = $columnDefinition['Default'];
         $primary = $columnDefinition['Key'] == 'PRI' ? true : false;
         $autoInc = strpos($columnDefinition['Extra'], 'auto_increment') === false ? false : true;
         if ($type == 'boolean' || $type == 'tinyint' && $size == 1) {
             $type = DooManageDb::COL_TYPE_BOOL;
         } elseif ($type == 'integer') {
             $type = DooManageDb::COL_TYPE_INT;
         } elseif ($type == 'double') {
             $type = DooManageDb::COL_TYPE_FLOAT;
         } elseif ($type == 'longtext') {
             $type = DooManageDb::COL_TYPE_CLOB;
         } elseif ($type == 'datetime') {
             $type = DooManageDb::COL_TYPE_TIMESTAMP;
         }
         $tableDefinition[$fieldName] = array('autoinc' => $autoInc, 'default' => $default, 'primary' => $primary, 'require' => $require, 'scope' => null, 'size' => $size, 'type' => $type);
     }
     return $tableDefinition;
 }
Пример #4
0
 public function user()
 {
     $winduser = $this->GetCookie('winduser');
     if ($winduser) {
         list($winduid, $windpwd, ) = explode("\t", $this->StrCode($winduser, 'DECODE'));
     }
     if (isset($winduid) && is_numeric($winduid) && strlen($windpwd) >= 16) {
         Doo::db()->reconnect('pw8');
         $query = "SELECT m.uid,m.username,m.password,m.icon,m.gender as sex,md.onlineip FROM pw_members m LEFT JOIN pw_memberdata md ON m.uid=md.uid WHERE m.uid='{$winduid}'";
         $query = str_replace('pw_', $this->tablepre, $query);
         $user = Lua::get_one($query);
         $onlineip = $this->clientIP();
         if (strpos($user['onlineip'], $onlineip) === false) {
             $iparray = explode(".", $onlineip);
             if (strpos($user['onlineip'], $iparray[0] . '.' . $iparray[1]) === false) {
                 return array();
             }
         } else {
             if (empty($user)) {
                 return array();
             } else {
                 if ($this->PwdCode($user['password']) != $windpwd) {
                     unset($user);
                     return array();
                 } else {
                     unset($user['password']);
                     return $user;
                 }
             }
         }
         Doo::db()->reconnect('dev');
     }
 }
Пример #5
0
 function remove_agg_tmp_tables()
 {
     require 'instrumentation.php';
     require 'simple-dal.php';
     $schema_id = $this->params['schema_id'];
     // shards
     $shards = Doo::db()->find('Shards', array('where' => "schema_id = {$schema_id}"));
     $drop_count = 0;
     foreach ($shards as $s) {
         $server = get_object_vars($s);
         $server['user'] = $s->username;
         $conn = SimpleDAL::factory($server);
         $conn->my_select_db($server['db']);
         //get tables
         $stmt = $conn->my_query("SHOW TABLES");
         while ($row = $conn->my_fetch_assoc($stmt)) {
             $table = $row['Tables_in_' . $server['db']];
             if (preg_match('/(aggregation_tmp_|agg_tmp_)/', $table)) {
                 $conn->my_query("DROP TABLE " . $table);
                 $drop_count++;
             }
         }
         $conn->my_close();
     }
     $this->res->message = "Dropped {$drop_count} Tables";
     $this->res->success = true;
 }
Пример #6
0
 public function get_by_id()
 {
     if (intval($this->id) <= 0) {
         return null;
     }
     return Doo::db()->find($this, array('limit' => 1));
 }
Пример #7
0
 public function user()
 {
     $_DCOOKIE = array();
     $prelength = strlen($this->cookiepre);
     foreach ($_COOKIE as $key => $val) {
         if (substr($key, 0, $prelength) == $this->cookiepre) {
             $_DCOOKIE[substr($key, $prelength)] = Lua::clean($val);
         }
     }
     unset($prelength);
     $discuz_auth_key = md5($this->authkey . $_SERVER['HTTP_USER_AGENT']);
     list($discuz_pw, $discuz_secques, $discuz_uid) = isset($_DCOOKIE['auth']) ? Lua::clean(explode("\t", $this->authcode($_DCOOKIE['auth'], 'DECODE', $discuz_auth_key)), 1) : array('', '', 0);
     $discuz_uid = intval($discuz_uid);
     Doo::db()->reconnect('dz7');
     $query = "select m.uid,m.username,m.password,m.gender as sex,mf.avatar as icon from cdb_members m left join cdb_memberfields mf on mf.uid=m.uid where m.uid='{$discuz_uid}'";
     $query = str_replace('cdb_', $this->tablepre, $query);
     $user = Lua::get_one($query);
     Doo::db()->reconnect('dev');
     if ($user && $discuz_pw == $user['password']) {
         unset($user['password']);
         $user['hash'] = substr(md5(substr(TIMESTAMP, 0, -7) . iconv('utf-8', 'gbk', $user['username']) . $discuz_uid . $discuz_pw . $discuz_auth_key), 8, 8);
         return $user;
     }
     return array();
 }
Пример #8
0
 public function test()
 {
     $this->load()->model('Food');
     $food = new Food();
     echo '<pre>';
     //print_r( $food->getById(14) );
     //print_r( $food->getById(14, array('limit'=>1)) );
     //print_r( $food->limit(10) );
     //print_r( $food->limit(10,'id,name') );
     //print_r( $food->limit(10,'name','id') );
     //print_r( $food->limit(10,'name,id','location') );
     //print_r( Food::_limit(10) );
     //print_r( $food->getOne() );
     //print_r( Food::_getOne() );
     //$food->location = 'Asia';
     //$food->food_type_id = 10;
     print_r($food->count());
     print_r(Food::_count());
     print_r(Food::_count($food));
     //Doo::cache('php')->set('foodtotal', Food::_count($food));
     //echo '<h1>'. Doo::cache('php')->get('foodtotal') .'</h1>';
     print_r(Food::getById__first(6));
     //$food->id = 14;
     //print_r( $food->getOne() );
     // print_r( $food->find() );
     //print_r( Food::_find($food) );
     //print_r( $food->getById_location__first(6, 'Malaysia') );
     //print_r( $food->getById_location(6, 'Malaysia', array('limit'=>1)) );
     //print_r( $food->relateFoodType($food, array('limit'=>'first')) );
     //print_r( $food->relateFoodType($food) );
     //print_r( $food->relateFoodType__first($food) );
     //print_r( Food::getById__location__first(6, 'Malaysia') );
     //print_r( Food::getById__location(6, 'Malaysia') );
     //print_r( Food::getById__first(6) );
     //print_r( Food::getByLocation('Malaysia') );
     //print_r( Food::relateFoodType__first($food) );
     //print_r( Food::relateFoodType() );
     //print_r( Food::relateFoodType_first() );
     //print_r( Food::_relate('', 'FoodType') );
     //
     //$f = new Food;
     //print_r( $f->relate('FoodType') );
     //print_r( $f->relate('FoodType', array('limit'=>'first')) );
     # if update/delete/insert cache auto purged on the Model.
     //$food->id = 6;
     //$food->name = 'Wan Tan Mee';
     //$food->update();
     //print_r($food->find());
     //$food->purgeCache();  #to delete cache manually
     //Food::_purgeCache();  #to delete cache manually
     # If no SQL is displayed, it means that the data are read from cache.
     # And of course your Model have to extend DooSmartModel
     print_r(Doo::db()->showSQL());
 }
Пример #9
0
 public function index()
 {
     $thisip = $this->clientIP();
     Lua::adminfail($thisip, 1);
     $username = Lua::post('username');
     $password = Lua::post('password');
     if (empty($username)) {
         Lua::admin_msg('信息提示', '请输入用户名');
     }
     if (empty($password)) {
         Lua::admin_msg('信息提示', '请输入密码');
     }
     $user = Lua::get_one("select * from lua_admin where username='******' and password='******' and gid='1'");
     if (empty($user)) {
         Lua::adminfail($thisip);
         Lua::admin_msg('信息提示', '用户名或密码错误');
     }
     $auth = Lua::authcode($user['uid'] . "\t" . $user['password'], 'ENCODE');
     $session = Doo::session('Lua');
     // 口令卡验证
     $sets = Doo::cache('php')->get('loginset');
     if ($sets && $sets['cardit'] == 1) {
         $cardcode = $session->get('cardcode');
         $cardit = intval(Lua::post('cardit'));
         if (empty($cardit)) {
             Lua::admin_msg('信息提示', '请输入口令卡');
         }
         $cardex = explode('@', $cardcode);
         $b1 = $cardex[0][1];
         $b2 = $cardex[1][1];
         $secureid = $user['secureid'];
         $sdb = Lua::get_one("select * from lua_secure where id='{$secureid}' and uid='" . $user['uid'] . "'");
         if (empty($sdb)) {
             Lua::admin_msg('信息提示', '请先绑定口令卡后再登录');
         }
         $securekey = unserialize($sdb['securekey']);
         $x = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
         $k1 = array_search($cardex[0][0], $x);
         $k2 = array_search($cardex[1][0], $x);
         $truekey = $securekey[$b1][$k1] . $securekey[$b2][$k2];
         $truekey = intval($truekey);
         if ($truekey != $cardit) {
             Lua::adminfail($thisip);
             Lua::admin_msg('信息提示', '输入的口令卡错误', '/' . ADMIN_ROOT . '/');
         }
     }
     // end
     $session->auth = $auth;
     Doo::db()->query("update lua_admin set logintime='" . time() . "',logs=logs+1,loginip='" . $this->clientIP() . "' where uid='" . $user['uid'] . "'");
     Lua::delete('lua_admin_fails', array('ip' => $thisip));
     Lua::write_log($user, '登录后台', '---', $user['channel']);
     Lua::admin_msg('操作提示', '登录成功', '/' . ADMIN_ROOT);
 }
Пример #10
0
 /**
  * @override solo en caso de poner excepciones
  * @see DooController::render()
  */
 public function renderc($file, $data = null, $enableControllerAccess = false, $includeTagClass = true)
 {
     if (!$data && is_array($file)) {
         $data = $file;
     }
     $data = array_merge(array('list' => array(), 'error' => null, 'action' => null), is_array($data) ? $data : array());
     if (!is_string($file)) {
         $file = $this->params['format'];
     }
     if (Doo::conf()->DEBUG_ENABLED) {
         $data['sql'] = Doo::db()->showSQL();
     }
     parent::renderc($file, $data, $enableControllerAccess, $includeTagClass);
 }
 function fields()
 {
     $res = new response();
     $db = $this->params["db"];
     $table = $this->params["table"];
     //query
     $result = Doo::db()->fetchAll("SHOW COLUMNS IN {$table} IN {$db}");
     foreach ($result as $row) {
         $data[] = array('field' => $row["Field"], 'type' => $row["Type"], 'null' => $row['Null'], 'key' => $row['Key'], 'default' => $row['Default']);
     }
     $res->data = $data;
     $res->success = true;
     echo $res->to_json();
 }
Пример #12
0
 function getResultadosEncuestas()
 {
     $r = null;
     if (!empty($this->id_respuesta)) {
         $query = 'SELECT COUNT(id_resultado_encuesta) AS valor, id_respuesta FROM ht_resultado_encuesta WHERE id_respuesta = ' . $this->id_respuesta . ' GROUP BY id_respuesta';
         $result = Doo::db()->query($query);
         $r = $result->fetch();
         if (empty($r)) {
             $r = array();
             $r['id_respuesta'] = $this->id_respuesta;
             $r['valor'] = 0;
         }
     }
     return $r;
 }
Пример #13
0
 function index()
 {
     session_start();
     if (Session::siExisteSesion()) {
         Doo::loadModel('CtEventos');
         $this->data['eventos'] = Doo::db()->find('CtEventos');
         $this->data['slug'] = 'eventos';
         Doo::loadModel('CtEncuesta');
         $enActivas = new CtEncuesta();
         $enActivas->activa = 1;
         $this->data['encuestas_activas'] = $enActivas->count();
         $this->renderc('admin/evento-ver-todos', $this->data);
     } else {
         header('location:' . Doo::conf()->APP_URL . 'ionadmin/login?error=1');
     }
 }
 function start_local_job_server($id, $port, $schema_id)
 {
     //get path
     $config = Doo::db()->getOne('SchemataConfig', array('where' => "schema_id = {$schema_id} AND var_name = 'gearmand_path'"));
     $gearmand_path = $config != false ? $config->var_value : '';
     if ($gearmand_path === "") {
         $path = getenv('PATH');
         putenv("PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/bin:{$path}");
         $which = `which gearmand`;
         if ($which) {
             $gearmand_path = trim($which);
         }
     } else {
         if (is_dir($gearmand_path)) {
             $gearmand_path = rtrim($gearmand_path, "/") . '/gearmand';
         }
     }
     $log_file = Doo::conf()->SITE_PATH . Doo::conf()->PROTECTED_FOLDER . "log/gearmand.{$id}.log";
     $pid_file = Doo::conf()->SITE_PATH . Doo::conf()->PROTECTED_FOLDER . "var/gearmand.{$id}.pid";
     if ($gearmand_path === "") {
         $fh = fopen($log_file, 'a+');
         fputs($fh, `date` . " - could not find gearmand in path!\n");
         return false;
     }
     if (file_exists($pid_file)) {
         unlink($pid_file);
     }
     //send command to shell
     $cmd = $gearmand_path . " -d -L 127.0.0.1 -p {$port} -l {$log_file} --pid-file={$pid_file}";
     $iam = trim(`whoami`);
     if ($iam === "root") {
         $cmd .= " -u shard-query";
     }
     //execute command
     exec($cmd, $output);
     //wait for pid file creation
     sleep(2);
     //check pid file
     if (!file_exists($pid_file)) {
         $fh = fopen($log_file, 'a+');
         fputs($fh, trim(`date`) . " - gearman could not be started.  PID file not found. [{$output}]\n");
         return false;
     }
     //return pid
     return file_exists($pid_file) ? file_get_contents($pid_file) : null;
 }
Пример #15
0
 function live()
 {
     //callback : required
     if (!isset($_GET['callback']) || !preg_match('/^[a-zA-Z0-9_]+$/', $_GET['callback'])) {
         die('Invalid callback name');
     }
     $callback = $_GET['callback'];
     //query db
     $results = Doo::db()->find('QuotesLive', array('asArray' => true));
     //convert to float to strip trailing zeros
     foreach ($results as $key => $row) {
         $results[$key]['bid'] = (double) $row['bid'];
         $results[$key]['offer'] = (double) $row['offer'];
     }
     //print it
     $this->setContentType('js');
     echo $callback . "(" . json_encode($results) . ");";
 }
 function gearman_status()
 {
     $res = new response();
     require_once 'Net/Gearman/Manager.php';
     $id = $this->params["id"];
     $server = Doo::db()->getOne('GearmanJobServers', array('where' => "id = {$id}"));
     if ($server == false) {
         $res->message = "invalid id";
         $res->success = false;
     } else {
         try {
             $manager = new Net_Gearman_Manager($server->hostname . ":" . $server->port);
             $res->data = $manager->status();
             $res->success = true;
         } catch (Net_Gearman_Exception $e) {
             $res->message = $e->getMessage();
             $res->success = false;
         }
     }
     echo $res->to_json();
 }
Пример #17
0
 private function del()
 {
     $id = Lua::get('id');
     $count = Doo::db()->count("select count(*) from lua_category where systemname='" . SYSNAME . "' and upid='{$id}'");
     if ($count > 0) {
         Lua::admin_msg('提示信息', '有下级栏目');
     }
     $db = Lua::get_one("select * from lua_category where id='{$id}' and systemname='" . SYSNAME . "'");
     if ($db) {
         $models = $this->_models_tree($db['model_id']);
         if ($models) {
             foreach ($models as $row) {
                 Doo::db()->query("delete from " . $row['tablename'] . " where catid='{$id}'");
             }
         }
     }
     Lua::delete('lua_category', array('systemname' => SYSNAME, 'id' => $id));
     $this->_cache();
     Lua::write_log($this->user, '删除栏目', "catid={$id}<br />title=" . $db['name'], SYSNAME);
     Lua::admin_msg('操作提示', '成功删除', './category.htm');
 }
Пример #18
0
 public function user()
 {
     $userCookie = $this->getCookie('winduser');
     if ($userCookie) {
         list($uid, $password) = explode("\t", $this->decrypt($userCookie));
         if ($uid) {
             Doo::db()->reconnect('pw9');
             $query = "select u.uid,u.username,u.password,i.gender as sex from pw_user u left join pw_user_info i on i.uid=u.uid where u.uid='{$uid}'";
             $query = str_replace('pw_', $this->tablepre, $query);
             $user = Lua::get_one($query);
             $user['sex'] = $user['sex'] == 1 ? 2 : 1;
             $user['icon'] = '';
             if ($this->getPwdCode($user['password']) != $password) {
                 return array();
             } else {
                 unset($user['password']);
                 return $user;
             }
             Doo::db()->reconnect('dev');
         }
     }
     return array();
 }
Пример #19
0
<?php

#Add include folder for shard-query
set_include_path(get_include_path() . PATH_SEPARATOR . '../include');
#load configs
include './protected/config/common.conf.php';
include './protected/config/routes.conf.php';
include './protected/config/db.conf.php';
#Just include this for production mode
//include $config['BASE_PATH'].'deployment/deploy.php';
include $config['BASE_PATH'] . 'Doo.php';
include $config['BASE_PATH'] . 'app/DooConfig.php';
# Uncomment for auto loading the framework classes.
spl_autoload_register('Doo::autoload');
Doo::conf()->set($config);
# remove this if you wish to see the normal PHP error view.
#include $config['BASE_PATH'].'diagnostic/debug.php';
# database usage
//Doo::useDbReplicate();	#for db replication master-slave usage
//Doo::db()->setMap($dbmap);
Doo::db()->setDb($dbconfig, $config['APP_MODE']);
//Doo::db()->sql_tracking = true;	#for debugging/profiling purpose
Doo::app()->route = $route;
# Uncomment for DB profiling
//Doo::logger()->beginDbProfile('doowebsite');
Doo::app()->run();
//Doo::logger()->endDbProfile('doowebsite');
//Doo::logger()->rotateFile(20);
//Doo::logger()->writeDbProfiles();
Пример #20
0
 /**
  * Delete an existing record. (Prepares and execute the DELETE statements)
  * @param mixed $model The model object to be deleted.
  * @param array $opt Associative array of options to generate the UPDATE statement. Supported: <i>where, limit, param</i>
  */
 public static function _delete($model, $opt = NULL)
 {
     $model->purgeCache();
     return Doo::db()->delete($model, $opt);
 }
Пример #21
0
 function fetch()
 {
     $schema_id = $this->params['schema_id'];
     $job_id = $this->params['job_id'];
     //lookup schema name
     $schema = Doo::db()->getOne('Schemata', array('where' => 'id = ' . $schema_id));
     //update jobs before we check!
     $shard_query = new ShardQuery($schema->schema_name);
     $shard_query->state->mapper->sweep_jobs();
     //get job
     $j = new Jobs();
     $j->id = $job_id;
     $j = $j->getOne();
     //check if job exist
     if (!$j) {
         $this->res->success = false;
         $this->res->message = "Job_ID: {$job_id} doesnt exist!";
         return null;
     }
     //check if job compeleted
     if ($j->job_status != 'completed') {
         $this->res->success = false;
         $this->res->message = "Job_ID: {$job_id} not completed!";
     } else {
         //get result from job_id
         $stmt = $shard_query->get_async_result($job_id);
         //build data
         if ($stmt) {
             $this->res->success = true;
             $this->res->data = $this->json_format($shard_query, $stmt);
             $shard_query->DAL->my_free_result($stmt);
         } else {
             //error
             $this->res->success = false;
             $this->res->data = $stmt;
             $this->res->message = $shard_query->DAL->my_error();
         }
     }
 }
Пример #22
0
 private function change()
 {
     $db = Lua::get_one("select status from lua_model where id='" . Lua::post('id') . "'");
     $rt = $db['status'] == 1 ? 0 : 1;
     Doo::db()->query("update lua_model set status='{$rt}' where id='" . Lua::post('id') . "'");
     Lua::println();
 }
Пример #23
0
 private function _query($db, $rs = array())
 {
     $fields = $this->_fields($db);
     $query = array();
     $subject = Lua::post('subject');
     if (empty($subject)) {
         return '标题';
     }
     $filename = Lua::post('filename');
     $query['subject'] = $subject;
     if ($filename) {
         $count = Doo::db()->count("select count(*) from " . $db['tablename'] . " where filename='{$filename}'");
         if (($rs && $rs['filename'] != $filename || empty($rs)) && $count > 0) {
             return '静态名称已存在';
         }
         $query['filename'] = $filename;
     }
     if ($fields) {
         foreach ($fields as $rs) {
             $field = $rs['fieldname'];
             $value = Lua::post($field);
             if ($rs['ismust'] == 1) {
                 if ($value == '') {
                     return $rs['name'];
                 }
             }
             if ($rs['fieldtype'] == 'checkbox') {
                 if ($value) {
                     $query[$field] = implode(',', $value);
                 } else {
                     $query[$field] = '';
                 }
             } else {
                 $query[$field] = $value;
             }
         }
     }
     return $query;
 }
Пример #24
0
 /**
  * Returns the database singleton, shorthand to Doo::db()
  * @return DooSqlMagic
  */
 public function db()
 {
     return Doo::db();
 }
Пример #25
0
 public function code()
 {
     $data = array();
     $data['active'] = false;
     if ($this->params['code']) {
         if (!self::$session->user) {
             $app_access_token = file_get_contents("https://graph.facebook.com/oauth/access_token?client_id=" . Doo::conf()->FACEBOOK['APP_ID'] . "&redirect_uri=" . urlencode(Doo::conf()->FACEBOOK['CANVAS_PAGE']) . "&client_secret=" . Doo::conf()->FACEBOOK['APP_SECRET'] . "&code=" . $this->params['code']);
             $userInfo = file_get_contents("https://graph.facebook.com/me?" . $app_access_token);
             if ($userInfo) {
                 $userInfo = json_decode($userInfo, true);
             }
             self::$session->user = $userInfo;
             $user = null;
             if (isset($userInfo['id']) && $userInfo['id']) {
                 $user = Doo::db()->find('User', array('where' => 'fb_user=?', 'param' => array($userInfo['id']), 'limit' => 1));
                 if (!$user) {
                     $user = new User();
                     $user->creation = date("Y-m-d h:m:s");
                 }
                 $properties = array();
                 $mapTransform = array('id' => 'fb_user');
                 $userInfo['gender'] = strtoupper($userInfo['gender'][0]);
                 foreach ($userInfo as $name => $value) {
                     if (isset($mapTransform[$name])) {
                         $name = $mapTransform[$name];
                     }
                     if (property_exists("User", $name)) {
                         $user->{$name} = $value;
                     } else {
                         $properties[$name] = $value;
                     }
                 }
                 $user->modification = date("Y-m-d h:m:s");
                 $user->active = 1;
                 if (!$user->id_user) {
                     $result = $user->insert();
                     if ($result) {
                         $user->id_user = $result;
                     }
                 } else {
                     $user->update();
                 }
                 if ($user->id_user) {
                     foreach ($properties as $name => $value) {
                         $prop = new UserProperty();
                         $prop->id_user = $user->id_user;
                         $prop->name = $name;
                         $prop->delete();
                         $prop->value = $value;
                         $prop->insert();
                     }
                     self::$session->user = $user;
                 }
             }
         }
     }
     if (self::$session->user) {
         $data['active'] = true;
         $data['user'] = array('fname' => self::$session->user->first_name, 'lname' => self::$session->user->last_name, 'timezone' => self::$session->user->timezone);
         $data['action'] = 'home';
     }
     $this->renderc($data);
 }
Пример #26
0
 public static function __callStatic($name, $args)
 {
     // Food::getById( $id );
     // Food::getById(14);
     // Food::getById(14, array('limit'=>1)) ;
     // Food::getById_location(14, 'Malaysia') ;
     // Food::getById_location(14, 'Malaysia', array('limit'=>1)) ;
     if (strpos($name, 'get') === 0) {
         if (self::$caseSensitive == false) {
             $field = strtolower(substr($name, 5));
         } else {
             $field = substr($name, 5);
         }
         // if end with _first, add 'limit'=>'first' to Option array
         if (substr($name, -7, strlen($field)) == '__first') {
             $field = str_replace('__first', '', $field);
             $first['limit'] = 1;
         }
         // underscore _ as AND in SQL
         if (strpos($field, '__') !== false) {
             $field = explode('__', $field);
         }
         $clsname = self::$className;
         $obj = new $clsname();
         if (is_string($field)) {
             $obj->{$field} = $args[0];
             //if more than the field total, it must be an option array
             if (sizeof($args) > 1) {
                 if (isset($first)) {
                     $args[1]['limit'] = 1;
                 }
                 return Doo::db()->find($obj, $args[1]);
             }
             if (isset($first)) {
                 return Doo::db()->find($obj, $first);
             }
             return Doo::db()->find($obj);
         } else {
             $i = 0;
             foreach ($field as $f) {
                 $obj->{$f} = $args[$i++];
             }
             //if more than the field total, it must be an option array
             if (sizeof($args) > $i) {
                 if (isset($first)) {
                     $args[$i]['limit'] = 1;
                 }
                 return Doo::db()->find($obj, $args[$i]);
             }
             if (isset($first)) {
                 return Doo::db()->find($obj, $first);
             }
             return Doo::db()->find($obj);
         }
     } else {
         if (strpos($name, 'relate') === 0) {
             $relatedClass = substr($name, 6);
             // if end with _first, add 'limit'=>'first' to Option array
             if (substr($name, -7, strlen($relatedClass)) == '__first') {
                 $relatedClass = str_replace('__first', '', $relatedClass);
                 $first['limit'] = 'first';
                 if (sizeof($args) === 0) {
                     $args[0] = $first;
                 } else {
                     if (is_array($args[0])) {
                         $args[0]['limit'] = 'first';
                     } else {
                         $args[1]['limit'] = 'first';
                     }
                 }
             }
             if (sizeof($args) === 0) {
                 return Doo::db()->relate(self::$className, $relatedClass);
             } else {
                 if (sizeof($args) === 1) {
                     if (is_array($args[0])) {
                         return Doo::db()->relate(self::$className, $relatedClass, $args[0]);
                     } else {
                         if (isset($first)) {
                             return Doo::db()->relate($args[0], $relatedClass, $first);
                         }
                         return Doo::db()->relate($args[0], $relatedClass);
                     }
                 } else {
                     return Doo::db()->relate($args[0], $relatedClass, $args[1]);
                 }
             }
         }
     }
 }
Пример #27
0
 public static function genPgSQL($path = null)
 {
     if ($path === null) {
         $path = Doo::conf()->SITE_PATH . Doo::conf()->PROTECTED_FOLDER . 'model/';
     }
     Doo::loadHelper('DooFile');
     $fileManager = new DooFile(0777);
     $dbconf = Doo::db()->getDefaultDbConfig();
     $dbSchema = $dbconf[6];
     $dbname = $dbconf[1];
     echo "<html><head><title>DooPHP Model Generator - DB: {$dbname}</title></head><body bgcolor=\"#2e3436\">";
     $smt = Doo::db()->query("SELECT table_name as name FROM INFORMATION_SCHEMA.tables WHERE table_schema = '{$dbSchema}'");
     $tables = $smt->fetchAll();
     foreach ($tables as $tbl) {
         $tblname = $tbl["name"];
         //tablename
         //Get table description
         $smt2 = Doo::db()->query("SELECT DISTINCT column_name AS name, data_type AS type, is_nullable AS null,\n                column_default AS default, ordinal_position AS position, character_maximum_length AS char_length,\n                character_octet_length AS oct_length FROM information_schema.columns\n                WHERE table_name = '{$tblname}' AND table_schema = '{$dbSchema}'   ORDER BY position");
         $fields = $smt2->fetchAll();
         //Get primary key
         $smt3 = Doo::db()->query("SELECT relname, indkey\n                  FROM pg_class, pg_index\n                 WHERE pg_class.oid = pg_index.indexrelid\n                   AND pg_class.oid IN (\n                    SELECT indexrelid\n                      FROM pg_index, pg_class\n                     WHERE pg_class.relname='{$tblname}'\n                       AND pg_class.oid=pg_index.indrelid\n                       AND indisprimary = 't')");
         //indkey
         $fields3 = $smt3->fetchAll();
         $smt4 = Doo::db()->query("SELECT t.relname, a.attname, a.attnum\n                     FROM pg_index c\n                LEFT JOIN pg_class t\n                       ON c.indrelid  = t.oid\n                LEFT JOIN pg_attribute a\n                       ON a.attrelid = t.oid\n                      AND a.attnum = ANY(indkey)\n                    WHERE t.relname = '{$tblname}'\n                      AND a.attnum = {$fields3[0]['indkey']}");
         $fields4 = $smt4->fetchAll();
         $pkey = $fields4[0]['attname'];
         //Prepare model class
         $classname = '';
         $temptbl = $tblname;
         for ($i = 0; $i < strlen($temptbl); $i++) {
             if ($i == 0) {
                 $classname .= strtoupper($temptbl[0]);
             } else {
                 if ($temptbl[$i] == '_' || $temptbl[$i] == '-' || $temptbl[$i] == '.') {
                     $classname .= strtoupper($temptbl[$i + 1]);
                     $arr = str_split($temptbl);
                     array_splice($arr, $i, 1);
                     $temptbl = implode('', $arr);
                 } else {
                     $classname .= $temptbl[$i];
                 }
             }
         }
         $filestr = "<?php\nclass {$classname}{\n";
         $fieldnames = array();
         foreach ($fields as $f) {
             $filestr .= "    public \${$f['name']};\n";
             $fieldnames[] = $f['name'];
         }
         $fieldnames = implode($fieldnames, "','");
         $filestr .= "    public \$_table = '{$tblname}';\n";
         $filestr .= "    public \$_primarykey = '{$pkey}';\n";
         $filestr .= "    public \$_fields = array('{$fieldnames}');\n";
         $filestr .= "}\n?>";
         if ($fileManager->create($path . "{$classname}.php", $filestr, 'w+')) {
             echo "<span style=\"font-size:190%;font-family: 'Courier New', Courier, monospace;\"><span style=\"color:#fff;\">Model for table </span><strong><span style=\"color:#e7c118;\">{$tblname}</span></strong><span style=\"color:#fff;\"> generated. File - </span><strong><span style=\"color:#729fbe;\">{$classname}</span></strong><span style=\"color:#fff;\">.php</span></span><br/><br/>";
         } else {
             echo "<span style=\"font-size:190%;font-family: 'Courier New', Courier, monospace;\"><span style=\"color:#f00;\">Model for table </span><strong><span style=\"color:#e7c118;\">{$tblname}</span></strong><span style=\"color:#f00;\"> could not be generated. File - </span><strong><span style=\"color:#729fbe;\">{$classname}</span></strong><span style=\"color:#f00;\">.php</span></span><br/><br/>";
         }
     }
     $total = sizeof($tables);
     echo "<span style=\"font-size:190%;font-family: 'Courier New', Courier, monospace;color:#fff;\">Total {$total} file(s) generated.</span></body></html>";
 }
Пример #28
0
 /**
  * Validate if value does Not Exist in database
  *
  * @param string $value Value of data to be validated
  * @param string $table Name of the table in DB
  * @param string $field Name of field you want to check
  * @return string
  */
 public function testDbNotExist($value, $table, $field, $msg = null)
 {
     $result = Doo::db()->fetchRow("SELECT COUNT({$field}) AS count FROM " . $table . ' WHERE ' . $field . ' = ? LIMIT 1', array($value));
     if (isset($result['count']) && $result['count'] > 0) {
         if ($msg !== null) {
             return $msg;
         }
         return 'Same value exists in database.';
     }
 }
Пример #29
0
 /**
  * Ending of a database profile and adds the profile result to memory
  * @param string $token This must be unique
  */
 public function endDbProfile($token)
 {
     $log = $this->_profiles[$token];
     $log[0] = "End SQL Profiling {$token}";
     $this->_logs[] = $log;
     if ($sqls = Doo::db()->showSQL()) {
         $this->_profiles[$token]['sql'] = implode("\n\r", array_slice($sqls, $this->_profiles[$token]['sqlstart']));
     } else {
         $this->_profiles[$token]['sql'] = '';
     }
     $this->_profiles[$token]['result'] = microtime(true) - $this->_profiles[$token][3];
     $this->_profiles[$token]['memory'] = $this->memory_used() - $this->_profiles[$token]['startmem'];
 }
Пример #30
0
 /**
  * Quotes a string for use in a query.
  *
  * Places quotes around the input string and escapes and single quotes within the input string, using a quoting style appropriate to the underlying driver.
  * @param string|array $string The string to be quoted. Or if an array itterate over each element and quote it
  * @param int $type Provides a data type hint for drivers that have alternate quoting styles
  * @return string Returns a quoted string that is theoretically safe to pass into an SQL statement. Returns FALSE if the driver does not support quoting in this way.
  */
 public function quote($value, $type = null)
 {
     if (is_array($value)) {
         for ($i = 0; $i < count($value); $i++) {
             $value[$i] = $this->quote($value[$i], $type);
         }
         return $value;
     } else {
         return Doo::db()->quote($value, $type);
     }
 }