Example #1
0
 public function testShouldReturnQueryInstanceWithSelect()
 {
     $query = new Query('users');
     $expected = 'Query';
     $result = $query->select(array('username', 'password'));
     $this->assertInstanceOf($expected, $result);
 }
Example #2
0
 /**
  * Get an array of models from the database.
  *
  * @param  array  $columns
  * @return array
  */
 private function _get($columns = array('*'))
 {
     if (is_null($this->query->selects)) {
         $this->query->select($columns);
     }
     return Hydrator::hydrate($this);
 }
Example #3
0
 /**
  * Возвращает очки по коду
  * 
  * @param int|null $userId - если передан код пользователя, то стсиема убедится, что очки даны этому пользователю
  * @return UserPointDO
  */
 public function getPointById($pointId, $userId = null)
 {
     $where['id_point'] = $pointId;
     if (is_inumeric($userId)) {
         $where['id_user'] = $userId;
     }
     return new UserPointDO($this->getRecEnsure(Query::select('*', 'ps_user_points', $where)));
 }
Example #4
0
 protected function doSearch(PostArrayAdapter $params)
 {
     /*
      * Параметры
      */
     $process = $params->int('process');
     $action = $params->int('action');
     $actionParent = $params->int('parent_action');
     $dateFrom = $params->int('date_from');
     $dateTo = $params->int('date_to');
     /*
      * Запрос
      */
     $what[] = 'id_rec';
     $what[] = 'concat(ifnull(id_user, ""), concat("/", id_user_authed)) as user_authed';
     $what[] = 'dt_event';
     $what[] = 'n_action';
     $what[] = 'v_data';
     $what[] = 'b_encoded';
     $where['id_process'] = $process;
     if ($actionParent) {
         $where['id_rec_parent'] = $actionParent;
     }
     if ($action) {
         $where['n_action'] = $action;
     }
     if ($dateFrom) {
         $where[] = Query::assocParam('dt_event', $dateFrom, true, '>=');
     }
     if ($dateTo) {
         $where[] = Query::assocParam('dt_event', $dateTo, true, '<=');
     }
     $order = 'dt_event asc, id_rec asc';
     $limit = 500;
     /*
      * Работа с данными
      */
     $query = Query::select($what, 'ps_audit', $where, null, $order, $limit);
     $result = PSDB::getArray($query);
     foreach ($result as &$row) {
         //Декодируем действие
         $row['n_action'] = BaseAudit::getByCode($process)->decodeAction($row['n_action'], false);
         //Декодируем данные
         $encoded = 1 * $row['b_encoded'];
         if ($encoded) {
             $row['v_data'] = print_r(BaseAudit::decodeData($row['v_data']), true);
         }
         unset($row['b_encoded']);
     }
     $results = new SearchResults($result, $query);
     $results->addSetting('v_data', SearchResults::COL_PRE);
     $results->addSetting('n_action', SearchResults::COL_NOWRAP);
     return $results;
 }
Example #5
0
function getMailCiudadanoRespuestas($id)
{
    include_once "Query.inc";
    $query = new Query();
    $registros = $query->select("mailCiudadano", "oficio", "idOficio={$id}");
    if ($registros) {
        foreach ($registros as $reg) {
            return array("mailCiudadano" => "{$reg->mailCiudadano}");
        }
    }
}
Example #6
0
 static function getElectives($program, $elective_type, $elective_group, $exclude = [])
 {
     $results = array();
     foreach (explode("|", $elective_group) as $group) {
         $q = new Query("electives");
         $q->select("course_code");
         $q->where("program_id=?\n\t\t\t\t\t\t\tAND elective_type=?\n\t\t\t\t\t\t\tAND note=?\n\t\t\t\t\t\t\tAND course_code NOT IN " . Query::valuelistsql($exclude), array_merge([$program, $elective_type, $group], $exclude));
         $results = array_merge($results, $q->executeFetchAll());
     }
     return $results;
 }
Example #7
0
 /**
  * Метод загражает карту 'код процесса' => 'код действия' => 'кол-во записей'
  * 
  * @return array
  */
 public function getProcessStatistic($dateTo)
 {
     $where = array();
     if ($dateTo) {
         $where[] = Query::assocParam('dt_event', $dateTo, true, '<=');
     }
     $result = array();
     foreach ($this->getArray(Query::select('id_process, n_action, count(1) as cnt', 'ps_audit', $where, 'id_process, n_action')) as $rec) {
         $result[$rec['id_process']][$rec['n_action']] = $rec['cnt'];
     }
     return $result;
 }
Example #8
0
 /**
  * 根据分类id获取分类名
  * @param type $id
  * @param type $level
  * @return type
  */
 public static function getCateName($id, $level = null)
 {
     $query = new Query(Yii::app()->db);
     $query->select('name');
     $query->from('groupon_cates');
     $query->andWhere('id=:id', array(':id' => $id));
     if ($level) {
         $query->andWhere('level=:level', array(':level' => $level));
     }
     $name = $query->queryScalar();
     return $name;
 }
Example #9
0
 public function getQuery()
 {
     $query = new Query(Yii::app()->db);
     $query->select('id,biz_id,name,city_id,area_id,is_reservation');
     $query->from('groupon_biz_shop');
     if ($this->biz_id) {
         $query->andWhere('biz_id=:bid', array(':bid' => $this->biz_id));
     }
     if ($this->name) {
         $query->andWhere(array('like', 'name', '%' . $this->name . '%'));
     }
     return $query;
 }
Example #10
0
 /**
  * Метод возвращает видимые пользователю объекты из базы
  */
 public function getVisibleObjects(FoldedResources $folded, $objName, array $visibleIdents)
 {
     $folded->assertWorkWithTable();
     $cacheKey = $folded->getUnique("visible-{$objName}");
     if (!$this->CACHE->has($cacheKey)) {
         $view = $folded->getTableView();
         $colIdent = $folded->getTableColumnIdent();
         $colStype = $folded->getTableColumnStype();
         $where = array();
         if ($colStype) {
             $where[$colStype] = $folded->getFoldingSubType();
         }
         $this->CACHE->set($cacheKey, $this->getArray(Query::select('*', $view, $where), null, ObjectQueryFetcher::inst($objName, $colIdent)->setIncludeKeys($visibleIdents)));
     }
     return $this->CACHE->get($cacheKey);
 }
Example #11
0
 public function process($get, $post)
 {
     $this->pageData["Title"] = "Home";
     // Select all of the courses that this user is already added or ignored
     $query = new Query('action');
     $result = $query->select('*', array(array('session_id', '=', $_COOKIE['sessionId'])));
     $idsAlreadyAdded = array();
     foreach ($result as $action) {
         array_push($idsAlreadyAdded, $action->get('course_id'));
     }
     // Generate all of the courses (for testing)
     $allCourses = array();
     $query = new Query('courses');
     $result = $query->select('*', '', array('number', 'ASC'), 20, false);
     while ($row = mysqli_fetch_array($result)) {
         try {
             $course = new Course();
             $course->findById($row['id']);
             if (!in_array($course->get('id'), $idsAlreadyAdded)) {
                 // Check that this course has not been added by the user yet
                 array_push($allCourses, array('id' => $course->get('id'), 'name' => ucwords(strtolower($course->get('name'))), 'department_id' => $course->get('department_id'), 'number' => $course->get('number'), 'description' => strlen($course->get('description')) == 0 ? 'No description' : $course->get('description')));
             }
         } catch (Exception $e) {
         }
     }
     $this->pageData['allCourses'] = $allCourses;
     // Select all of the courses that this user is already added
     $query = new Query('action');
     $result = $query->select('*', array(array('session_id', '=', $_COOKIE['sessionId']), array('choice', '=', 0)));
     $idsAlreadyAdded = array();
     foreach ($result as $action) {
         array_push($idsAlreadyAdded, $action->get('course_id'));
     }
     // Get all of the courses in this user's session
     $usersCourses = array();
     foreach ($idsAlreadyAdded as $courseId) {
         try {
             $course = new Course();
             $course->findById($courseId);
             array_push($usersCourses, array('id' => $course->get('id'), 'name' => ucwords(strtolower($course->get('name'))), 'department_id' => $course->get('department_id'), 'number' => $course->get('number')));
         } catch (Exception $e) {
         }
     }
     $this->pageData['usersCourses'] = $usersCourses;
 }
 /**
  * js(on)entity returns an json object for the select2 widget
  * @param  string $search Text for the lookup
  * @param  integer of the set value
  * @return json    [description]
  */
 public function actionJsentity($search = NULL, $id = NULL)
 {
     header('Content-type: application/json');
     $clean['more'] = false;
     $query = new Query();
     if (!is_Null($search)) {
         $mainQuery = $query->select('id, name AS text')->from('{{%entity}}')->where('UPPER(name) LIKE "%' . strtoupper($search) . '%"');
         $command = $mainQuery->createCommand();
         $rows = $command->queryAll();
         $clean['results'] = array_values($rows);
     } else {
         if (!is_null($id)) {
             $clean['results'] = ['id' => $id, 'text' => Entity::findOne($id)->name];
         } else {
             $clean['results'] = ['id' => 0, 'text' => 'None found'];
         }
     }
     echo Json::encode($clean);
     exit;
 }
Example #13
0
 public function process($get, $post)
 {
     if (!isset($post['course_id']) || !is_numeric($post['course_id']) || !isset($_COOKIE['sessionId']) || !is_numeric($_COOKIE['sessionId'])) {
         $this->failureReason = 'Sorry, there was an error.';
         return false;
     }
     $query = new Query('action');
     // Select all the courses that are in this user's session and have this course id
     $result = $query->select('*', array(array('course_id', '=', $post['course_id']), array('session_id', '=', $_COOKIE['sessionId'])), '', 1);
     if (count($result) != 0) {
         // Abort because this course is already in the user's model
         $this->failureReason = 'Sorry, there was an error';
         return false;
     }
     // Now add this course to the user's model
     $action = new Action();
     $action->set('course_id', $post['course_id']);
     $action->set('session_id', $_COOKIE['sessionId']);
     $action->save();
     return true;
 }
Example #14
0
 public function process($get, $post)
 {
     // Select all of the courses that this user is already added
     $query = new Query('action');
     $result = $query->select('*', array(array('session_id', '=', $_COOKIE['sessionId'])));
     $idsAlreadyAdded = array();
     foreach ($result as $action) {
         array_push($idsAlreadyAdded, $action->get('course_id'));
     }
     // Select all the courses where the query string is a sub-string of the name or id
     $query = new Query('courses');
     $result = $query->select('*', array(array('name', 'LIKE', '%' . $post['q'] . '%'), 'OR', array('number', 'LIKE', '%' . $post['q'] . '%')), array('number', 'ASC'), 100);
     $courses = array();
     foreach ($result as $course) {
         if (!in_array($course->get('id'), $idsAlreadyAdded)) {
             // Check that this course has not been added by the user yet
             array_push($courses, array('id' => $course->get('id'), 'name' => ucwords(strtolower($course->get('name'))), 'department_id' => $course->get('department_id'), 'number' => $course->get('number'), 'description' => strlen($course->get('description')) == 0 ? 'No description' : $course->get('description')));
         }
     }
     $this->pageData['courseResults'] = $courses;
     return true;
 }
Example #15
0
 /**
  * 获取子市区的键值对列表
  * @param int/null $pid 父ID
  * @param int $grade 等级
  * @return array
  */
 public static function getAreas($pid = null, $grade = self::GRADE_PROVINCE)
 {
     $key = 'arealist_' . $grade . '_' . $pid;
     $areas = Yii::app()->cache->get($key);
     //        dump($areas);
     if ($areas === false) {
         $query = new Query(Yii::app()->db);
         $query->select('id,name');
         $query->from('area');
         if ($pid == null) {
             $query->andWhere('parent_id is null');
         } else {
             $query->andWhere('parent_id=:pid', array(':pid' => $pid));
         }
         $areas = $query->queryAll();
         if (!empty($areas)) {
             $areas = A::map($areas, 'id', 'name');
         }
         Yii::app()->cache->set($key, $areas, 60 * 60 * 24);
     }
     //        dump($areas);
     return $areas;
 }
Example #16
0
 function _upload_db($old, $to, $path, $size, $type)
 {
     $data = file_get_contents($old);
     $uniqid = md5($data);
     $query = new Query();
     $query->select('id,path')->from('file')->where(array('uniqid' => $uniqid));
     $command = $query->createCommand();
     $row = $command->queryRow();
     if (!$row) {
         copy($old, $to);
         $data = array('path' => $path, 'uniqid' => $uniqid, 'size' => $size, 'type' => $type, 'uid' => $this->uid, 'created' => time(), 'admin' => $this->admin);
         \Yii::$app->db->createCommand()->insert('file', $data)->execute();
     } else {
         if (!file_exists(root_path() . $row['path'])) {
             copy($old, root_path() . $row['path']);
         }
     }
     $query = new Query();
     $query->select('id,path,type')->from('file')->where(array('uniqid' => $uniqid));
     $command = $query->createCommand();
     $row = $command->queryRow();
     @unlink($old);
     return $row;
 }
Example #17
0
 function p_items()
 {
     $list = array();
     while (1) {
         if ($this->lat[0] == 'item') {
             $this->lex();
             if ($this->lat[0] != 'WORD') {
                 return $this->unexpectedToken('WORD');
             }
             $value = $this->lat[1];
             $this->lex();
             $params = $this->p_params();
             if (is_a($params, 'Error')) {
                 return $params;
             }
             array_push($list, array($value, $params));
         } else {
             if ($this->lat[0] == 'sql') {
                 $this->lex();
                 if ($this->lat[0] != 'SQLCODE') {
                     return $this->unexpectedToken('SQLCODE');
                 }
                 $sql = $this->lat[1];
                 $this->lex();
                 while ($this->lat[0] == 'SQLCODE') {
                     $sql .= ' ' . $this->lat[1];
                     $this->lex();
                 }
                 $result = $this->p_end();
                 if (is_a($result, 'Error')) {
                     return $result;
                 }
                 $q = new Query();
                 $r = $q->select($sql);
                 while ($row = $r->next()) {
                     array_push($list, array($row['value'], $row));
                 }
             } else {
                 break;
             }
         }
     }
     return $list;
 }
Example #18
0
<?php

require_once 'config.php';
require_once 'functions.php';
require_once '../common/db.php';
try {
    // Database connection first.
    $db = new CompactDB($mt_dbhost, $mt_dbname, $mt_dbuser, $mt_dbpass);
    $q = new Query($db);
    $chunks = $q->select('id,content')->from('track')->where("processed=0")->run();
    // Required objects and set up
    $c = new Canvas(thisURL());
    $c->common->addScriptRef(APP_URL . 'files/jquery.js');
    $c->common->addScriptRef(APP_URL . 'files/jquery-effects.js');
    switch ($c->getMode()) {
        /* --------------------------------------------------------------------------------------------------------- */
        case 'show':
        default:
            // We create the toolbar
            $t = new Toolbar();
            $c->register($t);
            // If there are chunks to process, we display a button.
            if (count($chunks) > 0) {
                $t->addAction('Process ' . count($chunks) . ' tracks', "doConfirm('This action may take a long time and make the browser\\nto timeout. Are you sure you want to do this?','process')", 'go-jump');
            }
            // We retrieve all the tracks we have stored in a pretty table.
            $mtrx = $db->qSelect("select t.id, t.name, t.pid, from_unixtime(t.offset/1000) as t_start, round(max(e.t)/1000,1) as t_duration " . "from track as t, event as e where t.id=e.track_id and t.processed=1 group by e.track_id;");
            $tab = new Table($mtrx);
            $tab->setProperty('highlight', true);
            $tab->setProperty('numbering', true);
            $tab->setProperty('id', 'id');
Example #19
0
    public function ajax()
    {
        $w = new Word();
        $w->get(1, 1000);
    }
    public function queryById($id)
    {
        $s_id = (int) $id;
        $w = new Word();
        echo $w->queryById($s_id);
    }
    public function select()
    {
        $w = new Word();
        $rows = $w->selectLatest(100);
        //        foreach($rows as $key=>$val) {
        //            echo $val["w_desc"]."<hr>";
        //        }
        echo json_encode($rows);
    }
}
set_time_limit(0);
$q = new Query();
if (isset($_GET["id"])) {
    $q->queryById($_GET['id']);
} else {
    if (isset($_GET['select'])) {
        //$q->ajax();
        $q->select();
    }
}
Example #20
0
 /**
  * checkUserInDB()
  * Builds select query to check user in DB and returns result as an array
  *
  * @return array|false
  */
 private function checkUserInDB()
 {
     $query = new Query();
     $query->select()->from($this->table)->where($this->identityColumn . " = ?", $this->identity)->andWhere($this->credentialColumn . " = ?", $this->credential)->limit(1);
     return $this->dbAdapter->fetchRow($query);
 }
Example #21
0
<?php

include "sources/funciones.php";
if ($_SESSION["Activa"] and $_SESSION["Tipo_usuario"] == "administrador" and $_REQUEST) {
    $propietario = __($_REQUEST['propietario']);
    require "sources/Query.inc";
    $query = new Query();
    if ($query->select("propietario", "redaccion", "propietario='{$propietario}'")) {
        echo "<font style=' color: #CC0000'>El Propietario ya existe, intente nuevamente</font>";
    }
} else {
    redireccionar();
}
Example #22
0
<?php

include "sources/funciones.php";
if ($_SESSION["Activa"] and $_SESSION["Tipo_usuario"] == "administrador" and $_REQUEST) {
    $mail = __($_REQUEST['mail']);
    require "sources/Query.inc";
    $query = new Query();
    if ($query->select("correo", "revisor", "correo='{$mail}'")) {
        echo "<font style=' color: #CC0000'>El correo electrónico ya existe, intente nuevamente</font>";
    }
} else {
    redireccionar();
}
Example #23
0
function siExiste($campo, $tabla, $email)
{
    include_once "./conf/query.inc";
    $queryExiste = new Query();
    $valores = $queryExiste->select($campo, $tabla, $email);
    if ($valores) {
        foreach ($valores as $valor) {
            return TRUE;
        }
    }
    return FALSE;
}
 public function index()
 {
     require ROOT . '/Query.php';
     echo \Query::select('id', 'titre', 'contenu')->from('articles')->where('id = 1')->where('article.category_id = 1')->where('article.date > NOW()');
 }
Example #25
0
<?php

include "sources/funciones.php";
if ($_SESSION["Activa"] and $_SESSION["Tipo_usuario"] = "normal" and $_REQUEST) {
    $nOficio = strtolower($_REQUEST['nOficio']);
    if ($nOficio) {
        require "sources/Query.inc";
        $query = new Query();
        $regCupo = $query->select("idOficio idOficio,noOficio nOficio,asunto asunto,fecha fecha, status status", "oficio", "noOficio={$nOficio} and status=2");
        $regCupo2 = $query->select("idOficio idOficio,noOficio nOficio,status status", "oficio", "noOficio={$nOficio} and status=3");
        if ($regCupo) {
            echo "<table class='table table-condensed'>";
            echo "<thead>";
            echo "<tr>";
            echo "<th>N° de Oficio</th>";
            echo "<th>Asunto</th>";
            echo "<th>Fecha</th>";
            echo "<th style='text-align:center'>Generar Respuesta</th>";
            echo "</tr>";
            echo "</thead>";
            echo "<tbody>";
            foreach ($regCupo as $regC) {
                $fechaFormato = $regC->fecha;
                $meses = array("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
                echo "<tr>";
                echo "<td>{$regC->nOficio}</td>";
                echo "<td>{$regC->asunto}</td>";
                echo "<td>" . date('d', strtotime($fechaFormato)) . " de " . $meses[date('n', strtotime($fechaFormato)) - 1] . " de " . date('Y', strtotime($fechaFormato)) . "</td>";
                ?>
<td style="text-align:center"><a href='generarRespuesta.php?idOficio=<?php 
                echo $regC->idOficio;
Example #26
0
 public function actionAutocomplete($search = null, $id = null, $object_id = null)
 {
     /**
      * @todo Добавить отображение вложенности
      */
     $out = ['more' => false];
     if (!is_null($search)) {
         $query = new Query();
         $query->select(Property::tableName() . '.id, ' . Property::tableName() . '.name AS text')->from(Property::tableName())->andWhere(['like', Property::tableName() . '.name', $search])->limit(100);
         if (!is_null($object_id)) {
             $query->leftJoin(PropertyGroup::tableName(), PropertyGroup::tableName() . '.id = ' . Property::tableName() . '.property_group_id');
             $query->andWhere([PropertyGroup::tableName() . '.id' => $object_id]);
         }
         $command = $query->createCommand();
         $data = $command->queryAll();
         $out['results'] = array_values($data);
     } elseif ($id > 0) {
         $out['results'] = ['id' => $id, 'text' => Property::findOne($id)->name];
     } else {
         $out['results'] = ['id' => 0, 'text' => Yii::t('app', 'No matching records found')];
     }
     echo Json::encode($out);
 }
Example #27
0
 /**
  * Get release with Asociated Artist
  * Show Action
  * 
  * @param  Query $query
  * @param  string $permalink
  * @return Query
  */
 public function scopeReleaseDetails($query, $permalink)
 {
     $query->where(['permalink' => $permalink, 'active' => true])->with(['artist' => function ($query) {
         $query->select('id', 'name', 'permalink');
     }])->with(['tags' => function ($query) {
         $query->select('id', 'name', 'permalink');
     }]);
 }
Example #28
0
function getRevisorRobertScriptCase()
{
    include_once "Query.inc";
    $query = new Query();
    $regConsulta = $query->select("idRevisor", "revisor", "1");
    if ($regConsulta) {
        foreach ($regConsulta as $regC) {
            echo "case '{$regC->idRevisor}':\r\n                                \$('#Rev" . $regC->idRevisor . "').show();" . "break;";
        }
    }
}
Example #29
0
 * @param {optional} program - The name of the program to return
 *
 * @return An XML response containing programs that matched the search
 *
 * @example programs.php - This would return all of the programs
 * @example programs.php?program=Software - This would return all programs with a name like software
 */
if ($_SERVER['REQUEST_METHOD'] != 'GET') {
    http_response_code(405);
    echo '{"e":1, "msg":"Method must be GET."}';
    exit;
}
require_once 'lib/db.php';
$has_param = in_array('program', $_GET);
$q = new Query("programs");
$q->select("id");
$q->select("year");
$q->select("name");
if ($has_param) {
    $q->where('name LIKE ?', [$_GET['program']]);
}
$rows = $q->executeFetchAll();
$response = '<response e="0">';
foreach ($rows as $program) {
    $response .= '<program>';
    $response .= "<id>{$program['0']}</id>";
    $response .= "<year>{$program['1']}</year>";
    $response .= "<name>{$program['2']}</name>";
    $response .= '</program>';
}
$response .= '</response>';
Example #30
0
<?php
include("sources/funciones.php");
if ($_POST) {
    $usu = __(strtolower($_POST["usu"]));
    $pass = __($_POST["pass"]);
    $passEncriptado = sha1($pass);

    require("sources/Query.inc");
    $query = new Query();

    $login = $query->select("idLogin, usuario, password, tipoUsu", "login", "usuario='$usu' and password='******'");
    if ($login) {
        foreach ($login as $l) {
            switch ($l->tipoUsu) {
                case 2:
                    $_SESSION["Activa"] = true;
                    $_SESSION["ID"] = $l->idLogin;
                    $_SESSION["Usuario"] = $l->usuario;
                    $_SESSION["Tipo_usuario"] = "normal";
                    break;
                case 3:
                    $_SESSION["Activa"] = true;
                    $_SESSION["ID"] = $l->idLogin;
                    $_SESSION["Usuario"] = $l->usuario;
                    $_SESSION["Tipo_usuario"] = "administrador";
                    break;
            }
        }

        $respuesta = '
                    <img src="images/ok.png" width="100">