blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 116 | path stringlengths 2 241 | src_encoding stringclasses 31
values | length_bytes int64 14 3.6M | score float64 2.52 5.13 | int_score int64 3 5 | detected_licenses listlengths 0 41 | license_type stringclasses 2
values | text stringlengths 14 3.57M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
39e5b4f00e36f520f162de58fcc4f963eb5f152d | PHP | Jozeh-github/MyFramework | /base/MySQL.php | UTF-8 | 4,160 | 2.84375 | 3 | [] | no_license | <?php
class MySQL {
private $host = '';
private $user = '';
private $password = '';
private $schema = '';
private $type = '';
private $connection = NULL;
private $debug = false;
function __construct() {
$this->host = DB_HOST;
$this->schema = DB_SCHEMA;
$this->user = DB_USER;
$this->password = DB_PASSWORD;
$this->type = DB_TYPE;
}
public function showError($message = '') {
if($this->debug) {
if($message != '') {
die($message);
}
else {
die(mysql_error());
}
}
else {
die("");
}
}
public function open() {
if(!is_resource($this->connection)) {
$this->connection = mysql_connect($this->host, $this->user, $this->pass);
if(is_resource($this->connection)) {
if(!mysql_select_db($this->schema, $this->connection)) {
$this->showError();
}
else {
mysql_query('Set names utf8');
}
}
else {
$this->showError();
}
}
return $this;
}
public function close() {
if(is_resource($this->connection)) {
mysql_close($this->connection);
$this->connection = NULL;
}
return $this;
}
public function isOpen() {
return $this->connection;
}
public function insert($query = '') {
if(trim($query) != '') {
mysql_query($query, $this->connection) or $this->showError();
return mysql_insert_id($this->connection);
}
else {
return $this->showError('The query is empty.');
}
}
public function execute($query = '') {
if(trim($query) != '') {
return mysql_query($query, $this->connection) or $this->showError();
}
else {
return $this->showError('The query is empty.');
}
}
public function query($query = '') {
if(trim($query) != '') {
if(is_resource($this->connection)) {
return new MySQLResult($query, $this->connection);
}
}
else {
$this->showError('The query is empty.');
}
}
public function listFromQuery($query = '') {
if(trim($query) != '') {
$output = array();
$this->open();
$result = new MySQLResult($query, $this->connection);
$result->fetchRows();
while($result->hasRows()) {
array_push($output, $result->item);
}
$this->close();
return $output;
}
else {
$this->showError('The query is empty.');
}
}
}
class MySQLResult {
var $connection = NULL;
var $data = NULL;
var $item = NULL;
var $rows = 0;
var $curr = 0;
var $size = 0;
var $query = '';
var $debug = true;
function MySQLResult($query, $connection) {
$this->query = $query;
$this->connection = $connection;
}
public function setPagination($curr, $size) {
$this->curr = $curr;
$this->size = $size;
}
public function fetchRows() {
if($this->curr != 0) {
$this->data = mysql_query('Select count(*) as total from ('.$this->query.');') or $this->showError();
$this->hasRows();
$this->rows = $this->getField('total');
$this->data = mysql_query($this->query.' limit '.(($this->curr-1)*$this->size).', '.$this->size,';', $this->connection) or $this->showError();
}
else {
$this->data = mysql_query($this->query, $this->connection) or $this->showError();
$this->rows = mysql_num_rows($this->data);
}
}
public function showError($message = '') {
if($this->debug) {
if($message != '') {
die($message);
}
else {
die(mysql_error());
}
}
else {
die('');
}
}
public function getTotal() {
return $this->rows;
}
public function getPage() {
return $this->curr;
}
public function getPages() {
$tpages = ceil($this->rows/$this->size);
return $tpages;
}
public function countRows() {
if(is_resource($this->data)) {
return mysql_num_rows($this->data);
}
else {
$this->showError('Empty data');
}
}
public function hasRows() {
if(is_resource($this->data)) {
$this->item = mysql_fetch_assoc($this->data);
return $this->item;
}
else {
$this->showError('Empty data');
}
}
public function getField($field) {
return $this->item[$field];
}
public function seekRow($num) {
if(is_resource($this->data)) {
mysql_data_seek($this->data, $num);
return $this->fetchRows();
}
else {
$this->showError('No Data');
}
}
public function getFirst() {
return $this->seekRow(0);
}
}
?> | true |
e460068079c65cb35f678f8e5dcdbd1447b70b1d | PHP | ogustavo21/Tablero-Contable | /modulos/ejercicio/cls_ejercicio.php | UTF-8 | 2,386 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | <?php
/**
*
* @author Beyda Mariana Trejo Román <1130032@unav.edu.mx>
* @copyright 2017-2018 Área de Desarrollo UNAV
* @version 1.0
*/
class ejercicio
{
public $ejercicio;
public $nombre;
function __construct($ejercicio, $nombre)
{
$this->ejercicio = $ejercicio;
$this->nombre = $nombre;
}
public function insertar()
{
session_start();
require("../../conex/connect.php");
// AGREGAR
$insertE = "INSERT INTO `ejercicio`(`id_ejercicio`, `nombre`, `status`) VALUES ($this->ejercicio,'$this->nombre',1)";
$insertE = $mysqli->query($insertE);
if ($mysqli->error) {
echo "<script>if(confirm('Algunos datos no se pudieron guardar')){
document.location='/modulos/ejercicio/r_ejercicio.php';}
else{ alert('Operacion Cancelada');
}</script>";
}else{
echo "<script> document.location='/modulos/ejercicio/'; </script>";
}
}
public function modificar()
{
session_start();
require("../../conex/connect.php");
// AGREGAR
$updtZ = "UPDATE `ejercicio` SET `nombre`='$this->nombre' WHERE `id_ejercicio` = $_SESSION[id_tmp]";
$updtZ = $mysqli->query($updtZ);
if ($mysqli->error) {
echo "<script>if(confirm('Algunos datos no se pudieron guardar')){
document.location='/modulos/ejercicio/m_ejercicio.php';}
else{ alert('Operacion Cancelada');
}</script>";
}else{
unset($_SESSION[id_tmp]);
echo "<script> document.location='/modulos/ejercicio/'; </script>";
}
}
}
if (isset($_GET["estatus"])) {
session_start();
require("../../conex/connect.php");
$estatus = $_GET["estatus"];
$id = $_GET["id"];
$updtStatus = "UPDATE `ejercicio` SET `status`=0";
$updtStatus = $mysqli->query($updtStatus);
$updtZ = "UPDATE `ejercicio` SET `status`=$estatus WHERE `id_ejercicio` = $id";
$updtZ = $mysqli->query($updtZ);
if ($estatus == 1) {
$_SESSION["id_ejercicio"] = $id;
}else{
$_SESSION["id_ejercicio"] = "";
}
if ($mysqli->error) {
echo "<script>if(confirm('Algunos datos no se pudieron actualizar')){
document.location='/modulos/ejercicio';}
else{ alert('Operacion Cancelada');
}</script>";
}else{
echo "<script> document.location='/modulos/ejercicio/'; </script>";
}
}
?> | true |
89e7fc1f03a6f688d8f04e95f31d5eb8114495d7 | PHP | krcowles/ktesa | /admin/updteBks.php | UTF-8 | 1,591 | 2.546875 | 3 | [] | no_license | <?php
/**
* This script inserts a new book entered on the form "addBook.php" into
* the BOOKS table in MySQL.
* PHP Version 7.4
*
* @package Ktesa
* @author Tom Sandberg <tjsandberg@yahoo.com>
* @author Ken Cowles <krcowles29@gmail.com>
* @license No license to date
*/
session_start();
require_once "../php/global_boot.php";
$author = filter_input(INPUT_POST, 'author');
$title = filter_input(INPUT_POST, 'title');
$bkReq ="INSERT INTO BOOKS (title,author) VALUES(:title,:author);";
$addbk = $pdo->prepare($bkReq);
$addbk->bindValue(":title", $title);
$addbk->bindValue(":author", $author);
$addbk->execute();
?>
<!DOCTYPE html>
<html lang="en-us">
<head>
<title>Book Added</title>
<meta charset="utf-8" />
<meta name="description" content="Add book to BOOKS table" />
<meta name="author" content="Tom Sandberg and Ken Cowles" />
<meta name="robots" content="nofollow" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="../styles/bootstrap.min.css" rel="stylesheet" />
<link href="../styles/admintools.css" type="text/css" rel="stylesheet" />
<script src="../scripts/jquery.js"></script>
</head>
<body>
<script src="https://unpkg.com/@popperjs/core@2.4/dist/umd/popper.min.js"></script>
<script src="../scripts/bootstrap.min.js"></script>
<?php require "../pages/ktesaPanel.php"; ?>
<p id="trail">New Book Added</p>
<p id="active" style="display:none">Admin</p>
<div style="margin-left:24px;font-size:18px;">
<p>New Book Successfully Added to BOOKS Table</p>
<p style="color:brown;"><?= $author;?> ; <?= $title;?></p>
</div>
</body>
</html>
| true |
83596f43b18107ab12cd9358171bb3e0a559b42d | PHP | forkcms/forkcms | /src/Backend/Core/Js/ckfinder/core/connector/php/CKSource/CKFinder/Event/CreateFolderEvent.php | UTF-8 | 1,919 | 2.671875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | <?php
/*
* CKFinder
* ========
* http://cksource.com/ckfinder
* Copyright (C) 2007-2016, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*/
namespace CKSource\CKFinder\Event;
use CKSource\CKFinder\CKFinder;
use CKSource\CKFinder\Filesystem\Folder\WorkingFolder;
/**
* The CreateFolderEvent event class.
*/
class CreateFolderEvent extends CKFinderEvent
{
/**
* The working folder where the new folder is going to be created.
*
* @var WorkingFolder $workingFolder
*/
protected $workingFolder;
/**
* The new folder name.
*
* @var string
*/
protected $newFolderName;
/**
* Constructor.
*
* @param CKFinder $app
* @param WorkingFolder $workingFolder
* @param string $newFolderName
*/
public function __construct(CKFinder $app, WorkingFolder $workingFolder, $newFolderName)
{
$this->workingFolder = $workingFolder;
$this->newFolderName = $newFolderName;
parent::__construct($app);
}
/**
* Returns the working folder where the new folder is going to be created.
*
* @return WorkingFolder
*/
public function getWorkingFolder()
{
return $this->workingFolder;
}
/**
* Returns the name of the new folder.
*
* @return string
*/
public function getNewFolderName()
{
return $this->newFolderName;
}
/**
* Sets the name for the new folder.
*
* @param string $newFolderName
*/
public function setNewFolderName($newFolderName)
{
$this->newFolderName = $newFolderName;
}
}
| true |
eae3944441122786e02cdbe5341c4f7010268b1b | PHP | crackayus09/csv-Importer | /Controllers/ExportController.php | UTF-8 | 1,802 | 2.640625 | 3 | [] | no_license | <?php
/**
* Class ExportController
*/
class ExportController extends AppController
{
public function __construct()
{
parent::__construct();
$post_data = $this->postData();
$this->expOption = $this->arrExtract($post_data, "exp_option");
$this->filters = $this->arrExtract($post_data, "filters", []);
$this->fileName = $this->arrExtract($_SESSION, "file_name");
}
/**
* Used to export content to specific format
*/
public function index()
{
if (!empty($this->fileName) && !empty($this->expOption)) {
require_once("Models/ExportModel.php");
$ob_exporter = new ExportModel($this->fileName, $this->filters);
if ($ob_exporter->filteredCount > 0) {
switch ($this->expOption) {
case 'pdf':
$export_file = $ob_exporter->exportPdf();
break;
case 'excel':
$export_file = $ob_exporter->exportExcel();
break;
default:
$export_file = $ob_exporter->exportCsv();
break;
}
$response = [
"success" => true,
"message" => "File successfully exported.",
"data" => $export_file
];
} else {
$response = [
"success" => false,
"message" => "No Data to export."
];
}
} else {
$response = [
"success" => false,
"message" => "Invalid Access."
];
}
echo json_encode($response);
exit;
}
}
| true |
d426cf9362554b7539101f28fbdf536ff572b21a | PHP | wesleycsilva/simposio_cefet | /area_user/classes/Inscricao.php | UTF-8 | 10,436 | 2.6875 | 3 | [] | no_license | <?php
class Inscricao
{
public $id;
public $idEvento;
public $idSimposista;
public $situacao;
public $urlQrCode;
public function __construct($id = false)
{
if ($id) {
$this->id = $id;
$this->carregar();
}
}
public function carregar()
{
$query = "SELECT * FROM inscricao WHERE idInscricao = :id";
$conexao = ConexaoUser::pegarConexao();
$stmt = $conexao->prepare($query);
$stmt->bindValue(':id', $this->id);
$stmt->execute();
$linha = $stmt->fetch();
$this->idEvento = $linha['idEvento'];
$this->idSimposista = $linha['idSimposista'];
$this->situacao = $linha['situacao'];
$this->urlQrCode = $linha['urlQrCode'];
}
public static function listar()
{
$query = "SELECT p.id, p.nome, preco, quantidade, categoria_id, c.nome as categoria_nome
FROM inscricao p
INNER JOIN categorias c ON p.categoria_id = c.id
ORDER BY p.nome ";
$conexao = ConexaoUser::pegarConexao();
$resultado = $conexao->query($query);
$lista = $resultado->fetchAll();
return $lista;
}
public static function listarPorInscricao($idEvento, $idSimposista)
{
$query = "SELECT * FROM inscricao WHERE idEvento = :idEvento AND idSimposista = :idSimposista";
$conexao = ConexaoUser::pegarConexao();
$stmt = $conexao->prepare($query);
$stmt->bindValue(':idEvento', $idEvento);
$stmt->bindValue(':idSimposista', $idSimposista);
$stmt->execute();
return $stmt->fetchAll();
}
public function inserir($tipoSimposista)
{
$consultaInscricao = self::listarPorInscricao($this->idEvento, $this->idSimposista);
$campoAtualizar = 'qtdInscritos';
if ($tipoSimposista == 2) {
$campoAtualizar = 'qtdInscritosExternos';
}
if (count($consultaInscricao) == 0) {
$resultadoInscritos = self::consultaQtdInscritos($this->idEvento);
$haVagas = self::verificaVagas($resultadoInscritos, $tipoSimposista);
if ($haVagas) {
$query = "INSERT INTO inscricao (idEvento, idSimposista, situacao, urlQrCode)
VALUES (:idEvento, :idSimposista, :situacao, :urlQrCode)";
$conexao = ConexaoUser::pegarConexao();
$stmt = $conexao->prepare($query);
$stmt->bindValue(':idEvento', $this->idEvento);
$stmt->bindValue(':idSimposista', $this->idSimposista);
$stmt->bindValue(':situacao', $this->situacao);
$stmt->bindValue(':urlQrCode', $this->urlQrCode);
$stmt->execute();
$queryUpdate = "UPDATE evento SET $campoAtualizar = $campoAtualizar + 1 WHERE idEvento = :id";
// $conexao = ConexaoUser::pegarConexao();
$stmt = $conexao->prepare($queryUpdate);
$stmt->bindValue(':id', $this->idEvento);
$stmt->execute();
return ['status' => 200, 'mensagem' => 'Inscrição foi relizada com sucesso!'];
} else {
return ['status' => 400, 'mensagem' => 'Não há vagas disponíveis para esse evento!'];
}
} else {
$resultadoInscritos = self::consultaQtdInscritos($this->idEvento);
$haVagas = self::verificaVagas($resultadoInscritos, $tipoSimposista);
if ($haVagas) {
$this->id = $consultaInscricao[0]["idInscricao"];
$this->situcao = 1;
self::atualizar();
$queryUpdate = "UPDATE evento SET $campoAtualizar = $campoAtualizar + 1 WHERE idEvento = :id";
$conexao = ConexaoUser::pegarConexao();
$stmt = $conexao->prepare($queryUpdate);
$stmt->bindValue(':id', $this->idEvento);
$stmt->execute();
return ['status' => 200, 'mensagem' => 'Inscrição foi relizada com sucesso!'];
} else {
return ['status' => 400, 'mensagem' => 'Não há vagas disponíveis para esse evento!'];
}
}
}
public function cancelaInscricao($tipoSimposista)
{
$consultaInscricao = self::listarPorInscricao($this->idEvento, $this->idSimposista);
if (count($consultaInscricao) > 0) {
$this->id = $consultaInscricao[0]["idInscricao"];
$this->situcao = 2;
$query = "UPDATE inscricao SET situacao = :situacao, urlQrCode = :urlQrCode WHERE idInscricao = :id";
$conexao = ConexaoUser::pegarConexao();
$stmt = $conexao->prepare($query);
$stmt->bindValue(':situacao', $this->situcao);
$stmt->bindValue(':urlQrCode', $this->urlQrCode);
$stmt->bindValue(':id', $this->id);
$stmt->execute();
$campoAtualizar = 'qtdInscritos';
if ($tipoSimposista == 2) {
$campoAtualizar = 'qtdInscritosExternos';
}
$queryUpdate = "UPDATE evento SET $campoAtualizar = $campoAtualizar - 1 WHERE idEvento = :id";
// var_dump($queryUpdate, $this->idEvento);exit;
// $conexao = ConexaoUser::pegarConexao();
$stmt = $conexao->prepare($queryUpdate);
$stmt->bindValue(':id', $this->idEvento);
$stmt->execute();
return true;
} else {
return false;
}
}
public function atualizar()
{
self::consultaQtdInscritos($this->idEvento);
$query = "UPDATE inscricao SET situacao = :situacao, urlQrCode = :urlQrCode WHERE idInscricao = :id";
$conexao = ConexaoUser::pegarConexao();
$stmt = $conexao->prepare($query);
$stmt->bindValue(':situacao', $this->situcao);
$stmt->bindValue(':urlQrCode', $this->urlQrCode);
$stmt->bindValue(':id', $this->id);
$stmt->execute();
}
public function excluir()
{
$query = "DELETE FROM inscricao WHERE idInscricao = :id";
$conexao = ConexaoUser::pegarConexao();
$stmt = $conexao->prepare($query);
$stmt->bindValue('id', $this->id);
$stmt->execute();
}
public function consultaQtdInscritos($idEvento)
{
$query = "SELECT * FROM evento WHERE idEvento = :id";
$conexao = ConexaoUser::pegarConexao();
$stmt = $conexao->prepare($query);
$stmt->bindValue('id', $idEvento);
$stmt->execute();
$dadosEvento = $stmt->fetch();
$resultadoInscritos['qtdInscritos'] = $dadosEvento['qtdInscritos'];
$resultadoInscritos['qtdTotal'] = $dadosEvento['qtdTotal'];
$resultadoInscritos['qtdInscritosExternos'] = $dadosEvento['qtdInscritosExternos'];
$resultadoInscritos['qtdTotalExternos'] = $dadosEvento['qtdTotalExternos'];
return $resultadoInscritos;
}
public function verificaVagas($resultadoInscritos, $tipoSimposista)
{
$tipoCadastro = $tipoSimposista;
$retorno = true;
if ($tipoCadastro == 1) {
if (($resultadoInscritos['qtdInscritos'] + 1) > $resultadoInscritos['qtdTotal']) {
$retorno = false;
}
} elseif ($tipoCadastro == 2) {
if (($resultadoInscritos['qtdInscritosExternos'] + 1) > $resultadoInscritos['qtdTotalExternos']) {
$retorno = false;
}
}
return $retorno;
}
public function retornaInscricao($idEvento, $idSimposista)
{
$query = "SELECT * FROM inscricao WHERE idEvento = :idEvento and idSimposista = :idSimposista";
$conexao = ConexaoUser::pegarConexao();
$stmt = $conexao->prepare($query);
$stmt->bindValue(':idEvento', $idEvento);
$stmt->bindValue(':idSimposista', $idSimposista);
$stmt->execute();
$inscricao = $stmt->fetch();
if (is_array($inscricao)) {
$dadosInscricao['idInscricao'] = $inscricao['idInscricao'];
$dadosInscricao['idEvento'] = $inscricao['idEvento'];
$dadosInscricao['idSimposista'] = $inscricao['idSimposista'];
$dadosInscricao['situacao'] = $inscricao['situacao'];
$dadosInscricao['urlQrCode'] = $inscricao['urlQrCode'];
} else {
$dadosInscricao['idInscricao'] = null;
}
return $dadosInscricao;
}
public function consultaInscricao($idInscricao, $idEvento, $idSimposista)
{
$query = "SELECT * FROM inscricao WHERE idInscricao = :idInscricao and idEvento = :idEvento and idSimposista = :idSimposista";
$conexao = ConexaoUser::pegarConexao();
$stmt = $conexao->prepare($query);
$stmt->bindValue(":idInscricao", $idInscricao);
$stmt->bindValue(':idEvento', $idEvento);
$stmt->bindValue(':idSimposista', $idSimposista);
$stmt->execute();
$inscricao = $stmt->fetch();
if (is_array($inscricao)) {
$dadosInscricao['idInscricao'] = $inscricao['idInscricao'];
$dadosInscricao['idEvento'] = $inscricao['idEvento'];
$dadosInscricao['idSimposista'] = $inscricao['idSimposista'];
$dadosInscricao['situacao'] = $inscricao['situacao'];
$dadosInscricao['urlQrCode'] = $inscricao['urlQrCode'];
} else {
$dadosInscricao['idInscricao'] = null;
}
return $dadosInscricao;
}
public static function pesquisarInscricao($idInscricao)
{
$query = "SELECT idInscricao, idEvento, idSimposista, situacao FROM inscricao WHERE idInscricao = :idInsc";
$conexao = ConexaoUser::pegarConexao();
$stmt = $conexao->prepare($query);
$stmt->bindValue(":idInsc", $idInscricao, PDO::PARAM_INT);
$stmt->execute();
$res = $stmt->fetch();
return $res;
}
public function confirmaSituacao($idInscricao, $situacao)
{
$query = "UPDATE inscricao SET situacao = :situacao WHERE idInscricao = :idInscricao";
$conexao = ConexaoUser::pegarConexao();
$stmt = $conexao->prepare($query);
$stmt->bindValue(":idInscricao", $idInscricao);
$stmt->bindValue(':situacao', $situacao);
$stmt->execute();
return ['status' => 200, 'mensagem' => 'Presença confirmada com sucesso!'];
}
} | true |
b541fe260a2fd9ceb0d478db2e7696c50e7c5996 | PHP | MorganLedieu/ligue1 | /src/controleur/inscription.php | UTF-8 | 1,396 | 2.671875 | 3 | [] | no_license | <?php
/* page: inscription.php */
//connexion à la base de données:
$BDD = array();
$BDD['host'] = "localhost";
$BDD['user'] = "login4158";
$BDD['pass'] = "NcaPeMOaPkuZPAP";
$BDD['db'] = "dblogin4158";
$mysqli = mysqli_connect($BDD['host'], $BDD['user'], $BDD['pass'], $BDD['db']);
if(isset($_POST['pseudo'],$_POST['mdp'])){
if(empty($_POST['pseudo'])){
echo "Le champ Pseudo est vide.";
} elseif(strlen($_POST['pseudo'])>25){
echo "Le pseudo est trop long, il dépasse 25 caractères.";
} elseif(empty($_POST['mdp'])){
echo "Le champ Mot de passe est vide.";
} elseif(mysqli_num_rows(mysqli_query($mysqli,"SELECT * FROM membres WHERE pseudo='".$_POST['pseudo']."'"))==1){
echo "Ce pseudo est déjà utilisé.";
} else {
if(!mysqli_query($mysqli,"INSERT INTO membres SET pseudo='".$_POST['pseudo']."', mdp='".$_POST['mdp']."', email='".$_POST['email']."'" )){
echo "Une erreur s'est produite: ".mysqli_error($mysqli);
} else {
(!mysqli_query($mysqli,"INSERT INTO classement SET pseudo='".$_POST['pseudo']."', points='0'" ));
echo "Vous êtes inscrit avec succès!";
header("Location: http://serveur1.arras-sio.com/symfony4-4158/ligue1/index.php?page=connexion");
exit;
}
}
} | true |
4c7bd077d6dfa9ff25a45d8e6d4d7006a96518c2 | PHP | MagicSen/source_read | /live-camera-master/start.php | UTF-8 | 1,379 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
/**
* run with command
* php start.php start
*/
// 入口
ini_set('display_errors', 'on');
// 声明命名空间
use Workerman\Worker;
// pcntl扩展是PHP在Linux环境下进程控制的重要扩展
// 检查扩展
if(!extension_loaded('pcntl'))
{
exit("Please install pcntl extension. See http://doc3.workerman.net/install/install.html\n");
}
// posix扩展使得PHP在Linux环境可以调用系统通过POSIX标准提供的接口。WorkerMan主要使用了其相关的接口实现了守护进程化、用户组控制等功能。此扩展win平台不支持
if(!extension_loaded('posix'))
{
exit("Please install posix extension. See http://doc3.workerman.net/install/install.html\n");
}
// 标记是全局启动
define('GLOBAL_START', 1);
# 包含文件
require_once __DIR__ . '/vendor/autoload.php';
// 加载所有Applications/*/start.php,以便启动所有服务
foreach(glob(__DIR__.'/start_*.php') as $start_file)
{
// 这部分运行在子进程
require_once $start_file;
}
# 以debug(调试)方式启动
# php start.php start
# 以daemon(守护进程)方式启动
# php start.php start -d
# 一般来说在Worker::runAll();调用前运行的代码都是在主进程运行的,onXXX回调运行的代码都属于子进程。注意写在Worker::runAll();后面的代码永远不会被执行
// 运行所有服务
Worker::runAll();
| true |
1f48bba46a1df5bdc6b87c17850256bbda23a0e0 | PHP | nbdd0121/MW-DeltaDB | /includes/Hooks.php | UTF-8 | 1,386 | 2.703125 | 3 | [
"BSD-2-Clause"
] | permissive | <?php
use MediaWiki\Storage;
class DeltaDBHooks {
public static function onRevisionRecordInserted( Storage\RevisionRecord $rev) {
$parentId = $rev->getParentId();
if ( !$parentId ) return;
$revisionStore = MediaWiki\MediaWikiServices::getInstance()->getRevisionStore();
$parentRev = $revisionStore->getRevisionById($parentId);
list ( $location, $hash ) = self::getHashFromRevision( $rev );
list ( $parentLocation, $parentHash ) = self::getHashFromRevision( $parentRev );
if ( $location === null || $location !== $parentLocation) return;
DeltaDB::link( $location, $hash, $parentHash );
}
private static function getHashFromRevision( Storage\RevisionRecord $rev) {
$slot = $rev->getSlot( Storage\SlotRecord::MAIN, Storage\RevisionRecord::RAW );
list( $schema , $textId ) = explode( ':', $slot->getAddress());
if ( $schema !== 'tt') throw new MWException('Unknown schema');
$textId = intval( $textId );
$dbr = wfGetDB(DB_REPLICA);
$row = $dbr->selectRow(
'text',
[ 'old_text', 'old_flags' ],
[ 'old_id' => $textId ],
__METHOD__
);
if ( !$row ) return null;
$url = $row->old_text;
$flags = $row->old_flags;
if ( is_string( $flags ) ) {
$flags = explode( ',', $flags );
}
// Not from external, so $url isn't actually an URL.
if ( !in_array( 'external', $flags ) ) return null;
return DeltaDB::fromStoreUrl( $url );
}
}
| true |
557549d444d67d08f367c44c277d7f2c075b6b9c | PHP | ga503306/project_nfc_php | /www/api/outregister.php | UTF-8 | 584 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | <?php session_start(); ?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
if(empty($_SESSION['userid']))
{
echo '<meta http-equiv=REFRESH CONTENT=0;url=../index.html>';
?>
<script language="JavaScript">
window.alert('登入時發生錯誤!');
echo '<meta http-equiv=REFRESH CONTENT=0;url=../index.html>';
</script>
<?php
}
else{
//將session清空
unset($_SESSION['userid']);
?>
<script language="JavaScript">
window.alert('登出成功');
</script>
<?PHP
echo '<meta http-equiv=REFRESH CONTENT=0;url=../index.html>';
}
?> | true |
efa792a411087964206f50da7bc73f28e6fec355 | PHP | Natan1223/sistema_avaliacao_tcc | /sistema_avaliacao_tcc/model/avaliacao_desempenho.php | UTF-8 | 582 | 2.8125 | 3 | [] | no_license |
<?php
/*
* Class avaliacao_desempenho
*/
class avaliacao_desempenho
{
/* Atributes */
var $cod_avaliacao;
var $descricao_avaliacao;
/* Methods (set/get) */
function setcod_avaliacao( $cod_avaliacao )
{
$this->cod_avaliacao = $cod_avaliacao;
}
function getcod_avaliacao()
{
return $this->cod_avaliacao;
}
function setdescricao_avaliacao( $descricao_avaliacao )
{
$this->descricao_avaliacao = $descricao_avaliacao;
}
function getdescricao_avaliacao()
{
return $this->descricao_avaliacao;
}
}
?>
| true |
988065a60423bc3fa1603c5cfd793589b20a09c0 | PHP | foxrock/tekafiles | /inc/File_Report_Table.php | UTF-8 | 3,190 | 2.640625 | 3 | [] | no_license | <?php
class File_Report_table extends WP_List_Table {
function __construct () {
parent::__construct();
}
function get_columns () {
return array(
'cb' => "<input type='checkbox' />",
'user' => 'Usuario',
'locked' => 'Bloqueado');
}
function get_sortable_columns () {
return array(
'user' => 'user');
}
function column_default ($item, $column_name) {
return $item->$column_name;
}
function column_cb ($item) {
return "<input type='checkbox' name='user[]' value='$item->ID' />";
}
function column_locked ($item) {
if ($item->locked) return 'Si';
else return 'No';
}
function get_bulk_actions () {
return array(
'lock' => 'Bloquear',
'unlock' => 'Desbloquear');
}
function process_bulk_action () {
if ( isset( $_POST['_wpnonce'] ) && ! empty( $_POST['_wpnonce'] ) ) {
$nonce = filter_input( INPUT_POST, '_wpnonce', FILTER_SANITIZE_STRING );
$action = 'bulk-' . $this->_args['plural'];
if ( ! wp_verify_nonce( $nonce, $action ) )
wp_die( 'Nope! Security check failed!' );
}
if (isset($_POST['user'])) {
global $wpdb;
$action = $this->current_action();
$items = $_POST['user'];
$items = join(',', $items);
switch ($action) {
case 'lock':
$locked = 1;
break;
case 'unlock':
$locked = 0;
break;
}
$query = "UPDATE {$wpdb->prefix}tekafile_user
SET locked=$locked
WHERE ID IN ($items)";
$wpdb->query($query);
}
}
function prepare_items () {
if ($this->current_action()) $this->process_bulk_action();
global $wpdb;
$file_id = $_GET['t'];
$tu = $wpdb->prefix . 'tekafile_user';
$u = $wpdb->prefix . 'users';
$t = $wpdb->prefix . 'tekafile';
$query = "SELECT tu.ID as ID, u.display_name as user, tu.locked as locked
FROM $tu as tu
JOIN $u as u ON tu.user=u.ID
JOIN $t as t ON tu.tekafile=t.ID
WHERE tu.tekafile=$file_id";
$columns = $this->get_columns();
$hidden = array();
$per_page = 40;
$sortable = $this->get_sortable_columns();
$this->_column_headers = array($columns, $hidden, $sortable);
if ($_GET['orderby'] === 'u') $orderby = 'u.display_name';
if (isset($_GET['order'])) $order = mysql_real_escape_string($_GET["order"]);
if (isset($orderby) && isset($order)) $query .= ' ORDER BY '.$orderby.' '.$order;
$data = $wpdb->get_results($query);
$current_page = $this->get_pagenum();
$total_items = count($data);
$paged = !empty($_GET["paged"]) ? mysql_real_escape_string($_GET["paged"]) : '';
if(empty($paged) || !is_numeric($paged) || $paged<=0 ){ $paged=1; }
$totalpages = ceil($totalitems/$per_page);
if(!empty($paged) && !empty($per_page)){
$offset = ($paged - 1) * $per_page;
$query .= ' LIMIT ' . (int)$offset . ',' . (int)$per_page;
}
$this->items = $wpdb->get_results($query);
$this->set_pagination_args( array(
'total_items' => $total_items,
'per_page' => $per_page,
'total_pages' => ceil($total_items/$per_page)
) );
}
} | true |
f121adc5d5ac4ab7f763d14787e7e38946726be4 | PHP | ckrack/hydrometer-public-server | /src/Entity/Token.php | UTF-8 | 2,758 | 2.6875 | 3 | [
"BSD-3-Clause",
"Artistic-1.0",
"MIT",
"Artistic-1.0-Perl"
] | permissive | <?php
/*
* This file is part of the hydrometer public server project.
*
* @author Clemens Krack <info@clemenskrack.com>
*/
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Contract\Entity\TimestampableInterface;
use Knp\DoctrineBehaviors\Model\Timestampable\TimestampableTrait;
/**
* @ORM\Entity(repositoryClass="App\Repository\TokenRepository")
* @ORM\Table(name="token", options={"collate"="utf8mb4_unicode_ci", "charset"="utf8mb4"})
*/
class Token extends Entity implements TimestampableInterface
{
use TimestampableTrait;
public function __construct()
{
parent::__construct();
}
/**
* One of api, login, register.
*
* @ORM\Column(type="string", length=190, nullable=true)
*
* @var string
*/
protected $type;
/**
* @ORM\Column(name="value", type="string", length=190, nullable=true)
*
* @var string
*/
protected $value;
/**
* @ORM\Column(name="was_used", type="integer", length=1, nullable=true)
*
* @var string
*/
protected $wasUsed;
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="token")
* ORM\JoinColumn(
* name="user_id",
* referencedColumnName="id",
* nullable=true
* )
*/
protected $user;
/**
* Setter for Id.
* This is the only Id we allow to be set manually, as we use the one from the ESP board.
*
* @param int $id the id of the ESP-Board
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
public function getUser()
{
return $this->user;
}
/**
* @return self
*/
public function setUser($user)
{
$this->user = $user;
return $this;
}
/**
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* @param string $type
*
* @return self
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* @return string
*/
public function getValue()
{
return $this->value;
}
/**
* @param string $value
*
* @return self
*/
public function setValue($value)
{
$this->value = $value;
return $this;
}
/**
* @return string
*/
public function getWasUsed()
{
return $this->wasUsed;
}
/**
* @param string $wasUsed
*
* @return self
*/
public function setWasUsed($wasUsed)
{
$this->wasUsed = $wasUsed;
return $this;
}
}
| true |
984215b9b61c07542c64c2ee6b41ddd3c4414ee1 | PHP | schrecka/hello_generator | /hello_generator.php | UTF-8 | 3,813 | 2.71875 | 3 | [] | no_license | <!DOCTYPE html>
<html lang="en">
<head>
<!-- CSS file -->
<link rel="stylesheet" type="text/css" href="style.css">
<!-- Bootstrap -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<?php
//Shows all PHP ERRORS:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
//Select greeting language
if(isset($_POST['language'])) {
if($_POST['language'] == "english") {
$greeting = "Hello ";
}
else if($_POST['language'] == "french") {
$greeting = "Bonjour ";
}
else if($_POST['language'] == "portuguese") {
$greeting = "Olá ";
}
}
else if(isset($_GET['language'])) {
if($_GET['language'] == "english") {
$greeting = "Hello ";
}
else if($_GET['language'] == "french") {
$greeting = "Bonjour ";
}
else if($_GET['language'] == "portuguese") {
$greeting = "Olá ";
}
}
else {
$greeting = "Please select language ";
}
/*
1. Create an HTML form (1 field name "name_of_person" + submit);
2. Submit the form to the same URL;
3. Submission type is POST
4. Logic above is changed so that it handles both GET and POST
(form takes precedence over url)
*/
if(isset($_POST['name_of_person']) && ($_POST['name_of_person'] != "")) {
/*
//When my dad types in his name(Paul), message comes up on screen
if($_POST['name_of_person'] == "Paul") {
echo '<script language="javascript">';
echo 'alert("Your credit card has been stolen!")';
echo '</script>';
}
*/
$message = $greeting . $_POST['name_of_person'] . "!";
}
else if(isset($_GET['name_of_person'])) {
$message = $greeting . $_GET['name_of_person'] . "!";
}
else {
$message = "Please enter name above";
}
?>
</head>
<body>
<!--Title section-->
<div class="container">
<div class="jumbotron">
<h1>Welcome to the Hello Generator</h1>
<p>The worldwide leader in generating hellos</p>
</div>
</div>
<br>
<!--Form section-->
<div id="html_form">
<form class="form-inline" method="post">
<div class="form-group">
<!--Name form-->
<label for ="Enter Name:">Name:</label>
<input type="text" class="form-control" required placeholder="Enter name" name="name_of_person" oninvalid="this.setCustomValidity('Please enter name')"
oninput="this.setCustomValidity('')">
<!--Language dropdown menu-->
<label for="language">Language:</label>
<select name="language" class="form-control" required oninvalid="this.setCustomValidity('Please select language')" oninput="this.setCustomValidity('')">
<option value="">-Select-</option>
<option value="english">English</option>
<option value="french">French</option>
<option value="portuguese">Portuguese</option>
</select>
<!--Submit Button-->
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
</div>
<!--Message box-->
<div class="container">
<div id="str"></div>
<!--JS for message box (found on google)-->
<script>
var string = "<?php echo $message; ?>";
var str = string.split("");
var el = document.getElementById('str');
(function animate() {
str.length > 0 ? el.innerHTML += str.shift() : clearTimeout(running);
var running = setTimeout(animate, 90);
})();
</script>
</div>
</body>
</html> | true |
afa96b82f464c105e8a705357788e22c545ac38c | PHP | BuenoSoft/BuenoSoftMVC | /Model/TipoProductoModel.php | UTF-8 | 2,682 | 2.6875 | 3 | [] | no_license | <?php
namespace Model;
use \App\Session;
use \Clases\TipoProducto;
class TipoProductoModel extends AppModel
{
public function __construct() {
parent::__construct();
}
public function findByX($x) {
return $this->findByCondition($this->getCheckQuery(), [$x]);
}
/*------------------------------------------------------------------------------------*/
protected function getCheckMessage() {
return "Este tipo de producto ya existe";
}
protected function getCheckParameter($unique) {
return [$unique->getNombre()];
}
protected function getCheckQuery() {
return "select * from tipo_producto where tpNombre = ?";
}
/*------------------------------------------------------------------------------------*/
protected function getCreateParameter($object) {
return [$object->getNombre()];
}
protected function getCreateQuery() {
return "insert into tipo_producto(tpNombre) values(?)";
}
/*------------------------------------------------------------------------------------*/
protected function getFindParameter($criterio = null) {
return [$criterio];
}
protected function getFindQuery($criterio = null) {
return "select * from tipo_producto order by tpNombre";
}
/*------------------------------------------------------------------------------------*/
protected function getUpdateParameter($object) {
return [$object->getNombre(), $object->getId()];
}
protected function getUpdateQuery() {
return "update tipo_producto set tpNombre = ? where tpId = ?";
}
/*------------------------------------------------------------------------------------*/
protected function getFindXIdQuery() {
return "select * from tipo_producto where tpId = ?";
}
public function createEntity($row) {
$tp = new TipoProducto();
$tp->setId($row["tpId"]);
$tp->setNombre($row["tpNombre"]);
return $tp;
}
/*------------------------------------------------------------------------------------*/
protected function getDeleteParameter($object) {
return [$object->getId()];
}
protected function getDeleteQuery($notUsed = true) {
return "delete from tipo_producto where tpId = ?";
}
protected function getCheckDelete($object) {
if($this->execute("select * from productos where tpId = ?", [$object->getId()])){
Session::set("msg", Session::msgDanger("Hay productos utilizando este tipo"));
return false;
} else {
return true;
}
}
} | true |
9b4a5c6624dcc77c8ce52242506ec60145dbc8a5 | PHP | gudangcoding/cmsku2 | /library/.config.php | UTF-8 | 852 | 2.78125 | 3 | [] | no_license | <?php
//Membuat variable untuk koneksi, ubah sesuai dengan nama host dan database sesuai hosting
$host = "";
$user = "";
$pass = "";
$db = "";
//Menggunakan object mysqli untuk membuat koneksi dan menyimpannya dalam variable $mysqli
$mysqli = new mysqli($host, $user, $pass, $db);
//Menentukan default timezone
date_default_timezone_set('Asia/Jakarta');
//Membuat variabel yang berisi array nama-nama hari dan menggunakannya untuk mengkonversi nilai hari menjadi nama hari bahasa indonesia yang disimpan pada variabel $hari_ini
$nama_hari = array("Minggu","Senin","Selasa","Rabu","Kamis","Jumat","Sabtu");
$hari = date("w");
$hari_ini = $nama_hari[$hari];
//Membuat variable yang menyimpan nilai waktu
$tgl_sekarang = date("d");
$bln_sekarang = date("m");
$thn_sekarang = date("Y");
$tanggal = date('Ymd');
$jam = date("H:i:s"); | true |
1052ead7401da1513229a5244065ae0ad09fb23d | PHP | kaaterskil/traveloti | /module/Base/src/Base/Form/FriendFinderForm.php | UTF-8 | 1,690 | 2.765625 | 3 | [] | no_license | <?php
/**
* Traveloti Library
*
* @package Traveloti_Base
* @copyright Copyright (c) 2009-2012 Kaaterskil Management, LLC
* @version $Id: $
*/
namespace Base\Form;
use Config\Model\Profile;
use Zend\Form\Form;
use Zend\Form\Element;
/**
* FriendFinderForm Class
*
* @author Blair
*/
class FriendFinderForm extends Form {
private $interests = array();
public function __construct(array $interests = null){
parent::__construct();
if($interests != null) {
$this->interests = $interests;
$this->init();
}
}
/** @return array */
public function getInterests() {
return $this->interests;
}
public function setInterests(array $interests) {
$this->interests = $interests;
$this->reset();
$this->init();
}
private function init() {
$categories = array_keys($this->interests);
foreach ($categories as $category) {
$interests = $this->interests[$category];
$options = array();
foreach($interests as $interest) {
$key = $interest->getId();
$value = $interest->getDisplayName();
$options[$key] = $value;
}
$categoryElement = new Element\Select();
$categoryElement->setAttributes(array(
'class' => 'browser-form-element',
'id' => substr(md5($category), 0, 8),
'name' => $category,
));
$categoryElement->setLabel($category);
$categoryElement->setLabelAttributes(array(
'class' => 'browser-form-label',
));
$categoryElement->setEmptyOption('Select...');
$categoryElement->setValueOptions($options);
$this->add($categoryElement);
}
}
private function reset() {
$elements = $this->getElements();
foreach ($elements as $element) {
$this->remove($element);
}
}
}
?> | true |
1bdc8b94c48eb2f72d23d568c7435a5458d21d94 | PHP | rolwi/koala | /extensions/content/wave/classes/model/WaveTheme.class.php | UTF-8 | 6,718 | 2.859375 | 3 | [] | no_license | <?php
namespace Wave\Model;
/**
* Wheel model object for a wave side. It's a object with following attributes:
* OBJ_TYPE: "container_wavetheme"
* WAVETHEME_TYPE: "<type name string>"
* @author Dominik Niehus <nicke@uni-paderborn.de>
*
*/
abstract class WaveTheme extends WaveObject{
private $myEngine;
private $htmlTemplate;
private $plistXml;
private $themeBaseUrl;
private $themeName;
private $header = "";
private $title = "";
private $style_variations = "";
private $user_styles = "";
private $user_javascript = "";
private $plugin_header = "";
private $user_header = "";
private $toolbar = "";
private $logo = "";
private $site_title = "";
private $site_slogan = "";
private $sidebar_title = "";
private $sidebar = "";
private $plugin_sidebar = "";
private $breadcrumb = "";
private $content = "";
private $footer = "";
private $prev_chapter = "";
private $chapter_menu = "";
private $next_chapter = "";
public function setEngine($engine) {
$this->myEngine = $engine;
}
public function getEngine() {
return $this->myEngine;
}
public function setHtmlTemplate($htmlTemplate) {
$this->htmlTemplate = $htmlTemplate;
$this->convertRW2IT();
}
public function getHtmlTemplate() {
return $this->htmlTemplate;
}
public function setPlistXml($plistXml) {
$this->plistXml = $plistXml;
}
public function getPlistXml() {
return $this->plistXml;
}
public function setThemeBaseUrl($themeBaseUrl) {
$this->themeBaseUrl = $themeBaseUrl;
}
public function getThemeBaseUrl() {
return $this->themeBaseUrl;
}
public function setThemeName($themeName) {
$this->themeName = $themeName;
}
public function getThemeName() {
return $this->themeName;
}
abstract function getDownload($downloadPathArray);
private function convertRW2IT() {
$this->htmlTemplate = preg_replace("/%pathto\((.*)\)%/U", $this->getThemeBaseUrl() . "$1", $this->htmlTemplate);
$this->htmlTemplate = str_replace("%header%", "{HEADER}", $this->htmlTemplate);
$this->htmlTemplate = str_replace("%title%", "{TITLE}", $this->htmlTemplate);
$this->htmlTemplate = str_replace("%style_variations%", "{STYLE_VARIATIONS}", $this->htmlTemplate);
$this->htmlTemplate = str_replace("%user_styles%", "{USER_STYLES}", $this->htmlTemplate);
$this->htmlTemplate = str_replace("%user_javascript%", "{USER_JAVASCRIPT}", $this->htmlTemplate);
$this->htmlTemplate = str_replace("%plugin_header%", "{PLUGIN_HEADER}", $this->htmlTemplate);
$this->htmlTemplate = str_replace("%user_header%", "{USER_HEADER}", $this->htmlTemplate);
$this->htmlTemplate = str_replace("%toolbar%", "{TOOLBAR}", $this->htmlTemplate);
$this->htmlTemplate = str_replace("%logo%", "{LOGO}", $this->htmlTemplate);
$this->htmlTemplate = str_replace("%site_title%", "{SITE_TITLE}", $this->htmlTemplate);
$this->htmlTemplate = str_replace("%site_slogan%", "{SITE_SLOGAN}", $this->htmlTemplate);
$this->htmlTemplate = str_replace("%sidebar_title%", "{SIDEBAR_TITLE}", $this->htmlTemplate);
$this->htmlTemplate = str_replace("%sidebar%", "{SIDEBAR}", $this->htmlTemplate);
$this->htmlTemplate = str_replace("%plugin_sidebar%", "{PLUGIN_SIDEBAR}", $this->htmlTemplate);
$this->htmlTemplate = str_replace("%breadcrumb%", "{BREADCRUMB}", $this->htmlTemplate);
$this->htmlTemplate = str_replace("%content%", "{CONTENT}", $this->htmlTemplate);
$this->htmlTemplate = str_replace("%footer%", "{FOOTER}", $this->htmlTemplate);
$this->htmlTemplate = str_replace("%prev_chapter%", "{PREV_CHAPTER}", $this->htmlTemplate);
$this->htmlTemplate = str_replace("%chapter_menu%", "{CHAPTER_MENU}", $this->htmlTemplate);
$this->htmlTemplate = str_replace("%next_chapter%", "{NEXT_CHAPTER}", $this->htmlTemplate);
}
public function getHtml() {
$content = new \HTML_TEMPLATE_IT();
$content->setTemplate($this->htmlTemplate);
$content->setVariable("HEADER", $this->header);
$content->setVariable("TITLE", $this->title);
$content->setVariable("STYLE_VARIATIONS", $this->style_variations);
$content->setVariable("USER_STYLES", $this->user_styles);
$content->setVariable("USER_JAVASCRIPT", $this->user_javascript);
$content->setVariable("PLUGIN_HEADER", $this->plugin_header);
$content->setVariable("USER_HEADER", $this->user_header);
$content->setVariable("TOOLBAR", $this->toolbar);
$content->setVariable("LOGO", $this->logo);
$content->setVariable("SITE_TITLE", $this->site_title);
$content->setVariable("SITE_SLOGAN", $this->site_slogan);
$content->setVariable("SIDEBAR_TITLE", $this->sidebar_title);
$content->setVariable("SIDEBAR", $this->sidebar);
$content->setVariable("PLUGIN_SIDEBAR", $this->plugin_sidebar);
$content->setVariable("BREADCRUMB", $this->breadcrumb);
$content->setVariable("CONTENT", $this->content);
$content->setVariable("FOOTER", $this->footer);
$content->setVariable("PREV_CHAPTER", $this->prev_chapter);
$content->setVariable("CHAPTER_MENU", $this->chapter_menu);
$content->setVariable("NEXT_CHAPTER", $this->next_chapter);
return $content->get();
}
public function setHeader($header) {
$this->header = $header;
}
public function setTitle($title) {
$this->title = $title;
}
public function setStyleVariations($styleVariations) {
$this->style_variations = $styleVariations;
}
public function setUserStyles($userStyles) {
$this->user_styles = $userStyles;
}
public function setUserJavascript($userJavascript) {
$this->user_javascript = $userJavascript;
}
public function setPluginHeader($pluginHeader) {
$this->plugin_header = $pluginHeader;
}
public function setUserHeader($userHeader) {
$this->user_header = $userHeader;
}
public function setToolbar($toolbar) {
$this->toolbar = $toolbar;
}
public function setLogo($logo) {
$this->logo = $logo;
}
public function setSiteTitle($siteTitle) {
$this->site_title = $siteTitle;
}
public function setSiteSlogan($siteSlogan) {
$this->site_slogan = $siteSlogan;
}
public function setSidebarTitle($sidebarTitle) {
$this->sidebar_title = $sidebarTitle;
}
public function setSidebar($sidebar) {
$this->sidebar = $sidebar;
}
public function setPluginSidebar($pluginSidebar) {
$this->plugin_sidebar = $pluginSidebar;
}
public function setBreadcrumb($breadcrumb) {
$this->breadcrumb = $breadcrumb;
}
public function setContent($content) {
$this->content = $content;
}
public function setFooter($footer) {
$this->footer = $footer;
}
public function setPrevChapter($prevChapter) {
$this->prev_chapter = $prevChapter;
}
public function setChapterMenu($chapterMenu) {
$this->chapter_menu = $chapterMenu;
}
public function setNextChapter($nextChapter) {
$this->next_chapter = $nextChapter;
}
} | true |
e2049f96ab6718d098f5a3ff12c1d56be8335b91 | PHP | KyeBuff/todo-api | /app/Http/Controllers/Tasks.php | UTF-8 | 1,303 | 2.703125 | 3 | [] | no_license | <?php
namespace App\Http\Controllers;
use App\Task;
use App\Http\Requests\TaskRequest;
class Tasks extends Controller
{
public function create(TaskRequest $request)
{
// get post request data for title and article
$data = $request->only(["task", "priority"]);
// create article with data and store in DB
$task = Task::create($data);
// return the article along with a 201 status code
return response($task, 201);
}
public function list()
{
// get all the articles
return Task::all();
}
public function update(TaskRequest $request, Task $task)
{
// get post request data for title and article
$data = $request->only(["task", "priority"]);
// create article with data and store in DB
$task->fill($data)->save();
// return the article along with a 201 status code
return response($task, 201);
}
public function delete(Task $task)
{
$task->delete();
// use a 204 code as there is no content in the response
return response(null, 204);
}
public function complete(Task $task)
{
//Set complete prop of task to true
$task->complete = true;
//Use model to save task in table
$task->save();
// return the article along with a 201 status code
return $task;
}
}
| true |
316586d05562d51817c657e9196266417c552f77 | PHP | sanathkumarls/Pharmacy_MVC | /application/models/Customer.php | UTF-8 | 1,222 | 3 | 3 | [
"MIT"
] | permissive | <?php
/**
* Created by PhpStorm.
* User: sanathls
* Date: 29/09/19
* Time: 4:09 PM
*/
require_once __DIR__.'/../utilities/Database.php';
class Customer
{
public function addCustomer($name,$email,$phone,$address)
{
$db=new Database();
$con=$db->open_connection();
$query="insert into customer values (NULL,'$name','$email','$phone','$address')";
$result=$con->query($query);
return $result;
}
public function getCustomer($c_id = 0)
{
$db=new Database();
$con=$db->open_connection();
if($c_id != 0)
$query="select * from customer where `c_id` = '$c_id'";
else
$query="select * from customer";
$result=$con->query($query);
if($result->num_rows > 0)
return $result;
return false;
}
public function getCustomerName($c_id)
{
$db=new Database();
$con=$db->open_connection();
$query="select * from customer where c_id = '$c_id'";
$result=$con->query($query);
if($result->num_rows > 0)
{
$row = $result->fetch_assoc();
return $row['c_name'];
}
return "";
}
} | true |
b4d905005907ead661169f249627e02b0f6b2180 | PHP | rahilwazir/toddler-story | /src/RW/Modules/Child.php | UTF-8 | 4,848 | 2.703125 | 3 | [] | no_license | <?php
namespace RW\Modules;
use RW\PostTypes\Children;
use RW\PostTypes\ChildBlog;
/**
* Toddler Child Module
*
* @package
*
* @author rahilwazir
* @copyright 2014
* @version 1.0
* @access public
*/
class Child extends ParentModule
{
public static $post_id = 0;
/**
* @var int
*/
public static $global_post_id = 0;
public static function customPost()
{
return (self::$post_id > 0) ? self::$post_id : false;
}
/**
* Retrieve Child ID
* @return int
*/
public static function id()
{
if (self::getCurrentParentId() !== 0)
{
return user_info('ID');
}
}
public static function page()
{
return (is_singular(Children::$post_type));
}
public static function title()
{
global $post;
return get_the_title($post);
}
public static function dURL()
{
global $post;
return $post->post_name;
}
public static function thumb($size = 'dp')
{
global $post;
return (!has_post_thumbnail()) ?
'<img src="'.get_template_directory_uri() . '/images/avatar.png" alt="'.$post->post_title.'">' :
get_the_post_thumbnail($post->ID, $size);
}
public static function firstName()
{
global $post;
return (get_post_meta($post->ID, '_child_first_name', true))
? get_post_meta($post->ID, '_child_first_name', true)
: '';
}
public static function lastName()
{
global $post;
return (get_post_meta($post->ID, '_child_last_name', true))
? get_post_meta($post->ID, '_child_last_name', true)
: '';
}
public static function fullName($split_by = ' ')
{
return self::firstName() . $split_by . self::lastName();
}
public static function description()
{
global $post;
$content = get_post_field('post_content', $post->ID);
return ($content !== "")
? $content
: 'No description';
}
public static function birthDate()
{
global $post;
return (get_post_meta($post->ID, '_dob_child', true))
? get_post_meta($post->ID, '_dob_child', true)
: '';
}
public static function age()
{
return (self::birthDate() !== '') ?
process_date(self::birthDate()) :
'';
}
public static function sex()
{
global $post;
return (get_post_meta($post->ID, '_toddler_sex', true))
? get_post_meta($post->ID, '_toddler_sex', true)
: '';
}
public static function relation()
{
global $post;
return (get_post_meta($post->ID, '_toddler_relation', true))
? get_post_meta($post->ID, '_toddler_relation', true)
: '';
}
public static function bg($id = false)
{
global $post;
$bg_id = get_post_meta($post->ID, '_toddler_bg', true);
return ($bg_id) ? ( ($id === true) ? $bg_id : get_full_thumbnail_uri($bg_id)) : 0;
}
public static function publicAccess()
{
global $post;
return (get_post_meta($post->ID, '_toddler_ata', true))
? get_post_meta($post->ID, '_toddler_ata', true)
: '';
}
/**
* Check if child post is exists with the id given optionally with the post author
* @param int $id
* @param int $user_id
* @param string $post_type
* @return bool
*/
public static function existAt($id, $user_id = 0, $post_type = '')
{
$args = array(
'post_type' => ($post_type === '') ? Children::$post_type : $post_type,
'p' => intval($id),
'posts_per_page' => 1,
);
if ($user_id > 0) {
$args['post_author'] = $user_id;
} else {
$args['post_author'] = user_info('ID');
}
$query = get_custom_posts($args);
return ($query !== 0) ? true : false;
}
public static function blogPosts($id)
{
$blog_posts = \get_custom_posts(array(
'post_type' => ChildBlog::$post_type,
'author__in' => array($id),
'meta_key' => '_toddler_parent_child_user',
'meta_value' => $id,
'posts_per_page' => 10
));
return $blog_posts;
}
public static function getCurrent($id)
{
global $post;
self::$global_post_id = $post->ID;
$post = get_post( $id, OBJECT );
setup_postdata( $post );
}
public static function setCurrent()
{
global $post;
$post = self::$global_post_id;
}
} | true |
a78b15d86b3e6b974c367a9930ac2a7e3b48e0b7 | PHP | davin-bao/statistics | /src/DavinBao/Statistics/StatisticsStatistic.php | UTF-8 | 2,779 | 2.734375 | 3 | [
"MIT"
] | permissive | <?php
/**
* Created by PhpStorm.
* User: davin.bao
* Date: 14-5-12
* Time: 上午11:36
*/
namespace DavinBao\Statistics;
use LaravelBook\Ardent\Ardent;
use Config;
class StatisticsStatistic extends Ardent
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'statistics';
protected $results = array();
/**
* Laravel application
*
* @var Illuminate\Foundation\Application
*/
public static $app;
/**
* Ardent validation rules
*
* @var array
*/
public static $rules = array(
'name' => 'required|between:1,20',
'sql' => 'required'
);
/**
* Creates a new instance of the model
*/
public function __construct(array $attributes = array())
{
parent::__construct($attributes);
if ( ! static::$app )
static::$app = app();
}
public function getColumnNameArray(){
return explode('|', $this->column_names);
}
public function getResult(){
if(count($this->results)>0) return $this->results;
$sql = $this->sql;
$this->results = $this->convertArray(\DB::select($sql));
return $this->results;
}
public function getResultPaginate(){
if(count($this->results)<= 0){
$this->getResult();
}
$currentPage = \Paginator::getCurrentPage();
return array_slice($this->results, ($currentPage-1) * static::$app['config']->get('statistics::paginate_num'), static::$app['config']->get('statistics::paginate_num'));
}
public function links(){
if(count($this->results)<= 0){
$this->getResult();
}
return \Paginator::make($this->results, count($this->results), static::$app['config']->get('statistics::paginate_num'))->links();
}
public function convertArray($results){
$res = array();
foreach($results as $result){
array_push($res, get_object_vars($result));
}
return $res;
}
public function getChartColumn(){
$arrChratCol = array();
$results = $this->getResult();
if(is_array($results) && count($results)>0){
$result = $results[0];
}
if(is_array($result)){
$i =0;
foreach($result as $res){
if(is_double($res) || is_float($res) || is_int($res)) {
$arrChratCol[$i] = true;
}else{
$arrChratCol[$i] = false;
}
$i++;
}
}
$arrChratCol[0] = false;
return $arrChratCol;
}
public function getColumnData($colIndex = 0){
$arrCol = array();
$results = $this->getResult();
foreach ($results as $result) {
if(is_array($result) && count($result)>$colIndex){
$i =0;
foreach($result as $res) {
if($i == $colIndex) {
array_push($arrCol, $res);
}
$i++;
}
}
}
return $arrCol;
}
} | true |
acc3ec74560ace92fcb69072da903437f38e80ae | PHP | AkshatKSinghal/framework | /Utility/FieldValidator.php | UTF-8 | 1,702 | 2.859375 | 3 | [] | no_license | <?php
namespace Utility;
/**
* Class for Validating mandatory and optional fields against an array
*/
class FieldValidator
{
public static function checkFields($requestData, $fields, $subArrayName = 'main', $cntr = 0)
{
$checkedData = [];
$arrayTrace = $subArrayName;
foreach ($fields as $field => $fieldDetail) {
if ($fieldDetail['mandatory'] && !(array_key_exists($field, $requestData) && $requestData[$field] != '')) {
throw new \Exception("Mandatory Field not found " . $arrayTrace . '->' . $field);
} else {
if (isset($requestData[$field])) {
$nextRequestData = $requestData[$field];
if (empty($fieldDetail['data'])) {
$checkedData[$field] = $requestData[$field];
} else {
if ($fieldDetail['multiple']) {
// if (!isset($checkedData[$field])) {
// $checkedData[$field] = [];
// }
foreach ($requestData[$field] as $requestField) {
$checkedData[$field][] = self::checkFields($requestField, $fields[$field]['data'], $subArrayName);
}
$nextRequestData = $requestData[$field][$cntr];
} else {
$checkedData[$field] = self::checkFields($nextRequestData, $fieldDetail['data'], $subArrayName . '->' . $field);
}
}
}
}
}
return $checkedData;
}
}
| true |
2a51298b4bb77c54dfdfae6d4c14f6d00721dd72 | PHP | peslopes/computer-science-full-graduation | /Semestre 03/INF05005 - Linguagens Formais e Autômatos/Trabalho Final Formais/Parte02/TrabFormais2010-02_Parte02.php | UTF-8 | 21,303 | 2.796875 | 3 | [] | no_license | <?php
error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE);
/*
b) Tradução de AFNe para AFN;
Entrega dia: 14/10/2010
*/
/* Variáveis globais */
//Inicializados na função leDefinicaoDoAutomato
$lAlfabeto = NULL; //alfabeto
$lEstados = NULL; //estados do autômato
$lEstadosFinais = NULL; //estados finais
$estadoInicial = NULL; //estado inicial
$handle = NULL;
$fechoVazio = NULL; //fecho vazio de cada estado (etapa 1)
$fechoAlfabeto = NULL; //fecho de cada elemento do alfabeto (etapa 2)
$fechoVazioFinal = NULL; //fecho vazio de cada estado (da etapa 3)
//Inicializado na função leTransicoesDoAutomato
$mTransicoes = NULL; //matriz com as transições do autômato
$ehAFNe = false;
//Variáveis auxiliares
$lTokens = NULL; //usada na função tokeniza. A função tokeniza uma sequencia de transições separadas por ";" e coloca em $lTokes o resultado
$definicaoFormal = NULL; //captura a definicação formal do autômato
/* Algoritmo total:
1) lê definição da máquina (done)
2) lê tabela de transições (done)
3) analisa transições
Etapa 1) vê todas as transições do fecho vazio do estado analisado
Etapa 2) aplica sobre esses estados o fecho com a transição
Etapa 3) encontra o fecho vazio sobre o resultado da Etapa 2)
*/
//-----------------------------------------------------------------------------
//lê as definições do autômato (alfabeto, estados, estado inicial e estados finais)
function leDefinicaoDoAutomato($fileName)
{
global $lAlfabeto, $lEstados, $lEstadosFinais, $estadoInicial, $handle, $definicaoFormal;
$fileName = "automatons/".$fileName;
$handle = fopen($fileName,"r");
$buffer = fgets($handle); //pega a primeira linha do arquivo com nome $fileName até encontrar '\n'
$definicaoFormal = $buffer;
echo "------------------------------------<br>";
echo "Arquivo de entrada: <br>";
echo $definicaoFormal."<br>";
$buffer = strstr($buffer,"{");
//Captura Alfabeto
$auxAlfabeto = strtok($buffer,"}"); //Ex.: $s = halela; strtok($string,"l") == ha
$auxAlfabeto = strtok($auxAlfabeto,"{,");
$lAlfabeto[] = "e"; //e de vazio
$lAlfabeto[] = $auxAlfabeto;
while($auxAlfabeto != NULL)
{
$auxAlfabeto = strtok("{,");
if($auxAlfabeto != NULL)
$lAlfabeto[] = $auxAlfabeto;
}
//Captura Estados
$buffer = strstr($buffer,","); //$s = halela; strstr($s,"l") == lela
$buffer = strstr($buffer,"{");
$auxEstado = strtok($buffer,"}");
$auxEstado = strtok($auxEstado,"{,");
$lEstados[1] = $auxEstado;
while($auxEstado != NULL)
{
$auxEstado = strtok("{,");
if($auxEstado != NULL)
$lEstados[] = $auxEstado;
}
//Captura Estado Inicial
$buffer = strstr($buffer,"}");
$buffer = strstr($buffer,",");
$estadoInicial = strtok($buffer,",");
//Captura Estados Finais
$buffer = strstr($buffer,"{");
$buffer = strtok($buffer,"}");
$auxEstadoFinal = strtok($buffer,"{,");
$lEstadosFinais[] = $auxEstadoFinal;
while($auxEstadoFinal != NULL)
{
$auxEstadoFinal = strtok("{,");
if($auxEstadoFinal != NULL)
$lEstadosFinais[] = $auxEstadoFinal;
}
return;
}
//-----------------------------------------------------------------------------
//imprime as definições do autômato (alfabeto, estados, estado inicial e estados finais),
//capturadas na função leDefinicaoDoAutomato()
function imprimeDefinicaoDoAutomato()
{
global $lAlfabeto, $lEstados, $lEstadosFinais, $estadoInicial;
echo "Alfabeto: ";
for($i = 0; $i < sizeof($lAlfabeto); $i++){
echo $lAlfabeto[$i].", ";
}
echo "<br>";
echo "Estados: ";
for($i = 1; $i <= sizeof($lEstados); $i++){
echo $lEstados[$i].", ";
}
echo "<br>";
echo "Estados Finais: ";
for($i = 0; $i < sizeof($lEstadosFinais); $i++){
echo $lEstadosFinais[$i].".";
}
echo "<br>";
echo "Estado Inicial: ".$estadoInicial;
echo ".<br>-------------------------------------<br>";
return;
}
//-----------------------------------------------------------------------------
//lê as transições das máquinas - deve ser rodada depois da função le_automato()
function leTransicoesDoAutomato()
{
global $handle, $lAlfabeto, $mTransicoes, $ehAFNe;
$buffer = fgets($handle);
echo $buffer."<br>";
//echo "linha: ".$buffer.".<br>";
$estado = strtok($buffer," "); //pega primeiro estado
//echo " estado: $estado<br>";
for($i = 0; $i < sizeof($lAlfabeto); $i++)
{
unset($aux); //destroi $aux
$aux = strtok(" ");
//echo " trans: ".$lAlfabeto[$i].", aux: ".$aux.", i: $i<br>";
if($aux != '-' && $i == 0)
$ehAFNe = true;
if($i == sizeof($lAlfabeto) - 1)
{
$aux2 = substr($aux,0,-1);
$auxTransicoes[] = $aux2;
}
else
$auxTransicoes[] = $aux;
}
for($i = 0; $i < sizeof($lAlfabeto); $i++)
$mTransicoes[$estado][$lAlfabeto[$i]] = $auxTransicoes[$i]; //mtransicoes["q0"]["e"] = "-"
//mtransicoes["q0"]["a"] = "q1"
unset($buffer); //destroi buffer
$buffer = fgets($handle);
while(!feof($handle))
{
echo $buffer."<br>";
//echo "linha: ".$buffer.".<br>";
//$buffer[strlen($buffer) - 1] = NULL;
unset($auxTransicoes);
$estado = strtok($buffer," ");
//echo " estado: $estado<br>";
for($i = 0; $i < sizeof($lAlfabeto); $i++)
{
unset($aux);
$aux = strtok(" ");
//echo " trans: ".$lAlfabeto[$i].", aux: ".$aux.", i: $i<br>";
if($aux != '-' && $i == 0){
$ehAFNe = true;
//echo " ehAFNe: $ehAFNe!<br>";
}
if($i == sizeof($lAlfabeto) - 1)
{
$aux2 = substr($aux,0,-1);
$auxTransicoes[] = $aux2;
}
else
$auxTransicoes[] = $aux;
}
for($i = 0; $i < sizeof($lAlfabeto); $i++)
$mTransicoes[$estado][$lAlfabeto[$i]] = $auxTransicoes[$i];
unset($buffer); //destroi buffer
$buffer = fgets($handle);
}
fclose($handle);
return;
}
//--------------------------------------------------------------------------
//Imprime o autômato lido no arquivo de texto
function imprimeAutomatoDeEntrada()
{
global $mTransicoes, $lAlfabeto, $lEstados;
echo "------------------------------------<br>";
echo "Automato de entrada lido:<br>";
for($i = 1; $i <= sizeof($lEstados); $i++)
{
echo " ".$lEstados[$i]."<br>";
for($j = 0; $j < sizeof($lAlfabeto); $j++)
{
echo " ".$lAlfabeto[$j].": ";
echo $mTransicoes[$lEstados[$i]][$lAlfabeto[$j]].".<br>";
}
}
echo "------------------------------------<br>";
return;
}
//--------------------------------------------------------------------------
//Determina os fechos vazios de cada estado
function determinaFechosVazios()
{
global $mTransicoes, $lAlfabeto, $fechoVazio, $lEstados, $lTokens;
//Variáveis
$arrayEstados = NULL; //array com as diversas transições vazias de um mesmo estado
$arrayEstados2 = NULL;
$transConcatenadas = NULL; //array com a string inteira da transição, pode ter diversas transições vazias
echo "------------------------------------<br>";
echo "Passo 1: Fechos dos estados<br>";
for($i = 1; $i <= sizeof($lEstados); $i++) //determina o fecho para cada estado do autômato
{
//echo "Fecho de ".$lEstados[$i].":<br>";
//echo " Transicoes vazias: ".$mTransicoes[$lEstados[$i]][$lAlfabeto[0]]."<br>";
if($mTransicoes[$lEstados[$i]][$lAlfabeto[0]] != '-') //mtransicoes["q0"]["e"] != "-"
{
//echo " Diferente de '-'<br>";
$fechoVazio[$lEstados[$i]][] = $lEstados[$i]; //coloca ele mesmo na lista //fechoVazio["q0"][0] = "q0'
$lTokens = NULL; //limpa conteúdo de $lTokens
tokeniza($mTransicoes[$lEstados[$i]][$lAlfabeto[0]]); //"tokeniza" vai deixar em $lTokens todos os estados de transição vazia
$arrayEstados = $lTokens;
for($j = 0; $j < sizeof($arrayEstados); $j++)
{
//echo " arrayEstados[$j] = ".$arrayEstados[$j]."<br>";
//ve se o estado está no fecho, se não estiver coloca
if(array_search($arrayEstados[$j], $fechoVazio[$lEstados[$i]]) == NULL
&& $arrayEstados[$j] != '-'
&& $arrayEstados[$j] != $fechoVazio[$lEstados[$i]][0])
{ //o teste é igual a NULL, logo não achou o estado no fecho
$fechoVazio[$lEstados[$i]][sizeof($fechoVazio[$lEstados[$i]])] = $arrayEstados[$j];
//echo " 1fechoVazio[$lEstados[$i]][".sizeof($fechoVazio[$lEstados[$i]])."]: ".$arrayEstados[$j]."<br>";
//agora precisamos ver as transições vazias do arrayEstados[$j]
$lTokens = NULL; //limpa conteúdo de $lTokens
tokeniza($mTransicoes[$arrayEstados[$j]][$lAlfabeto[0]]);
$arrayEstados2 = NULL;
$arrayEstados2 = $lTokens;
//echo " ";
//echo "transicao: ".$arrayEstados2[0]."<br>";
for($k = 0; $k < sizeof($arrayEstados2); $k++)
{
if(array_search($arrayEstados2[$j], $fechoVazio[$lEstados[$i]]) == NULL
&& $arrayEstados2[$j] != '-'
&& $arrayEstados2[$j] != $fechoVazio[$lEstados[$i]][0])
{
$fechoVazio[$lEstados[$i]][sizeof($fechoVazio[$lEstados[$i]])] = $arrayEstados2[$k];
//echo " 2fechoVazio[$lEstados[$i]][".sizeof($fechoVazio[$lEstados[$i]])."]: ".$arrayEstados2[$j]."<br>";
}
}
}
}
}
else //estado sem transições vazias, logo o fecho vazio é vazio
{
$fechoVazio[$lEstados[$i]][] = $lEstados[$i]; //o fecho de um estado contém ele próprio sempre
//echo " Eh vazio, coloca so ele mesmo<br>";
}
}
for($i = 1; $i <= sizeof($lEstados); $i++) //determina o fecho para cada estado do autômato
{
sort($fechoVazio[$lEstados[$i]]);
echo $lEstados[$i].": ";
for($j = 0; $j < sizeof($fechoVazio[$lEstados[$i]]); $j++)
{
echo $fechoVazio[$lEstados[$i]][$j].".";
}
echo "<br>";
}
echo "------------------------------------<br>";
return;
}
//tokenizador, programa que tokeniza uma string em subpalavras. Coloca as subpalavras em um array
//e retorna esse mesmo array
function tokeniza($string)
{
global $lTokens;
$aux_string = strtok($string,";");
if(!array_search($aux_string, $lTokens) && $aux_string != $lTokens[0] && $aux_string != '-')
$lTokens[] = $aux_string;
while($aux_string != NULL)
{//inicializa algoritmo de tradução
$aux_string = strtok(";");
if($aux_string != NULL && !array_search($aux_string, $lTokens) && $aux_string != $lTokens[0] && $aux_string != '-')
$lTokens[] = $aux_string;
}
return;
}
//função pega os fechos vazios do passo 1) e determina as transições dos estados presentes em cada
//fecho para cada elemento do alfabeto
function determinaFechosAlfabeto()
{
global $mTransicoes, $lAlfabeto, $lEstados, $fechoVazio, $fechoAlfabeto, $lTokens;
$auxFechoAlf = NULL; //armazena todas as transições do fecho de cada elemento do alfabeto
echo "Passo 2: Determina Fechos Alfabeto<br>";
for($i = 1; $i <= sizeof($lEstados); $i++)
{
//echo "Estado: ".$lEstados[$i]."<br>";
for($j = 1; $j < sizeof($lAlfabeto); $j++)
{
//echo " ";
//echo "Alfabeto: ".$lAlfabeto[$j]."<br>";
for($k = 0; $k < sizeof($fechoVazio[$lEstados[$i]]); $k++)
{
//echo " ";
//echo "Fecho Vazio: ";
//for($a = 0; $a < sizeof($fechoVazio[$lEstados[$i]]); $a++)
//echo $fechoVazio[$lEstados[$i]][$a].".";
//echo "<br>";
$aux = $mTransicoes[$fechoVazio[$lEstados[$i]][$k]][$lAlfabeto[$j]];
$lTokens = NULL;
tokeniza($aux);
$auxFechoAlf = $lTokens;
//echo " ";
//echo "fechoVazio[$lEstados[$i]][$k]: ".$fechoVazio[$lEstados[$i]][$k]."<br>";
//echo " ";
//echo "auxFechoAlf: ";
//for($a = 0; $a < sizeof($auxFechoAlf); $a++)
//echo $auxFechoAlf[$a].".";
//echo "<br>";
for($l = 0; $l < sizeof($auxFechoAlf); $l++)
{
if( array_search($auxFechoAlf[$l], $fechoAlfabeto[$lEstados[$i]][$lAlfabeto[$j]]) == NULL
&& $auxFechoAlf[$l] != $fechoAlfabeto[$lEstados[$i]][$lAlfabeto[$j]][0]
&& $auxFechoAlf[$l] != '-' )
{
$fechoAlfabeto[$lEstados[$i]]
[$lAlfabeto[$j]]
[sizeof($fechoAlfabeto[$lEstados[$i]][$lAlfabeto[$j]])] = $auxFechoAlf[$l];
//echo " ";
//echo "----->>>Gravou: ".$fechoAlfabeto[$lEstados[$i]]
//[$lAlfabeto[$j]]
//[sizeof($fechoAlfabeto[$lEstados[$i]][$lAlfabeto[$j]])-1]."<br>";
}
}
}
}
}
for($i = 1; $i <= sizeof($lEstados); $i++){
echo $lEstados[$i].":<br>";
for($j = 1; $j < sizeof($lAlfabeto); $j++){
echo " ";
echo $lAlfabeto[$j].": ";
if(sizeof($fechoAlfabeto[$lEstados[$i]][$lAlfabeto[$j]]) == 0)
$fechoAlfabeto[$lEstados[$i]][$lAlfabeto[$j]][0] = "-";
for($k = 0; $k < sizeof($fechoAlfabeto[$lEstados[$i]][$lAlfabeto[$j]]); $k++){
echo $fechoAlfabeto[$lEstados[$i]][$lAlfabeto[$j]][$k].".";
}
echo "<br>";
}
}
echo "------------------------------------<br>";
return;
}
//função que pega os fechos gerados no passo 2) e para cada estado dos fechos vê os fechos vazios deles e
//une os resultados
function determinaFechosVaziosFinais()
{
global $mTransicoes, $lAlfabeto, $fechoVazio, $lEstados, $lEstadosFinais, $fechoAlfabeto, $fechoVazioFinal;
echo "------------------------------------<br>";
echo "Passo 3: Determina Fechos Vazios Finais<br>";
for($i = 1; $i <= sizeof($lEstados); $i++){
//echo "<br>".$lEstados[$i].":";
for($j = 1; $j < sizeof($lAlfabeto); $j++){
//echo "<br> ";
//echo $lAlfabeto[$j].": ";
for($k = 0; $k < sizeof($fechoAlfabeto[$lEstados[$i]][$lAlfabeto[$j]]); $k++){
$auxEstado = $fechoAlfabeto[$lEstados[$i]][$lAlfabeto[$j]][$k];
//echo "<br> ";
//echo "fechoAlfabeto[$lEstados[$i]][$lAlfabeto[$j]][$k]: ".$fechoAlfabeto[$lEstados[$i]][$lAlfabeto[$j]][$k];
for($l = 0; $l < sizeof($fechoVazio[$auxEstado]); $l++){
//echo "<br> ";
//echo "fechoVazio[$auxEstado][$l]: ".$fechoVazio[$auxEstado][$l];
if(array_search(
$fechoVazio[$auxEstado][$l], $fechoVazioFinal[$lEstados[$i]][$lAlfabeto[$j]]) == NULL
&& $fechoVazio[$auxEstado][$l] != $fechoVazioFinal[$lEstados[$i]][$lAlfabeto[$j]][0]
&& $fechoVazio[$auxEstado][$l] != '-' ){
$fechoVazioFinal[$lEstados[$i]][$lAlfabeto[$j]][] = $fechoVazio[$auxEstado][$l];
}
}
}
}
}
for($i = 1; $i <= sizeof($lEstados); $i++){
$novoFinal = true;
for($j = 1; $j < sizeof($lAlfabeto); $j++){
//echo "estado final: ".$lEstadosFinais[0]." e fechoVazio[0]: ".$fechoVazioFinal[$lEstados[$i]][$lAlfabeto[$j]][0]."<br>";
//echo "array_search, alfabeto: $lAlfabeto[$j], estado: $lEstados[$i]: ".(int)array_search($lEstadosFinais[0], $fechoVazioFinal[$lEstados[$i]][$lAlfabeto[$j]])."<br>";
if( array_search(
$lEstadosFinais[0], $fechoVazioFinal[$lEstados[$i]][$lAlfabeto[$j]]) == NULL
&& $lEstadosFinais[0] != $fechoVazioFinal[$lEstados[$i]][$lAlfabeto[$j]][0]
){
$novoFinal = false;
break;
}
}
if($novoFinal == true && array_search($lEstados[$i], $lEstadosFinais) == NULL && $lEstados[$i] != $lEstadosFinais[0])
$lEstadosFinais[] = $lEstados[$i];
}
//echo "Estados Finais: ";
//for($i = 0; $i < sizeof($lEstadosFinais); $i++){
//echo $lEstadosFinais[$i].", ";
//}
//echo "<br>";
for($i = 1; $i <= sizeof($lEstados); $i++){
echo $lEstados[$i].":<br>";
for($j = 1; $j < sizeof($lAlfabeto); $j++){
echo " ";
echo $lAlfabeto[$j].": ";
sort($fechoVazioFinal[$lEstados[$i]][$lAlfabeto[$j]]);
if(sizeof($fechoVazioFinal[$lEstados[$i]][$lAlfabeto[$j]]) == 0)
$fechoVazioFinal[$lEstados[$i]][$lAlfabeto[$j]][0] = "-";
for($k = 0; $k < sizeof($fechoVazioFinal[$lEstados[$i]][$lAlfabeto[$j]]); $k++){
echo $fechoVazioFinal[$lEstados[$i]][$lAlfabeto[$j]][$k].".";
}
echo "<br>";
}
}
echo "------------------------------------<br>";
return;
}
function unirTokens($lTokens)
{
$stringUnida = NULL;
for($i = 0; $i < sizeof($lTokens); $i++)
{
$stringUnida .= $lTokens[$i];
if($i != sizeof($lTokens) - 1)
$stringUnida .= ";";
}
return $stringUnida;
}
//Gera o arquiv de saída, baseando-se no $fechoVazioFinal
function geraArquivoSaida($fileName)
{
global $definicaoFormal, $lAlfabeto, $lEstados, $lEstadosFinais, $estadoInicial, $fechoVazioFinal;
$arqSaida = "automatons/".reset(explode(".",$fileName))."_saida.txt";
$handleSaida = fopen($arqSaida,"w");
echo "------------------------------------<br>";
echo "Arquivo de saida gerado: ".$arqSaida."<br>";
//gravando as transições
//M1=({a,b},{q0,q1,q2,q3},q0,{q3})
$buffer1 = strrchr($definicaoFormal,",");
//echo "buffer1: ".$buffer1."<br>";
$buffer = explode($buffer1,$definicaoFormal);
//echo "buffer[0]: ".$buffer[0]."<br>";
//M1=({a,b},{q0,q1,q2,q3},q0
$buffer[0] .= ",{";
//echo "buffer: ".$buffer[0]."<br>";
//M1=({a,b},{q0,q1,q2,q3},q0,{
sort($lEstadosFinais);
for($i = 0; $i < sizeof($lEstadosFinais); $i++){
if($i != sizeof($lEstadosFinais) - 1)
$buffer[0] .= $lEstadosFinais[$i].",";
else
$buffer[0] .= $lEstadosFinais[$i]."})";
}
$definicaoFormal = $buffer[0];
fwrite($handleSaida, $definicaoFormal);
fwrite($handleSaida, "\n");
echo "<br>Definicao Formal: ".$definicaoFormal."<br>";
for($i = 1; $i <= sizeof($lEstados); $i++){
fwrite($handleSaida, $lEstados[$i]);
echo $lEstados[$i];
for($j = 1; $j < sizeof($lAlfabeto); $j++){
$aux = " ".unirTokens($fechoVazioFinal[$lEstados[$i]][$lAlfabeto[$j]]);
fwrite($handleSaida, $aux);
echo $aux;
}
fwrite($handleSaida, "\n");
echo "<br>";
}
echo "------------------------------------<br>";
return;
}
?>
<html>
<head>
<title>Trabalho de Formais - 2010/02 - Parte 2</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<style type="text/css">
.style1 {font-family: Arial, Helvetica, sans-serif; font-size: 14px; }
.style2 {font-family: Arial, Helvetica, sans-serif; font-size: 18px; }
.style4 {font-family: Arial, Helvetica, sans-serif; font-size: 14px; }
.style5 {font-family: Arial, Helvetica, sans-serif; font-size: 11px; }
.style6 {color: #FF0000}
.style7 {font-size: 12px}
.style15 {font-family: Arial, Helvetica, sans-serif; font-size: 12px; }
</style>
</head>
<body>
<p><h2>Trabalho de Formais - 2010/02 - Parte 2 - Conversao de AFNe para AFN</h2></p>
<p><br>
Grupo: Joao Gross, Jefferson Stoffel, Henrique Weber<br>
Disciplina: Linguagens Formais e Automatos<br>
Professora: Aline Villavicencio<br><br>
</p>
<form name="form1" align="left" method="post" action="TrabFormais2010-02_Parte02.php?acao=traduzir">
<table width="250" class="txt_padrao" border="0">
<tr>
<td width="150" align="left" class="style15">Arquivo de entrada</td>
</tr>
<tr>
<td align="left" class="style7">
<select name="entrada" class="form style16" id="select2">
<option value="Selecione">Selecione</option>
<?php
if ($handle = opendir('automatons/')) {
echo "Directory handle: $handle\n";
//echo "Files:\n";
/* This is the correct way to loop over the directory. */
while(false !== ($file = readdir($handle))) {
if($file == '.' || $file == '..')
continue;
else
echo "<option value='".$file."'>".$file."</option>";
}
fclose($handle);
}
?>
</select>
</td>
<td><input type="submit" name="Submit" value="Traduzir"></td>
</tr>
</table>
</form>
<form action="recebeArquivo.php" method="post" enctype="multipart/form-data">
<label for="file">Automaton File Description: </label><input type="file" name="file" id="file" /><br />
<input type="submit" name="upload" value="Upload automaton!" /><br />
</form>
<br><br>
<?php
global $lEstados;
//Programa principal (Main)
if($_GET['acao'] == 'traduzir' && $_POST['entrada'] != 'Selecione' )
{
?>
<table width="1400" class="txt_padrao" border="0">
<tr>
<td align="left">
<?php
$fileName = $_POST['entrada'];
leDefinicaoDoAutomato($fileName);
leTransicoesDoAutomato();
if($ehAFNe == false)
{ //se $ehADNe for falso, então o autômao de entrada não tem transições vazias
echo "Automato escolhido nao eh AFNe!";
//echo "<script>alert('Automato escolhido nao eh AFNe!');document.location='TrabFormais2010-02_Parte02.php'</script>";
exit; //return 0; //fim da main
}
imprimeAutomatoDeEntrada();
?>
</td>
<td align="left">
<?php
determinaFechosVazios();
determinaFechosAlfabeto();
?>
</td>
<td align="left">
<?php
determinaFechosVaziosFinais();
?>
</td>
<td align="left">
<?php
geraArquivoSaida($fileName);
}
?>
</td>
</tr>
</table>
<br>
<a href=../trab_formais_2010_02.php>Voltar</a>
</body>
</html>
| true |
49797bd812e47deb982b7832279a65a791286303 | PHP | gzqsts/core | /src/validate/helper.php | UTF-8 | 1,211 | 2.734375 | 3 | [] | no_license | <?php
declare (strict_types = 1);
use Gzqsts\Core\validate\Validate;
if (!function_exists('validate')) {
/**
* 生成验证对象
* @param string|array $validate 验证器类名或者验证规则数组
* @param array $message 错误提示信息
* @param bool $batch 是否批量验证
* @param bool $failException 是否抛出异常
* @return Validate
*/
function validate($validate = '', array $message = [], bool $batch = false, bool $failException = true): Validate
{
if (is_array($validate) || '' === $validate) {
$v = new Validate();
if (is_array($validate)) {
$v->rule($validate);
}
} else {
if (strpos($validate, '.')) {
// 支持场景
[$validate, $scene] = explode('.', $validate);
}
$class = false !== strpos($validate, '\\') ? $validate : $validate;
$v = new $class();
if (!empty($scene)) {
$v->scene($scene);
}
}
return $v->message($message)->batch($batch)->failException($failException);
}
}
| true |
07b5f24a30f58d9400c2117170880acce6a736c1 | PHP | nsdevaraj/adamstudio | /Web/Adamstudio/bin-debug/phpscripts/getCategories.php | UTF-8 | 495 | 2.671875 | 3 | [] | no_license | <?php
include 'config.php';
include 'connect.php';
echo "<?xml version='1.0' ?>\n";
echo "<categories>"."\n";
$query = "SELECT code, label FROM categories ORDER BY code";
$result = mysql_query($query);
echo " <category code='*' label='All Categories' />\n";
while( $row=mysql_fetch_array($result, MYSQL_ASSOC) )
{
echo " <category code=\"".$row['code']."\" label=\"".$row['label']."\">\n";
echo " </category>\n";
}
echo "</categories>";
mysql_close($conn);
?> | true |
557c906f28c2e3d9e811168ab3989f2271f413b6 | PHP | fsiatama/CCI | /app/controllers/SectorController.php | UTF-8 | 2,550 | 2.546875 | 3 | [] | no_license | <?php
require PATH_APP.'min_agricultura/Repositories/SectorRepo.php';
require PATH_APP.'min_agricultura/Repositories/UserRepo.php';
class SectorController {
private $sectorRepo;
private $userRepo;
public function __construct()
{
$this->sectorRepo = new SectorRepo;
$this->userRepo = new UserRepo;
}
public function listAction($urlParams, $postParams)
{
$result = $this->userRepo->validateMenu('list', $postParams);
if ($result['success']) {
$result = $this->sectorRepo->grid($postParams);
}
return $result;
}
public function listIdAction($urlParams, $postParams)
{
return $this->sectorRepo->validateModify($postParams);
}
public function createAction($urlParams, $postParams)
{
$result = $this->userRepo->validateMenu('create', $postParams);
if ($result['success']) {
$result = $this->sectorRepo->create($postParams);
}
return $result;
}
public function modifyAction($urlParams, $postParams)
{
$result = $this->userRepo->validateMenu('modify', $postParams);
if ($result['success']) {
$result = $this->sectorRepo->modify($postParams);
}
return $result;
}
public function deleteAction($urlParams, $postParams)
{
$result = $this->userRepo->validateMenu('delete', $postParams);
if ($result['success']) {
$result = $this->sectorRepo->delete($postParams);
}
return $result;
}
public function jscodeAction($urlParams, $postParams)
{
$action = array_shift($urlParams);
$action = (empty($action)) ? 'list' : $action;
$result = $this->userRepo->validateMenu($action, $postParams);
if ($result['success']) {
if ($action == 'modify') {
$result = $this->sectorRepo->validateModify($postParams);
if (!$result['success']) {
return $result;
}
}
$postParams['is_template'] = true;
$params = array_merge($postParams, $result, compact('action'));
//el template de adicionar y editar son los mismos
$action = ($action == 'modify') ? 'create' : $action;
return new View('jsCode/sector.'.$action, $params);
}
return $result;
}
public function jscodeListAction($urlParams, $postParams)
{
$action = 'list';
$result = $this->userRepo->validateMenu($action, $postParams);
if ($result['success']) {
$postParams['is_template'] = true;
$params = array_merge($postParams, $result, compact('action'));
//el template de adicionar y editar son los mismos
$action = ($action == 'modify') ? 'create' : $action;
return new View('jsCode/sector.'.$action.'2', $params);
}
return $result;
}
}
| true |
cc35bf1d9bddc155b4aecbc336bf76c3ebaa17a2 | PHP | ZeraTheMant/mvsantiago-wellness | /php/backend/get_individual_provider_services_beta2.php | UTF-8 | 2,626 | 2.5625 | 3 | [] | no_license | <?php
require '../dbconfig.php';
//$inipath = php_ini_loaded_file();
$query = "
SELECT
provider_services.ps_id,
services.service_id,
services.service_name,
services.category_id,
services.appears_on_first_time,
providers_beta.provider_id,
providers_beta.provider_level,
providers_beta.days_worked,
category.category_id,
category.category_name
FROM
provider_services
INNER JOIN
services
ON
provider_services.service_id = services.service_id
INNER JOIN
providers_beta
ON
provider_services.provider_id = providers_beta.provider_id
INNER JOIN
category
ON
provider_services.category_id = category.category_id
WHERE
provider_services.provider_id = :provider_id";
$stmt = $conn->prepare($query);
$stmt->execute(
array(
':provider_id' => $_GET['provider_id']
)
);
if($stmt->rowCount() > 0){
$output = '
<h3>List of my Categories and Services</h3>
<p id="instruction">Displays all the categories and services that you as a provider are allowed to perform.</p>
<br>
<div id="provider-categories-services-container">
<table>
<thead>
<tr>
<th>Category</th>
<th>Service</th>
<th>Requires provider approval</th>
</tr>
</thead>
<tbody>
';
$provider_categories = $stmt->fetchAll();
foreach($provider_categories as $row){
$appearsOnFirstTime = 'Yes';
if($row['appears_on_first_time'] == "1"){
$appearsOnFirstTime = 'No';
}
$output .='
<tr class="actual-row">
<td>' . $row['category_name'] . '</td>
<td>' . $row['service_name'] . '</td>
<td>' . $appearsOnFirstTime . '</td>
</tr>
';
}
$days_worked = json_decode($provider_categories[0]["days_worked"], true);
$output .='
</tbody></table>
<br><br>
<h3>My Working Days and Hours</h3>
<p id="instruction">Displays your working days and hours.</p>
<br>
<table>
<thead>
<tr>
<th>Day</th>
<th>Start</th>
<th>End</th>
</tr>
</thead>
<tbody>
';
foreach ($days_worked as $key => $value){
$output .= '
<tr>
<td><label>' . $key . '</label></td>
<td><input style="width: 100%; box-sizing: border-box; padding: 5px;" type="time" value="' . $value['start'] . '" disabled/></td>
<td><input style="width: 100%; box-sizing: border-box; padding: 5px;" type="time" value="' . $value['end'] . '" disabled/></td>
</tr>
';
}
$output .= "</tbody></table></div>";
echo $output;
}
else{
echo "<p>No categories and services found for this provider.</p>";
}
?> | true |
ff8156f34937eb2332ab52c90a0641e8ecc6c0ee | PHP | brookinsconsulting/ezcommunity2 | /eztodo/classes/ezpriority.php | UTF-8 | 4,875 | 2.6875 | 3 | [] | no_license | <?php
//
// $Id: ezpriority.php 7992 2001-10-22 09:22:31Z $
//
// Definition of eZPriority class
//
// Created on: <04-Sep-2000 16:53:15 ce>
//
// This source file is part of eZ publish, publishing software.
//
// Copyright (C) 1999-2001 eZ Systems. All rights reserved.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, US
//
//!! eZTodo
//! The eZPriority handles the priority informasjon.
/*!
Handles the priority informasjon stored in the database. All the todo's have a priority status.
*/
class eZPriority
{
//! eZPriority
/*!
eZPriority Constructor.
*/
function eZPriority( $id = -1 )
{
if ( $id != -1 )
{
$this->ID = $id;
$this->get( $this->ID );
}
}
//! store
/*!
Stores the priority object to the database.
Returnes the ID to the eZPriority object if the store is a success.
*/
function store()
{
$db =& eZDB::globalDatabase();
$db->begin();
$name = $db->escapeString( $this->Name );
if ( !isSet ( $this->ID ) )
{
$db->lock( "eZTodo_Priority" );
$this->ID = $db->nextID( "eZTodo_Priority", "ID" );
$res[] = $db->query( "INSERT INTO eZTodo_Priority
(ID, Name)
VALUES
('$this->ID', '$name')" );
$db->unlock();
}
else
{
$res[] = $db->query( "UPDATE eZTodo_Priority SET
ID='$this->ID',
Name='$name'
WHERE ID='$this->ID' ");
}
eZDB::finish( $res, $db );
return $this->ID;
}
//! delete
/*!
Deletes the priority object in the database.
*/
function delete()
{
$db =& eZDB::globalDatabase();
$res[] = $db->query( "DELETE FROM eZTodo_Priority WHERE ID='$this->ID'" );
eZDB::finish( $res, $db );
}
//! get
/*!
Gets a priority object from the database, where ID == $id
*/
function get( $id )
{
$db =& eZDB::globalDatabase();
if ( $id != "" )
{
$db->array_query( $priority_array, "SELECT * FROM eZTodo_Priority WHERE ID='$id'" );
if ( count( $priority_array ) > 1 )
{
die( "Error: Priority's with the same ID was found in the database. This shouldent happen." );
}
else if ( count( $priority_array ) == 1 )
{
$this->ID = $priority_array[0][$db->fieldName( "ID" )];
$this->Name = $priority_array[0][$db->fieldName( "Name" )];
$ret = true;
}
}
return $ret;
}
//! getAll
/*!
Gets all the priority informasjon from the database.
Returns the array in $priority_array ordered by name.
*/
function getAll()
{
$db =& eZDB::globalDatabase();
$priority_array = 0;
$return_array = array();
$priority_array = array();
$db->array_query( $priority_array, "SELECT ID FROM eZTodo_Priority ORDER BY Name" );
for ( $i = 0; $i < count( $priority_array ); $i++ )
{
$return_array[$i] = new eZPriority( $priority_array[$i][$db->fieldName( "ID" )], 0 );
}
return $return_array;
}
//! name
/*!
Tilte of the priority.
Returns the name of the priority as a string.
*/
function name()
{
return htmlspecialchars( $this->Name );
}
//! setName
/*!
Sets the name of the priority.
The new name of the priority is passed as a paramenter ( $value ).
*/
function setName( $value )
{
$this->Name = $value;
}
//! id
/*!
Id of the priority.
Returns the id of the priority as a string.
*/
function id()
{
return $this->ID;
}
var $ID;
var $Name;
}
?>
| true |
d8cdb3884259d376ad2cf0764931b7b6213aa0eb | PHP | tuananh97/php | /phpfiles/if-else.php | UTF-8 | 562 | 4.09375 | 4 | [] | no_license | <!DOCTYPE html>
<html>
<head>
<title>PHP If & Else</title>
</head>
<body>
<?php
//first example
$value1 = 123;
$value2 = 1235;
if($value1==$value2){
echo " The condition is true<br/>";
}
else{
echo " The condition is not true<br/>";
}
//second example
$city = "London";
if(
$city=="Syedney"){
echo $city . " Is in Austerlia<br/>";
}
else{
echo " This city is not in Austerlia<br/>";
}
//Third example
$person = "xubair";
$weight = 70;
if($person<=80){
echo $person . " Is Not vary fat!";
}
else{
echo $person . " Is Varey Fat!";
}
?>
</body>
</html>
| true |
47eb779d79f6ece829d7af1d41721eb75f1fb387 | PHP | luomingchu/jx | /enterprise/app/controllers/CaptchaController.php | UTF-8 | 2,958 | 3.015625 | 3 | [
"MIT"
] | permissive | <?php
/**
* 验证码控制器
*
* @author Latrell Chan
*/
class CaptchaController extends BaseController
{
/**
* 获取短信验证码
*
* @param string $mobile
*/
public function getSmsVcode()
{
// 验证输入。
$validator = Validator::make(Input::all(), array(
'mobile' => array(
'required',
'regex:/^1[3-8][0-9]{9}$/'
)
));
if ($validator->fails()) {
return Response::make($validator->messages()->first(), 402);
}
// 调用短信验证码宏,发送短信验证码。
return Response::smsvcode(Input::get('mobile'));
}
/**
* 短信验证码的验证规则
*
* @param string $attribute
* @param string $value
* @param array $parameters
* @param Validator $validator
*/
public function validateSmsVcode($attribute, $value, $parameters, $validator)
{
// 取出要验证的手机号。
$mobile = array_get($validator->getData(), isset($parameters[0]) ? $parameters[0] : 'mobile');
// 计算缓存的key。
$key = 'captcha/' . $mobile;
// 取出验证码,并与输入进行比较。
$sms = Cache::get($key);
if ($value == $sms['vcode']) {
// 删除缓存。
if (! empty($parameters[1]) && $parameters[1] == 'final') {
Cache::forget($key);
}
return true;
}
return false;
}
/**
* 发送邮箱验证码
*
* @param string $email
*/
public function getEmailVcode()
{
// 验证输入。
$validator = Validator::make(Input::all(), array(
'email' => array(
'required',
'email'
)
));
if ($validator->fails()) {
return Response::make($validator->messages()->first(), 402);
}
// 调用短信验证码宏,发送短信验证码。
return Response::emailvcode(Input::get('email'));
}
/**
* 邮箱验证码的验证规则
*
* @param string $attribute
* @param string $value
* @param array $parameters
* @param Validator $validator
*/
public function validateEmailVcode($attribute, $value, $parameters, $validator)
{
// 取出要验证的手机号。
$email = array_get($validator->getData(), isset($parameters[0]) ? $parameters[0] : 'email');
// 计算缓存的key。
$key = 'email_captcha/' . $email;
// 取出验证码,并与输入进行比较。
$email_vcode = Cache::get($key);
if (trim($value) == $email_vcode['vcode']) {
// 删除缓存。
if (! empty($parameters[1]) && $parameters[1] == 'final') {
Cache::forget($key);
}
return true;
}
return false;
}
}
| true |
dac140e325f34c56ca303fe2a8c0cce85e54aa10 | PHP | SergeySG/sms_edge_test | /console/migrations/m190423_084108_create_users_table.php | UTF-8 | 636 | 2.515625 | 3 | [] | no_license | <?php
use yii\db\Migration;
/**
* Handles the creation of table `{{%users}}`.
*/
class m190423_084108_create_users_table extends Migration
{
/**
* {@inheritdoc}
*/
public function safeUp()
{
$this->createTable('{{%users}}', [
'usr_id' => $this->primaryKey(),
'usr_name' => $this->string()->notNull(),
'usr_active' => $this->tinyInteger()->notNull()->defaultValue(0),
'usr_created' => $this->integer()->notNull(),
]);
}
/**
* {@inheritdoc}
*/
public function safeDown()
{
$this->dropTable('{{%users}}');
}
}
| true |
e4bb1b9c46c9421095eb7e94bfc4591245bd6c30 | PHP | RahimAJ/usep-svrs | /search.php | UTF-8 | 2,326 | 2.53125 | 3 | [] | no_license | <?php include('templates/header.php') ?>
<?php include('templates/navbar.php') ?>
<?php
include('includes/dbh-inc.php');
if (isset($_GET['searchType'], $_GET['searchInput'])) {
$searchType = $_GET['searchType'];
$searchInput = $_GET['searchInput'];
if (empty($searchType) || ($searchInput == "")) {
header("Location: ./home.php?search=emptyfields");
}
if ($searchType == "student_id") {
$search_array = mysqli_query($conn, "SELECT * FROM students WHERE student_id LIKE '%$searchInput%'");
}
if ($searchType == "name") {
$search_array = mysqli_query($conn, "SELECT * FROM students WHERE student_lastname LIKE '%$searchInput%' OR student_firstname LIKE '%$searchInput%'");
}
} else {
header("Location: ./home.php?search=error");
}
?>
<div class="container mt-4">
<h3>Search</h3>
<table id="datatable" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>Student ID</th>
<th>Lastname</th>
<th>Firstname</th>
<th>Course</th>
<th style="width: 12%">Violations</th>
</tr>
</thead>
<tbody>
<?php while ($row = mysqli_fetch_array($search_array)) {
if ($row['deleted'] != NULL)
continue; ?>
<tr onclick="window.location='student-list.php?student-id=<?php echo $row['student_id']; ?>'">
<td><?php echo $row['student_id']; ?></td>
<td><?php echo $row['student_lastname']; ?></td>
<td><?php echo $row['student_firstname']; ?></td>
<td><?php echo $row['course_id']; ?></td>
<td>
<?php
$student_id = $row['student_id'];
$result = mysqli_query($conn, "SELECT * FROM violations WHERE (student_id = '$student_id') AND (deleted IS NULL);");
echo mysqli_num_rows($result);
?>
</td>
</tr>
<?php
} ?>
</tbody>
</table>
</div>
<?php include('templates/footer.php') ?>
<script>
$(document).ready(function() {
$('#datatable').DataTable();
});
</script> | true |
2482f1125a01ff8d0babb4a163e223bdbcb115f9 | PHP | bearsunday/BEAR.Package | /src/Provide/Error/Status.php | UTF-8 | 849 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace BEAR\Package\Provide\Error;
use BEAR\Resource\Exception\BadRequestException;
use Koriym\HttpConstants\StatusCode;
use RuntimeException;
use Throwable;
final class Status
{
/** @var int */
public $code;
/** @var string */
public $text;
public function __construct(Throwable $e)
{
/** @var array<int, string> $text */
$text = (new StatusCode())->statusText;
if ($e instanceof BadRequestException) {
$this->code = $e->getCode();
$this->text = $text[$this->code] ?? '';
return;
}
if ($e instanceof RuntimeException) {
$this->code = 503;
$this->text = $text[$this->code];
return;
}
$this->code = 500;
$this->text = $text[$this->code];
}
}
| true |
72b3041966c61e5497db6c280dbeeea5f5275aff | PHP | SwedbankPay/swedbank-pay-sdk-php | /src/SwedbankPay/Api/Service/Invoice/Resource/Request/Invoice.php | UTF-8 | 651 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | <?php
namespace SwedbankPay\Api\Service\Invoice\Resource\Request;
use SwedbankPay\Api\Service\Invoice\Resource\Request\Data\InvoiceInterface;
use SwedbankPay\Api\Service\Resource\Request as RequestResource;
/**
* Invoice data object
*/
class Invoice extends RequestResource implements InvoiceInterface
{
/**
* @return string
*/
public function getInvoiceType()
{
return $this->offsetGet(self::INVOICE_TYPE);
}
/**
* @param string $invoiceType
* @return $this
*/
public function setInvoiceType($invoiceType)
{
return $this->offsetSet(self::INVOICE_TYPE, $invoiceType);
}
}
| true |
7bfee6bd3d70004e4f7a4ecfe353d961a4b88d6d | PHP | LikikCZ/cviceni-4ep-sk1-mvc-opakovani | /src/controllers/uzivatele_controller.php | UTF-8 | 4,392 | 2.625 | 3 | [] | no_license | <?php
class Uzivatele
{
private function prihlasovaci_udaje_jsou_kompletni()
{
if(!isset($_POST["jmeno"]))
return false;
if(!isset($_POST["heslo"]))
return false;
return true;
}
private function registracni_udaje_jsou_kompletni()
{
if(!isset($_POST["jmeno"]))
return false;
if(empty(trim($_POST["jmeno"])))
return false;
if(!isset($_POST["heslo"]))
return false;
if(empty(trim($_POST["heslo"])))
return false;
if(!isset($_POST["heslo_znovu"]))
return false;
if(empty(trim($_POST["heslo_znovu"])))
return false;
return true;
}
private function ujdaje_k_prispevku_jsou_kompletni()
{
if(!isset($_POST["zatimnwm"]))
return false;
if(empty(trim($_POST["zatimnwm"])))
return false;
return true;
}
private function registracni_udaje_jsou_v_poradku($jmeno, $heslo, $heslo_znovu)
{
if(strlen($jmeno) < 1)
return false;
if(strlen($heslo) < 1)
return false;
if($heslo_znovu != $heslo)
return false;
return true;
}
private function ujdaje_k_prispevku_jsou_v_poradku($jmeno, $heslo, $heslo_znovu)
{
if(strlen($jmeno) < 1)
return false;
if(strlen($heslo) < 1)
return false;
if($heslo_znovu != $heslo)
return false;
return true;
}
public function registrovat()
{
if($this->registracni_udaje_jsou_kompletni())
{
// zpracovani dat z formulare
$jmeno = trim($_POST["jmeno"]);
$heslo = trim($_POST["heslo"]);
$heslo_znovu = trim($_POST["heslo_znovu"]);
if($this->registracni_udaje_jsou_v_poradku($jmeno, $heslo, $heslo_znovu))
{
$uzivatel = new Uzivatel($jmeno, $heslo);
if($uzivatel->zaregistrovat())
return spustit("uzivatele", "prihlasit");
else
return spustit("stranky", "error");
}
else
require_once "views/uzivatele/registrovat.php";
}
else
{
// zobrazeni formulare k vyplneni
require_once "views/uzivatele/registrovat.php";
}
}
public function prihlasit()
{
if($this->prihlasovaci_udaje_jsou_kompletni())
{
$jmeno = trim($_POST["jmeno"]);
$heslo = trim($_POST["heslo"]);
if(Uzivatel::existuje($jmeno, $heslo))
{
global $zakladni_url;
session_destroy();
unset($_SESSION["prihlaseny_uzivatel"]);
session_start();
$_SESSION["prihlaseny_uzivatel"] = $jmeno;
header("location:".$zakladni_url."index.php/stranky/profil/");
}
else
require_once "views/uzivatele/prihlasit.php";
}
else
{
// zobrazeni formulare k vyplneni
require_once "views/uzivatele/prihlasit.php";
}
}
public function pridat_prispevek()
{
if($this->ujdaje_k_prispevku_jsou_kompletni())
{
$nazev = trim($_POST["nazev"]);
$obsah = trim($_POST["obsah"]);
$jmeno = $_SESSION["prihlaseny_uzivatel"];
$zobrazovat = "ano";
if($this->ujdaje_k_prispevku_jsou_v_poradku($nazev, $obsah))
{
$prispevek = new Prispevek($jmeno, $nazev, $obsah, $zobrazovat);
if($prispevek->pridat_prispevek())
return spustit("stranky", "profil");
else
return spustit("stranky", "error");
}
else
require_once "views/uzivatele/pridat_prispevek.php";
}
else
{
// zobrazeni formulare k vyplneni
require_once "views/uzivatele/pridat_prispevek.php";
}
}
public function odhlasit()
{
global $zakladni_url;
session_destroy();
session_start();
header("location:".$zakladni_url."index.php/stranky/default/");
}
}
| true |
f4a7a0b22a7ebad8fa3ab5bea3a34acaa9734d44 | PHP | fr3d3rico/fuzen-pri | /engine/persistence/CategoriaPS.php | UTF-8 | 2,686 | 2.921875 | 3 | [] | no_license | <?php
require("Persistence.php");
class CategoriaPS extends Persistence {
function __construct() {
parent::__construct();
}
function __destruct() {
parent::__destruct();
}
function cadastrar($categoria) {
$isCadastrado = true;
$labels = "";
$values = "";
//Valores
if( strlen($categoria->titulo) > 0 ) {
$labels = $labels . "titulo,";
$values = $values . "'" . $categoria->titulo . "',";
}
if( strlen($categoria->usuario_id) > 0 ) {
$labels = $labels . "usuario_id,";
$values = $values . $categoria->usuario_id . ",";
}
//Magica rsrsrsrs
$labels = $labels . "[[";
$values = $values . "[[";
$labels = str_replace(",[[", " ", $labels);
$values = str_replace(",[[", " ", $values);
$sql = "insert into categoria (" . $labels . ") values (". $values .")";
$result = pg_query($sql) or die("Query failed: " . pg_last_error());
return $isCadastrado;
}
function alterar($categoria) {
$isAlterado = true;
$sql = "update categoria set titulo = '". $categoria->titulo ."', ativo = ". $categoria->ativo .", usuario_id = ". $categoria->usuario_id ." where id = ". $categoria->id;
$result = pg_query($sql) or die("Query failed: " . pg_last_error());
return $isAlterado;
}
function consultarCategoria($id) {
$categoria = null;
$sql = "select id, titulo, usuario_id, ativo from categoria where id = " . $id;
$result = pg_query($sql) or die("Query failed: " . pg_last_error());
if(pg_num_rows($result) > 0) {
for($i = 0; $i < pg_num_rows($result); $i++) {
$line = pg_fetch_array($result, $i, PGSQL_NUM);
$categoria = new Categoria();
$categoria->id = $line[0];
$categoria->titulo = $line[1];
$categoria->usuario_id = $line[2];
$categoria->ativo = $line[3];
break;
}
}
return $categoria;
}
function consultar() {
$listaCategoria = null;
$sql = "select id, titulo, usuario_id, ativo from categoria order by titulo";
$result = pg_query($sql) or die("Query failed: " . pg_last_error());
if(pg_num_rows($result) > 0) {
$listaCategoria = array();
for($i = 0; $i < pg_num_rows($result); $i++) {
$line = pg_fetch_array($result, $i, PGSQL_NUM);
$categoria = new Categoria();
$categoria->id = $line[0];
$categoria->titulo = $line[1];
$categoria->usuario_id = $line[2];
$categoria->ativo = $line[3];
array_push($listaCategoria, serialize($categoria));
}
}
return $listaCategoria;
}
function remover($id) {
if( $id != null && strlen($id) > 0 ) {
$sql = "delete from categoria where id = " . $id;
pg_query($sql) or die("Query failed: " . pg_last_error());
}
}
}
?> | true |
1ea00d1c3edeeb0e6068181aa0e76076987330df | PHP | emaphp/eMapper | /lib/eMapper/Reflection/ClassProperty.php | UTF-8 | 2,676 | 2.78125 | 3 | [
"MIT"
] | permissive | <?php
namespace eMapper\Reflection;
use Omocha\AnnotationBag;
/**
* The ClassProperty class provides access to a property metadata.
* @author emaphp
*/
class ClassProperty {
/**
* Property name
* @var string
*/
protected $name;
/**
* Reflection property instance
* @var \ReflectionProperty
*/
protected $reflectionProperty;
/**
* Column name
* @var string
*/
protected $column;
/**
* Property type
* @var string
*/
protected $type;
/**
* Indicates if property is primary key
* @var bool
*/
protected $primaryKey;
/**
* Indicates if property is unique
* @var bool
*/
protected $unique;
/**
* Indicates if property must check for duplicates
* @var string
*/
protected $checkDuplicate;
/**
* Indicates if property is read only
* @var bool
*/
protected $readOnly;
/**
* Indicates if property is nullable
* @var bool
*/
protected $nullable;
public function __construct($propertyName, \ReflectionProperty $reflectionProperty, AnnotationBag $propertyAnnotations) {
$this->name = $propertyName;
$this->reflectionProperty = $reflectionProperty;
$this->reflectionProperty->setAccessible(true);
//parse annotations
$this->column = $propertyAnnotations->has('Column') ? $propertyAnnotations->get('Column')->getValue() : $propertyName;
$this->type = $propertyAnnotations->has('Type') ? $propertyAnnotations->get('Type')->getValue() : null;
$this->primaryKey = $propertyAnnotations->has('Id');
$this->unique = $propertyAnnotations->has('Unique');
//on duplicate checks
if ($this->unique && $propertyAnnotations->has('OnDuplicate')) {
$duplicate = $propertyAnnotations->get('OnDuplicate')->getValue();
$this->checkDuplicate = !in_array($duplicate, ['ignore', 'update']) ? 'ignore' : $duplicate;
}
$this->readOnly = $propertyAnnotations->has('ReadOnly');
$this->nullable = $propertyAnnotations->has('Nullable');
}
public function getName() {
return $this->name;
}
public function getReflectionProperty() {
return $this->reflectionProperty;
}
public function getColumn() {
return $this->column;
}
public function getAttribute() {
return $this->attribute;
}
public function getType() {
return $this->type;
}
public function isPrimaryKey() {
return $this->primaryKey;
}
public function isUnique() {
return $this->unique;
}
public function checksForDuplicates() {
return !is_null($this->checkDuplicate);
}
public function getCheckDuplicate() {
return $this->checkDuplicate;
}
public function isReadOnly() {
return $this->readOnly;
}
public function isNullable() {
return $this->nullable;
}
}
| true |
711674ab1db16de255fc2503e69d3671f5d81c7d | PHP | matthisstenius/php-projekt | /src/post/model/PostDAL.php | UTF-8 | 2,943 | 2.953125 | 3 | [] | no_license | <?php
namespace post\model;
require_once("src/common/model/DALBase.php");
require_once("src/post/model/Post.php");
class PostDAL extends \common\model\DALBase {
/**
* @param project\model\Project $project
* @return array
*/
public function getPosts(\project\model\Project $project) {
$result = array();
$stm = self::getDBConnection()->prepare("SELECT idPost, title, content, User_idUser AS userID, User.username, added,
projectID_Project AS projectID FROM Post
INNER JOIN User ON User.idUser = User_idUser
WHERE projectID_Project=:projectID
ORDER BY added DESC");
$projectID = $project->getProjectID();
$stm->bindParam(':projectID', $projectID, \PDO::PARAM_INT);
$stm->execute();
while ($row = $stm->fetch(\PDO::FETCH_ASSOC)) {
$result[] = $row;
}
return $result;
}
/**
* @param int $id
* @return array
*/
public function getPost($postID) {
$stm = self::getDBConnection()->prepare("SELECT idPost, title, content, User_idUser AS userID, User.username, added,
projectID_Project AS projectID FROM Post
INNER JOIN User ON User.idUser = User_idUser
WHERE idPost=:id");
$stm->bindParam(':id', $postID, \PDO::PARAM_INT);
$stm->execute();
$row = $stm->fetch(\PDO::FETCH_ASSOC);
return $row;
}
/**
* @param post\model\Post $post
* @return int PostID
*/
public function addPost(\post\model\Post $post) {
$pdo = self::getDBConnection();
$stm = $pdo->prepare("INSERT INTO Post (title, content, added, projectID_Project, User_idUser)
VALUES(:title, :content, :added, :projectID, :userID)");
$title = $post->getTitle();
$content = $post->getContent();
$added = $post->getDateAdded();
$projectID = $post->getProjectID();
$userID = $post->getUserID();
$stm->bindParam(':title', $title);
$stm->bindParam(':content', $content);
$stm->bindParam(':added', $added);
$stm->bindParam(':projectID', $projectID);
$stm->bindParam(':userID', $userID);
$stm->execute();
return +$pdo->lastInsertId();
}
/**
* @param post\model\Post $post
* @return void
*/
public function editPost(\post\model\Post $post) {
$stm = self::getDBConnection()->prepare("UPDATE Post SET title = :title, content = :content
WHERE idPost = :postID");
$postTitle = $post->getTitle();
$postContent = $post->getContent();
$postID = $post->getPostID();
$stm->bindParam(':title', $postTitle, \PDO::PARAM_STR);
$stm->bindParam(':content', $postContent, \PDO::PARAM_STR);
$stm->bindParam(':postID', $postID, \PDO::PARAM_INT);
$stm->execute();
}
/**
* @param \post\model\Post $post
* @return void
*/
public function deletePost(\post\model\Post $post) {
$stm = self::getDBConnection()->prepare('DELETE FROM Post WHERE idPost = :id');
$postID = $post->getPostID();
$stm->bindParam(':id', $postID, \PDO::PARAM_INT);
$stm->execute();
}
} | true |
d5dacefc601e62b5bebe3398c8ff114701ab401b | PHP | simmstein/csv | /src/Deblan/Csv/CsvParser.php | UTF-8 | 3,957 | 3.171875 | 3 | [
"BSD-2-Clause"
] | permissive | <?php
namespace Deblan\Csv;
/**
* class Csv.
*
* @author Simon Vieille <simon@deblan.fr>
*/
class CsvParser
{
/**
* @var string
*/
protected $delimiter = ';';
/**
* @var string
*/
protected $enclosure = '"';
/**
* @var string
*/
protected $endOfLine = "\n";
/**
* @var array
*/
protected $datas = [];
/**
* @var array
*/
protected $headers = [];
/**
* @var bool
*/
protected $hasHeaders = false;
/**
* Set the value of "delimiter".
*
* @param string $delimiter
*
* @return Csv
*/
public function setDelimiter($delimiter)
{
$this->delimiter = (string) $delimiter;
return $this;
}
/**
* Get the value of "delimiter".
*
* @return array
*/
public function getDelimiter()
{
return $this->delimiter;
}
/**
* Set the value of "enclosure".
*
* @param string $enclosure
*
* @return Csv
*/
public function setEnclosure($enclosure)
{
$this->enclosure = (string) $enclosure;
return $this;
}
/**
* Get the value of "enclosure".
*
* @return string
*/
public function getEnclosure()
{
return $this->enclosure;
}
/**
* Set the value of "endOfLine".
*
* @param string $endOfLine
*
* @return Csv
*/
public function setEndOfLine($endOfLine)
{
$this->endOfLine = (string) $endOfLine;
return $this;
}
/**
* Get the value of "endOfLine".
*
* @return string
*/
public function getEndOfLine()
{
return $this->endOfLine;
}
/**
* Get the value of "hasHeaders".
*
* @return bool
*/
public function getHasHeaders()
{
return $this->hasHeaders;
}
/**
* Set the value of "headers".
*
* @param bool $hasHeaders
*
* @return Csv
*/
public function setHasHeaders($hasHeaders)
{
$this->hasHeaders = (bool) $hasHeaders;
return $this;
}
/**
* Get the value of "headers".
*
* @return array
*/
public function getHeaders()
{
return $this->headers;
}
/**
* Get the value of "datas".
*
* @return array
*/
public function getDatas()
{
return $this->datas;
}
/*
* Parses a string.
*
* @param string $string
*
* @return CsvParser
*/
public function parseString($string)
{
$this->datas = [];
$this->headers = [];
$lines = str_getcsv($string, $this->endOfLine);
foreach ($lines as $key => $line) {
$data = $this->parseLine($line, $this->hasHeaders && $key === 0);
if ($data === null) {
continue;
}
if ($this->hasHeaders && $key === 0) {
$this->headers = $data;
} else {
$this->datas[] = $data;
}
}
return $this;
}
/*
* Parses a line.
*
* @param string $line
* @param bool $isHeaders
*
* @return array
*/
public function parseLine($line, $isHeaders = false)
{
$line = trim($line);
if (empty($line)) {
return null;
}
$csv = str_getcsv($line, $this->delimiter, $this->enclosure);
if (!$isHeaders && $this->hasHeaders && !empty($this->headers)) {
foreach ($this->headers as $key => $header) {
$csv[$header] = isset($csv[$key]) ? $csv[$key] : null;
}
}
return $csv;
}
/*
* Parses a file.
*
* @param string $filaname
*
* @return CsvParser
*/
public function parseFile($filename)
{
return $this->parseString(file_get_contents($filename));
}
}
| true |
17ee4cfa0f7a7888cd5e66a9b215cca1dddbbdd5 | PHP | kartikkchauhan/codeTrek_app | /user/submit_Question.php | UTF-8 | 670 | 2.671875 | 3 | [] | no_license | <?php
session_start();
include_once("../config.php");
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$title = $_POST["title"];
$description = $_POST["description"];
$tags = $_POST["tags"];
#getting date
$yrdata= strtotime(date("Y/m/d"));
$date= date('M d, Y', $yrdata);
$userId = $_SESSION['user'];
#inserting value in data base
$query=mysqli_query($con, "INSERT INTO `asked_questions`(`question_Title`, `question_Description`, `questions_Tags`, `user_Id`,`date`) VALUES ('$title','$description','$tags','$userId','$date')");
if ($query)
{
# code...
header("Location: ../index.php");
}
else
{
echo "error";
}
}
?> | true |
59ff379a8b5dba8393f336e8a81adcc80eae93e1 | PHP | veakulin/i7 | /classes/VRClient.php | UTF-8 | 1,318 | 2.640625 | 3 | [] | no_license | <?php
class VRClient extends VRClientBase {
public function __construct(string $apiUrl, Credentials $credentials) {
parent::__construct($apiUrl, $credentials);
}
public function countryEnum(array $query = null) {
$result = $this->enum("countryEnum", $query);
return $result->result->countries;
}
public function regionEnum(array $query = null) {
$result = $this->enum("regionEnum", $query);
return $result->result->regions;
}
public function identTypeEnum(array $query = null) {
$result = $this->enum("identTypeEnum", $query);
return $result->result->identTypes;
}
public function domainEnum(array $query = null) {
$result = $this->enum("domainEnum", $query);
return $result->result->domains;
}
public function clientCreate(array $client) {
$result = $this->synchronized("clientCreate", $client);
return $result->result->id;
}
public function domainCreate(array $domain) {
$result = $this->synchronized("domainCreate", $domain);
return $result->result->id;
}
public function domainUpdate(array $params) {
$result = $this->synchronized("domainUpdate", $params);
return $result->result->id;
}
}
| true |
f21de76e174e58e1475b28ff3852874bd750fa50 | PHP | ChristianStulen/Backend2021 | /Inlamning-03-VG/App.php | UTF-8 | 2,528 | 3.21875 | 3 | [] | no_license | <?php
class App{
//Endpoint and a standard value of the amount of products to be shown.
public static $endpoint ="http://localhost/Inlamning-03-VG/Api/index.php";
public static $nrShow = 10;
//Main, if wrong input is entered the page gets redirected to error screen.
public static function main()
{
$nrShow=$_GET['show'] ?? self::$nrShow;
try {
if (!in_array($nrShow, range(1,10)))
header("Location: http://localhost/Inlamning-03-VG/Api/index.php?show=$nrShow");
elseif(!preg_match_all("/^[1-9][0-9]*$/", $nrShow))
header("Location: http://localhost/Inlamning-03-VG/Api/index.php?show=$nrShow");
else{
$array = self::getData();
self::allProducts($array);
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
//Get data and throws if there is not access.
public static function getData()
{
$nrShow=$_GET['show'] ?? self::$nrShow;
$json = file_get_contents(self::$endpoint."?show=$nrShow");
if (!$json)
throw new Exception("Cannot access ".self::$endpoint);
return json_decode($json, true);
}
//Echos out the products in a nice format.
public static function allProducts($array)
{
$result = "<div class='row'>";
foreach ($array as $key => $value) {
$picture =$value['picture'];
$title = $value['title'];
$price = $value['price'];
$description = $value['description'];
$stock = $value['stock'];
$result .= "
<div class='col-lg-4 col-md-6 mb-4'>
<div class='card h-100'>
<a><img class='card-img-top' src=Images/$picture alt=''></a>
<div class='card-body'>
<h4 class='card-title'>
<a>$title</a>
</h4>
<h5>$$price kr</h5>
<p class='card-text'>$description</p>
<h5>Antal i lager: $stock</h5>
</div>
</div>
</div>";
}
$result .= "</div>";
echo $result;
}
}
| true |
9df6b3b7b91ccd70c097ca27c01e92bccca49e48 | PHP | drake1004/search_keyword | /index.php | UTF-8 | 796 | 2.609375 | 3 | [] | no_license | <?php
/**
* execute class
*/
use library\curl;
require_once 'library\curl.php';
if(isset($_GET['keyword'])){
$keyword = explode(" ",$_GET['keyword']);
$keyword = str_replace(array("'",'"'),"",$keyword[0]);
$url = "http://xlab.pl/feed/";
$curl = new curl($url);
$data = $curl->returnData("rss");
if($data)
{
$items = $data->channel->item;
$allItems = array();
foreach($items as $item)
{
$description = $item->description;
preg_match("/$keyword/Ui",$description,$results);
if(count($results)>0){
$allItems [] = $item->asXML();
}
}
foreach($allItems as $itemContent){
echo $itemContent;
}
}
}
| true |
c57974ebc03afb89c9628b3da86a69a91989cb5c | PHP | cshopb/email_spam | /database/migrations/2015_10_16_053713_create_emails_table.php | UTF-8 | 1,066 | 2.703125 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateEmailsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('emails', function (Blueprint $table) {
$table->increments('id');
$table->integer('customer_id')->unsigned();
$table->foreign('customer_id')->references('id')->on('customers')->onDelete('cascade');
$table->enum('list', array('white_list', 'black_list'));
$table->string('email');
$table->timestamps();
// http://laravel.io/forum/10-12-2014-two-field-in-combination-should-be-unique-in-database
// http://laravel.com/api/5.1/Illuminate/Database/Schema/Blueprint.html#method_unique
$table->unique(array('customer_id', 'email'));
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('emails');
}
}
| true |
021bc39b7c63822ad3fcc12d25beaf097e0610d6 | PHP | manualweb/manual-php | /tipos-datos/forzar-tipo-integer.php | UTF-8 | 258 | 3.359375 | 3 | [] | no_license | <?php
$valor_booleano = true;
$valor_float = 8.9;
echo 'Valor booleano '.(int)$valor_booleano.'<br>';
echo 'Valor float '.(int)$valor_float.'<br>';
echo 'Valor booleano '.intval($valor_booleano).'<br>';
echo 'Valor float '.intval($valor_float).'<br>';
?> | true |
51a100cfee91057ee14777052e2022a631aaf563 | PHP | Ryzki/bkp_serviceon | /application/models/orders/Cart_model.php | UTF-8 | 18,874 | 2.734375 | 3 | [] | no_license | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CI_Model API for cart management .
*
* <p>
* We are using this model to assign, unassign, change and get delivery status of orders.
* </p>
* @package Orders
* @subpackage orders-model
* @author pradeep singh
* @category CI_Model API
*/
class Cart_model extends CI_Model {
function __construct() {
parent::__construct();
}
/**
* Function for getting order cart session.
*
* @access private
* @return cookie session record
* @version 1.0001
*/
public function getCartSession( $id ) {
return md5(date(DATE_RFC822).time().$id);
}
public function getOrderItemCount( $map ) {
$params = array('session_cookie'=>$map['session_cookie'],'restid'=>$map['restid']);
$this->db->select('sum(quantity) as cart_count', FALSE)
->from(TABLES::$ORDER_CART)
->where($params);
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
public function addSubItemsToCart( $map ) {
$this->db->insert(TABLES::$ORDER_SUB_CART,$map);
return $map;
}
public function removeSubItemsFromCart($map) {
$params = array('session_cookie'=>$map['session_cookie'],'option_id'=>$map['option_id']);
$this->db->where($params);
$this->db->delete(TABLES::$ORDER_SUB_CART);
}
public function removeSubItemSetFromCart($map) {
$params = array('session_cookie'=>$map['session_cookie'],'option_id'=>$map['option_id'],'itemset'=>$map['itemset']);
$this->db->where($params);
$this->db->delete(TABLES::$ORDER_SUB_CART);
}
/**
* Function for adding order items to session cart.
*
* @access public
* @param array itemMap
* @since Beta 1.0001 - 01-Aug-09
* @version 1.0001
*/
public function addItemToCart( $map) {
$params = array('session_cookie'=>$map['session_cookie'],'option_id'=>$map['option_id']);
$this->db->select('COUNT(*) as count')->from(TABLES::$ORDER_CART)->where($params);
$query = $this->db->get();
$result = $query->result_array();
if($result[0]['count'] <=0 ) {
$this->db->insert(TABLES::$ORDER_CART,$map);
}else {
$this->increaseItemQuantity( $map );
}
return $map;
}
public function getOrderTotal( $map ) {
$params = array('a.session_cookie'=>$map['cart_session'],'a.restid'=>$map['restid']);
$this->db->select('SUM(a.quantity*b.price) AS total',FALSE)
->from(TABLES::$ORDER_CART.' AS a')
->join(TABLES::$MENU_ITEM_TABLE.' AS b','a.itemid = b.id','inner')
->where($params)
->group_by('a.session_cookie');
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
/**
* Function for removing items from order session cart.
*
* @access public
* @param integer itemid
* @since Beta 1.0001 - 01-Aug-09
* @version 1.0001
*/
public function removeItemFromCart( $map ) {
$params = array('session_cookie'=>$map['session_cookie'],'option_id'=>$map['option_id'],'restid'=>$map['restid']);
$this->db->select('quantity')->from(TABLES::$ORDER_CART)->where($params);
$query = $this->db->get();
$result = $query->result_array();
if(count($result) > 0) {
if ($result[0]['quantity'] <=1 ) {
$this->db->where($params);
$this->db->delete(TABLES::$ORDER_CART);
} else {
$quantity = $result[0]['quantity'];
$qty = array();
$qty['quantity'] = $quantity - 1;
$this->db->where($params);
$this->db->update(TABLES::$ORDER_CART,$qty);
}
}
}
public function deleteItemFromCart( $map ) {
$params = array('session_cookie'=>$map['session_cookie'],'option_id'=>$map['option_id'],'restid'=>$map['restid']);
$this->db->where($params);
$this->db->delete(TABLES::$ORDER_CART);
}
/**
* Function for updating item quantity in order cart.
*
* @access public
* @param array itemMap
* @since Beta 1.0001 - 01-Aug-09
* @version 1.0001
*/
public function updateItemQuantity( $map ) {
$params = array('session_cookie'=>$map['session_cookie'],'option_id'=>$map['option_id'],'restid'=>$map['restid']);
$this->db->where($params);
$qty = array('quantity'=>$map['quantity']);
$this->db->update(TABLES::$ORDER_CART,$qty);
}
public function increaseItemQuantity($map) {
$params = array('session_cookie'=>$map['session_cookie'],'option_id'=>$map['option_id'],'restid'=>$map['restid']);
$this->db->select('quantity')->from(TABLES::$ORDER_CART)->where($params);
$query = $this->db->get();
$result = $query->result_array();
if(count($result) > 0) {
$quantity = $result[0]['quantity'];
$qty = array();
$qty['quantity'] = $quantity + 1;
$this->db->where($params);
$this->db->update(TABLES::$ORDER_CART,$qty);
}
}
/**
* Function for getting order cart.
*
* @access public
* @param integer restid
* @return array array of multi result set
* @since Beta 1.0001 - 01-Aug-09
* @version 1.0001
*/
public function getOrderCart( $map ) {
$params = array('a.session_cookie'=>$map['session_cookie']);
$this->db->select('a.itemid,a.option_id,a.quantity,a.size', FALSE)
->from(TABLES::$ORDER_CART.' AS a')
->where($params);
//->order_by('c.name','asc');
$query = $this->db->get();
//echo $this->db->last_query();
$result = $query->result_array();
return $result;
}
/* public function getOrderCart( $map ) {
$params = array('a.session_cookie'=>$map['session_cookie'],'a.restid'=>$map['restid']);
$this->db->select('a.itemid,a.option_id,a.quantity,b.price,(a.quantity * b.price) as totalprice,(a.quantity *b.packaging) as packaging,a.size,c.name,c.description,c.vat_tax,c.service_tax', FALSE)
->from(TABLES::$ORDER_CART.' AS a')
->join(TABLES::$MENU_ITEM_PRICE.' AS b','a.option_id = b.id','inner')
->join(TABLES::$MENU_ITEM.' AS c','b.itemid = c.id','inner')
->where($params)
->order_by('c.name','asc');
$query = $this->db->get();
$result = $query->result_array();
return $result;
} */
public function getOrderSubItemsBySubcat( $map ) {
$params = array('a.session_cookie'=>$map['cart_session'],'a.restid'=>$map['restid']);
$this->db->select('a.itemid,GROUP_CONCAT(DISTINCT b.sub_item_name SEPARATOR ",") as subitems,c.price,SUM(c.price) as subprice,b.sub_cat_name,b.itemset', FALSE)
->from(TABLES::$ORDER_CART.' AS a')
->join(TABLES::$ORDER_SUB_CART.' AS b',' a.session_cookie = b.session_cookie','left')
->join(TABLES::$ORDER_SUB_ITEM.' AS c','b.sub_item_id = c.sub_item_id','left')
->where($params)
->where('b.sub_item_key = c.sub_item_key')
->where('a.itemid','b.itemid',FALSE)
->group_by('b.itemid')
->group_by('b.itemset')
->group_by('b.sub_cat_name');
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
public function getGlobalIdByItemId( $itemid ) {
$params = array('id'=>$itemid);
$this->db->select('global_id')
->from(TABLES::$MENU_ITEM_TABLE)
->where($params);
$query = $this->db->get();
$result = $query->result_array();
return $result[0]['global_id'];
}
public function getOrderSubCart( $map) {
$params = array('a.session_cookie'=>$map['cart_session'],'a.restid'=>$map['restid']);
$this->db->select('a.itemid,a.sub_item_id,a.sub_item_key,a.itemset,b.price')
->from(TABLES::$ORDER_SUB_CART.' AS a')
->join(TABLES::$ORDER_SUB_ITEM.' AS b','b.sub_item_id = a.sub_item_id','left')
->where($params)
->where('a.sub_item_key = b.sub_item_key');
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
public function getOrderSubCartByItemSet( $map ) {
$params = array('session_cookie'=>$map['cart_session'],'restid'=>$map['restid']);
$this->db->select('itemid,MAX(itemset) as items')
->from(TABLES::$ORDER_SUB_CART)
->where($params)
->group_by('itemid');
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
/**
* Function for checking order cart.
*
* @access public
* @param integer restid
* @return array array of multi result set
* @since Beta 1.0001 - 01-Aug-09
* @version 1.0001
*/
public function checkOrderCart( $restid , $cart_session) {
$params = array('a.session_cookie'=>$cart_session,'a.restid'=>$restid);
$this->db->select('a.itemid,a.quantity,b.name,b.price,(a.quantity * b.price) as total,(a.quantity *b.packaging) as packaging,c.name as category',FALSE)
->from(TABLES::$ORDER_CART.' AS a')
->join(TABLES::$MENU_ITEM_TABLE.' AS b','a.itemid = b.id','inner')
->join(TABLES::$CATEGORY_TABLE.' AS c','b.catid = c.id','inner')
->where($params)
->order_by('b.name','asc')
->order_by('c.id','asc');
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
/**
* Function for clearing order cart.
*
* @access public
* @param integer restid
* @since Beta 1.0001 - 01-Aug-09
* @version 1.0001
*/
public function clearOrderCart( $map ) {
$params = array('session_cookie'=>$map['session_cookie'],'restid'=>$map['restid']);
$this->db->where($params);
$this->db->delete(TABLES::$ORDER_CART);
$params = array('session_cookie'=>$map['session_cookie'],'restid'=>$map['restid']);
$this->db->where($params);
$this->db->delete(TABLES::$ORDER_SUB_CART);
}
/**
* Function for clearing order cart.
*
* @access public
* @param integer restid
* @since Beta 1.0001 - 01-Aug-09
* @version 1.0001
*/
public function clearOrderSubCart( $map ) {
$params = array('session_cookie'=>$map['cart_session']);
$this->db->where($params);
$this->db->delete(TABLES::$ORDER_SUB_CART);
}
/**
* Function for getting item from order cart.
*
* @access public
* @param integer restid
* @param integer itemid
* @return array array of single result set
* @since Beta 1.0001 - 01-Aug-09
* @version 1.0001
*/
public function getItemFromCart( $map ) {
$params = array('a.session_cookie'=>$map['cart_session'],'a.restid'=>$map['restid'],'a.itemid'=>$map['itemid']);
$this->db->select('a.itemid,a.restid,a.quantity,b.catid,b.name,b.price,(a.quantity * b.price) as total,(a.quantity *b.packaging) as packaging,b.sub_cat', FALSE)
->from(TABLES::$ORDER_CART.' AS a')
->join(TABLES::$MENU_ITEM_TABLE.' AS b','a.itemid = b.id','inner')
->where($params)->order_by('b.name','asc');
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
/* ************************* Order deals cart implementation ********** ******************* */
public function addDealsToCart( $itemMap ) {
$params = array('session_cookie'=>$itemMap['cart_session'],'dealid'=>$itemMap['dealid']);
$this->db->select('COUNT(*) as count')->from(TABLES::$ORDER_DEALS_CART)->where($params);
$query = $this->db->get();
$result = $query->result_array();
if($result[0]['count'] <=0 ) {
$params = array('session_cookie'=>$itemMap['cart_session'],'restid'=>$itemMap['restid'],'dealid'=>$itemMap['dealid']);
/* New item */
$this->db->insert(TABLES::$ORDER_DEALS_CART,$params);
$map['message'] = 'Deal Applied To Cart';
$map['status'] = 0;
}else {
// $this->updateDealsInCart( $itemMap );
$map['message'] = 'Deal Applied To Cart';
$map['status'] = 1;
}
return $map;
}
public function updateDealsInCart( $itemMap ) {
$params = array('session_cookie'=>$itemMap['cart_session'],'restid'=>$itemMap['restid']);
$dealid = $itemMap['dealid'];
$dealid = array('dealid'=>$dealid);
$this->db->where($params);
$this->db->update(TABLES::$ORDER_DEALS_CART,$dealid);
}
public function getOrderDealsCart( $requestMap ) {
$params = array('a.session_cookie'=>$requestMap['cart_session'],'a.restid'=>$requestMap['restid'],'c.service'=>$requestMap['service']);
$this->db->select('a.dealid,b.discount,b.disc_type,c.billed_to,b.discount_mode,b.discount_share,b.lower_limit', FALSE)
->from(TABLES::$ORDER_DEALS_CART.' AS a')
->join(TABLES::$DEAL_DISC_TABLE.' AS b','a.dealid = b.deal_id','inner')
->join(TABLES::$DEAL_TABLE.' AS c','b.deal_id = c.id','inner')
->where($params);
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
public function getOrderTotalDealsCart( $requestMap ) {
$params = array('a.session_cookie'=>$requestMap['cart_session'],'a.restid'=>$requestMap['restid'],'c.service'=>$requestMap['service']);
$this->db->select('a.dealid,c.billed_to', FALSE)
->from(TABLES::$ORDER_DEALS_CART.' AS a')
->join(TABLES::$DEAL_TABLE.' AS c','a.dealid = c.id','inner')
->where($params);
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
public function getItemDealsCart( $requestMap ) {
$params = array('a.session_cookie'=>$requestMap['cart_session'],'d.session_cookie'=>$requestMap['cart_session'],'a.restid'=>$requestMap['restid'],'c.service'=>$requestMap['service']);
$this->db->select('DISTINCT a.dealid,b.discount,b.price,b.sell_price,b.cost_price,c.billed_to,d.quantity,b.itemid', FALSE)
->from(TABLES::$ORDER_DEALS_CART.' AS a')
->join(TABLES::$DEAL_ITEM.' AS b','a.dealid = b.deal_id','inner')
->join(TABLES::$DEAL_TABLE.' AS c','b.deal_id = c.id','inner')
->join(TABLES::$ORDER_CART.' AS d',' b.itemid = d.itemid','inner')
->where('b.itemid IN('.$requestMap['deal_items'].')','',FALSE)
->where($params);
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
public function clearOrderDealsCart( $requestMap ) {
$params = array('session_cookie'=>$requestMap['cart_session'],'restid'=>$requestMap['restid']);
$this->db->where($params);
$this->db->delete(TABLES::$ORDER_DEALS_CART);
}
public function removeDealFromCart( $requestMap ) {
$params = array('session_cookie'=>$requestMap['cart_session'],'restid'=>$requestMap['restid'],'dealid'=>$requestMap['dealid']);
$this->db->where($params);
$this->db->delete(TABLES::$ORDER_DEALS_CART);
}
public function getItemSubItemsByIdNSet($itemid,$restid,$itemset, $cart_session){
$params = array('session_cookie'=>$cart_session,'restid'=>$restid,'itemid'=>$itemid,'itemset'=>$itemset);
$this->db->select('sub_item_id,sub_item_key')
->from(TABLES::$ORDER_SUB_CART)
->where($params);
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
public function getOrderSubItemsItemset( $map ) {
$params = array('session_cookie'=>$map['session_cookie'],'restid'=>$map['restid'],'itemid'=>$map['itemid']);
$this->db->select('max(itemset) as itemset',FALSE)
->from(TABLES::$ORDER_SUB_CART)
->where($params);
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
public function removeItemSubItemsFromCart( $itemid,$restid,$itemset, $cart_session ) {
$params = array('session_cookie'=>$cart_session,'itemid'=>$itemid,'restid'=>$restid,'itemset'=>$itemset);
$this->db->where($params);
$this->db->delete(TABLES::$ORDER_SUB_CART);
}
public function getItemSubItemsFromCart($map) {
$params = array('session_cookie'=>$map['session_cookie'],'restid'=>$map['restid'],'option_id'=>$map['option_id'],'itemset'=>$map['itemset']);
$this->db->select('sub_item_id,subitem_price')
->from(TABLES::$ORDER_SUB_CART)
->where($params);
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
/* public function getAllSubItemsFromCart($map) {
$params = array('session_cookie'=>$map['session_cookie'],'restid'=>$map['restid']);
$this->db->select('a.itemid,a.option_id,a.sub_item_id,a.itemset,b.option_cat_id,b.option_cat_name,b.sortorder as ocatsortorder,c.sub_item_name,d.price');
$this->db->from(TABLES::$ORDER_SUB_CART.' AS a');
$this->db->join(TABLES::$MENU_OPTION_CATEGORY.' AS b','a.option_id=b.id','inner');
$this->db->join(TABLES::$MENU_OPTION.' AS c','b.new_sub_item_key=c.new_sub_item_key','inner');
$this->db->join(TABLES::$MENU_OPTION_PRICE.' AS d','c.sub_item_id=d.sub_item_id','inner');
$this->db->where('a.sub_item_id=c.sub_item_id','',false);
$this->db->where($params);
$this->db->order_by('a.option_id','ASC');
$this->db->order_by('a.itemset','ASC');
$this->db->order_by('b.option_cat_id','ASC');
$this->db->order_by('b.sortorder','ASC');
$this->db->order_by('c.sub_item_name','ASC');
$query = $this->db->get();
$result = $query->result_array();
return $result;
}*/
public function getAllSubItemsFromCart($map) {
$params = array('session_cookie'=>$map['session_cookie'],'restid'=>$map['restid']);
$this->db->select('a.itemid,a.option_id,a.sub_item_id,a.itemset');
$this->db->from(TABLES::$ORDER_SUB_CART.' AS a');
$this->db->where($params);
$this->db->order_by('a.option_id','ASC');
$this->db->order_by('a.itemset','ASC');
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
public function addAllSubItemsToCart( $batch ) {
$this->db->insert_batch(TABLES::$ORDER_SUB_CART,$batch);
}
public function addBatchItemToCart($map) {
$params = array('session_cookie'=>$map['session_cookie'],'restid'=>$map['restid']);
$this->db->where($params);
$this->db->delete(TABLES::$ORDER_CART);
$this->db->insert_batch(TABLES::$ORDER_CART,$map['items']);
}
public function addBatchSubItemToCart($map) {
$params = array('session_cookie'=>$map['session_cookie'],'restid'=>$map['restid']);
$this->db->where($params);
$this->db->delete(TABLES::$ORDER_SUB_CART);
$this->db->insert_batch(TABLES::$ORDER_SUB_CART,$map['subitems']);
}
}
?> | true |
8bcd8c7dd3dfffbe939bef188bf843bbce647f27 | PHP | octalmage/wib | /php-7.3.0/Zend/tests/int_underflow_64bit.phpt | UTF-8 | 570 | 3.09375 | 3 | [
"Zend-2.0",
"BSD-4-Clause-UC",
"BSD-3-Clause",
"LicenseRef-scancode-other-permissive",
"TCL",
"ISC",
"Zlib",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"blessing",
"MIT"
] | permissive | --TEST--
testing integer underflow (64bit)
--SKIPIF--
<?php if (PHP_INT_SIZE != 8) die("skip this test is for 64bit platform only"); ?>
--FILE--
<?php
$doubles = array(
-9223372036854775808,
-9223372036854775809,
-9223372036854775818,
-9223372036854775908,
-9223372036854776808,
);
foreach ($doubles as $d) {
$l = (int)$d;
var_dump($l);
}
echo "Done\n";
?>
--EXPECT--
int(-9223372036854775808)
int(-9223372036854775808)
int(-9223372036854775808)
int(-9223372036854775808)
int(-9223372036854775808)
Done
| true |
9bde44eaa90e83571ea79cd3f63c7c436d4548d1 | PHP | SvenAlHamad/Subench | /app/Lib/View.php | UTF-8 | 548 | 2.609375 | 3 | [] | no_license | <?php
namespace Subench\Lib;
use Webiny\Component\TemplateEngine\TemplateEngineTrait;
class View
{
use TemplateEngineTrait;
static public function showView($view, $data = [], $hasHeader = false, $master = true)
{
$data = array_merge($data, [
'_viewTpl' => $view,
'_hasHeader' => $hasHeader
]
);
if($master){
self::templateEngine()->render('master.tpl', $data);
}else{
self::templateEngine()->render($view, $data);
}
}
} | true |
e9412b6c91eb26f58c53f7c9eadf7d797bf6d651 | PHP | Miuss/mqtt-cms | /core/class/Title.php | UTF-8 | 991 | 2.65625 | 3 | [] | no_license | <?php
class Title {
public $title = NULL;
public $page = NULL;
public function __construct() {
global $DB;
$result = $DB->query("SELECT * FROM `setting`");
$data = $result->fetch_object();
$this->title = $data->title;
}
public function getTitle($get) {
global $DB;
global $server;
global $servers_tag;
switch($get["page"]) {
case "user":
switch($get["view"]){
case "login" :
$pagetitle = "登录_";break;
case "forgetpass" :
$pagetitle = "密码找回_";break;
}
case "device":
switch($get["view"]){
case "index" :
$pagetitle = "设备管理_";break;
case "setting" :
$device = $get["device"];
$result = $DB->query("SELECT * FROM `devices` WHERE `id` = '{$device}'");
$data = $result->fetch_object();
$pagetitle = "设备".$data->id."_设备管理_";break;
}
}
return $pagetitle.$this->title;
}
}
?> | true |
bc3016b0e6fa7f207cdec9ffbf4e9ec57717f5dc | PHP | bileto/criticalsection | /tests/CriticalSectionTests/RedisCriticalSectionTest.phpt | UTF-8 | 4,891 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace BiletoTests\CriticalSectionTests;
require_once(__DIR__ . '/bootstrap.php');
use Mockery;
use Mockery\LegacyMockInterface;
use Mockery\MockInterface;
use Redis;
use Bileto\CriticalSection\CriticalSection;
use Bileto\CriticalSection\Driver\IDriver;
use Tester\TestCase;
use Tester\Assert;
class RedisCriticalSectionTest extends TestCase
{
const TEST_LABEL = "test";
/** @var CriticalSection */
private $criticalSection;
/** @var IDriver|MockInterface|LegacyMockInterface */
private $driver;
protected function setUp(): void
{
$this->driver = Mockery::mock(IDriver::class);
$this->criticalSection = new CriticalSection($this->driver);
}
protected function tearDown(): void
{
Mockery::close();
}
public function testCanBeEnteredAndLeft(): void
{
$this->driver->shouldReceive('acquireLock')->once()->andReturn(TRUE);
$this->driver->shouldReceive('releaseLock')->once()->andReturn(TRUE);
Assert::false($this->criticalSection->isEntered(self::TEST_LABEL));
Assert::true($this->criticalSection->enter(self::TEST_LABEL));
Assert::true($this->criticalSection->isEntered(self::TEST_LABEL));
Assert::true($this->criticalSection->leave(self::TEST_LABEL));
Assert::false($this->criticalSection->isEntered(self::TEST_LABEL));
}
public function testCannotBeEnteredTwice(): void
{
$this->driver->shouldReceive('acquireLock')->once()->andReturn(TRUE);
$this->driver->shouldReceive('releaseLock')->once()->andReturn(TRUE);
Assert::true($this->criticalSection->enter(self::TEST_LABEL));
Assert::true($this->criticalSection->isEntered(self::TEST_LABEL));
Assert::false($this->criticalSection->enter(self::TEST_LABEL));
Assert::true($this->criticalSection->leave(self::TEST_LABEL));
}
public function testCannotBeLeftWithoutEnter(): void
{
$this->driver->shouldReceive('acquireLock')->never();
$this->driver->shouldReceive('releaseLock')->never();
Assert::false($this->criticalSection->isEntered(self::TEST_LABEL));
Assert::false($this->criticalSection->leave(self::TEST_LABEL));
}
public function testCannotBeLeftTwice(): void
{
$this->driver->shouldReceive('acquireLock')->once()->andReturn(TRUE);
$this->driver->shouldReceive('releaseLock')->once()->andReturn(TRUE);
Assert::true($this->criticalSection->enter(self::TEST_LABEL));
Assert::true($this->criticalSection->isEntered(self::TEST_LABEL));
Assert::true($this->criticalSection->leave(self::TEST_LABEL));
Assert::false($this->criticalSection->leave(self::TEST_LABEL));
}
public function testIsNotEnteredOnNotAcquiredLock(): void
{
$this->driver->shouldReceive('acquireLock')->once()->andReturn(FALSE);
$this->driver->shouldReceive('releaseLock')->never();
Assert::false($this->criticalSection->isEntered(self::TEST_LABEL));
Assert::false($this->criticalSection->enter(self::TEST_LABEL));
Assert::false($this->criticalSection->isEntered(self::TEST_LABEL));
}
public function testIsNotLeftOnNotReleasedLock(): void
{
$this->driver->shouldReceive('acquireLock')->once()->andReturn(TRUE);
$this->driver->shouldReceive('releaseLock')->once()->andReturn(FALSE);
Assert::true($this->criticalSection->enter(self::TEST_LABEL));
Assert::true($this->criticalSection->isEntered(self::TEST_LABEL));
Assert::false($this->criticalSection->leave(self::TEST_LABEL));
Assert::true($this->criticalSection->isEntered(self::TEST_LABEL));
}
public function testMultipleCriticalSectionHandlers(): void
{
$this->driver->shouldReceive('acquireLock')->once()->andReturn(TRUE);
$this->driver->shouldReceive('acquireLock')->once()->andReturn(FALSE);
$this->driver->shouldReceive('releaseLock')->once()->andReturn(TRUE);
$criticalSection = $this->criticalSection;
$criticalSection2 = new CriticalSection($this->driver);
Assert::false($criticalSection->isEntered(self::TEST_LABEL));
Assert::false($criticalSection2->isEntered(self::TEST_LABEL));
Assert::true($criticalSection->enter(self::TEST_LABEL));
Assert::false($criticalSection2->enter(self::TEST_LABEL));
Assert::true($criticalSection->isEntered(self::TEST_LABEL));
Assert::false($criticalSection2->isEntered(self::TEST_LABEL));
Assert::true($criticalSection->leave(self::TEST_LABEL));
Assert::false($criticalSection2->leave(self::TEST_LABEL));
Assert::false($criticalSection->isEntered(self::TEST_LABEL));
Assert::false($criticalSection2->isEntered(self::TEST_LABEL));
}
}
(new RedisCriticalSectionTest())->run();
| true |
f123fbe61d26c9dd974a83a1a3c70e8683ddef78 | PHP | family2099/Homework_annotation | /050_Loop/testFor.php | UTF-8 | 456 | 3.5625 | 4 | [] | no_license | <?php
//for為你的程式碼需要重覆多次執行的時候使用,當符合條件時,
//for 迴圈就會一直執行到不符合條件為止
//for( 設定初始值 ; 比對運算式 ; 初始值執行動作 )
//本案例為雙層迴圈,如果i+j整除4的話跳過第二層迴圈
for ($i = 1; $i <= 3; $i++) {
for ($j = 1; $j <= 4; $j++) {
echo "$i , $j <br>";
if (($i + $j) % 4 == 0)
break;//跳過出迴圈
}
echo "-----<br>";
}
?> | true |
b2fa7bbbfc6106b33c5fc2c38fe97506615f7721 | PHP | jamessw-byui/cs313-php | /web/week07/sign_up.php | UTF-8 | 3,209 | 3.078125 | 3 | [] | no_license | <?php
// Start the session
session_start();
$dbUrl = getenv('DATABASE_URL');
if (empty($dbUrl)) {
// example localhost configuration URL with postgres username and a database called cs313db
// adding a comment
$dbUrl = "";
}
$dbopts = parse_url($dbUrl);
$dbHost = $dbopts["host"];
$dbPort = $dbopts["port"];
$dbUser = $dbopts["user"];
$dbPassword = $dbopts["pass"];
$dbName = ltrim($dbopts["path"], '/');
try {
$db = new PDO("pgsql:host=$dbHost;port=$dbPort;dbname=$dbName", $dbUser, $dbPassword);
// this line makes PDO give us an exception when there are problems,
// and can be very helpful in debugging! (But you would likely want
// to disable it for production environments.)
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $ex) {
echo "<p>error: " . $ex->getMessage() . "</p>";
die();
}
$passwordMeetsRequirements = false;
if(isset($_POST['password'])) {
if(strlen($_POST['password']) >= 7 && preg_match('~[0-9]~', $_POST['password'])) {
$passwordMeetsRequirements = true;
}
}
$passwordMatch=true;
if($_POST['password'] != null && $passwordMeetsRequirements && $_POST['password'] == $_POST['passwordVerify']) {
if(isset($_POST['username'])) {
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$newStatement = $db->prepare(
"INSERT INTO users (username, password) VALUES (:username, :password)"
);
$newStatement->bindParam(':username',$username);
$newStatement->bindParam(':password',$password);
// execute the statement
$newExecuteSuccess = $newStatement->execute();
$newURL = "login.php";
header('Location: ' . $newURL);
};
} else {
if($_POST['password'] != null) {
$passwordMatch=false;
};
};
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sign in</title>
<script src="sign_up.js"></script>
</head>
<body>
<?php
if($passwordMatch==false && $_POST['password']) {
echo '<p style="color:red">Password does not match</p>';
}
if($passwordMeetsRequirements == false && $_POST['password']) {
echo '<p style="color:red">Password Requires at least 7 Characters and needs to contain a number</p>';
}
?>
<p style="color:red; visibility:hidden;" id=alertMessage>They don't meet the requirements of 7 characters and needing a number</p>
<form action="sign_up.php" method="POST">
<label for="username">Username:</label>
<input type="text" name="username"><br>
<label for="password">Password:</label>
<input type="password" name="password" oninput="checkPasswordRequirements(this.value)" id="password"> <p style="color:red; visibility:hidden;" id='matchMessage'>Passwords don't matvh</p><br>
<label for="password">Verify Password:</label>
<input type="password" name="passwordVerify" oninput="checkPasswordsMatch()" id="passwordVerify"><br>
<button type="submit">Submit</button>
</form>
</body>
</html> | true |
a14451c003397b52a0607f994a06832acf1f6fbb | PHP | JoshDoug/ci6230-airline-cw | /src/admin/index.php | UTF-8 | 1,361 | 2.609375 | 3 | [] | no_license | <?php
require_once '../../private/initialise.php';
require_once(INCLUDE_ROOT . '/adminAuthRequired.php');
if (isset($_POST['registerAdmin'])) {
$expected = ['firstName', 'lastName', 'email', 'password', 'confirm'];
// Assign $_POST variables to simple variables and check all fields have values
foreach ($_POST as $key => $value) {
if (in_array($key, $expected)) {
$$key = trim($value); // Use a variable variable (pretty cool)
if (empty($$key)) {
$errors = true;
}
}
}
if (!$errors) { // Proceed only if there are no errors
if ($password === $confirm) {
// Check that the email hasn't already been registered
$emailExists = checkEmailExists($email);
if ($emailExists) {
$errors['failed'] = "Email is already registered.";
} else {
$registerAdmin = registerAdmin($firstName, $lastName, $email, $password);
if ($registerCustomer) {
$_SESSION['authenticatedAdmin'] = $email;
header('Location: index.php');
exit;
}
}
}
}
}
// Display admin details and add option to add additional admin and link to flight management page
require_once(VIEW_ROOT . '/admin/adminView.php') ?>
| true |
cd28d08913afc0e19bfff4ce84c4faac24aba83b | PHP | ali/dds2 | /server/views/assign-slide.php | UTF-8 | 1,022 | 2.625 | 3 | [] | no_license | <!--
Each selected machine from the dropdown & the uuid of our slide is posted to
do-assign-slide.php which then does the (actual) assignment.
-->
<?php include 'header.php'?>
<?php
global $url;
$deck_uuid=$url[1];
?>
<div class='container'>
<div class='span5'>
<h1>Assign slides Yo</h1>
<p>Choose a machine from the dropdown on the left and a set of slides from the dropdown on the right </p>
</div>
<div class='span9'>
<form class='form-horizontal' name='machine_names' action='/do-assign-slide' method='POST'>
<input type='hidden' name='uuid' value='<?=$deck_uuid?>'>
<select name='machine_fqdn[]' multiple="multiple">
<?php
$machines_array = Machine::all_machines();
foreach ($machines_array as $machine){
echo '<option>';
echo $machine->get_name();
echo '</option>';
}
?>
</select>
<button class="btn">Add to Deck</button>
</form>
</div>
</div>
<?php include 'footer.php'?>
| true |
3093cb340f37ff17cf04b38b09fbcf6c35a9deeb | PHP | CedrickOka/wsse-authentication-bundle | /src/Command/UserCommand.php | UTF-8 | 1,386 | 2.796875 | 3 | [
"MIT"
] | permissive | <?php
namespace Oka\WSSEAuthenticationBundle\Command;
use Oka\WSSEAuthenticationBundle\Model\WSSEUserManipulatorInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\Question;
/**
*
* @author Cedrick Oka Baidai <okacedrick@gmail.com>
*
*/
abstract class UserCommand extends Command
{
/**
* @var WSSEUserManipulatorInterface $userManipulator
*/
protected $userManipulator;
public function __construct(WSSEUserManipulatorInterface $userManipulator)
{
parent::__construct();
$this->userManipulator = $userManipulator;
}
/**
* {@inheritdoc}
*/
protected function configure()
{
$this->addArgument('username', InputArgument::REQUIRED, 'The username');
}
/**
* {@inheritdoc}
*/
protected function interact(InputInterface $input, OutputInterface $output)
{
if (!$input->getArgument('username')) {
$question = new Question('Please choose a username:');
$question->setValidator(function($username){
if (true === empty($username)) {
throw new \Exception('Username can not be empty');
}
return $username;
});
$answer = $this->getHelper('question')->ask($input, $output, $question);
$input->setArgument('username', $answer);
}
}
}
| true |
a8dd4cdd9587172feaf309ca2d9a00b90fefa6ac | PHP | blueberryln/savile-row-society | /app/Model/Model/Wishlist.php | UTF-8 | 3,458 | 2.5625 | 3 | [] | no_license | <?php
App::uses('AppModel', 'Model');
/**
* Wishlist Model
*
* @property User $User
* @property Product $Product
*/
class Wishlist extends AppModel {
/**
* Display field
*
* @var string
*/
public $displayField = 'product_id';
/**
* Validation rules
*
* @var array
*/
public $validate = array(
'user_id' => array(
'numeric' => array(
'rule' => array('numeric'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'product_entity_id' => array(
'numeric' => array(
'rule' => array('numeric'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
);
//The Associations below have been created with all possible keys, those that are not needed can be removed
/**
* belongsTo associations
*
* @var array
*/
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Entity' => array(
'className' => 'Entity',
'foreignKey' => 'product_entity_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
/**
* Get one by User ID and Product ID
* @return type
*/
function get($user_id, $product_entity_id) {
return $this->find('first', array(
'conditions' => array(
'Wishlist.user_id' => $user_id,
'Wishlist.product_entity_id' => $product_entity_id
)
));
}
/**
* Get all by User ID
* @param type $user_id
* @return type
*/
function getByUserID($user_id) {
return $this->find('list', array(
'conditions' => array(
'Wishlist.user_id' => $user_id
),
'fields' => array(
'Wishlist.product_entity_id'
)
));
}
/**
* Remove by User ID and Product ID
* @return type
*/
function remove($user_id, $product_entity_id) {
return $this->deleteAll(array('Wishlist.user_id' => $user_id, 'Wishlist.product_entity_id' => $product_entity_id), false, false);
}
function getUserLikedItems($user_id, $last_liked_id, $limit = 2){
$find_array = array(
'conditions' => array('Wishlist.user_id' => $user_id),
'fields' => array('Wishlist.product_entity_id', 'Wishlist.id'),
'order' => array('Wishlist.id DESC'),
'limit' => $limit,
);
if($last_liked_id > 0){
$find_array['conditions'][] = 'Wishlist.id < ' . $last_liked_id;
}
return $this->find('all', $find_array);
}
}
| true |
d0ce922fb6d2ba0f883c13365567bad1ba5e8375 | PHP | abdouthetif/TheLazyStreaming | /src/Entity/Liste.php | UTF-8 | 1,571 | 2.515625 | 3 | [] | no_license | <?php
namespace App\Entity;
use App\Repository\ListeRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=ListeRepository::class)
*/
class Liste
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $name;
/**
* @ORM\Column(type="integer", nullable=true)
*/
private $id_movie;
/**
* @ORM\Column(type="integer", nullable=true)
*/
private $id_serie;
/**
* @ORM\ManyToOne(targetEntity=User::class, inversedBy="listes")
* @ORM\JoinColumn(nullable=false)
*/
private $user;
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getIdMovie(): ?int
{
return $this->id_movie;
}
public function setIdMovie(?int $id_movie): self
{
$this->id_movie = $id_movie;
return $this;
}
public function getIdSerie(): ?int
{
return $this->id_serie;
}
public function setIdSerie(?int $id_serie): self
{
$this->id_serie = $id_serie;
return $this;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
}
| true |
47399c0eaa68f75c31ad4f4525fa9a2cc2e1433f | PHP | dojoVader/ciims-modules-dashboard | /components/CiiDashboardController.php | UTF-8 | 3,324 | 2.53125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | <?php
/**
* Controller is the customized base controller class.
* All controller classes for this application should extend from this base class.
*/
class CiiDashboardController extends CiiController
{
/**
* Retrieve assetManager from anywhere without having to instatiate this code
* @return CAssetManager
*/
public function getAsset()
{
return Yii::app()->assetManager->publish(YiiBase::getPathOfAlias('application.modules.dashboard.assets'), true, -1, YII_DEBUG);
}
/**
* Automatically bind some Javascript black magic!
* Since _nearly_ every page has a bunch of javascript, all javascript for a particular controller
* is now wrapped up in modules.dashboard.assets.js.dashboard.<controller>.js
*
* This makes management of the code _very_ friendly and easy to handle. Additionally, it separates
* out the js and the php code
*
* This deliberately occurs afterRender because script order does matter for the dashboard. This really needs to be dead last
*/
protected function afterRender($view, &$output)
{
Yii::app()->clientScript->registerScriptFile($this->asset.'/js/dashboard/' . $this->id. '.js', CClientScript::POS_END);
Yii::app()->clientScript->registerScript($this->id.'_'.$this->action->id, '$(document).ready(function() { CiiDashboard.'.CiiInflector::titleize($this->id).'.load'.CiiInflector::titleize($this->action->id).'(); });', CCLientScript::POS_END);
}
/**
* Before action method
* @param CAction $action The aciton
* @return boolean
*/
public function beforeAction($action)
{
// Redirect to SSL if this is set in the dashboard
if (!Yii::app()->getRequest()->isSecureConnection && Cii::getConfig('forceSecureSSL', false))
$this->redirect('https://' . Yii::app()->getRequest()->serverName . Yii::app()->getRequest()->requestUri);
return parent::beforeAction($action);
}
/**
* @return string[] action filters
*/
public function filters()
{
return array(
'accessControl'
);
}
/**
* Handles errors
*/
public function actionError()
{
if (Yii::app()->user->isGuest)
return $this->redirect($this->createUrl('/login?next=' . Yii::app()->request->requestUri));
if($error=Yii::app()->errorHandler->error)
{
if(Yii::app()->request->isAjaxRequest)
echo $error['message'];
else
$this->render('error', array('error' => $error));
}
else
$this->redirect($this->createUrl('/error/403'));
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow authenticated admins to perform any action
'users'=>array('@'),
'expression'=>'Yii::app()->user->role>=5'
),
array('deny', // deny all users
'users'=>array('*'),
'deniedCallback' => array($this, 'actionError')
),
);
}
/**
* @var string the default layout for the controller view. Defaults to '//layouts/column1',
* meaning using a single column layout. See 'protected/views/layouts/column1.php'.
*/
public $layout='main';
} | true |
e092fa6c42d0221955250191456eb59d8ac32a02 | PHP | kmaloneVillanova/CSC2053 | /lab5/crm/includes/book-utilities.inc.php | UTF-8 | 1,934 | 3.234375 | 3 | [] | no_license | <?php
function readCustomers($filename) {
// read the file into memory; if there is an error then stop processing
$arr = file($filename) or die('ERROR: Cannot find file');
// our data is semicolon-delimited
$delimiter = ';';
// loop through each line of the file
foreach ($arr as $line) {
// returns an array of strings where each element in the array
// corresponds to each substring between the delimiters
$splitcontents = explode($delimiter, $line);
$aCustomer = array();
$aCustomer['id'] = $splitcontents[0];
$aCustomer['name'] = utf8_encode($splitcontents[1] . ' ' . $splitcontents[2]);
$aCustomer['email'] = utf8_encode($splitcontents[3]);
$aCustomer['university'] = utf8_encode($splitcontents[4]);
$aCustomer['address'] = utf8_encode($splitcontents[5]);
$aCustomer['city'] = utf8_encode($splitcontents[6]);
$aCustomer['country'] = utf8_encode($splitcontents[8]);
$aCustomer['sales'] = utf8_encode($splitcontents[11]);
// add customer to array of customers
$customers[$aCustomer['id']] = $aCustomer;
}
return $customers;
}
function readOrders($customer, $filename) {
$arr = file($filename) or die('ERROR: Cannot find file');
// our data is comma-delimited
$delimiter = ',';
// loop through each line of the file
foreach ($arr as $line) {
$splitcontents = explode($delimiter, $line);
$anOrder = array();
$anOrder['id'] = $splitcontents[0];
$anOrder['customer'] = $splitcontents[1];
$anOrder['isbn'] = $splitcontents[2];
$anOrder['title'] = $splitcontents[3];
$anOrder['category'] = $splitcontents[4];
$orders[] = $anOrder;
}
foreach ($orders as $ord) {
if ($ord['customer'] == $customer) $filtered[] = $ord;
}
if (isset($filtered) )
return $filtered;
else
return null;
}
?> | true |
323e00debbdf5409f130d7a4838cfe660056d1ba | PHP | frapgn/php-adv-charts | /step1-method1/index.php | UTF-8 | 1,537 | 2.515625 | 3 | [] | no_license | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Metodo 1</title>
</head>
<body>
<canvas id="line-chart"></canvas>
<?php // ----- JAVASCRIPT ----- ?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<script>
$.ajax({
url: 'server.php',
method: 'GET',
success: function(database) {
buildLineChart(database);
},
error: function() {
}
});
function buildLineChart(database) {
var ctx = $('#line-chart');
var lineChart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
datasets: [{
label: 'Boh',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: database
}]
}
});
}
</script>
<?php // ----- JAVASCRIPT ----- ?>
</body>
</html>
| true |
2091f5367aab3a3eefd0e4772a6efe2cbf81943d | PHP | kristapsmors/bitcoin-chart | /app/helpers/template.php | UTF-8 | 134 | 3.015625 | 3 | [
"MIT"
] | permissive | <?php
function currency($amount, $currency, $decimals = 2)
{
return sprintf('%s%s', $currency, number_format($amount, $decimals));
} | true |
fb10a346b78285841110bb649e9b731195300ffc | PHP | tmakij/drunken-octo-tyrion | /libs/models/aihe.php | UTF-8 | 1,294 | 3.109375 | 3 | [] | no_license | <?php
final class Aihe extends IDobject {
private $nimi;
function __construct($id, $nimi) {
$this->id = $id;
$this->nimi = $nimi;
}
public function poistaAihe($id) {
try {
tallennaTietokantaan('DELETE FROM aihe WHERE id = ?', array($id));
} catch (PDOException $ex) {
return false;
}
return true;
}
public static function uusiAihe($nimi) {
return tallennaAinutlaatuinen('SELECT nimi FROM aihe WHERE nimi = ?', array($nimi), 'INSERT INTO aihe(nimi) VALUES(?)', array($nimi));
}
public static function getAihe($id) {
$tulos = $id !== -1 ? querySingle('SELECT nimi, id FROM aihe where id = ?', array($id)) :
querySingle('SELECT nimi, id FROM aihe LIMIT 1', array());
$aihe = new Aihe($tulos->id, $tulos->nimi);
return $aihe;
}
public static function getAiheet() {
$tulos = queryArray('SELECT nimi, id FROM aihe ORDER BY nimi', array());
$aiheet = array();
foreach ($tulos as $aiheTulos) {
$aihe = new Aihe($aiheTulos->id, $aiheTulos->nimi);
array_push($aiheet, $aihe);
}
return $aiheet;
}
public function __toString() {
return $this->nimi;
}
}
| true |
27221d23814f45ab6be0faedb2594617be4cd510 | PHP | anconaesselmann/Composition | /src/aae/persistence/adapters/db/DataToMySQL.php | UTF-8 | 8,597 | 2.8125 | 3 | [] | no_license | <?php
// /**
// *
// */
// namespace aae\persistence\adapters\db {
// /**
// * @author Axel Ancona Esselmann
// * @package aae\persistence\adapters\db
// */
// use \aae\persistence\adapters\db\connections\DBConnectionInterface as DBConnectionInterface;
// use \aae\persistence\adapters\db\connections\MySQlDBConnection as MySQlDBConnection;
// class DataToMySQL implements \aae\persistence\AdapterInterface {
// private $dbConnection = null;
// public function __construct() {
// $this->setDbConnection(new MySQlDBConnection());
// }
// public function setDbConnection(DBConnectionInterface $connectionInstance) {
// $this->dbConnection = $connectionInstance;
// }
// public function persist($data, $settings) {
// $this->_validateSettings($settings);
// $data = $this->_convertFromDataFieldsToColumns($data, $settings);
// $stmt = $this->_getPreparedPersistStatement($data, $settings);
// $this->_bindParameters($stmt, $data);
// $result = $stmt->execute();
// $stmt->close();
// return $result;
// }
// /*public function persist($data, $settings) {
// $this->_validateSettings($settings);
// $config = $this->_getConfigAssoc($settings);
// $dbConnection = $this->_getDbConnection($settings);
// $dbName = $config['dbName'];
// $tableName = $this->_getTableNames($settings);
// $data = $this->_convertFromDataFieldsToColumns($data, $settings);
// $columnNames = "";
// $values = "";
// foreach (get_object_vars($data) as $varName => $value) {
// if (strlen($columnNames) > 0) {
// $columnNames .= ", ";
// $values .= ", ";
// }
// $columnNames .= $varName;
// if (!is_int ($value) &&
// !is_float($value) &&
// !is_null ($value) &&
// !is_bool ($value))
// {
// $value = "\"".strval($value)."\"";
// }
// $values .= $value;
// }
// $queryString = "
// INSERT INTO $dbName.$tableName ($columnNames)
// VALUES ($values)
// ";
// print($queryString);
// $result = $dbConnection->query($queryString);
// if (!$result) {
// throw new \Exception("Error Processing Request", 1);
// }
// return $result;
// }*/
// public function retrieve($data, $settings) {
// $this->_validateSettings($settings);
// $config = $this->_getConfigAssoc($settings);
// $dbName = $config['dbName'];
// $tableName = $this->_getTableNames($settings);
// $dbConnection = $this->_getDbConnection($settings);
// $queryString = "SELECT * FROM $dbName.$tableName";
// $result = $dbConnection->query($queryString);
// if ($result) {
// $assoc = $result->fetch_assoc();
// $matchingAssoc = $this->_convertFromColumnsToDataFields($assoc, $settings);
// $data = $this->_updateData($data, $matchingAssoc);
// return $data;
// } else {
// return false;
// }
// }
// private function _updateData($data, $matchingAssoc) {
// foreach ($matchingAssoc as $key => $value) {
// if (property_exists($data, $key)) {
// $data->$key = $value;
// }
// }
// return $data;
// }
// private function _convertFromColumnsToDataFields($assoc, $settings) {
// $tableName = $settings['tableName'];
// $matchingAssoc = array();
// if (is_array($tableName)) {
// foreach ($settings['tableName'] as $table => $columns) {
// $tableName = $table; // TODO: This does not deal with multiple tables
// foreach ($columns as $columnName => $fieldName) {
// $matchingAssoc[$fieldName] = $assoc[$columnName];
// }
// }
// } else {
// $matchingAssoc = $assoc;
// }
// return $matchingAssoc;
// }
// private function _getColumnNames($data) {
// return array_keys(get_object_vars($data));
// }
// private function _getBindingParams($data) {
// $bindingTypes = "";
// $bindingArray = array("");
// foreach (get_object_vars($data) as $varName => $value) {
// $bindingArray[] = &$data->$varName;
// $bindingTypes .= "s";
// }
// $bindingArray[0] = $bindingTypes;
// return $bindingArray;
// }
// private function _getPreparedValues($data) {
// $result = array();
// $result = array_fill(0, count(get_object_vars($data)), "?");
// return $result;
// }
// private function _getPersistQueryString($data, $settings) {
// $config = $this->_getConfigAssoc($settings);
// $dbName = $config['dbName'];
// $tableName = $this->_getTableNames($settings);
// return sprintf("INSERT INTO %s.%s (%s) VALUES (%s) ",
// $dbName,
// $tableName,
// implode(", ", $this->_getColumnNames($data)),
// implode(", ", $this->_getPreparedValues($data)));
// }
// private function _bindParameters($stmt, $data) {
// call_user_func_array(array($stmt, 'bind_param'), $this->_getBindingParams($data));
// }
// private function _getPreparedPersistStatement($data, $settings) {
// $db = $this->_getDbConnection($settings);
// $queryString = $this->_getPersistQueryString($data, $settings);
// return $db->prepare($queryString);
// }
// private function _getConfigAssoc($source) {
// if (is_string($source['dbConfig'])) {
// $config = $this->_getJSONFromDir($source['dbConfig']);
// } else {
// $config = $source['dbConfig'];
// }
// return $config;
// }
// private function _convertFromDataFieldsToColumns($data, $settings) {
// $tableName = $settings['tableName'];
// if (is_array($tableName)) {
// foreach ($settings['tableName'] as $table => $columns) {
// $tableName = $table; // TODO: This does not deal with multiple tables
// $temp = new \stdClass();
// foreach ($columns as $columnName => $fieldName) {
// $temp->$columnName = $data->$fieldName;
// }
// $data = $temp;
// }
// }
// return $data;
// }
// private function _getTableNames($settings) {
// if (is_array($settings['tableName'])) {
// foreach ($settings['tableName'] as $table => $columns) {
// $tableName = $table;
// }
// } else {
// $tableName = $settings['tableName'];
// }
// return $tableName;
// }
// private function _getDbConnection($settings) {
// $dbConfig = new \aae\persistence\adapters\db\DBConfig($settings['dbConfig']);
// $dbConnection = $this->dbConnection->getConnection($dbConfig);
// if (array_key_exists('logger', $settings)) {
// $dbConnection->setLogger($settings['logger']); // TODO: UNTESTED!!!
// }
// return $dbConnection;
// }
// private function _getJSONFromDir($dir) {
// $fileContent = file_get_contents($dir);
// $fileContent = preg_replace('/\s*(?!<\")\/\*[^\*]+\*\/(?!\")\s*/', '', $fileContent);
// $json = json_decode($fileContent, true);
// return $json;
// }
// private function _validateSettings($settings) {
// if (!is_array($settings)) throw new \Exception("Settings arguments have to be arrays" , 210142006);
// if (!array_key_exists('tableName', $settings)) throw new \Exception("Settings have to have a 'tableName' key", 210142010);
// if (!array_key_exists('dbConfig' , $settings)) throw new \Exception("Settings have to have a 'dbConfig' key" , 210142015);
// $this->_validateDBCOnfig($settings['dbConfig']);
// }
// private function _validateDBCOnfig($dbConfig) {
// if (!is_array($dbConfig)) {
// if (is_string($dbConfig)) {
// if (!file_exists($dbConfig)) {
// throw new \Exception("The dbConfig file at '".$dbConfig."' does not exist.", 210142017);
// } else {
// // TODO: here the file is parsed just to determine validity, meaning it will have to be parsed a second time.
// $dbConfig = $this->_getJSONFromDir($dbConfig);
// if (!$dbConfig) throw new \Exception("The configuration file '".$dbConfig."' contains invalid JSON.", 210142136);
// }
// } else {
// throw new \Exception("The settings value for dbConfig either has to be a valid path or an associative array.", 210142034);
// }
// } else {
// $dbConfig = $dbConfig;
// }
// $this->_validateDBConfigAssoc($dbConfig);
// }
// private function _validateDBConfigAssoc($dbConfig) {
// $requiredArrayKeys = array(
// 'dbName' => 210142043,
// 'password' => 210142058,
// 'user' => 210142102,
// 'host' => 210142104);
// foreach ($requiredArrayKeys as $arrayKey => $errorCode) {
// if (!array_key_exists($arrayKey, $dbConfig)) {
// throw new \Exception("The dbConfig has to have a '$arrayKey' key.", $errorCode);
// }
// }
// }
// }
// } | true |
b9f215c7df71ae37cbf19387d516e7581603c268 | PHP | ayushi710/Hygiea | /practice.php | UTF-8 | 311 | 3.015625 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: momin
* Date: 10/10/2017
* Time: 3:53 PM
*/
$real_ans = 5.5;
$test = intval($real_ans);
echo $real_ans - $test;
?>
<input type="text" value="hello">
<?php
$array = array(
'key1' =>54.1,
'65' =>10
);
echo array_sum($array);
?>
| true |
03487c1800843e4750c473b2cdd927519a4a4309 | PHP | crazypig1/htdocs | /admin/data/07_product_detail.php | UTF-8 | 598 | 2.546875 | 3 | [] | no_license | <?php
//1:加载init.php 9:28--9:33
require("00_init.php");
//2:获取参数lid(id数字)
$lid = $_REQUEST["lid"];
//3:创建SQL语句并且发送SQL
$sql = " SELECT lid,title,price,spec";
$sql .= " category,name,cpu,disk FROM";
$sql .= " xz_laptop WHERE lid = $lid";
@$result = mysqli_query($conn,$sql);
@$row = mysqli_fetch_assoc($result);
if(!$row){
//echo mysqli_error($conn);//显示详细错误信息
die('{"code":-1,"msg":"'.mysqli_error($conn).'"}');
//停止php运行,并且输出字符串
}
//4:抓取一行关联
//5:转换JSON字符串并且输出
echo json_encode($row);
| true |
58939ea2adabd8ec447ad0df94063fba594b241d | PHP | sedamiqaelyan/ACA | /Daily/day16/index.php | UTF-8 | 481 | 3.46875 | 3 | [] | no_license | <!Doctype html>
<html>
<head>
</head>
<body>
<?php
/* $myAssocArray=[
"name"=>"seda",
"lastname"=>"miqaelyan",
"age"=>"26",
];
$arrayKeys=array_keys($myAssocArray);
var_dump($arrayKeys);*/
/* function polyndrom($string) {
if(strrev($string)==$string){
echo "is Polindrom";
}
else {
echo "is no Polindrom";
}
}
polyndrom("asdsa");*/
?>
</body>
</html> | true |
a6c559165ce17e9bbadac846e3d8febae1dec193 | PHP | viethoangCIT/vietkids | /group3/view/test_dev/add_answer_dev.php | UTF-8 | 4,754 | 2.59375 | 3 | [] | no_license | <?php
//*****************************************
//FUNCTION HEADER
//*****************************************
$function_title = "Nhập Câu Hỏi";
//tạo liên kết nhập tin
echo $this->Template->load_function_header($function_title);
//*****************************************
//END FUNCTION HEADER
//*****************************************
//*****************************************
//BEGIN: FORM NHẬP BÀI THI
//*****************************************
$name = "";
$id_question = "";
$question_name = "";
$id_test = "";
$test_name = "";
$id_created_user = "";
$created_username = "";
$created_fullname = "";
$created = "";
if($array_answer != null)
{
$name = $array_answer["0"]["name"];
$id_question = $array_answer["0"]["id_question"];
$question_name = $array_answer["0"]["question_name"];
$id_test = $array_answer["0"]["id_test"];
$test_name = $array_answer["0"]["test_name"];
$id_created_user = $array_answer["0"]["id_created_user"];
$created_username = $array_answer["0"]["created_username"];
$created_fullname = $array_answer["0"]["created_fullname"];
$created = $array_answer["0"]["created"];
}
$str_form_row_answer = "";
//gọi hàm $this->Template->load_input() để tạo string input nhập tên bài this
$str_input_name_answer = $this->Template->load_textbox(array("name"=>"name", "value"=>$name, "style"=>"width:200px;"));
//gọi hàm $this->Template->load_form_row để tạo một dòng nhập tên bài thi và input tên câu hỏi
$str_form_row_answer .= $this->Template->load_form_row(array("title"=>"Tên","input"=>$str_input_name_answer));
//tạo textbox id câu hỏi
$str_select_id_question_answer = $this->Template->load_selectbox(array("name"=>"id_question","value"=>$id_question,"style"=>"width:200px;"),$array_question);
$str_form_row_answer .= $this->Template->load_form_row(array("title"=>"Id Câu hỏi","input"=>$str_select_id_question_answer));
//tạo textbox tên câu hỏi
$str_input_question_name_answer = $this->Template->load_textbox(array("name"=>"question_name","value"=>$question_name,"style"=>"width:200px;"));
$str_form_row_answer .= $this->Template->load_form_row(array("title"=>"Tên câu hỏi","input"=>$str_input_question_name_answer));
//tạo textbox id bài thi
$str_input_id_test_answer = $this->Template->load_textbox(array("name"=>"id_test","value"=>$id_test,"style"=>"width:200px;"));
$str_form_row_answer .= $this->Template->load_form_row(array("title"=>"ID bài thi","input"=>$str_input_id_test_answer));
//tạo textbox tên bai thi
$str_input_test_name_answer = $this->Template->load_textbox(array("name"=>"test_name","value"=>$test_name,"style"=>"width:200px;"));
$str_form_row_answer .= $this->Template->load_form_row(array("title"=>"Tên bài thi","input"=>$str_input_test_name_answer));
//tạo textbox id user
$str_input_id_created_user_answer = $this->Template->load_textbox(array("name"=>"id_created_user","value"=>$id_created_user,"style"=>"width:200px;"));
$str_form_row_answer .= $this->Template->load_form_row(array("title"=>"Id user","input"=>$str_input_id_created_user_answer));
//tạo textbox tao username
$str_input_created_username_answer = $this->Template->load_textbox(array("name"=>"created_username","value"=>$created_username,"style"=>"width:200px;"));
$str_form_row_answer .= $this->Template->load_form_row(array("title"=>"Username","input"=>$str_input_created_username_answer));
//tạo textbox tao fullname
$str_input_created_fullname_answer = $this->Template->load_textbox(array("name"=>"created_fullname","value"=>$created_fullname,"style"=>"width:200px;"));
$str_form_row_answer .= $this->Template->load_form_row(array("title"=>"fullname","input"=>$str_input_created_fullname_answer));
//tạo textbox tao username
$str_input_created_answer = $this->Template->load_textbox(array("name"=>"created","value"=>$created,"style"=>"width:200px;"));
$str_form_row_answer .= $this->Template->load_form_row(array("title"=>"Ngày tạo","input"=>$str_input_created_answer));
//gọi hàm $this->Template->load_button() để tạo string input type = button, nút bấm để lưu
$str_save_button = $this->Template->load_button(array("value"=>"Lưu","type"=>"submit"),"Lưu");
//gọi hàm $this->Template->load_form_row để tạo một dòng có nút lưu
$str_form_row_answer .= $this->Template->load_form_row(array("title"=>"","input"=>$str_save_button));
$str_form_answer = $this->Template->load_form(array("method"=>"post","action"=>"/test/add_answer"),$str_form_row_answer);
echo $str_form_answer;
//tạo
//*****************************************
//END: FORM NHẬP BÀI THI
//*****************************************
?> | true |
818ca52723f73ab388d6e60b97415807f097929b | PHP | arajcany/ApplicationStub | /src/Utility/Install/VersionControl.php | UTF-8 | 8,106 | 2.703125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Utility\Install;
use arajcany\ToolBox\Utility\TextFormatter;
use Cake\Core\Configure\Engine\IniConfig;
use Cake\ORM\TableRegistry;
use Cake\Utility\Hash;
use Cake\Utility\Security;
use Cake\Utility\Text;
/**
* Class Version
*
* @property \App\Model\Table\SettingsTable $Settings
* @property \App\Model\Table\InternalOptionsTable $InternalOptions
* @property IniConfig $IniConfig
*
* @package App\Utility\Install
*/
class VersionControl
{
public $InternalOptions;
public $Settings;
public $IniConfig;
public function __construct()
{
$this->InternalOptions = TableRegistry::getTableLocator()->get('InternalOptions');
$this->Settings = TableRegistry::getTableLocator()->get('Settings');
$this->IniConfig = new IniConfig();
}
/**
* Full path and filename of the version.json file
*
* @return string
*/
public function getVersionJsnFullPath()
{
return CONFIG . 'version.json';
}
/**
* Full path and filename of the version.json file
*
* @return string
*/
public function getVersionIniFilename()
{
return pathinfo($this->getVersionJsnFullPath(), PATHINFO_FILENAME);
}
/**
* Full path and filename of the version.json file
*
* @return string
*/
public function getVersionHistoryJsnFullPath()
{
return CONFIG . 'version_history.json';
}
/**
* Full path and filename of the version.json file
*
* @return string
*/
public function getVersionHistoryJsnFilename()
{
return pathinfo($this->getVersionHistoryJsnFullPath(), PATHINFO_FILENAME);
}
/**
* Return the contents of version.json in array format.
* If version.json does not exist, default is created and returned.
*
* @return array
*/
public function getVersionJsn()
{
$fileToRead = $this->getVersionJsnFullPath();
if (is_file($fileToRead)) {
$versionData = json_decode(file_get_contents($fileToRead), JSON_OBJECT_AS_ARRAY);;
} else {
$versionData = $this->getDefaultVersionJsn();
$this->putVersionJsn($versionData);
}
return $versionData;
}
/**
* Write the version.json file
*
* Should call $this->validateIni($data) to validate $data first
*
* @param array $data
* @return bool
*/
public function putVersionJsn($data = [])
{
$fileToWrite = $this->getVersionJsnFullPath();
return file_put_contents($fileToWrite, json_encode($data, JSON_PRETTY_PRINT));
}
/**
* Return the contents of version_history.json in array format.
* If version_history.json doe not exist, default is created and returned.
*
* @return array
*/
public function getVersionHistoryJsn()
{
$fileToRead = $this->getVersionHistoryJsnFullPath();
if (is_file($fileToRead)) {
$versionData = json_decode(file_get_contents($fileToRead), JSON_OBJECT_AS_ARRAY);;
} else {
$versionData = [$this->getDefaultVersionJsn()];
$this->putVersionHistoryJsn($versionData);
}
return $versionData;
}
/**
* Write the version_history.json file
*
* Should call $this->validateIni($data) to validate $data first
*
* @param array $data
* @return bool
*/
public function putVersionHistoryJsn($data = [])
{
$fileToWrite = $this->getVersionHistoryJsnFullPath();
return file_put_contents($fileToWrite, json_encode($data, JSON_PRETTY_PRINT));
}
/**
* Return the contents of version_history.json in hashed TXT format.
*
* @return string
*/
public function getVersionHistoryHashtxt()
{
$versionData = $this->getVersionHistoryJsn();
$versionData = json_encode($versionData);
$versionData = \arajcany\ToolBox\Utility\Security\Security::encrypt64Url($versionData);
return $versionData;
}
/**
* Format of the version.json
*
* @return array
*/
public function getDefaultVersionJsn()
{
return [
'name' => APP_NAME,
'tag' => '0.0.0',
'desc' => APP_DESC,
'codename' => '',
];
}
/**
* Get the current version tag
*
* @return string
*/
public function getCurrentVersionTag()
{
$version = $this->getVersionJsn();
return $version['tag'];
}
/**
* Sort the Version History
*
* @param $unsorted
* @return array
*/
public function sortVersionHistoryArray($unsorted)
{
$keys = array_keys($unsorted);
natsort($keys);
$keys = array_reverse($keys);
$sorted = [];
foreach ($keys as $key) {
$sorted[$key] = $unsorted[$key];
}
return $sorted;
}
/**
* Increment a classic software version number
*
* @param string $number in the format xx.xx.xx
* @param string $part the part to increment, major | minor | patch
* @return string
*/
public function incrementVersion($number, $part = 'patch')
{
$numberParts = explode('.', $number);
if ($part == 'major') {
$numberParts[0] += 1;
$numberParts[1] = 0;
$numberParts[2] = 0;
}
if ($part == 'minor') {
$numberParts[1] += 1;
$numberParts[2] = 0;
}
if ($part == 'patch') {
$numberParts[2] += 1;
}
return implode('.', $numberParts);
}
/**
* Display the versionHistory.json file in encrypted format
*
* @return false|array
*/
public function _getOnlineVersionHistoryHash()
{
$remote_update_url = TextFormatter::makeEndsWith($this->Settings->getSetting('remote_update_url'), "/");
$arrContextOptions = [
"ssl" => [
"verify_peer" => false,
"verify_peer_name" => false,
],
];
$versionHistoryHash = @file_get_contents($remote_update_url . "version_history_hash.txt", false, stream_context_create($arrContextOptions));
if ($versionHistoryHash) {
$versionHistoryHash = \arajcany\ToolBox\Utility\Security\Security::decrypt64Url($versionHistoryHash);
$versionHistoryHash = @json_decode($versionHistoryHash, JSON_OBJECT_AS_ARRAY);
if (is_array($versionHistoryHash)) {
return $versionHistoryHash;
} else {
return false;
}
} else {
return false;
}
}
/**
* Display the versionHistory.json file in encrypted format
*
* @return false|array
*/
public function _getOnlineVersionHistoryHashForDebug()
{
$remote_update_url = TextFormatter::makeEndsWith($this->Settings->getSetting('remote_update_url'), "/");
$arrContextOptions = [
"ssl" => [
"verify_peer" => false,
"verify_peer_name" => false,
],
];
$versionHistoryHash = @file_get_contents($remote_update_url . "version_history_hash.txt", false, stream_context_create($arrContextOptions));
return $versionHistoryHash;
}
/**
* Publish the version history hash to the sFTP site
*
* @return bool
*/
public function _publishOnlineVersionHistoryHash()
{
$sftp = $this->InternalOptions->getUpdateSftpSession();
if ($sftp === false) {
return false;
}
//publish the hash
$versionHistoryHash = $this->getVersionHistoryHashtxt();
if (strlen($versionHistoryHash) > 0) {
$result = $sftp->put('versionHistory' . APP_NAME . '.hash', $versionHistoryHash);
if ($result == 1) {
return 1;
} else {
return 0;
}
} else {
return 0;
}
}
}
| true |
8819ff8c682fc905cdad741ac6d7be2a70d43ad6 | PHP | antlr/antlr-php-runtime | /src/Tree/SyntaxTree.php | UTF-8 | 1,158 | 2.859375 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
declare(strict_types=1);
namespace Antlr\Antlr4\Runtime\Tree;
use Antlr\Antlr4\Runtime\Interval;
/**
* A tree that knows about an interval in a token stream
* is some kind of syntax tree. Subinterfaces distinguish
* between parse trees and other kinds of syntax trees we might want to create.
*/
interface SyntaxTree extends Tree
{
/**
* Return an {@see Interval} indicating the index in the
* {@see TokenStream} of the first and last token associated with this
* subtree. If this node is a leaf, then the interval represents a single
* token and has interval i..i for token index i.
*
* An interval of i..i-1 indicates an empty interval at position
* i in the input stream, where 0 <= i <= the size of the input
* token stream. Currently, the code base can only have i=0..n-1 but
* in concept one could have an empty interval after EOF.
*
* If source interval is unknown, this returns {@see Interval::invalid()}.
*
* As a weird special case, the source interval for rules matched after
* EOF is unspecified.
*/
public function getSourceInterval(): Interval;
}
| true |
fa94dfc3740b4d4bf134d9479fd31c8cf741cf5e | PHP | OmarMohamed95/lacommerce | /app/Repositories/CustomFieldRepository.php | UTF-8 | 906 | 2.875 | 3 | [] | no_license | <?php
namespace App\Repositories;
use App\Model\CustomField;
use App\Repositories\Contracts\CustomFieldRepositoryInterface;
class CustomFieldRepository implements CustomFieldRepositoryInterface
{
/**
* Get all customFields
*
* @return Illuminate\Support\Collection
*/
public function all()
{
return CustomField::all();
}
/**
* Get single customField by id
*
* @param int $customFieldId
* @return CustomField
*/
public function find(int $customFieldId)
{
return CustomField::find($customFieldId);
}
/**
* Get customField by column
*
* @param string $column
* @param mixed $value
* @return Illuminate\Support\Collection
* @throws QueryException
*/
public function findBy(string $column, $value)
{
return CustomField::where($column, $value)->get();
}
} | true |
4ddf8ec3ae44fb168ec6a0ed3a2b14bab9cda7b0 | PHP | ChernyakovSI/project_vdele | /common/models/ProjectTeam.php | UTF-8 | 2,201 | 2.625 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace common\models;
use Yii;
/**
* This is the model class for table "project_team".
*
* @property int $id
* @property int $id_team
* @property int $id_project
* @property int $created_at
* @property int $updated_at
*/
class ProjectTeam extends \yii\db\ActiveRecord
{
public $team;
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'project_team';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['id_team', 'id_project', 'created_at', 'updated_at'], 'integer'],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'id_team' => 'Команда',
'id_project' => 'Проект',
'created_at' => 'Создан',
'updated_at' => 'Изменен',
'team' => 'Команда',
];
}
public static function deleteTeamFromProject($id_team, $id_project)
{
if ((isset($id_team)) && ($id_team > 0) && isset($id_project) && ($id_project > 0)) {
$query = ProjectTeam::find();
$model = $query->where(['project_team.id_project' => $id_project,
'project_team.id_team' => $id_team])->all();
foreach ($model as $key => $strTeam) {
$strTeam->delete();
}
return true;
}
}
public static function getTeamsForProject($id_project)
{
if ((isset($id_project)) && ($id_project > 0)) {
$columns_array = [
'team.id as id_team',
'team.name as team',
];
$query = Team::find()->select($columns_array)->leftJoin('project_team as project_team', 'team.id = project_team.id_team AND project_team.id_project = '.$id_project);
$model = $query->where('project_team.id_team IS NULL')->orderBy('team.name')->all();
$arrTeams = [];
foreach ($model as $key => $strTeam) {
$arrTeams[$strTeam['id_team']] = $strTeam['team'];
}
return $arrTeams;
}
}
}
| true |
9b3d3509c448689d73a059db2876347ff77683c6 | PHP | MohnDoe/quotrs | /model/class.artist.php | UTF-8 | 6,863 | 2.765625 | 3 | [] | no_license | <?php
require_once 'core.php';
Class Artist
{
public $id;
public $name;
public $description;
public $url_image;
public $urlFacebook;
public $urlTwitter;
public $urlSite;
public $urlOther;
public $url_rg;
public $delimiter_url_image = "?";
public $is_valid = false;
function __construct ($idArtist = NULL, $initParams = [])
{
foreach ($initParams as $nameParam => $value) {
$this->initParams[$nameParam] = $value;
}
if (!is_null ($idArtist)) {
$this->id = $idArtist;
/* INITIALISATION */
$this->init ();
if($idArtist == -1){
$this->name = "Artiste inconnu(e)";
$this->is_valid = false;
}
}
}
public function init ()
{
if ($data = $this->artist_exists ()) {
$this->is_valid = true;
$this->name = $data['nom_artist'];
$this->description = $data['description_artist'];
$this->url_image = $data['url_picture_artist'];
/*
if($data['url_picture_artist'] != "" && $data['url_picture_artist'] != null){
//une image existe dans la base de donnée
$url_image_array = explode($this->delimiter_url_image, $data['url_picture_artist']);
$url_image = $url_image_array[0];
$timestamp_last_check = $url_image_array[1];
if(time()+(24 * 60 * 60) > (int)$timestamp_last_check){
// si la derniere check est inférieur à 1 journée
$this->url_image = $url_image;
}else{
$this->url_image = $this->getURLPicture();
}
}else{
$this->url_image = $this->getURLPicture();
}
*/
$this->urlFacebook = $data['url_facebook_artist'];
$this->urlTwitter = $data['url_twitter_artist'];
$this->urlSite = $data['url_site_artist'];
$this->urlOther = $data['url_other_artist'];
}
}
public function artist_exists ()
{
$req = DB::$db->query ('SELECT * FROM ' . DB::$tableArtists . ' WHERE id_artist = ' . $this->id . ' LIMIT 1');
return $req->fetch ();
}
public function getQuotes(){
$req = DB::$db->query('SELECT * FROM ' . DB::$tableQuotes . ' WHERE id_artist = '.$this->id);
$result = [];
while($data = $req->fetch()){
$result[] = new Quote($data['id_quote'], ['isHashID'=>false, 'init_artist' => true]);
}
return $result;
}
public function getAlbums(){
$req = DB::$db->query('SELECT * FROM ' . DB::$tableAlbums . ' WHERE id_artist = '.$this->id);
$result = [];
while($data = $req->fetch()){
$result[] = new Album($data['id_album'], ['isHashID'=>false]);
}
return $result;
}
public function getNbQuotes(){
$req = DB::$db->query('SELECT COUNT(*) AS result FROM ' . DB::$tableQuotes . ' WHERE id_artist = '.$this->id);
$data = $req->fetch();
return $data['result'];
}
private function getURLPicture () {
$url_picture_result = null;
// INIT AWS S3 CLIENT
$_AWS_S3_CLIENT = Aws\S3\S3Client::factory (
[
'key' => AWS_ACCESS_KEY_ID,
'secret' => AWS_SECRET_ACCESS_KEY,
'region' => AWS_S3_REGION
]);
$key_artist_image = ARTISTES_IMAGES_FOLDER . '/' . $this->id . '/original_image.jpg';
if ($_AWS_S3_CLIENT->doesObjectExist (S3_BUCKET_NAME, $key_artist_image)) {
// artist image exists
$url_picture_result = WEBROOT . $key_artist_image;
}
if(!is_null($url_picture_result)){
$this->saveURLPicture($url_picture_result);
}
return $url_picture_result;
}
private function saveURLPicture ($url_picture_result) {
DB::$db->query ("UPDATE " . DB::$tableArtists . " SET `url_picture_artist`=\"" . $url_picture_result . $this->delimiter_url_image . time() . "\" WHERE id_artist = " . $this->id);
}
/**
* @return int
*/
public function addArtist ($comeFromRG = true) {
if($comeFromRG){
$req = "INSERT INTO ".DB::$tableArtists."
(id_artist, nom_artist, url_picture_artist, url_other_artist)
VALUES
(:id_artist, :nom_artist, :url_picture_artist, :url_other_artist)";
$query = DB::$db->prepare($req);
$query->bindParam(':nom_artist', $this->name);
$query->bindParam(':id_artist', $this->id);
$query->bindParam(':url_picture_artist', $this->url_image);
$query->bindParam(':url_other_artist', $this->url_rg);
$query->execute();
}else{
$this->name = htmlspecialchars($this->name);
$req = "INSERT INTO ".DB::$tableArtists."
(nom_artist)
VALUES
(:nom_artist)";
$query = DB::$db->prepare($req);
$query->bindParam(':nom_artist', $this->name);
$query->execute();
$id_new_artist = DB::$db->lastInsertId();
return (int)$id_new_artist;
}
}
static function searchArtists($search){
//TODO : secure that
$search = "%".$search."%";
$req = "SELECT *
FROM ".DB::$tableArtists."
WHERE `nom_artist` LIKE :query
LIMIT 0 , 7";
$query = DB::$db->prepare($req);
$query->bindParam(':query', $search, PDO::PARAM_STR);
$query->execute();
$result = [];
while($data = $query->fetch()){
$Artist = new Artist();
$Artist->id = $data['id_artist'];
$Artist->name = $data['nom_artist'];
$result[] = $Artist;
}
return $result;
}
public function toArray(){
$array = [];
$array['id'] = $this->id;
$array['name'] = $this->name;
return $array;
}
public function toJSON(){
return json_encode($this->toArray());
}
}
?>
| true |
60fbc7083ea9148c880bf2ebfba68ce44a2b5111 | PHP | cretz/meh | /src/Meh/Compiler/Context.php | UTF-8 | 4,021 | 3.03125 | 3 | [] | no_license | <?php
namespace Meh\Compiler;
use Meh\Lua\Ast\FunctionDeclaration;
use Meh\MehException;
class Context
{
use PhpHelper;
/** @var Builder */
public $bld;
/** @var mixed[] Stack (but reversed, a "FILO" of sorts) */
public $childContexts = [];
/** @var bool */
public $debugEnabled = false;
public function __construct()
{
$this->bld = new Builder();
}
/** @param string $string */
public function debug($string)
{
// TODO: make this smarter w/ more params and format
if ($this->debugEnabled) {
echo("DEBUG: " . $string . "\n");
}
}
/** @return ClassContext|null */
public function peekClass()
{
foreach ($this->childContexts as $context) {
if ($context instanceof ClassContext) return $context;
}
return null;
}
/** @return FunctionContext|null */
public function peekFunc()
{
foreach ($this->childContexts as $context) {
if ($context instanceof FunctionContext) return $context;
}
return null;
}
/** @return VariableContext|null */
public function peekGlobalVarCtx()
{
if (empty($this->childContexts)) return null;
return $this->childContexts[count($this->childContexts) - 1];
}
/**
* @param int $depth
* @return LoopContext|null
*/
public function peekLoop($depth = 1)
{
$currDepth = 0;
foreach ($this->childContexts as $context) {
if ($context instanceof LoopContext && ++$currDepth == $depth) return $context;
}
return null;
}
/** @return VariableContext|null */
public function peekVarCtx()
{
foreach ($this->childContexts as $context) {
if ($context instanceof VariableContext) return $context;
}
return null;
}
/** @return ClassContext */
public function popClass()
{
if (empty($this->childContexts) || !($this->childContexts[0] instanceof ClassContext)) {
throw new MehException('Class context not at top of stack');
}
return array_shift($this->childContexts);
}
/** @return FunctionContext */
public function popFunc()
{
if (empty($this->childContexts) || !($this->childContexts[0] instanceof FunctionContext)) {
throw new MehException('Function context not at top of stack');
}
return array_shift($this->childContexts);
}
/** @return LoopContext */
public function popLoop()
{
if (empty($this->childContexts) || !($this->childContexts[0] instanceof LoopContext)) {
throw new MehException('Loop context not at top of stack');
}
return array_shift($this->childContexts);
}
/** @return VariableContext */
public function popVarCtx()
{
if (empty($this->childContexts) || !($this->childContexts[0] instanceof VariableContext)) {
throw new MehException('Variable context not at top of stack');
}
return array_shift($this->childContexts);
}
/**
* @param \PHPParser_Node_Stmt_Class $node
* @return ClassContext
*/
public function pushClass(\PHPParser_Node_Stmt_Class $node)
{
$ctx = new ClassContext($node);
array_unshift($this->childContexts, $ctx);
return $ctx;
}
/**
* @param string $name
* @return FunctionContext
*/
public function pushFunc($name)
{
$ctx = new FunctionContext($name);
array_unshift($this->childContexts, $ctx);
return $ctx;
}
/** @return LoopContext */
public function pushLoop()
{
$ctx = new LoopContext();
array_unshift($this->childContexts, $ctx);
return $ctx;
}
/** @return VariableContext */
public function pushVarCtx()
{
$ctx = new VariableContext();
array_unshift($this->childContexts, $ctx);
return $ctx;
}
}
| true |
4b6f0f50c8251ebfde8c8aeb3a5bfbbe885c7819 | PHP | ruerp76/Exo2-php-Les-conditions | /index.php | UTF-8 | 1,457 | 4.0625 | 4 | [] | no_license | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Exo 2 - PHP - Les conditions</title>
</head>
<body>
<?php
// Exercice 1
$age=17;
if ($age>=18) {
echo "Vous êtes majeur";
}
else {
echo "Vous êtes mineur </br>";
}
// Exercice 2
$age=17;
$genre="femme";
if ($genre!="homme") {
echo"Vous êtes une femme";
}
else {
echo "Vous êtes un homme";
}
if ($age>=18) {
echo " et vous êtes majeur";
}
else {
echo " et vous êtes mineur </br>";
}
// Exercice 3
$maVariable='homme';
if ($maVariable !='homme') {
echo "C'est une développeuse";
}
else {
echo "C'est un développeur !! </br>";
}
// Exercice 4
$monAge=19;
if ($monAge>=18) {
echo "Tu es majeur </br>";
}
else {
echo "Tu n'es pas majeur </br>";
}
// Exercice 5
$maVariable=true;
if ($maVariable==false) {
echo "C'est pas bon !!! </br>";
}
else {
echo "C'est ok !! </br>";
}
// Exercice 6
$maVariable=false;
if ($maVariable==true) {
echo "C'est ok !!";
}
else {
echo "C'est pas bon !!!";
}
?>
</body>
</html>
| true |
26fd869b418109a7260645f1c6746657831c18c8 | PHP | AndrewSteyn/Online-store | /include/shop.php | UTF-8 | 4,983 | 2.84375 | 3 | [
"MIT"
] | permissive | <?php
session_start();
include_once 'connect.php';
include_once 'product.php';
//Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;}
$currentid = $_SESSION["id"];
?>
<?php
$currentid = $_SESSION["id"];
if (isset($_POST['cartname'])) {
$loggedInUser = $_SESSION["id"];
$cleanname = ($_POST['cartname']);
$cleanprice = ($_POST['cartprice']);
$cleanimage = ($_POST['cartimage']);
$sql = "INSERT INTO cart (user_id, product_name, product_price, product_image)
VALUES ('$loggedInUser','$cleanname','$cleanprice', '$cleanimage')";
//Execute query and validate success
if ($mysqli->query($sql)) {
//echo "<br><br><br><div class=\"confirmMessage\"><p>Item Added To Cart</p></div>";
unset($sql);
} else {
echo "<br><br><br><div class=\"confirmMessage\"> Error: <br>"."<br>" . $mysqli->error . "</div";
}
}
$www = "SELECT * FROM cart WHERE user_id = $currentid";
$cartNumber = mysqli_query($mysqli, $www);
$num_rows = mysqli_num_rows($cartNumber);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="vieport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="../css/styles.css">
<title>Products</title>
</head>
<body>
<!-- Nav Bar Starts -->
<nav class="navbar navbar-expand-lg navbar-light bg-light mx-auto fixed-top">
<a class="navbar-brand" href="index.php"><img src="../images/logo.jpg"width="40" height="40"> Di's Jewels</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#"> <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="about.php">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="shop.php">Products</a>
</li>
<li class="nav-item">
<a class="nav-link" href="gallery.php">Gallery</a>
</li>
<li class="nav-item">
<a class="nav-link" href="contact.php">Contact</a>
</li>
<li class="nav-item">
<a class="nav-link" href="shoppingCart.php">Shopping cart: <?php echo $num_rows ; ?> items </a>
</li>
</ul>
</div>
</nav>
<!-- Navbar ends -->
<!-- header of page starts -->
<div class="jumbotron jumbotron-fluid">
<div class="container text-dark">
<h1 class="display-4">Di van der Riet Jewellery</h1>
<p class="lead">These unique hand-mand pieces are crafted in the heart of the karoo, each with its own soal.</p>
</div>
</div>
<!-- end of heeder -->
<!-- products -->
<div class="items">
<?php
$sql = "SELECT * FROM products";
$results = mysqli_query($mysqli, $sql);
$row = mysqli_fetch_assoc($results);
if (mysqli_num_rows($results)>0){
while($row = mysqli_fetch_assoc($results)){
$products = new product($row["product_name"],$row["product_price"],$row["product_description"],$row["product_image"]);
$products->displayProduct();
}
}else{
echo "No products available";
}
?>
<!-- end products -->
<br>
<br>
<button class="btn" onclick="topFunction()" id="myBtn" title="Go to top">Back To Top</button>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://unpkg.com/vue"></script>
<script src="../scripts/store.js"></script>
<script src="../scripts/vueScripts.js"></script>
</body>
<footer id="footer">
<p>Created by: Andrew Steyn</p>
<p>Contact information: <a id="email" href="andrewpvdrsteyn@gmail.com"> andrewpvdrsteyn@gmail.com</a></p>
</footer>
</html> | true |
da6c2f14ecf23f837b8bdb6e52520f4c968b90e1 | PHP | kamdjouduplex/ERP | /app/PageNotes.php | UTF-8 | 726 | 2.5625 | 3 | [] | no_license | <?php
namespace App;
/**
* @SWG\Definition(type="object", @SWG\Xml(name="User"))
*/
use Illuminate\Database\Eloquent\Model;
class PageNotes extends Model
{
/**
* @var string
* @SWG\Property(property="url",type="strng")
* @SWG\Property(property="note",type="string")
* @SWG\Property(property="category_id",type="integer")
* @SWG\Property(property="user_id",type="integer")
*/
protected $fillable = [
'url', 'category_id', 'note', 'user_id',
];
public function user()
{
return $this->hasOne("\App\User","id", "user_id");
}
public function pageNotesCategories()
{
return $this->hasOne("\App\PageNotesCategories","id", "category_id");
}
}
| true |
0a0f9dbb9d27789da48836fc75fd935e945b5a1a | PHP | Foodtopia/foodtopia-php | /test01.php | UTF-8 | 310 | 3 | 3 | [] | no_license | <?php
define('MY_CONST', 123); // 常數定義
echo MY_CONST;
echo '<br>';
echo __DIR__;
echo '<br>';
echo __FILE__. '<br>';
echo __LINE__. '<br>';
echo PHP_VERSION. '<br>';
$a = 55;
$b = 'aaa';
$b1 = true;
$b2 = True;
$b3 = TRUE;
$b = false;
echo '----<br>';
echo false;
echo '----<br>';
echo true;
| true |
e41078299fd1bbd905755ea04938e750bfe795d4 | PHP | hytcdinghaoyu/blast_swoft | /app/Services/PayServiceInterface.php | UTF-8 | 500 | 2.734375 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
namespace App\Services;
use Swoft\Bean\Annotation\Bean;
/**
* @Bean(ref="rovio")
* Interface PayServiceInterface
* @package App\Services
*/
interface PayServiceInterface{
/**
* 获取余额
* @return mixed
*/
public function getBalance() : int;
/**
* 付钱
* @return mixed
*/
public function payMoney($amount) : bool;
/**
* 送钱
* @return mixed
*/
public function presentMoney($amount) : bool;
}
| true |
6d88682c1dc67136e5d0bfaef73447629c49fde8 | PHP | asdf0577/wufan | /module/Album/src/Album/Form/CSVUploadForm.php | UTF-8 | 930 | 2.71875 | 3 | [] | no_license | <?php
namespace Album\Form;
use Zend\Form\Form;
use Zend\Form\Element;
class CSVUploadForm extends Form
{
public function __construct($name = null)
{
parent::__construct('Upload');
$this->setAttribute('method', 'post');
$this->setAttribute('enctype', 'multipart/form-data');
$this->addElements();
}
public function addElements()
{
$CSVupload = new Element('CSVUpload');
$CSVupload->setLabel('CSV Upload');
$CSVupload->setAttributes(array(
'type'=>'file',
));
$CSVupload->setAttributes(array(
'multiple'=>true,
));
$this->add($CSVupload);
$submit = new Element('submit');
$submit->setAttributes(array(
'type' => 'submit',
'value' => '上传',
'id'=>'CSVsubmit',
));
$this->add($submit);
}
} | true |
882d863b32a016c60dacb34077a84b9a6569990d | PHP | liweist/siegelion | /src/Siegelion/System/Exception/ApplicationException.php | UTF-8 | 905 | 2.703125 | 3 | [
"MIT"
] | permissive | <?php
namespace Siegelion\System\Exception;
class ApplicationException extends \Exception
{
public static function appNotExist($sApp)
{
return new self('App "'.$sApp.'" does not exist.');
}
public static function actionNotExist($sAction)
{
return new self('Action "'.$sAction.'" does not exist.');
}
public static function actionRequired()
{
return new self('Action must be required.');
}
public static function viewPageNotExist($sView)
{
return new self('View Page "'.$sView.'" does not exist.');
}
public static function viewBaseNotExist($sViewBase)
{
return new self('View Base "'.$sViewBase.'" does not exist.');
}
public static function callbackNotExist($sObjectName, $sCallback)
{
return new self('Callback Function "'.$sObjectName.'::'.$sCallback.'" does not exist.');
}
} | true |
38bd831a887a94cabe1d9e3f203c2b65719ed495 | PHP | acassiovilasboas/system-from-school | /app/Repositories/Eloquent/AbstractRepository.php | UTF-8 | 1,782 | 2.890625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Repositories\Eloquent;
use Exception;
use Illuminate\Support\Facades\DB;
abstract class AbstractRepository
{
/**
* @var model
*/
protected $model;
/**
*
*/
public function __construct()
{
$this->model = $this->resolveModel();
}
public function getAll($orderBy = null)
{
try{
return $this->model
->orderBy($orderBy)
->paginate(10);
} catch (Exception $e) {
return $this->model
->paginate(10);
}
}
public function save($data)
{
try {
DB::beginTransaction();
$result = $this->model->create($data)->fresh();
DB::commit();
} catch (Exception $e) {
DB::rollBack();
throw new Exception('Erro inesperado ao salvar.');
}
return $result;
}
public function getById($id)
{
return $this->model->find($id);
}
public function update($data, $id)
{
try {
DB::beginTransaction();
$result = $this->model->where('id', $id)->update($data);
DB::commit();
} catch (Exception $e) {
DB::rollBack();
throw new Exception('Erro inesperado ao atualizar.');
}
return $result;
}
public function destroy($id)
{
try {
DB::beginTransaction();
$result = $this->model->destroy($id);
DB::commit();
} catch (Exception $e) {
DB::rollBack();
throw new Exception('Erro inesperado ao deletar.');
}
return $result;
}
protected function resolveModel()
{
return app($this->model);
}
} | true |
6ac872220ebd3de6349afc7e9372fa34e1e946a4 | PHP | designitgmbh/monkeyTables | /src/Factory/Factory.php | UTF-8 | 542 | 2.625 | 3 | [
"BSD-2-Clause"
] | permissive | <?php
namespace Designitgmbh\MonkeyTables\Factory;
class Factory
{
private static $modelNamespace = "App\\Models\\";
protected static function getFullClassName($shortClassName)
{
$className = self::$modelNamespace . $shortClassName;
if (!class_exists($className)) {
$className = $shortClassName;
}
return $className;
}
protected static function createInstance($className)
{
$className = self::getFullClassName($className);
return new $className;
}
}
| true |
d45fe9c375a7814213d80b861dc1aadec24e213d | PHP | PROGRAMADORFSABA/SOMVC | /App/Models/DAO/MarcaDAO.php | UTF-8 | 2,474 | 2.78125 | 3 | [] | no_license | <?php
namespace App\Models\DAO;
use App\Models\Entidades\Marca;
class MarcaDAO extends BaseDAO
{
public function listar($codMarca = null)
{
if ($codMarca) {
$resultado = $this->select(
"SELECT * FROM marca WHERE marcacod = $codMarca "
);
$dado = $resultado->fetch();
if ($dado) {
$marca = new Marca();
$marca->setMarcaCod($dado['marcacod']);
$marca->setMarcaNome($dado['marcanome']);
return $marca;
}
} else {
$resultado = $this->select(
"SELECT * FROM marca ORDER BY marcanome "
);
$dados = $resultado->fetchAll();
if ($dados) {
$lista = [];
foreach ($dados as $dado) {
$marca = new Marca();
$marca->setMarcaCod($dado['marcacod']);
$marca->setMarcaNome($dado['marcanome']);
$lista[] = $marca;
}
return $lista;
}
}
return false;
}
public function salvar(Marca $marca)
{
try {
$marcaNome =$marca->getMarcaNome();
return $this->insert(
'marca',
":marcanome ",
[
':marcanome' => $marcaNome
]
);
} catch (\Exception $e) {
throw new \Exception("Erro na gravação de dados. ".$e, 500);
}
}
public function atualizar(Marca $marca){
try {
$marcaCod =$marca->getMarcaCod();
$marcaNome =$marca->getMarcaNome();
return $this->update(
'marca',
"marcanome = :marcaNome",
[
':marcaCod' => $marcaCod,
':marcaNome' => $marcaNome,
],
"marcacod = :marcaCod"
);
} catch (\Exception $e) {
throw new \Exception("Erro na gravação de dados. ".$e, 500);
}
}
public function excluir(Marca $marca)
{
try {
$marcaCod =$marca->getMarcaCod();
return $this->delete('marca', "marcacod = $marcaCod");
} catch (Exception $e) {
throw new \Exception("Erro ao deletar. ".$e, 500);
}
}
}
| true |
a77f0782b7a9231694122be03ac17a228e4d719c | PHP | viashop/admin_cake | /app_application/src/AppVialoja/Model/ClienteConvite.php | UTF-8 | 4,430 | 2.734375 | 3 | [] | no_license | <?php
/**
* @copyright Vialoja (http://vialoja.com.br)
* @author William Duarte <williamduarteoficial@gmail.com>
* @version 1.0.1
* Date: 21/10/16 às 23:22
*/
use AppVialoja\Interfaces\Model\IClienteConvite;
class ClienteConvite extends AppModel implements IClienteConvite
{
public $name = 'ClienteConvite';
public $useDbConfig = 'default';
public $useTable = 'cliente_convite';
use \AppVialoja\Traits\Entity\TClienteConvite;
/**
* Listar Usuário(s)
* @param Shop $shop
* @return array|null
*/
public function listar(Shop $shop) {
try {
if (!is_int($shop->getIdShop())) {
throw new \LogicException(ERROR_LOGIC_VAR . 'getIdShop int');
}
$conditions = array(
'fields' => array(
'ClienteConvite.email',
'ClienteConvite.token',
'ClienteConvite.status'
),
'conditions' => array(
'ClienteConvite.id_shop_default' => $shop->getIdShop()
)
);
return $this->find('all', $conditions);
} catch (\PDOException $e) {
\Exception\VialojaDatabaseException::errorHandler($e);
} catch (\LogicException $e) {
\Exception\VialojaInvalidLogicException::errorHandler($e);
}
}
/**
* Deleta as os convites se existir
* @param ClienteConvite $convite
*/
public function deletar(ClienteConvite $convite) {
try {
if (!is_string($convite->getToken())) {
throw new \LogicException(ERROR_LOGIC_VAR . 'token string');
}
$conditions = array(
'ClienteConvite.token' => $convite->getToken()
);
if (!$this->deleteAll($conditions)) {
throw new \RuntimeException();
}
} catch (\PDOException $e) {
\Exception\VialojaDatabaseException::errorHandler($e);
} catch (\LogicException $e) {
\Exception\VialojaInvalidLogicException::errorHandler($e);
}
}
/**
* Recusar convite
* @param ClienteConvite $convite
*/
public function recusar(ClienteConvite $convite) {
try {
if (!is_string($convite->getToken())) {
throw new \LogicException(ERROR_LOGIC_VAR . 'token string');
}
/** Update com recusado **/
$fields = array(
'ClienteConvite.status' => 1
);
$conditions = array(
'ClienteConvite.status' => 0,
'ClienteConvite.token' => $convite->getToken()
);
if (!$this->updateAll($fields, $conditions)) {
throw new \RuntimeException();
}
} catch (\PDOException $e) {
\Exception\VialojaDatabaseException::errorHandler($e);
} catch (\LogicException $e) {
\Exception\VialojaInvalidLogicException::errorHandler($e);
}
}
/**
* Verifica se existe Convite
* @param ClienteConvite $convite
* @return bool
*/
public function existsConvite(ClienteConvite $convite) {
try {
if (!is_string($convite->getToken())) {
throw new \LogicException(ERROR_LOGIC_VAR . 'token string');
}
$conditions = array(
'conditions' => array(
'ClienteConvite.status' => 0,
'ClienteConvite.token' => $convite->getToken()
)
);
if ($this->find('count', $conditions) <= 0)
return false;
return true;
} catch (\PDOException $e) {
\Exception\VialojaDatabaseException::errorHandler($e);
} catch (\LogicException $e) {
\Exception\VialojaInvalidLogicException::errorHandler($e);
}
}
/**
* Verifica se tem convite
* @param ClienteConvite $convite
* @return array|null
*/
public function conviteDados(ClienteConvite $convite) {
try {
if (!is_string($convite->getToken())) {
throw new \LogicException(ERROR_LOGIC_VAR . 'token string');
}
$conditions = array(
'fields' => array(
'ClienteConvite.id',
'ClienteConvite.id_shop_default',
'ClienteConvite.email'
),
'conditions' => array(
'ClienteConvite.status' => 0,
'ClienteConvite.token' => $convite->getToken()
)
);
return $this->find('first', $conditions);
} catch (\PDOException $e) {
\Exception\VialojaDatabaseException::errorHandler($e);
} catch (\LogicException $e) {
\Exception\VialojaInvalidLogicException::errorHandler($e);
}
}
/**
* Deletar Convite
* @param int $id
*/
public function deletarId($id)
{
try {
$this->id = intval($id);
if ($this->exists()) {
$this->delete();
}
} catch (\PDOException $e) {
\Exception\VialojaDatabaseException::errorHandler($e);
} catch (\LogicException $e) {
\Exception\VialojaInvalidLogicException::errorHandler($e);
}
}
}
| true |
a635325a0b9599a038507124785de64510d59585 | PHP | vietpn/coccoc_blog | /models/UserModel.php | UTF-8 | 772 | 2.96875 | 3 | [] | no_license | <?php
class UserModel extends DbModel
{
public $id;
public $username;
public $password;
public $date_created;
public function __construct()
{
parent::__construct();
}
/**
* @inheritdoc
*/
public static function tableName()
{
return 'user';
}
/**
* Get user by username and password
* @return array
*/
public function getByUsernamePass()
{
$sth = $this->db->prepare("SELECT id FROM " . static::tableName() . " WHERE
username = :username AND password = MD5(:password)");
$sth->execute(array(
':username' => $this->username,
':password' => $this->password
));
$data = $sth->fetch();
return $data;
}
} | true |
c8629a3aa82160619df9478700bb2c850627ce92 | PHP | eddymio/rhm-accounting | /module/MyJournal/src/Service/Factory/JournalManagerFactory.php | UTF-8 | 739 | 2.6875 | 3 | [] | no_license | <?php
namespace MyJournal\Service\Factory;
use Interop\Container\ContainerInterface;
use MyJournal\Service\JournalManager;
/**
* This is the factory class for JournalManager service. The purpose of the factory
* is to instantiate the service and pass it dependencies (inject dependencies).
*/
class JournalManagerFactory
{
/**
* This method creates the JournalManager service and returns its instance.
*/
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$connectionManager = $container->get('doctrine.connection.orm_exercice');
$entityManager = $container->get('doctrine.entitymanager.orm_exercice');
return new JournalManager($entityManager,$connectionManager);
}
} | true |
3b5c1482d9c52791495ed5b5f0a7c52aa1d37f74 | PHP | CarmaSys/CarmaLinkSDK | /PHP/lib/ReportConfig.php | UTF-8 | 10,124 | 2.6875 | 3 | [] | no_license | <?php
namespace CarmaLink;
/**
* Represents a CarmaLink configuration.
*
* @class ReportConfig
*/
class ReportConfig {
const API_THRESHOLD = "threshold";
const API_ALLOWANCE = "allowance";
const API_LOCATION = "location";
const API_BUZZER = "buzzer";
const API_DELETE_CONFIG = "OFF";
const API_PARAMS = "optionalParams";
const API_CONDITIONS = "optionalConditions";
const SPEEDING = "SPEEDING";
const ODOMETER = "ODOMETER";
const DURATION_TO_SERVICE = "DURATION_TO_SERVICE";
const DISTANCE_TO_SERVICE = "DISTANCE_TO_SERVICE";
const BATTERY_VOLTAGE = "BATTERY_VOLTAGE";
const BATTERY_VOLTAGE_LOW = "IS_LOW_BATTERY_VOLTAGE";
const EMISSION_MONITORS = "EMISSION_MONITORS";
const FUEL_LEVEL = "FUEL_LEVEL";
const TIRE_PRESSURE_LOW = "IS_LOW_TIRE_PRESSURE";
const FUEL_RATE = "FUEL_RATE";
/**
* @access public
* @var int
*/
public $id = 0;
/**
* @access public
* @var int|float
*/
public $threshold = 0;
/**
* @access public
* @var int|float
*/
public $allowance = 0.0;
/**
* @access public
* @var bool
*/
public $location = false;
/**
* @access public
* @var string
*/
public $buzzer = NULL;
/**
* @access public
* @var array
*/
public $params = null;
/**
* @access public
* @var array
*/
public $conditions = null;
/**
* @access public
* @var ConfigStatus
*/
public $state = ConfigStatus::UNKNOWN_STATUS;
/**
* @access protected
* @var ConfigType
*/
protected $_config_type;
/**
* @access private
* @var string
*/
private $__api_version;
/**
* Constructor
*
* @param int|float threshold
* @param int|float allowance
* @param bool location
* @param bool location
* @param array optional params
* @param array optional condition
* @param CarmaLink\ConfigStatus status
* @return void
*/
public function __construct($id = 0, $threshold = NULL, $allowance = NULL, $location = NULL, $params = NULL, $conditions = NULL, $state = NULL, $config_type = NULL) {
$this->__api_version = CarmaLinkAPI::API_VERSION;
$this->id = $id;
$this->threshold = $threshold;
$this->allowance = $allowance;
$this->location = $location;
$this->params = $params;
$this->conditions = $conditions;
if ($state) { $this->state = $state; }
}
/**
* Sets the protected member variable if valid.
*
* @param string|ConfigType config_type
* @return bool
*/
public function setReportConfigType($config_type) {
if ($config_type === $this->_config_type || !ConfigType::isValidReportConfigType($config_type)) { return false; }
$this->_config_type = $config_type;
return true;
}
/**
* Converts object to associative array.
*
* @return array
*/
public function toArray() {
$a = Array();
// The reasoning behind all of the null checks:
// If an object is null when sent, it should not, by default, consider that a 0. It should consider it as
// NULL, and a thing to be ignored. This allows a person to do simple updates to a threshold via simple
// requests, such as JUST updating the buzzer, or threshold.
if ($this->threshold !== NULL) { $a[self::API_THRESHOLD] = (float) $this->threshold; }
if ($this->allowance !== NULL) { $a[self::API_ALLOWANCE] = (float) $this->allowance; }
if ($this->params !== NULL) { $a[self::API_PARAMS] = (!empty($this->params) ? $this->params : null); }
if ($this->location !== NULL) { $a[self::API_LOCATION] = (bool)$this->location; }
if ($this->conditions !== NULL) { $a[self::API_CONDITIONS] = $this->conditions; }
if ($this->buzzer !== NULL) { $a[self::API_BUZZER] = (string)$this->buzzer; }
return $a;
}
/**
* Utility to setup a config's optional parameters based on a device
* @param CarmaLink device Custom data object representing CarmaLink
* @param Config config Config object to setup
* @return array|NULL
*/
protected static function setupConfigParams($parameters) {
if (!$parameters) { return NULL; }
$a = array();
//all functions are set.
if ($parameters->odometer) { $a[] = self::ODOMETER; }
if ($parameters->distanceToService) { $a[] = self::DISTANCE_TO_SERVICE; }
if ($parameters->durationToService) { $a[] = self::DURATION_TO_SERVICE; }
if ($parameters->batteryVoltage) { $a[] = self::BATTERY_VOLTAGE; $a[] = self::BATTERY_VOLTAGE_LOW; }
if ($parameters->tirePressure) { $a[] = self::TIRE_PRESSURE_LOW; }
if ($parameters->emissionMonitors) { $a[] = self::EMISSION_MONITORS; }
if ($parameters->fuelLevel) { $a[] = self::FUEL_LEVEL; }
if ($parameters->fuelRate) { $a[] = self::FUEL_RATE; }
return $a;
}
/**
* Utility to setup a config's optional conditions based on booleans sent in from a device.
* @param bool useBatteryVoltage is low battery voltage condition set?
* @param bool useTirePressure is low tire pressure condition set?
* @param bool useEmissionMonitors is emission Monitors condition set?
* @return array|NULL
*/
protected static function setupConfigConds($conditions) {
if(!$conditions) { return NULL; }
$a = array();
//all functions are set.
if ($conditions->batteryVoltage) { $a[] = self::BATTERY_VOLTAGE_LOW; }
if ($conditions->tirePressure) { $a[] = self::TIRE_PRESSURE_LOW; }
if ($conditions->emissionMonitors) { $a[] = self::EMISSION_MONITORS; }
return $a;
}
/**
* Utility method to create a new Config instance based on a device and report type. assets don't have any of these configurations, so nothing happens there.
*
* @param CarmaLink device A custom data object representing a CarmaLink
* @param string|ConfigType config_type
* @return Config|bool return new config object, or false to delete configuration
*/
private static function createConfigFromDevice(CarmaLink $device, $config_type) {
$config = new ReportConfig();
if (!$config->setReportConfigType($config_type)) {
throw new CarmaLinkAPIException("Invalid configuration type : " . $config_type);
}
$config->location = (bool) $device->getUseGps();
switch ($config->_config_type) {
case ConfigType::CONFIG_DIGITAL_INPUT_0:
case ConfigType::CONFIG_DIGITAL_INPUT_1:
case ConfigType::CONFIG_DIGITAL_INPUT_2:
case ConfigType::CONFIG_DIGITAL_INPUT_3:
case ConfigType::CONFIG_DIGITAL_INPUT_4:
case ConfigType::CONFIG_DIGITAL_INPUT_5:
case ConfigType::CONFIG_DIGITAL_INPUT_6:
case ConfigType::CONFIG_DRIVER_LOG:
case ConfigType::CONFIG_GREEN_BAND:
/* These are not supported yet*/
return NULL;
break;
case ConfigType::CONFIG_HARD_ACCEL:
case ConfigType::CONFIG_HARD_BRAKING:
case ConfigType::CONFIG_HARD_CORNERING:
case ConfigType::CONFIG_STATUS:
case ConfigType::CONFIG_IDLING:
case ConfigType::CONFIG_OVERSPEEDING:
case ConfigType::CONFIG_ENGINE_OVERSPEED:
case ConfigType::CONFIG_PARKING_BRAKE:
case ConfigType::CONFIG_PARKING:
case ConfigType::CONFIG_SEATBELT:
case ConfigType::CONFIG_TRANSPORTED:
case ConfigType::CONFIG_TRIP_REPORT:
case ConfigType::CONFIG_HEALTH:
$deviceConfig = $device->getConfig($config_type);
if($deviceConfig === NULL) { return NULL; }
if ($deviceConfig->reportEnabled === FALSE) { return FALSE; }
if($deviceConfig->config_type === ConfigType::CONFIG_STATUS) {
if ((int)$deviceConfig->threshold < ConfigType::CONFIG_STATUS_MINIMUM_PING) { return FALSE; }
} else if($deviceConfig->config_type === ConfigType::CONFIG_IDLING) {
if ((int)$deviceConfig->allowance < ConfigType::CONFIG_IDLING_MINIMUM_ALLOWANCE) { return FALSE; }
}
$config->threshold = $deviceConfig->threshold;
$config->allowance = $deviceConfig->allowance;
$config->buzzer = $deviceConfig->buzzer_volume;
$config->params = self::setupConfigParams($deviceConfig->optionalParameters);
$config->conditions = self::setupConfigConds($deviceConfig->optionalConditions);
break;
}
return $config;
}
/**
* Shortcut method which retreives a configuration object and converts to an array.
*
* @uses ReportConfig::createConfigFromDevice()
* @uses ReportConfig::toArray()
*
* @param CarmaLink device Representation of CarmaLink
* @param string|ConfigType config_type
* @return array|bool|null returns array of config parameters or false if it should be deleted, and null if the device does not support that config type.
*/
public static function getConfigArray(CarmaLink $device, $config_type) {
$newConfig = self::createConfigFromDevice($device, $config_type);
return ($newConfig !== FALSE && $newConfig !== NULL) ? $newConfig->toArray() : $newConfig;
}
/**
* Static factory
*
* @param string|stdClass obj Either a JSON string or a stdClass object representing a Config
* @param ConfigType config_type A valid ConfigType
* @return ReportConfig
*/
public static function Factory($obj, $config_type) {
if (!$obj) { return FALSE; }
if (!is_object($obj) && is_string($obj)) {
try { $obj = json_decode($obj); }
catch(Exception $e) { throw new CarmaLinkAPIException("Could not instantiate ReportConfig with provided JSON data ".$e->getMessage()); }
}
// set any missing fields to NULL
foreach (array("configId","threshold","allowance","location","buzzer","optionalParams","optionalConditions","status") as $prop) {
$obj->$prop = isset($obj->$prop) ? $obj->$prop : NULL;
}
$config = new ReportConfig(
(int)$obj->configId,
(float)$obj->threshold,
(float)$obj->allowance,
(bool)$obj->location,
$obj->optionalParams,
$obj->optionalConditions,
$obj->status
);
if($obj->buzzer) {
$config->buzzer = $obj->buzzer; }
$config->setReportConfigType($config_type);
return $config;
}
}
| true |
dabc364d99115d16f230e4a1e9873ece5b4f2e1e | PHP | superhero2007/slim_cms | /slim_cms_frontend/system/cron/followup.job.php | UTF-8 | 11,775 | 2.84375 | 3 | [] | no_license | <?php
/*
This code is executed every 10 minutes of every day as a CRON job
There are 6 options for the cron jobs:
1) Email - This emails a teplated email to the client
2) Call - Emails a notice to the account owner (if there is no account owner it emails to info@greenbizcheck.com)
3) Head Office - Emails a notice to info@greenbizcheck.com
4) Delete - Deletes any results from the crm followup table allowing a reschedule
5) Issue Assessment + email client - Automaticaly issues a new assessment to a client along with a notification email
6) Function - Takes the sql query result and the function arguments to start a process
*/
$followup = new followup($db);
class followup {
private $db;
private $clientEmail;
private $clientChecklist;
public function __construct($db) {
$this->db = $db;
$this->clientEmail = new clientEmail($this->db);
$this->clientChecklist = new clientChecklist($this->db);
$this->processFollowups();
}
private function processFollowups() {
if($result = $this->db->query(sprintf('
SELECT
`followup_trigger_id`,
`name`,
`sql`,
`action`,
`email_stationary`,
`email_subject`,
`function_arguments`
FROM `%1$s`.`followup_trigger`
ORDER BY `followup_trigger_id` ASC;
',
DB_PREFIX.'crm'
))) {
while($row = $result->fetch_object()) {
switch($row->action) {
case 'email': {
$this->emailFollowup($row->followup_trigger_id,$row->sql,$row->email_stationary,$row->email_subject);
break;
}
case 'call': {
$this->phoneFollowup($row->followup_trigger_id,$row->sql,$row->name);
break;
}
case 'head office': {
$this->headOfficeFollowup($row->followup_trigger_id,$row->sql,$row->name);
break;
}
case 'head office + associate': {
$this->associateAndHeadOfficeFollowup($row->followup_trigger_id,$row->sql,$row->name);
break;
}
case 'delete': {
//Deletes any results from the crm followup table allowing a reschedule
break;
}
case 'issue assessment + email client': {
$this->issueAssessmentAndSendEmail($row->followup_trigger_id,$row->sql,$row->email_stationary,$row->email_subject);
break;
}
//Takes the results of the sql query along with the function arguments from the trigger and fires a function
case 'function': {
$this->processFunction($row->followup_trigger_id, $row->sql, $row);
break;
}
}
}
$result->close();
}
return;
}
//Processes the arguments passed in the trigger
public function processFunction($followup_trigger_id, $sql, $data) {
if($result = $this->db->query($sql)) {
while($row = $result->fetch_object()) {
if(isset($row->client_id) && !$this->hasBeenTriggered($followup_trigger_id, $row->client_id, $row->identifier)) {
//Takes the argument and attempts to run it
eval($data->function_arguments);
//set the admin-crm to mark the job as complete
$this->reportFollowup($row->client_id,$followup_trigger_id, $row->identifier);
}
}
}
return;
}
//Auto issues a new assessment
public function issueAssessmentAndSendEmail($followup_trigger_id,$sql,$email_stationary,$email_subject) {
if($result = $this->db->query($sql)) {
while($row = $result->fetch_object()) {
if(isset($row->client_id) && !$this->hasBeenTriggered($followup_trigger_id, $row->client_id, $row->client_checklist_id)) {
//Issue the new assessment
$row->issued_client_checklist_id = $this->clientChecklist->autoIssueChecklist($row->checklist_id, $row->client_id);
//Send the email to the client
$this->clientEmail->send(
$row->client_id,
$email_subject,
$email_stationary,
$row,
null,
null,
true
);
//set the admin-crm to mark the job as complete
$this->reportFollowup($row->client_id,$followup_trigger_id, $row->client_checklist_id);
}
}
$result->close();
}
return;
}
//Finds all of the email jobs that are to be completed, processes them and then adds them to the ADMIN-CRM to mark as completed.
private function emailFollowup($followup_trigger_id,$sql,$email_stationary,$email_subject) {
$processed_followups = $this->getProcessedFollowups($followup_trigger_id);
if($result = $this->db->query($sql)) {
while($row = $result->fetch_object()) {
if(isset($row->client_id) && !in_array($row->client_id,$processed_followups)) {
//Check to see if auto emails are checked for the client
if($this->clientEmail->allowAutoEmail($row->client_id) == true) {
$this->clientEmail->send(
$row->client_id,
$email_subject,
$email_stationary,
$row,
null,
null,
true
);
}
//Report the triggered email to the database so that it is only sent once even if auto emails are disabled
$this->reportFollowup($row->client_id,$followup_trigger_id);
}
}
$result->close();
}
return;
}
//This function will send a notice email to the associate assigned to the client, and if not associate exists an email is sent to info@greenbizcheck.com
private function phoneFollowup($followup_trigger_id,$sql,$name) {
$processed_followups = $this->getProcessedFollowups($followup_trigger_id);
$from = 'GreenBizCheck <webmaster@greenbizcheck.com>';
$returnPath = '-fwebmaster@greenbizcheck.com';
$company = 'GreenBizCheck';
$emailHeaders =
"From: $from\r\n".
"Reply-To: $from\r\n".
"Return-Path: $from\r\n".
"Organization: $company\r\n".
"X-Priority: 3\r\n".
"X-Mailer: PHP". phpversion() ."\r\n".
"MIME-Version: 1.0\r\n".
"Content-type: text/html; charset=UTF-8\r\n";
if($result = $this->db->query($sql)) {
while($row = $result->fetch_object()) {
if(isset($row->client_id) && !in_array($row->client_id,$processed_followups)) {
//Checks to see if the associate_email value is set (it is an email address) and if so BCC's the associate
if(isset($row->associate_email)) {
$recipientEmail = $row->associate_email;
}
else
{
$recipientEmail = "info@greenbizcheck.com";
}
$emailBody =
'<html>'.
'<body>'.
'<h1>Automatic Followup Notification</h1>'.
'<h2>'.$name.'</h2>'.
'<p><a href="http://www.greenbizcheck.com/admin2010/index.php?page=clients&mode=client_edit&client_id='.$row->client_id.'">Click here to access the user/client details</a>.</p>'.
'<p>The following details have been provided:</p>'.
'<dl>';
foreach($row as $key => $val) {
$emailBody .=
'<dt><strong>'.$key.'</strong></dt>'.
'<dd>'.$val.'</dd>';
}
$emailBody .=
'</dl>'.
'</body>'.
'</html>';
mail($recipientEmail,'Automatic Followup Notification',$emailBody,$emailHeaders,'-fwebmaster@greenbizcheck.com');
$this->reportFollowup($row->client_id,$followup_trigger_id);
}
}
$result->close();
}
return;
}
//Function sends email to Head Office and CC's Associate
private function associateAndHeadOfficeFollowup($followup_trigger_id,$sql,$name) {
$processed_followups = $this->getProcessedFollowups($followup_trigger_id);
$from = 'GreenBizCheck <webmaster@greenbizcheck.com>';
$returnPath = '-fwebmaster@greenbizcheck.com';
$company = 'GreenBizCheck';
$emailHeaders =
"From: $from\r\n".
"Reply-To: $from\r\n".
"Return-Path: $from\r\n".
"Organization: $company\r\n".
"X-Priority: 3\r\n".
"X-Mailer: PHP". phpversion() ."\r\n".
"MIME-Version: 1.0\r\n".
"Content-type: text/html; charset=UTF-8\r\n";
if($result = $this->db->query($sql)) {
while($row = $result->fetch_object()) {
if(isset($row->client_id) && !in_array($row->client_id,$processed_followups)) {
//Checks to see if the associate_email value is set (it is an email address) and if so CC's the associate
if(isset($row->associate_email)) {
$emailHeaders .= "CC:" . $row->associate_email . "\r\n";
}
$emailBody =
'<html>'.
'<body>'.
'<h1>Automatic Followup Notification</h1>'.
'<h2>'.$name.'</h2>'.
'<p><a href="http://www.greenbizcheck.com/admin2010/index.php?page=clients&mode=client_edit&client_id='.$row->client_id.'">Click here to access the user/client details</a>.</p>'.
'<p>The following details have been provided:</p>'.
'<dl>';
foreach($row as $key => $val) {
$emailBody .=
'<dt><strong>'.$key.'</strong></dt>'.
'<dd>'.$val.'</dd>';
}
$emailBody .=
'</dl>'.
'</body>'.
'</html>';
mail('info@greenbizcheck.com','Automatic Followup Notification',$emailBody,$emailHeaders,'-fwebmaster@greenbizcheck.com');
$this->reportFollowup($row->client_id,$followup_trigger_id);
}
}
$result->close();
}
return;
}
//Function to send notice email to info@grenbizcheck.com (Head Office) and not to the associate
private function headOfficeFollowup($followup_trigger_id,$sql,$name) {
$processed_followups = $this->getProcessedFollowups($followup_trigger_id);
$from = 'GreenBizCheck <webmaster@greenbizcheck.com>';
$returnPath = '-fwebmaster@greenbizcheck.com';
$company = 'GreenBizCheck';
$emailHeaders =
"From: $from\r\n".
"Reply-To: $from\r\n".
"Return-Path: $from\r\n".
"Organization: $company\r\n".
"X-Priority: 3\r\n".
"X-Mailer: PHP". phpversion() ."\r\n".
"MIME-Version: 1.0\r\n".
"Content-type: text/html; charset=UTF-8\r\n";
if($result = $this->db->query($sql)) {
while($row = $result->fetch_object()) {
if(isset($row->client_id) && !in_array($row->client_id,$processed_followups)) {
$emailBody =
'<html>'.
'<body>'.
'<h1>Automatic Followup Notification</h1>'.
'<h2>'.$name.'</h2>'.
'<p><a href="http://www.greenbizcheck.com/admin2010/index.php?page=clients&mode=client_edit&client_id='.$row->client_id.'">Click here to access the user/client details</a>.</p>'.
'<p>The following details have been provided:</p>'.
'<dl>';
foreach($row as $key => $val) {
$emailBody .=
'<dt><strong>'.$key.'</strong></dt>'.
'<dd>'.$val.'</dd>';
}
$emailBody .=
'</dl>'.
'</body>'.
'</html>';
mail('info@greenbizcheck.com','Automatic Followup Notification',$emailBody,$emailHeaders,'-fwebmaster@greenbizcheck.com');
$this->reportFollowup($row->client_id,$followup_trigger_id);
}
}
$result->close();
}
return;
}
private function reportFollowup($client_id,$followup_trigger_id, $identifier=null) {
$this->db->query(sprintf('
INSERT INTO `%1$s`.`followup` SET
`client_id` = %2$d,
`followup_trigger_id` = %3$d,
`identifier` = %4$d
',
DB_PREFIX.'crm',
$client_id,
$followup_trigger_id,
$identifier
));
return;
}
//Gets the processed followups
private function getProcessedFollowups($followup_trigger_id) {
$processed_followups = array();
if($result = $this->db->query(sprintf('
SELECT
`client_id`
FROM `%1$s`.`followup`
WHERE `followup_trigger_id` = %2$d;
',
DB_PREFIX.'crm',
$followup_trigger_id
))) {
while($row = $result->fetch_object()) {
$processed_followups[] = $row->client_id;
}
$result->close();
}
return($processed_followups);
}
//returns a bool (true or false) if the client has already had this trigger for the identifier
//Basically a trigger can only run once on the given identifier - that could be a checklistId, invoiceId etc.
private function hasBeenTriggered($followup_trigger_id, $client_id, $identifier) {
$isSent = false;
if($result = $this->db->query(sprintf('
SELECT
`client_id`
FROM `%1$s`.`followup`
WHERE `followup_trigger_id` = %2$d
AND `client_id` = %3$d
AND `identifier` = %4$d;
',
DB_PREFIX.'crm',
$followup_trigger_id,
$client_id,
$identifier
))) {
while($row = $result->fetch_object()) {
$isSent = true;
}
$result->close();
}
return($isSent);
}
}
?> | true |
f3a05484bb7983218f7f4231998d89c055af0bc5 | PHP | xionghuimin/Cybersecurity-learning-materials | /代码审计/php代码审计/PHP代码审计分段讲解(很基础详细)/11 sql闭合绕过.php | UTF-8 | 769 | 2.796875 | 3 | [] | no_license | <?php
if($_POST[user] && $_POST[pass]) {
$conn = mysql_connect("*******", "****", "****");
mysql_select_db("****") or die("Could not select database");
if ($conn->connect_error) {
die("Connection failed: " . mysql_error($conn));
}
$user = $_POST[user];
$pass = md5($_POST[pass]);
//select user from php where (user='admin')#
//exp:admin')#
$sql = "select user from php where (user='$user') and (pw='$pass')";
$query = mysql_query($sql);
if (!$query) {
printf("Error: %s\n", mysql_error($conn));
exit();
}
$row = mysql_fetch_array($query, MYSQL_ASSOC);
//echo $row["pw"];
if($row['user']=="admin") {
echo "<p>Logged in! Key: *********** </p>";
}
if($row['user'] != "admin") {
echo("<p>You are not admin!</p>");
}
}
?>
| true |
42dc611eb0b7cd492660ae5ec5224bb009ae87ce | PHP | AleioD/EjercicioSQL0627 | /series.php | UTF-8 | 572 | 3.109375 | 3 | [] | no_license | <?php
require_once "conection.php";
$stmt = $db->prepare("SELECT title, id FROM series");
$stmt->execute();
$series = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Series</title>
</head>
<body>
<div class="">
<h2>Listado de Series</h2>
<ul>
<?php foreach ($series as $oneSerie): ?>
<li><a href="serie.php?id=<?=$oneSerie["id"]?>"><?=$oneSerie["title"] ?></a><br></li>
<?php endforeach; ?>
</ul>
</div>
</body>
</html>
| true |
f9dbe243552d088f8f4d4fc48928bc9aec589106 | PHP | betopinheiro1005/curso-php-85bits | /aula-19/aula-19b.php | UTF-8 | 560 | 3.140625 | 3 | [
"MIT"
] | permissive | <?php
$dll = new \SplDoublyLinkedList();
$dll->push("laranja");
$dll->push("banana");
$dll->push("limão");
$dll->push("maçã");
$dll->push("uva");
$dll->push("abacaxi");
echo "Cabeça: ". $dll->bottom(). "<br/>";
echo "Cauda: ". $dll->top(). "<br/>";
$prev = null;
$dll->rewind(); //rebobinando
while ($dll->valid()) {
$current = $dll->current();
echo 'Anterior: '.$prev, "<br/>";
echo 'Atual: '.$current, "<br/>";
$prev = $current;
$dll->next();
$next = $dll->current();
echo 'Próximo: '.$next. "<br/>";
echo "<br/>";
} | true |
e63fcdb4c2b982e671914101613b672f8d342d6c | PHP | asasouza/dalloglio-mvc-framework | /app.widgets/Element.class.php | UTF-8 | 1,188 | 3.453125 | 3 | [] | no_license | <?php
class Element{
private $name;
private $class;
private $properties;
protected $children;
public function __construct($name, $class = NULL){
$this->name = $name;
$this->class = $class;
}
public function __set($name, $value){
$this->properties[$name] = $value;
}
public function setClass($class){
$this->class = $class;
}
public function addClass($class){
$this->class = is_null($this->class) ? $class : $this->class . " " . $class;
}
public function add($child){
$this->children[] = $child;
}
private function open(){
echo "<{$this->name}";
if ($this->class) {
echo " class=\"{$this->class}\"";
}
if ($this->properties) {
foreach ($this->properties as $name => $value) {
$name = str_replace("_", "-", $name);
echo " {$name}=\"{$value}\" ";
}
}
echo ">";
}
private function close(){
echo "</{$this->name}>\r\n";
}
public function show(){
$this->open();
echo "\r\n";
if ($this->children) {
foreach ($this->children as $child) {
if (is_object($child)) {
$child->show() . "\r\n";
}
elseif (is_string($child) or is_numeric($child)) {
echo $child;
}
}
}
$this->close();
}
}
?> | true |
eeebf7a91b2490e28e9dad297f1bdab2444edc35 | PHP | fwbadsoden/fw_bs_on_fuel | /fuel/application/models/Pressarticles_model.php | UTF-8 | 4,440 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | <?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
require_once('abstract_module_model.php');
class PressArticles_model extends Abstract_module_model {
public $required = array('name', 'source_id', 'datum', 'category_id');
public $foreign_keys = array('source_id' => 'pressarticle_sources_model', 'category_id' => array(FUEL_FOLDER => 'fuel_categories_model', 'where' => array('context' => 'pressarticles')));
function __construct() {
parent::__construct('fw_pressarticles');
}
/**
* Lists the module's items
*
* @access public
* @param int The limit value for the list data (optional)
* @param int The offset value for the list data (optional)
* @param string The field name to order by (optional)
* @param string The sorting order (optional)
* @param boolean Determines whether the result is just an integer of the number of records or an array of data (optional)
* @return mixed If $just_count is true it will return an integer value. Otherwise it will return an array of data (optional)
*/
public function list_items($limit = NULL, $offset = 0, $col = 'id', $order = 'asc', $just_count = FALSE) {
$this->db->order_by('datum', 'desc');
$this->db->join('pressarticle_sources', 'pressarticle_sources.id = pressarticles.source_id');
$this->db->select('pressarticles.id as id, pressarticles.name as name, pressarticle_sources.name as quelle, pressarticles.datum as datum, pressarticles.published as published');
$data = parent::list_items($limit, $offset, $col, $order, $just_count);
if (!$just_count) {
foreach ($data as $key => $val) {
$data[$key]['datum'] = get_ger_date($data[$key]['datum']);
}
}
if ($col == 'datum')
array_sorter($data, $col, $order);
return $data;
}
/**
* Add specific changes to the form_fields method
*
* @access public
* @param array Values of the form fields (optional)
* @param array An array of related fields. This has been deprecated in favor of using has_many and belongs to relationships (deprecated)
* @return array An array to be used with the Form_builder class
*/
public function form_fields($values = array(), $related = array()) {
$fields = parent::form_fields($values, $related);
$fields['name']['order'] = 1;
$fields['category_id']['label'] = lang("form_label_category");
$fields['category_id']['order'] = 2;
$fields['source_id']['label'] = lang('form_label_press_source');
$fields['source_id']['order'] = 3;
$fields['datum']['order'] = 4;
$fields['section_example'] = array('type' => 'section', 'tag' => 'h3', 'value' => lang("form_label_press_section"));
$fields['section_example']['order'] = 5;
$fields['online_article']['label'] = lang('form_label_press_link');
$fields['online_article']['comment'] = lang('form_comment_press_link');
$fields['online_article']['attributes'] = 'placeholder="http://"';
$fields['online_article']['order'] = 6;
$fields['asset'] = array('label' => lang('form_label_file'),
'folder' => 'pressarticles',
'type' => 'asset',
'class' => 'file',
'order' => 7,
'comment' => lang('form_comment_press_asset'),
'hide_options' => true,
'accept' => 'jpg|jpeg|png|pdf');
$fields['published']['type'] = 'hidden';
return $fields;
}
public function options_list($key = 'id', $val = 'name', $where = array(), $order = TRUE, $group = TRUE) {
$this->db->order_by('datum desc, name desc, id desc');
$this->db->select('id, name, datum');
$query = $this->db->get('pressarticles');
foreach ($query->result() as $row) {
$data[$row->id] = get_ger_date($row->datum) . ' - ' . $row->name;
}
return $data;
}
public function get_years() {
$years = array();
$query = $this->db->query('SELECT DISTINCT substring( datum, 1, 4 ) as datum FROM ' . $this->db->dbprefix('pressarticles'));
foreach ($query->result() as $row) {
$years[] = $row->datum;
}
rsort($years);
return $years;
}
}
class PressArticle_model extends Abstract_module_record {
}
?> | true |
eedc49851b846004e51ad6040972d88969061792 | PHP | WATARAI-IF/lib | /office/PhpPresentation/Writer/PowerPoint2007/AbstractLayoutPack.php | UTF-8 | 4,639 | 2.609375 | 3 | [] | no_license | <?php
/**
* This file is part of PHPPresentation - A pure PHP library for reading and writing
* presentations documents.
*
* PHPPresentation is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPPresentation/contributors.
*
* @link https://github.com/PHPOffice/PHPPresentation
* @copyright 2009-2015 PHPPresentation contributors
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpPresentation\Writer\PowerPoint2007;
/**
* \PhpOffice\PhpPresentation\Writer\PowerPoint2007\LayoutPack
*/
abstract class AbstractLayoutPack
{
/**
* Master slides
*
* Structure:
* - masterid
* - body
*
* @var array
*/
protected $masterSlides = array();
/**
* Master slide relations
*
* Structure:
* - master id
* - id (relation id)
* - type
* - contentType
* - target (full path in OpenXML package)
* - contents (body)
*
* @var array
*/
protected $masterSlideRels = array();
/**
* Themes
*
* Structure:
* - masterid
* - body
*
* @var array
*/
protected $themes = '';
/**
* Theme relations
*
* Structure:
* - masterid
* - id (relation id)
* - type
* - contentType
* - target (full path in OpenXML package)
* - contents (body)
*
* @var array
*/
protected $themeRelations = array();
/**
* Array of slide layouts.
*
* These are all an array consisting of:
* - id (int)
* - masterid (int)
* - name (string)
* - body (string)
*
* @var array
*/
protected $layouts = array();
/**
* Layout relations
*
* Structure:
* - layoutId (referencing layout id in layouts array)
* - id (relation id)
* - type
* - contentType
* - target (full path in OpenXML package)
* - contents (body)
*
* @var array
*/
protected $layoutRelations = array();
/**
* Get master slides
*
* @return array
*/
public function getMasterSlides()
{
return $this->masterSlides;
}
/**
* Get master slide relations
*
* @return array
*/
public function getMasterSlideRelations()
{
return $this->masterSlideRels;
}
/**
* Get themes
*
* @return array
*/
public function getThemes()
{
return $this->themes;
}
/**
* Get theme relations
*
* @return array
*/
public function getThemeRelations()
{
return $this->themeRelations;
}
/**
* Get array of slide layouts
*
* @return array
*/
public function getLayouts()
{
return $this->layouts;
}
/**
* Get array of slide layout relations
*
* @return array
*/
public function getLayoutRelations()
{
return $this->layoutRelations;
}
/**
* Find specific slide layout.
*
* This is an array consisting of:
* - masterid
* - name (string)
* - body (string)
*
* @param string $name
* @param int $masterId
* @return array
* @throws \Exception
*/
public function findLayout($name = '', $masterId = 1)
{
foreach ($this->layouts as $layout) {
if ($layout['name'] == $name && $layout['masterid'] == $masterId) {
return $layout;
}
}
throw new \Exception("Could not find slide layout $name in current layout pack.");
}
/**
* Find specific slide layout id.
*
* @param string $name
* @param int $masterId
* @return int
* @throws \Exception
*/
public function findLayoutId($name = '', $masterId = 1)
{
foreach ($this->layouts as $layoutId => $layout) {
if ($layout['name'] == $name && $layout['masterid'] == $masterId) {
return $layoutId;
}
}
throw new \Exception("Could not find slide layout $name in current layout pack.");
}
}
| true |
80506081d8698e320022bfcd6de999a95afd2b83 | PHP | aloiluca/innovation | /partials/functions.php | UTF-8 | 13,753 | 3.359375 | 3 | [] | no_license | <?php
/**
* Questa funzione riceve 4 parametri di tipo stringa ed esegue la connessione al database:
*
* 1. Esegue la connessione all HostServer.
* 2. Si connette al database richiesto.
*
* - in caso di successo restituisce un oggetto di tipo mysqli.
* - in caso di fallimento restituisce false.
*
* @param string $servername
* @param string $username
* @param string $password
* @param string $database
* @return bool|false|mysqli
*/
function getConnection($servername, $username, $password, $database){
$conn= mysqli_connect($servername, $username, $password );
$db = mysqli_select_db($conn, $database);
if (!$conn) {
return false;
}
elseif (!$db) {
return false;
}
else{
// echo "connessi al database: $database";
return $conn;
}
}
/**
*
* La funzione riceve 2 parametri:
* - la connessione al database.
* - un array contenente i path dei file in cui si trovano gli statement da eseguire sul database:
*
* Se sono presenti più query all'interno dello stesso file vengono separate dalla stringa '--' ed eseguite una alla volta:
*
* Per ogni query, in caso di errore viene inserito l'elemento $nome_file => $query all'iterno dell'array $result_array.
* Nel caso in cui la query avvenga con successo viene inserito invece l'elemento $nome_file => 'Eseguita correttamente'.
*
* In ogni caso la funzione restituisce l'array $result_array che contiene appunto quali query sono eseguite correttamente
* e quali invece hanno riscontrato degli errori.
*
* @param mysqli $connection
* @param array $migration_files
* @return array $result_array
*/
function migrate($connection, array $migration_files) {
$result_array = array();
foreach ($migration_files as $index => $migration ) {
$content = file_get_contents($migration);
$array_statements = explode('--', $content);
foreach ($array_statements as $statement) {
$result = mysqli_query($connection, $statement);
if (!$result) {
$error = [$migration => 'Errore' ];
$result_array = array_merge($result_array , $error);
}
else {
$success = [$migration => 'Eseguita correttamente' ];
$result_array = array_merge($result_array , $success);
}
}
}
return $result_array;
}
/**
* Questa funzione prende una stringa come parametro e versifica se ci sono caratteri speciali e li sostituisce con
* codici in modo che il browser reinderizza il carattere in modo corrretto.
* Il pattern è racchiuso da 2 deliitatori identificati da '/' o '#'.
*
* @param $text
* @return mixed
*/
function replace_special_character($text) {
preg_replace('#à#', 'à', $text); // Replace à with à
preg_replace('#á#', 'á', $text); // Replace á with á
preg_replace('#è#', 'è', $text); // Replace è with è
preg_replace('#é#', 'é', $text); // Replace é with é
preg_replace('#ì#', 'ì', $text); // Replace ì with ì
preg_replace('#í#', 'ì', $text); // Replace í with í
preg_replace('#ò#', 'ò', $text); // Replace ò with ò
preg_replace('#ó#', 'ò', $text); // Replace ó with ó
preg_replace('#ù#', 'ù', $text); // Replace ù with ù
preg_replace('#ù#', 'ù', $text); // Replace ú with ú
preg_replace('#À#', 'À', $text);
preg_replace('#Á#', 'Á', $text);
preg_replace('#È#', 'È', $text);
preg_replace('#É#', 'É', $text);
preg_replace('#Ì#', 'Ì', $text);
preg_replace('#Í#', 'Í', $text);
preg_replace('#Ò#', 'Ò', $text);
preg_replace('#Ó#', 'Ó', $text);
preg_replace('#Ù#', 'Ù', $text);
preg_replace('#Ú#', 'Ú', $text);
preg_replace('#£#', '£', $text); // Replace £ with £
preg_replace('#§#', '§', $text); // Replace § with §
preg_replace('#ç#', 'ç', $text); // Replace ç with ç
preg_replace('#°#', '°', $text); // Replace ° with °
preg_replace('#€#', '€', $text); // Replace € with €
return $text;
}
/**
* La funzione prende 2 parametri, in base al 2° con uno switch decide quale query eseguire per mostare gli articoli.
*
* @param mysqli $conn
* @param string $scelta
*/
function getNews($conn, $scelta) {
switch ( $scelta ) {
case 'AllNews':
/* Stampo tutti gli articoli presenti nel database */
$sql = "SELECT * FROM articoli";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$titolo = replace_special_character($row["titolo"]);
$sottotitolo = replace_special_character($row["sottotitolo"]);
$categoria = replace_special_character($row["categoria"]);
$data = $row["data"];
$id = $row["id"];
$autore = replace_special_character($row["autore"]);
/* Il nome dell'immagine dell'articolo è data dalla stringa 'articolo' + id + '.jpg' */
$img = 'articolo' . $id . '.jpg'; // articolo1.jpg
echo '
<div style="background-image:url(resources/img/articoli/' . $img . ')"; class="articolo">
<form action="/innovation/articolo.php" method="POST">
<h1><button type="submit" id="submit" name="submit">' . $titolo . '</button></h1>
<input style="display:none" type="hidden" name="id" value="' . $id . '"></p>
<h4>' . $sottotitolo . '</h4>
<h6>Data: ' . $data . '</h6>
<p>Categoria: ' . $categoria . '</p>
<p>Autore: ' . $autore . '</p>
</form>
</div>
';
}
}
else {
echo '<p class="messaggio-avviso">Non è presente alcun articolo </p>';
}
break;
case 'ByCategory':
$categorie_scelte = $_POST["categorie_scelte"];
$stringa_categorie = implode(",", $categorie_scelte);
$singola_categoria = explode(",", $stringa_categorie);
/* Se è settata $singola_categoria[0] è uguale al valore, altrimenti uguale a stringa " "! */
$categoria1 = isset($singola_categoria[0]) ? $singola_categoria[0] : ' ';
$categoria2 = isset($singola_categoria[1]) ? $singola_categoria[1] : ' ';
$categoria3 = isset($singola_categoria[2]) ? $singola_categoria[2] : ' ';
$categoria4 = isset($singola_categoria[3]) ? $singola_categoria[3] : ' ';
$sql = "SELECT * FROM articoli WHERE categoria = '" . $categoria1 . "' OR categoria = '" . $categoria2 .
"' OR categoria = '" . $categoria3 . "' OR categoria = '" . $categoria4 . "';";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$titolo = replace_special_character($row["titolo"]);
$sottotitolo = replace_special_character($row["sottotitolo"]);
$categoria = replace_special_character($row["categoria"]);
$data = $row["data"];
$id = $row["id"];
$autore = replace_special_character($row["autore"]);
/* Il nome dell'immagine dell'articolo è data dalla stringa 'articolo' + id + '.jpg' */
$img = 'articolo' . $id . '.jpg'; // articolo1.jpg
echo '
<div style="background-image:url(resources/img/articoli/' . $img . ')"; class="articolo">
<form action="/innovation/articolo.php" method="POST">
<div id="submit">
<h1><button type="submit" name="submit">' . $titolo . '</button></h1>
</div>
<input style="display:none" type="hidden" name="id" value="' . $id . '"></p>
<h4>' . $sottotitolo . '</h4>
<p>Data: ' . $data . '</p>
<p>Categoria: ' . $categoria . '</p>
<p>Autore: ' . $autore . '</p>
</form>
</div>
';
}
} else {
echo '<p class="messaggio-avviso">Non ci sono articoli per la categoria scelta.</p> ';
}
break;
case 'ByAuthor':
$autore = $_POST["autore"];
$sql = "SELECT * FROM articoli WHERE autore = '" . $autore . "';";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$titolo = replace_special_character($row["titolo"]);
$sottotitolo = replace_special_character($row["sottotitolo"]);
$categoria = replace_special_character($row["categoria"]);
$data = $row["data"];
$id = $row["id"];
$autore = replace_special_character($row["autore"]);
/* Il nome dell'immagine dell'articolo è data dalla stringa 'articolo' + id + '.jpg' */
$img = 'articolo' . $id . '.jpg'; // articolo1.jpg
echo '
<div style="background-image:url(resources/img/articoli/' . $img . ')"; class="articolo">
<form action="/innovation/articolo.php" method="POST">
<h1><button type="submit" id="submit" name="submit">' . $titolo . '</button></h1>
<input style="display:none" type="hidden" name="id" value="' . $id . '"></p>
<h4>' . $sottotitolo . '</h4>
<h6>Data: ' . $data . '</h6>
<p>Categoria: ' . $categoria . '</p>
<p>Autore: ' . $autore . '</p>
</form>
</div>
';
}
} else {
echo '<p class="messaggio-avviso">Non ci sono articoli per l\'autore scelto.</p> ';
}
break;
case 'ByAllFilter';
$categorie_scelte = $_POST["categorie_scelte"];
$stringa_categorie = implode(",", $categorie_scelte);
$singola_categoria = explode(",", $stringa_categorie);
/* Se è settata $singola_categoria[0] è uguale al valore, altrimenti uguale a stringa " "! */
$categoria1 = isset($singola_categoria[0]) ? $singola_categoria[0] : ' ';
$categoria2 = isset($singola_categoria[1]) ? $singola_categoria[1] : ' ';
$categoria3 = isset($singola_categoria[2]) ? $singola_categoria[2] : ' ';
$categoria4 = isset($singola_categoria[3]) ? $singola_categoria[3] : ' ';
$autore = $_POST["autore"];
$sql = "SELECT * FROM articoli WHERE (autore = '" . $autore . "') && (categoria = '" . $categoria1 . "' OR categoria = '" . $categoria2 .
"' OR categoria = '" . $categoria3 . "' OR categoria = '" . $categoria4 . "');";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$titolo = replace_special_character($row["titolo"]);
$sottotitolo = replace_special_character($row["sottotitolo"]);
$categoria = replace_special_character($row["categoria"]);
$data = $row["data"];
$id = $row["id"];
/* Il nome dell'immagine dell'articolo è data dalla stringa 'articolo' + id + '.jpg' */
$img = 'articolo' . $id . '.jpg'; // articolo1.jpg
echo '
<div style="background-image:url(resources/img/articoli/' . $img . ')"; class="articolo">
<form action="/innovation/articolo.php" method="POST">
<h1><button type="submit" id="submit" name="submit">' . $titolo . '</button></h1>
<input style="display:none" type="hidden" name="id" value="' . $id . '"></p>
<h4>' . $sottotitolo . '</h4>
<h6>Data: ' . $data . '</h6>
<p>Categoria: ' . $categoria . '</p>
<p>Autore: ' . $autore . '</p>
</form>
</div>
';
}
} else {
echo '<p class="messaggio-avviso">Non ci sono articoli per i filtri scelti </p>' ;
}
break;
}
} | true |
eef0bb12ed632619e2924b393333fe10e571dba9 | PHP | ztavruz/MenOfFuture | /game/Galaxi/Albion/Albion.php | UTF-8 | 648 | 2.9375 | 3 | [] | no_license | <?php
namespace Game\Galaxi\Albion;
use Game\Galaxi\Galaxi;
class Albion extends Galaxi
{
// protected $name;
// protected $description;
// protected $position;
// protected $arraySistems = [];
// protected $arrayData = [];
public function __construct()
{
$this->name = "Альбион";
$this->description = "Центральная галактика, по слухам прародина предтеч.";
$this->color_test = "#80787E";
$this->arraySistems =
[
[1,1,1],
[1,1,1],
[1,1,1]
];
parent::__construct();
}
} | true |
d87b88d6e934b66949ab34c667c42c94425fa63d | PHP | phpclassic/php-shopify | /lib/CurlRequest.php | UTF-8 | 5,472 | 2.859375 | 3 | [
"Apache-2.0"
] | permissive | <?php
/**
* Created by PhpStorm.
* @author Tareq Mahmood <tareqtms@yahoo.com>
* Created at 8/17/16 2:50 PM UTC+06:00
*/
namespace PHPShopify;
use PHPShopify\Exception\CurlException;
use PHPShopify\Exception\ResourceRateLimitException;
/*
|--------------------------------------------------------------------------
| CurlRequest
|--------------------------------------------------------------------------
|
| This class handles get, post, put, delete HTTP requests
|
*/
class CurlRequest
{
/**
* HTTP Code of the last executed request
*
* @var integer
*/
public static $lastHttpCode;
/**
* HTTP response headers of last executed request
*
* @var array
*/
public static $lastHttpResponseHeaders = array();
/**
* Total time spent in sleep during multiple requests (in seconds)
*
* @var int
*/
public static $totalRetrySleepTime = 0;
/**
* Curl additional configuration
*
* @var array
*/
protected static $config = array();
/**
* Initialize the curl resource
*
* @param string $url
* @param array $httpHeaders
*
* @return resource
*/
protected static function init($url, $httpHeaders = array())
{
// Create Curl resource
$ch = curl_init();
// Set URL
curl_setopt($ch, CURLOPT_URL, $url);
//Return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'PHPClassic/PHPShopify');
foreach (self::$config as $option => $value) {
curl_setopt($ch, $option, $value);
}
$headers = array();
foreach ($httpHeaders as $key => $value) {
$headers[] = "$key: $value";
}
//Set HTTP Headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
return $ch;
}
/**
* Implement a GET request and return output
*
* @param string $url
* @param array $httpHeaders
*
* @return string
*/
public static function get($url, $httpHeaders = array())
{
//Initialize the Curl resource
$ch = self::init($url, $httpHeaders);
return self::processRequest($ch);
}
/**
* Implement a POST request and return output
*
* @param string $url
* @param array $data
* @param array $httpHeaders
*
* @return string
*/
public static function post($url, $data, $httpHeaders = array())
{
$ch = self::init($url, $httpHeaders);
//Set the request type
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
return self::processRequest($ch);
}
/**
* Implement a PUT request and return output
*
* @param string $url
* @param array $data
* @param array $httpHeaders
*
* @return string
*/
public static function put($url, $data, $httpHeaders = array())
{
$ch = self::init($url, $httpHeaders);
//set the request type
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
return self::processRequest($ch);
}
/**
* Implement a DELETE request and return output
*
* @param string $url
* @param array $httpHeaders
*
* @return string
*/
public static function delete($url, $httpHeaders = array())
{
$ch = self::init($url, $httpHeaders);
//set the request type
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
return self::processRequest($ch);
}
/**
* Set curl additional configuration
*
* @param array $config
*/
public static function config($config = array())
{
self::$config = $config;
}
/**
* Execute a request, release the resource and return output
*
* @param resource $ch
*
* @throws CurlException if curl request is failed with error
*
* @return string
*/
protected static function processRequest($ch)
{
# Check for 429 leaky bucket error
while (1) {
$output = curl_exec($ch);
$response = new CurlResponse($output);
self::$lastHttpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (self::$lastHttpCode != 429) {
break;
}
$apiCallLimit = $response->getHeader('X-Shopify-Shop-Api-Call-Limit');
if (!empty($apiCallLimit)) {
$limitHeader = explode('/', $apiCallLimit, 2);
if (isset($limitHeader[1]) && $limitHeader[0] < $limitHeader[1]) {
throw new ResourceRateLimitException($response->getBody());
}
}
$retryAfter = $response->getHeader('Retry-After');
if ($retryAfter === null) {
break;
}
self::$totalRetrySleepTime += (float)$retryAfter;
sleep((float)$retryAfter);
}
if (curl_errno($ch)) {
throw new Exception\CurlException(curl_errno($ch) . ' : ' . curl_error($ch));
}
// close curl resource to free up system resources
curl_close($ch);
self::$lastHttpResponseHeaders = $response->getHeaders();
return $response->getBody();
}
}
| true |
aa56678c7058726cfd4e8e5c8153edf739774e14 | PHP | Selim-Reza-Swadhin/Image_Upload_PHP | /insert_image.php | UTF-8 | 766 | 2.640625 | 3 | [] | no_license | <?php
include 'inc/header.php';
include 'lib/config.php';
include 'lib/Database.php';
$db = new Database();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$permited = array('jpg', 'jpeg', 'png', 'gif');
$file_name = $_FILES['image']['name'];
$file_size = $_FILES['image']['size'];
$file_temp = $_FILES['image']['tmp_name'];
$folder = "uploads/";
move_uploaded_file($file_temp, $folder.$file_name);
$query = "INSERT INTO insert_image(image) VALUES('$file_name')";
$inserted_rows = $db->insert($query);
if ($inserted_rows) {
echo "<span class='success'>Image Inserted Successfully.
</span>";
}else {
echo "<span class='error'>Image Not Inserted !</span>";
}
}
?>
<?php include 'inc/footer.php';?>
| true |
9689074aed5ca5338da5ecc4b268969c6d50edb2 | PHP | mraycheva/photo-albums-manager | /photo/sql/get-all.php | UTF-8 | 336 | 2.703125 | 3 | [] | no_license | <?php
require_once(__DIR__ . '/../../base/sql/execute-statement.php');
function getAll()
{
$id = $_GET["id"];
$sql = 'SELECT * FROM photo WHERE album_id = ' . $id . ' ORDER BY id';
$res = execute($sql);
$photos = array();
while ($row = $res->fetch_assoc()) {
$photos[] = $row;
}
return $photos;
}
| true |