Obtém a Conexão e a Syntax, executa a query!
519451
private function execute()
    {
        $this->connect();
        try {
            $this->getSyntax();
            $this->read->execute();
            $this->result = $this->read->fetchAll();

        } catch (\PDOException $e) {
            $this->result = null;
            $this->erro = "<b>Erro ao Ler: ({$this->tabela})</b> {$e->getMessage()}";
        }

        parent::setDefault();
    }
1265011
function Input(server) {
  // Konstruktorin sisältöä ei dokumentoida
  /**#nocode+*/

  var self = this
    , rli = readline.createInterface(process.stdin, process.stdout, function (partial) {
      return [server.commands.suggest(partial), partial];
    });

  process.stdin.resume();
  process.stdin.setEncoding('utf8');

  if (process.platform !== "win32") {
    process.on('SIGINT', function processSIGINT() {
      log.notice('Received ' + 'SIGINT'.red);
      // Lakataan kuuntelemasta stdin-syötettä.
      // Node sulkeutuu jahka kaikki eventit on kutsuttu, eikä uusia ole lisätty event-luuppiin.
      process.stdin.destroy();
      server.close();
    });
  }

  rli.on('close', function rliClose() {
    process.stdin.destroy();
    server.close();
  });

  rli.on('line', function rliLine(input){
    var msg = input.trim();
    if (!msg) { return; }
    // Käsitellään serverikomennot
    server.commands.call(msg.split(' ')[0], splitString(msg).splice(1));
  });

  // Tästä eteenpäin dokumentoidaan taas jos on jotain dokumentoitavaa
  /**#nocode-*/
}
1238468
public function query()
    {
        if ($this->fixtureOfflineModeEnabled()) {
            // Ignore query
            return null;
        }

        if ($this->usesFixtures() && $this->showFixtureWarnings) {
            echo 'WARNING: query() does not work with fixtures - please use other SQL methods';
        }

        return call_user_func_array(array('parent', 'query'), func_get_args());
    }
316256
public function msisdnDetect()
    {
        try {
            $currentConnectIp = $this->getCurrentConnectIp();
            $this->logger->debug(__FUNCTION__, 'getCurrentConnectIp: ' . $currentConnectIp);
            $mobileDetect = new MobileDetect();
            if ($mobileDetect->isMobile() || $mobileDetect->isTablet()) {
                $currentSessionIp = $this->getUserIpInSession();
                $currentTelco     = $this->getTelcos();
                $currentTelcoId   = $currentTelco['telco_id'];
                $this->logger->debug(__FUNCTION__, 'getUserIpInSession: ' . $currentSessionIp);
                $this->logger->debug(__FUNCTION__, 'currentTelco: ' . json_encode($currentTelco));
                $this->logger->debug(__FUNCTION__, 'currentTelcoId: ' . $currentTelcoId);
                /**
                 * Nhận diện thuê bao
                 * Logic u mê vãi :))
                 */
                if (// Nếu như người dùng thay đổi ip và đã nhận diện nhà mạng
                    (($currentConnectIp != $currentSessionIp) && ($currentTelcoId != 0) && ($this->getDetectChannelInSession() === NULL || strtoupper($this->getDetectChannelInSession()) != self::CHANNEL_IS_LOGIN)) ||
                    // Hoặc Nếu như người dùng là khách & check ip ra nhà mạng
                    ($this->getMsisdnInSession() !== NULL && $this->getMsisdnInSession() == 'GUEST' && $currentTelcoId != 0 && ($this->getDetectChannelInSession() === NULL || strtoupper($this->getDetectChannelInSession()) != self::CHANNEL_IS_LOGIN)) ||
                    // Hoặc Nếu chưa nhận diện nhà mạng mà check ip ra nhà mạng
                    ($this->msisdnHasDetect() !== NULL && $this->msisdnHasDetect() == FALSE && $currentTelcoId != 0 && ($this->getDetectChannelInSession() === NULL || strtoupper($this->getDetectChannelInSession()) != self::CHANNEL_IS_LOGIN))
                ) {
                    /**
                     * Trường hợp cần nhận diện thuê bao
                     * Xử lý lưu session và callback trong thư viện MSISDN
                     */
                    $msisdn = $this->getMsisdn();
                    // Chỗ này cần xử lý Redirect nà
                    if (isset($this->objectSession) && $this->objectSession != NULL && is_object($this->objectSession)) {
                        $this->logger->info(__FUNCTION__, 'Session with CI Session Class');
                        $link_redirect = ($this->objectSession->has_userdata('link_redirect_affer_detect') ? $this->objectSession->userdata('link_redirect_affer_detect') : '');
                    } else {
                        $this->logger->info(__FUNCTION__, 'Session with The Http Foundation Component');
                        $link_redirect = ($this->session->has('link_redirect_affer_detect') ? $this->session->get('link_redirect_affer_detect') : '');
                    }
                    $this->logger->debug(__FUNCTION__, 'Link Redirect: ' . $link_redirect);
                    if (isset($this->objectSession) && $this->objectSession != NULL && is_object($this->objectSession)) {
                        $this->logger->info(__FUNCTION__, 'Session with CI Session Class');
                        if (!$this->objectSession->has_userdata(self::SESSION_ID_LINK_REDIRECT_MSISDN_DETECT)) {
                            $this->objectSession->set_userdata(self::SESSION_ID_LINK_REDIRECT_MSISDN_DETECT, self::SESSION_VALUE_LINK_REDIRECT_MSISDN_DETECT);
                            Utils::redirect($link_redirect);
                        }
                    } else {
                        $this->logger->info(__FUNCTION__, 'Session with The Http Foundation Component');
                        if (!$this->session->has(self::SESSION_ID_LINK_REDIRECT_MSISDN_DETECT)) {
                            $this->session->set(self::SESSION_ID_LINK_REDIRECT_MSISDN_DETECT, self::SESSION_VALUE_LINK_REDIRECT_MSISDN_DETECT);
                            Utils::redirect($link_redirect);
                        }
                    }

                    return $msisdn;
                }
            } else {
                $this->logger->warning(__FUNCTION__, 'Device is not Mobile or Tablet');

                return NULL;
            }
        }
        catch (\Exception $e) {
            $message = 'Error File: ' . $e->getFile() . ' - Line: ' . $e->getLine() . ' - Code: ' . $e->getCode() . ' - Message: ' . $e->getMessage();
            $this->logger->error(__FUNCTION__, $message);

            return FALSE;
        }

        return NULL;
    }
873150
function map($view_content, $view_params = array())
	{
		// trova tutte le regole racchiuse tra doppie graffe
		$rules = ViewUtility::find_rules($view_content, '{{', '}}');

        foreach ($rules as $rule) 
        {
        	// estrapola la parte di codice racchiusa
            $rule_code = str_replace('{{', '', $rule);
            $rule_code = str_replace('}}', '', $rule_code);
            $rule_code = trim($rule_code);
			$rule_code = trim($rule_code, ';');

			// memorizza qui l'esito dell'elaborazione
			$rule_code_value = null;

			// se è una sola parola
			// presumibilmente è una variabile
			// in tal caso, esegui la stampa del valore
			if(strpos($rule_code, '$') === 0)
			{
				// cerca tra i parametri della vista
				if ($rule_code_value == null)
				{
					$rule_code_variable = ltrim($rule_code, '$');
					foreach ($view_params as $param_key => $param_value) 
					{
						if($param_key == $rule_code_variable)
						{
							$rule_code_value = $param_value;
							break;
						}
					}
				}
			}
			else
			{
				// si tratta di una funzione presumibilmente
				$rule_code_value = eval("$rule_code;");
				if($rule_code_value == null)
				{
					// it is a void function
					$rule_code_value = eval("return $rule_code;");
				}
			}

            $view_content = str_replace($rule, $rule_code_value, $view_content);
        }
        return $view_content;

	}
433597
public function create($name, $module, $dir, $author, $email)
    {
        $fs = new Filesystem();

        if (!$this->jsDir) {
            throw new \Exception('O diretório de código javascript "injector.directory.src" da aplicação não foi definido!');
        }

        $moduleDir = $this->getModuleDir($dir);

        if (!$fs->exists($moduleDir)) {
            throw new \Exception(sprintf('O módulo %s não existe!', $module));
        }

        $serviceFile = $this->getServiceFile($name, $moduleDir);

        if ($fs->exists($serviceFile)) {
            throw new \Exception(sprintf('O serviço %s já existe!', $name));
        }

        $this->createService($name, $serviceFile, $module, $author, $email);
    }
1166232
def ConsultarRemito(self, cod_remito=None, id_req=None,
                        tipo_comprobante=None, punto_emision=None, nro_comprobante=None):
        ""
        print(self.client.help("consultarRemito"))
        response = self.client.consultarRemito(
                                authRequest={'token': self.Token, 'sign': self.Sign, 'cuitRepresentada': self.Cuit},
                                codRemito=cod_remito,
                                idReq=id_req,
                                tipoComprobante=tipo_comprobante,
                                puntoEmision=punto_emision,
                                nroComprobante=nro_comprobante)
        ret = response.get("consultarRemitoReturn", {})
        id_req = ret.get("idReq", 0)
        self.remito = rec = ret.get("remito", {})
        self.__analizar_errores(ret)
        self.__analizar_observaciones(ret)
        self.__analizar_evento(ret)
        self.AnalizarRemito(rec)
        return id_req
1023237
def _get_notification(self, email, token):
        '''  '''        
        url = u'{notification_url}{notification_code}?email={email}&token={token}'.format(
            notification_url=self.notification_url,
            notification_code=self.notification_code,
            email=email,
            token=token)
        req = requests.get(url)
        if req.status_code == 200:
            self.xml = req.text
            logger.debug( u'XML com informacoes da transacao recebido: {0}'.format(self.xml) )
            transaction_dict = xmltodict.parse(self.xml)
            # Validar informações recebidas
            transaction_schema(transaction_dict)
            self.transaction = transaction_dict.get('transaction')
        else:
            raise PagSeguroApiException(
                        u'Erro ao fazer request para a API de notificacao:' + 
                        ' HTTP Status=%s - Response: %s' % (req.status_code, req.text))
1333940
def quadro?(node)
      # Texto original: 
      # Quadro perfil: Perfil dos voluntários do experimento
      #
      # Depois do parse:
      #
      # {"t"=>"Para","c"=>[{"t"=>"Str","c"=>"Quadro"},{"t"=>"Space"},{"t"=>"Str","c"=>"perfil:"},{"t"=>"Space"},{"t"=>"Str","c"=>"Perfil"},{"t"=>"Space"},{"t"=>"Str","c"=>"dos"},{"t"=>"Space"},{"t"=>"Str","c"=>"voluntários"},{"t"=>"Space"},{"t"=>"Str","c"=>"do"},{"t"=>"Space"},{"t"=>"Str","c"=>"experimento"}]}
      para = node["c"]
      
      node["t"] == "Para" and node["c"].length>=5 and string_contendo?("Quadro",para[0]) and space?(para[1]) and quadro_id?(para[2]) and space?(para[3]) and string?(para[4])
    end
676239
public function getConnection()
    {
        // Autre BDD que celle par defaut. soit avec un autre connector de la config, ou avec autre ID de connexion de la config
        if ($this->dbConnector !== null || count($this->idConnection) > 0) {
            $dbConnector = ($this->dbConnector !== null) ? $this->dbConnector : Config::get()['connection'];
            $connector = 'DawPhpOrm\Database\Connectors\\'.ucfirst($dbConnector).'Connector';

            $db = new $connector($this->idConnection);
            
            return $db->getConnection();
        }

        // BDD par defaut avec connector de config et avec ID de config
        if (self::$connection === null) {
            $connector = 'DawPhpOrm\Database\Connectors\\'.ucfirst(Config::get()['connection']).'Connector';

            $db = new $connector();
            self::$connection = $db->getConnection();
        }

        return self::$connection;
    }
373411
static function download($reqst = '')
    {
        //checando a existencia do arquivo solicitado
        $reqst = static::fileExists($reqst);
        if($reqst == false) return false;

        //gerando header apropriado
        include static::$config.'mimetypes.php';
        $ext = end((explode('.', $reqst)));
        if (!isset($_mimes[$ext])) $mime = 'text/plain';
        else $mime = (is_array($_mimes[$ext])) ? $_mimes[$ext][0] : $_mimes[$ext];

        //get file
        $dt = file_get_contents($reqst);

        //download
        ob_end_clean();
        ob_start('ob_gzhandler');

        header('Vary: Accept-Language, Accept-Encoding');
        header('Content-Type: ' . $mime);
        header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 31536000) . ' GMT');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($reqst)) . ' GMT');
        header('Cache-Control: must_revalidate, public, max-age=31536000');
        header('Content-Length: ' . strlen($dt));
        header('Content-Disposition: attachment; filename='.basename($reqst)); 
        header('ETAG: '.md5($reqst));
        exit($dt);
    }
385341
function makeQuery()
    {
        $query = array();
        foreach($this->query as $paramater) {
            $operator = ($paramater[1] != '=') ? $paramater[1] : '' ;
            $query[$paramater[0] . $operator] = $paramater[2];
        }
        return $query;
    }
435530
public function ajouter()
    {
        $authentifie = new archiAuthentification();
        $formulaire = new formGenerator();
        if ($authentifie->estConnecte()) {
            $tabForm=$this->getAdresseFields();
            $this->connexionBdd->getLock(array('historiqueAdresse'));
            $errors = $formulaire->getArrayFromPost($tabForm); // recupere les donnees POST suivant les champs de tabForm , tabForm est passé en référence, il contient donc les valeurs des champs a la sortie de la fonction
            $this->nettoieCoordonneesAdresse($tabForm); // permet de garder l'id de la rue, quartier, sousQuartier le plus bas dans la hierarchie , a partir duquel on peut retrouver le reste

            if (count($errors)==0) {
            // on regarde si l'adresse existe deja parmis les adresses valides (non "archivees")
                $sql = "SELECT ha1.idAdresse as idAdresse
						FROM historiqueAdresse ha1, historiqueAdresse ha2
						WHERE ha2.idAdresse = ha1.idAdresse
						AND ha1.idRue='".$tabForm['rue']['value']."'
								AND ha1.idSousQuartier='".$tabForm['sousQuartier']['value']."'
										AND ha1.idQuartier='".$tabForm['quartier']['value']."'
												AND ha1.idVille='".$tabForm['ville']['value']."'
														AND ha1.idPays='".$tabForm['pays']['value']."'
																AND ha1.numero = '".$tabForm['numero']['value']."'
																		AND ha1.date='".$tabForm['date']['value']."'
																				AND ha1.idIndicatif='".$tabForm['indicatif']['value']."'
																						GROUP BY ha1.idAdresse, ha1.idHistoriqueAdresse
																						HAVING ha1.idHistoriqueAdresse = max(ha2.idHistoriqueAdresse)";

                //debug($sql);

                $resCheckExist=$this->connexionBdd->requete($sql);

                if (mysql_num_rows($resCheckExist)>1) {
                    echo "plusieurs adresse existe concernant cette adresse, pas d'ajout, veuillez prevenir l'administrateur.<br>";
                } elseif (mysql_num_rows($resCheckExist)==1) {
                    echo "l'adresse existe deja dans la base";
                    // recuperation de l'id existant
                    $fetchAdresseExistante=mysql_fetch_array($resCheckExist);
                } else {
                    // ajout
                    // recherche du nouvel idAdresse
                    $resIdAdresse = $this->connexionBdd->requete("select max(idAdresse) as maxIdAdresse from historiqueAdresse");
                    $nouvelIdAdresse=0;
                    if (mysql_num_rows($resIdAdresse)>0) {
                        $fetchNouvelIdAdresse = mysql_fetch_array($resIdAdresse);
                        $nouvelIdAdresse = $fetchNouvelIdAdresse["maxIdAdresse"] + 1;
                    }

                    $sql = "INSERT INTO historiqueAdresse (idUtilisateur,idAdresse,date,description,nom,idRue,numero,idQuartier,idSousQuartier,idPays,idVille) VALUES (
							'".$authentifie->getIdUtilisateur()."',
							'".$nouvelIdAdresse."',
							\"".$this->date->toBdd($tabForm['date']['value'])."\",
							\"".$tabForm['description']['value']."\",
							\"".$tabForm['nom']['value']."\",
							'".$tabForm['rue']['value']."',
							'".$tabForm['numero']['value']."',
							'".$tabForm['quartier']['value']."',
							'".$tabForm['sousQuartier']['value']."',
							'".$tabForm['pays']['value']."',
							'".$tabForm['ville']['value']."'
							)";

                    $this->connexionBdd->requete($sql);

                    $cache = new cacheObject();
                    $cache->refreshCache();
                }
            } else {
                echo $this->afficheFormulaire($tabForm);
            }




            $this->connexionBdd->freeLock(array('historiqueAdresse'));
        } else {
            echo "erreur : Vous devez etre authentifié pour faire un ajout<br>";
        }
    }
350929
private function execute()
    {
        $this->connect();
        try {
            $this->create->execute($this->dados);
            $this->result = $this->conn->lastInsertId();
        } catch (\PDOException $e) {
            $this->result = null;
            $this->erro = "<b>Erro ao cadastrar: ({$this->tabela})</b> {$e->getMessage()}";
        }

        parent::setDefault();
    }
1233537
public function withNotNull()
    {
        /**
         * @var PropertyContract[] $propertiesWithNotNull
         */
        $propertiesWithNotNull = $this::$schema->getPropertiesWithNotNullConstraint();
        if (!$propertiesWithNotNull) {
            return $this;
        }

        foreach ($propertiesWithNotNull as $property) {
            if (is_null($this->{$property->getProperty()})) {
                throw new Exception("Propriedade obrigatória não pode ser nula [ " . $property->getAlias() . " ]", 400);
            }
        }

        return $this;
    }
580142
public function index() {
		$this->Prg->commonProcess();
        $conds = $this->Cliente->parseCriteria( $this->Prg->parsedParams() );
		$this->Cliente->recursive = 0;
                
        $descuentoMaximo = Configure::read('Mozo.descuento_maximo');
        $currentRole = $this->Session->read('Auth.User.role');
             
        
        if ( strtolower($currentRole) == 'mozo' && is_numeric( $descuentoMaximo ) ) {                
            $conds['OR'] = array(
                    "Descuento.porcentaje <= $descuentoMaximo",
                    'Descuento.porcentaje IS NULL'
                );
        }
        $this->Paginator->settings['conditions'] = $conds;
        
        $descuentos = $this->Cliente->Descuento->find('list');
		$tipoDocumentos = $this->Cliente->TipoDocumento->find('list');
		$ivaResponsabilidades = $this->Cliente->IvaResponsabilidad->find('list');
		$this->set(compact('descuentos', 'tipoDocumentos', 'ivaResponsabilidades'));
		$this->set('clientes', $this->Paginator->paginate());
		$this->set('_serialize', array('clientes'));
	}
806140
public function getQuery(): Query
    {
    	// TODO: Bindings could be defined only locally in this method because it has to be regenerated on every call

        if (count($this->from) == 0) {
            throw new Exception('Can not build SELECT query, there is no FROM table defined');
        }

        $query = "SELECT\n";

        if (sizeof($this->fields) == 0) {
            $query .= "\t*";
        } else {
            foreach ($this->fields as $fld) {
                $field = $fld['name'];
                $as = $fld['as'];

                $query .= "\t{$field}";
                if ($as !== null) {
                    $query .= " as {$as}";
                }

                $query .= ",\n";
            }

            $query = substr($query, 0, -2);
        }

        $query .= "\nFROM";
        foreach ($this->from as $from) {
            if ($from['table'] instanceof static) {
                /* @var $subSelect \Koldy\Db\Query\Select */
                $subSelect = $from['table'];
                $subSql = $subSelect->__toString();
                $subSql = str_replace("\n", "\n\t", $subSql);
                $query .= " (\n\t{$subSql}\n) {$from['alias']}\n";

                $subSelectBindings = $subSelect->getBindings();
                if (!$subSelectBindings->isEmpty()) {
                    $this->getBindings()->addBindingsFromInstance($subSelectBindings);
                }
            } else {
                $query .= "\n\t{$from['table']}";
                if ($from['alias'] !== null) {
                    $query .= " as {$from['alias']},";
                } else {
                    $query .= ',';
                }
            }
        }
        $query = substr($query, 0, -1);

        foreach ($this->joins as $join) {
            $query .= "\n\t{$join['type']} {$join['table']} ON ";

            if (is_array($join['first'])) {
                foreach ($join['first'] as $joinArg) {
                    if ($joinArg instanceof Expr) {
                        $query .= "{$joinArg} AND ";

                    } else if (is_array($joinArg) && count($joinArg) == 2) {
                        $query .= "{$joinArg[0]} = {$joinArg[1]} AND ";

                    } else if (is_array($joinArg) && count($joinArg) == 3) {
                        $query .= "{$joinArg[0]} {$joinArg[1]} {$joinArg[2]} AND ";

                    } else if (is_array($joinArg) && count($joinArg) == 4) {
                        if (substr($query, -5) == ' AND ') {
                            $query = substr($query, 0, -5);
                        }

                        $query .= " {$joinArg[0]} {$joinArg[1]} {$joinArg[2]} {$joinArg[3]} AND ";

                    } else {
                        throw new Exception('Unknown JOIN argument');

                    }
                }

                $query = substr($query, 0, -5);
            } else {
                if ($join['operator'] === null) {
                    throw new Exception('Operator can\'t be null');
                }

                if ($join['second'] === null) {
                    throw new Exception('Second parameter can\'t be null');
                }

                $query .= "{$join['first']} {$join['operator']} {$join['second']}";
            }
        }

        if ($this->hasWhere()) {
            $query .= "\nWHERE\n\t" . trim($this->getWhereSql());
        }

        if (sizeof($this->groupBy) > 0) {
            $query .= "\nGROUP BY";
            foreach ($this->groupBy as $r) {
                $query .= " {$r['field']},";
            }
            $query = substr($query, 0, -1);
        }

        $sizeofHaving = count($this->having);
        if ($sizeofHaving > 0) {
            $query .= "\nHAVING";
            if ($sizeofHaving == 1) {
                $nl = ' ';
            } else {
                $nl = "\n\t";
            }

            foreach ($this->having as $index => $having) {
                $link = ($index > 0) ? "{$having['link']} " : '';
                if ($having['value'] instanceof Expr) {
                    $query .= "{$nl}{$link}{$having['field']} {$having['operator']} {$having['value']}";
                } else {
	                //$bindName = $this->bind($having['field'], $having['value'], 'h');
	                $bindName = $this->getBindings()->makeAndSet('h' . $having['field'], $having['value']);
	                $query .= "{$nl}{$link}{$having['field']} {$having['operator']} :{$bindName}";
                }
            }
        }

        if (sizeof($this->orderBy) > 0) {
            $query .= "\nORDER BY";
            foreach ($this->orderBy as $r) {
                $query .= "\n\t{$r['field']} {$r['direction']},";
            }
            $query = substr($query, 0, -1);
        }

        if ($this->limit !== null) {
            $query .= "\nLIMIT {$this->limit->howMuch} OFFSET {$this->limit->start}";
        }

        return new Query($query, $this->getBindings(), $this->getAdapterConnection());
    }