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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
e93843028f73e2ee7687f427591b933096c67ea4 | PHP | mengtry-coder/2bc_bms | /backend/models/ProjectTimesheetTag.php | UTF-8 | 836 | 2.5625 | 3 | [] | permissive | <?php
namespace backend\models;
use Yii;
/**
* This is the model class for table "project_timesheet_tag".
*
* @property int $id
* @property int $id_project_timesheet
* @property string $id_tag
*/
class ProjectTimesheetTag extends \yii\db\ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'project_timesheet_tag';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['id_project_timesheet'], 'integer'],
[['id_tag'], 'string', 'max' => 50],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'id_project_timesheet' => 'Id Project Timesheet',
'id_tag' => 'Id Tag',
];
}
}
| true |
4a143b28cf43d58e765a9c47f0e344ae7443718e | PHP | FilipenkoDanil/shop | /app/Services/CurrencyRates.php | UTF-8 | 933 | 2.71875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Services;
use GuzzleHttp\Client;
class CurrencyRates
{
public static function getRates()
{
$url = 'https://api.privatbank.ua/p24api/pubinfo?json&exchange&coursid=5';
$client = new Client();
$response = $client->request('GET', $url);
if ($response->getStatusCode() !== 200) {
throw new \Exception('Problem with currency API');
}
$rates = json_decode($response->getBody()->getContents(), true);
foreach (CurrencyConversion::getCurrencies() as $currency) {
if (!$currency->is_main) {
foreach ($rates as $rate) {
if ($rate['ccy'] == $currency->code) {
$curRate = $rate['sale'];
$currency->update(['rate' => $curRate]);
$currency->touch();
}
}
}
}
}
}
| true |
2c82beca7415bafb54c38b9032f2be5368a1042d | PHP | suinua/game_chef | /src/game_chef/pmmp/form/team_game_map_forms/TeamGameMapListForm.php | UTF-8 | 1,162 | 2.59375 | 3 | [
"MIT"
] | permissive | <?php
namespace game_chef\pmmp\form\team_game_map_forms;
use form_builder\models\simple_form_elements\SimpleFormButton;
use form_builder\models\SimpleForm;
use game_chef\repository\TeamGameMapDataRepository;
use pocketmine\Player;
class TeamGameMapListForm extends SimpleForm
{
public function __construct() {
try {
$mapList = TeamGameMapDataRepository::loadAll();
} catch (\Exception $e) {
$errorMessage = $e->getMessage();
parent::__construct("エラーが発生しました", $errorMessage, []);
return;
}
$mapListAsElements = [];
foreach ($mapList as $map) {
$mapListAsElements[] = new SimpleFormButton(
$map->getName(),
null,
function (Player $player) use ($map) {
$player->sendForm(new TeamGameMapDetailForm($map));
}
);
}
parent::__construct("チームゲーム用のマップ一覧", "", $mapListAsElements);
}
function onClickCloseButton(Player $player): void {
$player->sendForm(new TeamGameMapForm());
}
}
| true |
edceb241cee451ae505aa70c149880e6d530873d | PHP | JesusDPH20/ss-UNAM-CERT | /ss-unam-cert-noticert/descargaNoticias.php | UTF-8 | 490 | 2.5625 | 3 | [] | no_license | <?php
session_start();
$noticias = $_POST['dom'];
//die();
//CREACIÓN DEL ARCHIVO HTML - FUNCIONA
$myfile = fopen("news_".date('Y_m_d-h_i_s_a').".html", "w+");
$html = "<h1>Estas son las noticias</h1><br>";
fwrite($myfile, $html);
fclose($myfile);
file_put_contents('news_'.date('Y_m_d-h_i_s_a').'.html', $_POST['dom']);
header('Content-Disposition: attachment;filename=news_'.date('Y_m_d-h_i_s_a').'.html');
readfile('news_'.date('Y_m_d-h_i_s_a').'.html');
?>
| true |
5d6060e1d0e9f5d0c8c019e636bd2953e7162e8f | PHP | SuRaMoN/e-to-e | /src/EToE/Exception/ErrorException.php | UTF-8 | 297 | 2.6875 | 3 | [] | no_license | <?php
namespace EToE\Exception;
use EToE\Error;
class ErrorException extends \ErrorException
{
public function __construct(Error $error)
{
parent::__construct($error->getErrorMessage(), 0, $error->getErrorNumber(),
$error->getOriginatingFile(), $error->getOriginatingFileLine());
}
}
| true |
538e05fb5051ba777171825aef8fe0f4a8e3fdef | PHP | koandamb01/eopProject | /mentors.php | UTF-8 | 5,447 | 2.6875 | 3 | [] | no_license | <?php
session_start();
// Check if user is logged in using the session variable
if ( $_SESSION['logged_in'] != 1 ) {
$_SESSION['message'] = "You must log in before viewing registration page!";
header("location: error.php");
}
$active = $_SESSION['active'];
$firstname = $_SESSION['firstname'];
if(!$active){
header("location: profile.php");
}
require 'functions/pdo.php';
require 'functions/functions.php';
require 'functions/vars.php';
/* declare page variable */
$page = 'Mentors';
/*start html beginning tags and display page navigation bar */
header_Nav($page, $firstname);
/* Display section breadcrumb */
breadcrumb($page);
$course_name = '';
if(isset($_POST['search'])){
if(empty($_POST['course'])){
$stmt = $pdo->query('SELECT * FROM tblmentors ORDER BY firstname ASC');
$rows = $stmt->fetchAll();
}
else{
$course_name = $_POST['course'];
$sql = 'SELECT DISTINCT mentor_id FROM tblcourses WHERE course_name = :course_name ORDER BY mentor_id ASC';
$stmt = $pdo->prepare($sql);
$stmt->execute(['course_name' => $course_name]);
$row_ids = $stmt->fetchAll();
$rows = new ArrayObject();
foreach ($row_ids as $row_id) {
$sql = 'SELECT * FROM tblmentors WHERE mentor_id = :mentor_id';
$stmt = $pdo->prepare($sql);
$stmt->execute(['mentor_id' => $row_id->mentor_id]);
$row = $stmt->fetch();
$rows->append($row);
}
}
}
else{
$stmt = $pdo->query('SELECT * FROM tblmentors ORDER BY firstname ASC');
// Fecth all result after the search
$rows = $stmt->fetchAll();
}
$today = date("l");
$days = array(1 => "Monday", 2 => "Tuesday", 3 => "Wednesday", 4 => "Thursday", 5 => "Friday"); // array the work week days
foreach ($days as $key => $value) {
if ($value == $today) {
$today = $key;
}
}
// Prints the day, date, month, year, time, AM or PM
//echo date("l F jS\, Y h:i:s A") . "<br>";
?>
<section id="main">
<div class="container">
<form id="myForm" action="<?php echo(htmlspecialchars($_SERVER['PHP_SELF']));?>" method="post">
<div class="panel panel-default">
<div class="panel-heading main-color-bg">
<div class="row">
<div class="col-md-2">
<h3 class="panel-title">Mentors</h3>
</div>
<div class="col-md-1 pull-right">
<button class="btn btn-warning" name="reset">Reset</button>
</div>
<div class="col-md-1 pull-right">
<button class="btn btn-success" name="search">Search</button>
</div>
<div class="col-md-3 pull-right">
<input class="form-control" type="text" name="course" value="<?php echo $course_name; ?>" pattern="[A-Za-z]{3}[0-9]{3}" title="Invalid Course Name!" placeholder="CRS101...">
</div>
</div>
</div>
</form>
<div class="panel-body">
<br>
<table class="table table-striped table-hover table-height">
<thead>
<tr>
<th>Edit</th>
<th>Firstname</th>
<th>Lastname</th>
<th>AcadYear</th>
<th>Email</th>
<th>Available Today?</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
foreach ($rows as $row) {
echo '<tr>
<td><a class="btn btn-sm btn-danger" href="edit_mentor.php?mentor_id=' .$row->mentor_id. '">Edit Mentor</a></td>
<td>'. $row->firstname . '</td>
<td>'. $row->lastname . '</td>
<td>'. $row->academic_year . '</td>
<td>'. $row->email . '</td>';
$sql = 'SELECT * FROM tblschedule WHERE mentor_id = :mentor_id AND day = :day';
$stmt = $pdo->prepare($sql);
$stmt->execute(['mentor_id' => $row->mentor_id, 'day' => $today]);
$count = $stmt->rowCount();
if($count == 0){
echo '<td>No<td>';
}else{
echo '<td>Yes<td>';
}
echo '<td><a class="btn btn-sm btn-success" href="mentors.php?mentor_id=' .$row->mentor_id. '">Schedule</a></td>
</tr>';
}
?>
</tbody>
</table>
</div>
</div>
</div>
</section>
<?php
if(isset($_GET['mentor_id'])){
$mentor_id = $_GET['mentor_id'];
require 'show_schedule.php';
}
?>
<!-- Footer -->
<?php footer(); ?> | true |
129519da2ad42eef4ae80ad8d6c7eb9acfff9b27 | PHP | escalantejulian18/PHPMySQL | /Práctico 6/tp6/admin/borrar.php | ISO-8859-1 | 1,957 | 2.671875 | 3 | [] | no_license | <?php
// Incluimos la clase de singleton
require_once $_SERVER['DOCUMENT_ROOT'] . '/tp6/includes/php/Singleton/Sesion.php';
//generamos el id de session
if (!isset($_SESSION['initiated'])){
session_regenerate_id();
$_SESSION['initiated'] = true;
}
// Incluimos la clase de singleton
require_once $_SERVER['DOCUMENT_ROOT'] . '/tp6/includes/php/ActiveRecord/ActiveRecordFactory.php';
// Obtenemos la instancia del Registry
$oSesion = \Sgu\Singleton\Sesion::getInstance();
// Obtenemos el id del usuario
$idUsuario = $_GET['id'];
// Inicializamos las variables que contendran la informacin del usuario
$oUsuario = \Sgu\ActiveRecord\ActiveRecordFactory::getUsuario();
// Obtenemos la informacin desde la base de datos
$oUsuario->fetch($idUsuario);
// Obtenemos el nombre del usuario en base a su id
$usuario = $oUsuario->getNombre();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>SGU | Borrar Usuario</title>
<link type="text/css" rel="stylesheet" href="/tp6/includes/css/estilos.css">
</head>
<body>
<div class="wraper">
<?php require_once $_SERVER['DOCUMENT_ROOT'] . '/tp6/includes/php/header.php'; ?>
<?php require_once $_SERVER['DOCUMENT_ROOT'] . '/tp6/includes/php/menu.php'; ?>
<form action="/tp6/admin/eliminar_usuario.php" method="get">
<input type="hidden" name="id" value="<?php echo $idUsuario; ?>">
<fieldset>
<legend>Borrar Usuario</legend>
<div class="center mensaje">
<p>
Está seguro que desea eliminar el usuario "<?php echo htmlentities($usuario); ?>"?
</p>
<p>
<input type="submit" value="Si" class="button">
<input type="button" value="No" class="button" onclick="history.back();">
</p>
</div>
</fieldset>
</form>
<div class="push"></div>
</div>
<?php require_once $_SERVER['DOCUMENT_ROOT'] . '/tp6/includes/php/footer.php'; ?>
</body>
</html> | true |
50c06214d28f266c7e581bbf222f1ad6aa3ce281 | PHP | iNtergrated/l5-fixtures | /src/Mayconbordin/L5Fixtures/Loaders/CsvLoader.php | UTF-8 | 637 | 2.75 | 3 | [] | no_license | <?php namespace Mayconbordin\L5Fixtures\Loaders;
use League\Csv\Reader;
class CsvLoader extends AbstractLoader
{
public function load($path)
{
$data = $this->metadata->getFilesystem()->read($path);
return $this->getReader($data)->fetchAssoc();
}
/**
* @param string $data
* @return static
*/
protected function getReader($data)
{
$csv = Reader::createFromString($data);
$delimiters = $csv->detectDelimiterList(10, ['|']);
if (sizeof($delimiters) > 0) {
$csv->setDelimiter(array_values($delimiters)[0]);
}
return $csv;
}
} | true |
240d29cf039e4a7a08d0a390e23a2fa89653262a | PHP | piyushchauhan2011/pux-routing-example | /index.php | UTF-8 | 4,817 | 2.90625 | 3 | [] | no_license | <?php
require 'vendor/autoload.php'; // use PCRE patterns you need Pux\PatternCompiler class.
use Pux\Executor;
// Get the database connection and return the reference for use
function getConnection() {
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "diehard4";
$dbname = "pux_test";
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
// Index Controller
class IndexController {
public function indexAction() {
include "frontend/index.html";
}
}
// Wine Controller
class WineController {
public function __construct() {
$this->dbh = getConnection();
header('Content-Type: application/json');
}
public function indexAction() {
$sql = "SELECT * FROM wines ORDER BY name";
try {
$db = $this->dbh;
$stmt = $db->query($sql);
$wines = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo '{"wines": ' . json_encode($wines) . '}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
public function showAction($id) {
$sql = "SELECT * FROM wines WHERE id=:id";
try {
$db = $this->dbh;
$stmt = $db->prepare($sql);
$stmt->bindParam("id", $id);
$stmt->execute();
$wine = $stmt->fetchObject();
$db = null;
echo json_encode($wine);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
public function createAction() {
$sql = "INSERT INTO wines (name, grapes, country, region, year, description) VALUES (:name, :grapes, :country, :region, :year, :description)";
try {
$db = $this->dbh;
$stmt = $db->prepare($sql);
$stmt->bindParam("name", $_POST['name']);
$stmt->bindParam("grapes", $_POST['grapes']);
$stmt->bindParam("country", $_POST['country']);
$stmt->bindParam("region", $_POST['region']);
$stmt->bindParam("year", $_POST['year']);
$stmt->bindParam("description", $_POST['description']);
$stmt->execute();
$wine->id = $db->lastInsertId();
$db = null;
echo json_encode($wine);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
public function updateAction($id) {
// Remember to send request using x-www-form-urlencoded
parse_str(file_get_contents('php://input'),$_PUT);
$wine = $_PUT;
$sql = "UPDATE wines SET name=:name, grapes=:grapes, country=:country, region=:region, year=:year, description=:description, picture=:picture WHERE id=:id";
try {
$db = $this->dbh;
$stmt = $db->prepare($sql);
$stmt->bindParam("name", $wine['name']);
$stmt->bindParam("grapes", $wine['grapes']);
$stmt->bindParam("country", $wine['country']);
$stmt->bindParam("region", $wine['region']);
$stmt->bindParam("year", $wine['year']);
$stmt->bindParam("description", $wine['description']);
$stmt->bindParam("picture", $wine['picture']);
$stmt->bindParam("id", $id);
$stmt->execute();
$db = null;
echo json_encode($wine);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
public function destroyAction($id) {
$sql = "DELETE FROM wines WHERE id=:id";
try {
$db = $this->dbh;
$stmt = $db->prepare($sql);
$stmt->bindParam("id", $id);
$stmt->execute();
$db = null;
echo '{"success":{"text":"Deleted successfully."}}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
public function searchAction($query) {
$sql = "SELECT * FROM wines WHERE UPPER(name) LIKE :query ORDER BY name";
try {
$db = $this->dbh;
$stmt = $db->prepare($sql);
$query = "%".$query."%";
$stmt->bindParam("query", $query);
$stmt->execute();
$wines = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo '{"wines": ' . json_encode($wines) . '}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
}
// Routing Variable
$mux = new Pux\Mux;
// WineController Routings
$mux->get('/', ['IndexController', 'indexAction']);
$mux->get('/wines', ['WineController', 'indexAction']);
$mux->get('/wines/:id', ['WineController', 'showAction']);
$mux->post('/wines', ['WineController', 'createAction']);
$mux->put('/wines/:id', ['WineController', 'updateAction']);
$mux->delete('/wines/:id', ['WineController', 'destroyAction']);
$mux->get('/wines/search/:query', ['WineController', 'searchAction']);
// General Stuff for starting Pux application
if (!isset($_SERVER['PATH_INFO'])) {
$route = $mux->dispatch('/');
} else {
$route = $mux->dispatch($_SERVER['PATH_INFO']);
}
Executor::execute($route);
| true |
c5f5db4c574ccfa246bf876a9d1fbf2d93ef4970 | PHP | Alex223/Estadistica-Finanza | /Finanza/Controlador/Coberturas/ValidaRegistros.php | UTF-8 | 1,075 | 2.671875 | 3 | [] | no_license | <?php
include_once '../../Modelo/Conexion.php';
$conexión = new Conexion();
$conexión->conectar();
if (!$conexión) {
echo "No pudo conectarse a la BD: " . mysql_error();
exit;
}
if (!mysql_select_db($conexión->base())) {
echo "No ha sido posible seleccionar la BD: " . mysql_error();
exit;
}
$control ="1";
$sql_0 = "SELECT * from coberturas";
$sql_1 = "SELECT * from forma_de_pago";
$sql_2 = "SELECT * from banco";
$sql_3 = "SELECT * from tipo_estado_c";
$sql_4 = "SELECT * from tipo_estado_bodega";
$resultado_0 = mysql_query($sql_0);
$resultado_1 = mysql_query($sql_1);
$resultado_2 = mysql_query($sql_2);
$resultado_3 = mysql_query($sql_3);
$resultado_4 = mysql_query($sql_4);
if (mysql_num_rows($resultado_0) == 0 ) {
$control="2";
}
if( mysql_num_rows($resultado_1) == 0){
$control="3";
}
if(mysql_num_rows($resultadao_2) == 0){
$control="4";
}
if(mysql_num_rows($resultado_3)==0){
$control="5";
}
if(mysql_num_rows($resultado_4) == 0)
{
$control=6;
}
echo $control;
?>
| true |
b83c08e33aec0450e0a93032b7a90ae257a4c7d6 | PHP | jiacheng-0/IS113-Dump | /is113/LT2-2019-Prep/IS113_TrialLT1_SetA_2018 James/q3flip.php | UTF-8 | 3,070 | 3.125 | 3 | [] | no_license | <?php
// this will autoload the class that we need in our code
spl_autoload_register(function ($class) {
// we are assuming that it is in the same directory as common.php
// otherwise we have to do
// $path = 'path/to/' . $class . ".php"
$path = $class . ".php";
require $path;
});
?>
<html>
<body>
<form method='post'>
Name:
<select name='student'>
<?php
$dao = new CourseDAO;
$names = $dao->retrieveNames();
foreach ($names as $name) {
$selected = '';
if (isset($_POST['student']) && $_POST['student'] == $name) {
$selected = 'selected';
}
echo "<option value = '$name' $selected>$name</option>";
}
echo "</select>";
?>
<input type='submit' name='show_timetable'>
</form>
<?php
function timetable_filler($stu)
{
$times = ['830' => '08:30am-10:00am', '1000' => '10:00am-11:30am', '1200' => '12:00nn-1:30pm',
'1330' => '1:30pm-3:00pm', '1530' => '3:30pm-5:00pm', '1700' => '5:00pm-6:30pm'];
$days = ['MON', 'TUE', 'WED', 'THU', 'FRI'];
$dao = new CourseDAO;
echo "<table border='1'><tr><td></td>";
$times_values_long = array_values($times);
$times_values_short = array_keys($times);
for ($i = 0; $i <= 4; $i++) {
$day = $days[$i];
echo "<th align='center'>$day</th>";
}
echo "</tr>";
$skipper = [];
$skipper_counter = 0;
for ($i = 0; $i <= 5; $i++) {
echo "<tr>";
$time = $times_values_long[$i];
$time2 = $times_values_short[$i];
echo "<td>$time</td>";
$stu_courses = $dao->retrieveCourses($stu);
if ($skipper_counter === 2) {
$skipper_counter = 0;
$skipper = [];
}
for ($j = 0; $j <= 4; $j++) {
if (!in_array($j, $skipper)) {
$current_day = $days[$j];
$checker = 'no';
foreach ($stu_courses as $course) {
if ($course->weekOfDay == $current_day && $course->startTime == $time2) {
if ($course->weekOfDay == $current_day && $course->startTime == $time2) {
$length = $course->numUnits;
$code = $course->courseCode;
$desc = $course->courseDesc;
if ($length > 1) {
$skipper[] = $j;
}
echo "<td rowspan='$length' align='center'>$code<br>$desc</td>";
$checker = 'yes';
}
}
}
if ($checker == 'no') {
echo "<td></td>";
}
}
}
if (!empty($skipper)) {
$skipper_counter += 1;
}
echo "</tr>";
}
echo "</table>";
}
// var_dump($_POST['student']);
if (isset($_POST['student'])) {
timetable_filler($_POST['student']);
}
?>
</body>
</html>
| true |
5f69e64ea14075605eb8256b60affe742cd17854 | PHP | zeineb2000/projetweb | /modifierregistree.php | UTF-8 | 1,681 | 2.515625 | 3 | [
"MIT",
"CC-BY-3.0",
"CC-BY-4.0"
] | permissive | <HTML>
<head>
</head>
<body>
<?PHP
include "../entities/registre.php";
include "../core/registreC.php";
if (isset($_GET['cin'])){
$registreC=new registreC();
$result=$registreC->recupererregistre($_GET['cin']);
foreach($result as $row){
$cin=$row['cin'];
$nom=$row['nom'];
$prenom=$row['prenom'];
$mail=$row['mail'];
$pass=$row['pass'];
?>
<form method="POST">
<table>
<caption>Modifier registre</caption>
<tr>
<td>cin</td>
<td><input type="number" name="cin" value="<?PHP echo $cin ?>"></td>
</tr>
<tr>
<td>nom</td>
<td><input type="text" name="nom" value="<?PHP echo $nom ?>"></td>
</tr>
<tr>
<td>prenom</td>
<td><input type="text" name="prenom" value="<?PHP echo $prenom ?>"></td>
</tr>
<tr>
<td>mail</td>
<td><input type="text" name="mail" value="<?PHP echo $mail ?>"></td>
</tr>
<tr>
<td>pass</td>
<td><input type="password" name="pass" value="<?PHP echo $pass ?>"></td>
</tr>
<!-- <tr>
<td>Petsrace</td>
<td><input type="text" name="petsrace" value="<?PHP echo $petsrace ?>"></td>
</tr>
<tr>
<td>Prix</td>
<td><input type="number" name="prix" value="<?PHP echo $prix ?>"></td>
</tr> -->
<tr>
<td></td>
<td><input type="submit" name="modifier" value="modifier"></td>
</tr>
<tr>
<td></td>
<td><input type="hidden" name="cin_ini" value="<?PHP echo $_GET['cin'];?>"></td>
</tr>
</table>
</form>
<?PHP
}
}
if (isset($_POST['modifier'])){
$registre=new registre($_POST['cin'],$_POST['nom'],$_POST['prenom'],$_POST['mail'],$_POST['pass']);
$registreC->modifierregistre($registre,$_POST['cin_ini']);
echo $_POST['cin'];
header('Location: afficherregistree.php');
}
?>
</body>
</HTMl>
| true |
1deb681aee2585b9cc3ba38239afc67f3dd76fc8 | PHP | lekster/md_new | /new/libraries/common/Aop/Go/Aop/Pointcut/TrueMethodPointcut.php | UTF-8 | 914 | 2.703125 | 3 | [
"MIT"
] | permissive | <?php
/**
* Go! OOP&AOP PHP framework
*
* @copyright Copyright 2012, Lissachenko Alexander <lisachenko.it@gmail.com>
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
namespace Go\Aop\Pointcut;
use ReflectionMethod;
use TokenReflection\ReflectionMethod as ParsedReflectionMethod;
/**
* True method pointcut matches all methods in specific class
*/
class TrueMethodPointcut extends StaticMethodMatcherPointcut
{
/**
* Performs matching of point of code
*
* @param mixed $method Specific part of code, can be any Reflection class
*
* @return bool
*/
public function matches($method)
{
/** @var $method ReflectionMethod|ParsedReflectionMethod */
if (!$method instanceof ReflectionMethod && !$method instanceof ParsedReflectionMethod) {
return false;
}
return true;
}
}
| true |
a34d3ed06681f79c09826dd377bb0024c055d78f | PHP | yla06/php_framework | /Core/View/Storage.php | UTF-8 | 1,055 | 2.984375 | 3 | [] | no_license | <?php
namespace View;
class Storage
{
private static $_data = [];
public static function setData( $name, $value, $secure = true )
{
self::$_data[$name] = ( $secure ) ? self::xss( $value ) : $value;
}
public static function getData($name)
{
return ( isset ( self::$_data[$name] ) ) ? self::$_data[$name] : null;
}
public static function remover( $name)
{
unset( $_data[$name] );
}
public static function getAllData( )
{
return self::$_data;
}
public static function removerAllData( )
{
self::$_data= [];
}
/**
* Метод обработки печатных данных от XSS
*
* @param mixed $data
* @return mixed
*/
private static function xss( $data )
{
if ( is_array( $data ) )
{
array_walk_recursive(
$data,
function( &$item, $key ){
$item = htmlspecialchars( $item );
}
);
return $data;
}
return htmlspecialchars( $data );
}
}
| true |
e99ddc9f0ee1190f40d4b20a211ae13a989d6ce9 | PHP | chienle29/anime2 | /app/Model/Media/MediaFile.php | UTF-8 | 16,263 | 2.8125 | 3 | [] | no_license | <?php
namespace CTMovie\Model\Media;
use Illuminate\Filesystem\Filesystem;
/**
* Class MediaFile
* @package CTMovie\Model\Media
*/
class MediaFile
{
/** @var string Raw source URL after "find-replace in image URLs" options applied to it. */
private $sourceUrl;
/** @var string Raw source URL retrieved from the target site */
private $originalSourceUrl;
/** @var string */
private $localUrl;
/** @var string */
private $localPath;
/** @var bool True if this file is a gallery image. */
private $isGalleryImage = false;
/** @var string|null */
private $mediaTitle;
/** @var string|null */
private $mediaDescription;
/** @var string|null */
private $mediaCaption;
/** @var string|null */
private $mediaAlt;
/** @var string */
private $originalFileName;
/** @var int|null Media ID of this file, retrieved by inserting the media into the database. */
private $mediaId;
/** @var array Stores the paths of the copies of the file */
private $copyFilePaths = [];
/**
* @param string $sourceUrl See {@link $sourceUrl}
* @param string $localPath See {@link $localPath}
*/
public function __construct($sourceUrl, $localPath) {
$this->sourceUrl = $sourceUrl;
$this->setLocalPath($localPath);
$this->originalFileName = $this->getFileSystem()->name($this->localPath ?: $sourceUrl);
}
/**
* @return string
*/
public function getSourceUrl() {
return $this->sourceUrl;
}
/**
* @param string $sourceUrl
* @return MediaFile
*/
public function setSourceUrl($sourceUrl) {
$this->sourceUrl = $sourceUrl;
return $this;
}
/**
* @return string
*/
public function getOriginalSourceUrl() {
return $this->originalSourceUrl ?: $this->getSourceUrl();
}
/**
* @param string $originalSourceUrl
* @return MediaFile
*/
public function setOriginalSourceUrl($originalSourceUrl) {
$this->originalSourceUrl = $originalSourceUrl;
return $this;
}
/**
* @return string
*/
public function getLocalUrl() {
// If there is no local URL, create it.
if ($this->localUrl === null) {
$url = FileService::getInstance()->getUrlForPathUnderUploadsDir($this->getLocalPath());
if ($url !== null) {
$this->localUrl = $url;
}
}
return $this->localUrl ? $this->localUrl : '';
}
/**
* @param string $localUrl
* @return MediaFile
*/
public function setLocalUrl($localUrl) {
$this->localUrl = $localUrl;
return $this;
}
/**
* @return string
*/
public function getOriginalFileName() {
return $this->originalFileName;
}
/**
* @return string
*/
public function getLocalPath() {
return $this->localPath;
}
/**
* @param string $localPath
* @return MediaFile
*/
public function setLocalPath($localPath) {
if ($localPath !== null) {
$this->localPath = realpath($localPath) ?: null;
} else {
$this->localPath = null;
}
// Make the local URL null, since the path of the file has just changed.
$this->localUrl = null;
return $this;
}
/**
* @return bool
*/
public function isGalleryImage() {
return $this->isGalleryImage;
}
/**
* @param bool $isGalleryImage
* @return MediaFile
*/
public function setIsGalleryImage($isGalleryImage) {
$this->isGalleryImage = $isGalleryImage;
return $this;
}
/**
* @return string
*/
public function getMediaTitle() {
return $this->mediaTitle !== null ? $this->mediaTitle : preg_replace('/\.[^.]+$/', '', $this->getBaseName());
}
/**
* @param null|string $mediaTitle
* @return MediaFile
*/
public function setMediaTitle($mediaTitle) {
$this->mediaTitle = $mediaTitle;
return $this;
}
/**
* @return string
*/
public function getMediaDescription() {
return $this->mediaDescription !== null ? $this->mediaDescription : '';
}
/**
* @param null|string $mediaDescription
* @return MediaFile
*/
public function setMediaDescription($mediaDescription) {
$this->mediaDescription = $mediaDescription;
return $this;
}
/**
* @return string
*/
public function getMediaCaption() {
return $this->mediaCaption !== null ? $this->mediaCaption : '';
}
/**
* @param null|string $mediaCaption
* @return MediaFile
*/
public function setMediaCaption($mediaCaption) {
$this->mediaCaption = $mediaCaption;
return $this;
}
/**
* @return string
*/
public function getMediaAlt() {
return $this->mediaAlt !== null ? $this->mediaAlt : '';
}
/**
* @param null|string $mediaAlt
* @return MediaFile
*/
public function setMediaAlt($mediaAlt) {
$this->mediaAlt = $mediaAlt;
return $this;
}
/**
* @return int|null
*/
public function getMediaId() {
return $this->mediaId;
}
/**
* @param int|null $mediaId
*/
public function setMediaId($mediaId) {
$this->mediaId = $mediaId;
}
/*
* OPERATIONS
*/
/**
* @return bool True if the media file exists.
* @since 1.8.0
*/
public function exists() {
return $this->getFileSystem()->exists($this->getLocalPath());
}
/**
* @return bool True if the media file path is a file.
* @since 1.8.0
*/
public function isFile() {
return strlen($this->getFileSystem()->extension($this->getLocalPath())) > 0;
}
/**
* @return string Directory of the media file
* @since 1.8.0
*/
public function getDirectory() {
return $this->getFileSystem()->dirname($this->getLocalPath());
}
/**
* @return string Name of the media file
* @since 1.8.0
*/
public function getName() {
return $this->getFileSystem()->name($this->getLocalPath());
}
/**
* @return string Base name of the file, i.e. file name with extension.
* @since 1.8.0
*/
public function getBaseName() {
return $this->getFileSystem()->basename($this->getLocalPath());
}
/**
* @return string Extension of the media file
* @since 1.8.0
*/
public function getExtension() {
return $this->getFileSystem()->extension($this->getLocalPath());
}
/**
* @return string Mime type or empty string if mime type does not exist.
* @since 1.8.0
*/
public function getMimeType() {
$mimeType = $this->getFileSystem()->mimeType($this->getLocalPath());
return $mimeType ? $mimeType : '';
}
/**
* @return string MD5 hash of the file.
* @since 1.8.0
*/
public function getMD5Hash() {
return $this->getFileSystem()->hash($this->getLocalPath());
}
/**
* @return string A unique SHA1 string created by using {@link uniqid()} and the base name of the file
* @since 1.8.0
*/
public function getRandomUniqueHash() {
return sha1($this->getBaseName() . uniqid('wpcc'));
}
/**
* @return int File size in kilobytes.
* @since 1.8.0
*/
public function getFileSizeByte() {
return $this->getFileSize();
}
/**
* @return int File size in kilobytes.
* @since 1.8.0
*/
public function getFileSizeKb() {
return (int) ($this->getFileSize() / 1000);
}
/**
* @return int File size in megabytes.
* @since 1.8.0
*/
public function getFileSizeMb() {
return (int) ($this->getFileSize() / 1000000);
}
/**
* Rename the file.
*
* @param string $newName New name of the file. Without extension.
* @return bool True if the renaming was successful.
* @since 1.8.0
*/
public function rename($newName) {
$newName = FileService::getInstance()->validateFileName($newName);
// If there is no name after validation, assign a default name.
if (!$newName) $newName = 'no-name';
// If the new name is the same as the old name, stop by indicating success.
if ($newName === $this->getName()) return true;
// Rename the file
$newPath = $this->getUniqueFilePath($newName, $this->getDirectory());
$success = $this->move($newPath);
if (!$success) return false;
// If there are copies, rename them as well.
$copyFilePaths = $this->copyFilePaths;
// First, clear the copy file paths since we are gonna rename them.
$this->clearCopyFilePaths();
// Rename the copy files
foreach($copyFilePaths as $copyFilePath) {
// Get the directory of the copy file
$directoryPath = $this->getFileSystem()->dirname($copyFilePath);
// Get a unique name for the copy file in the same directory
$newCopyFilePath = $this->getUniqueFilePath($this->getName(), $directoryPath);
// Try to rename the file
if (@$this->getFileSystem()->move($copyFilePath, $newCopyFilePath)) {
// If renamed, store it.
$this->addCopyFilePath($newCopyFilePath);
// If testing, remove the old copy file path from test file paths.
MediaService::getInstance()->removeTestFilePath($copyFilePath);
} else {
// Otherwise, inform the user.
}
}
return $success;
}
/**
* @param string $newPath New path of the file
* @return bool True if the operation has been successful.
* @since 1.8.0
*/
public function move($newPath) {
$newPath = FileService::getInstance()->forceDirectorySeparator($newPath);
if (!$newPath) return false;
$result = @$this->getFileSystem()->move($this->getLocalPath(), $newPath);
// If the file was moved, set the new path.
if ($result) {
// If this is a test, remove the previous local path.
MediaService::getInstance()->removeTestFilePath($this->getLocalPath());
$this->setLocalPath($newPath);
} else {
// Otherwise, inform the user.
//File %1$s could not be moved to ... Need log
}
return $result;
}
/**
* @param string $newDirectoryPath New directory path
* @return bool True if the file has been successfully moved. Otherwise, false.
* @since 1.8.0
*/
public function moveToDirectory($newDirectoryPath) {
$newDirectoryPath = FileService::getInstance()->forceDirectorySeparator($newDirectoryPath);
if (!$newDirectoryPath) return false;
// Make sure the directories exist. If not, create them. Stop if they do not exist.
if (!$this->makeDirectory($newDirectoryPath)) return false;
// We now have the target directory created. Let's move the file to that directory.
return $this->move($newDirectoryPath . DIRECTORY_SEPARATOR . $this->getBaseName());
}
/**
* @param string $directoryPath Target directory path
* @return false|string False if the operation was not successful. Otherwise, copied file's path.
* @since 1.8.0
*/
public function copyToDirectory($directoryPath) {
$directoryPath = FileService::getInstance()->forceDirectorySeparator($directoryPath);
if (!$directoryPath) return false;
// Make sure the directories exist. If not, create them. Stop if they do not exist.
if (!$this->makeDirectory($directoryPath)) return false;
// Get the new name
$copyPath = $this->getUniqueFilePath($this->getName(), $directoryPath);
// Copy the file
$success = $this->getFileSystem()->copy($this->getLocalPath(), $copyPath);
// If the file is copied, store the copy file's path.
if ($success) $this->addCopyFilePath($copyPath);
return $success === false ? false : $copyPath;
}
/**
* Delete the local file.
*
* @return bool True if the file has been successfully deleted. Otherwise, false.
* @since 1.8.0
*/
public function delete() {
$result = $this->getFileSystem()->delete($this->getLocalPath());
if (!$result) {
// Inform the user if the file could not be deleted
//File xxx could not be deleted.
}
return $result;
}
/**
* Delete copies of the local file.
*
* @return bool True if all of the copy file have been deleted. Otherwise, false.
* @since 1.8.0
*/
public function deleteCopyFiles() {
if (!$this->copyFilePaths) return true;
$success = true;
// Delete a copy file
foreach($this->copyFilePaths as $copyPath) {
if (!$this->getFileSystem()->delete($copyPath)) {
$success = false;
// Inform the user if the file could not be deleted
//File xxx could not be deleted.
} else {
// If file is deleted and this is a test, remove the path from test file paths.
MediaService::getInstance()->removeTestFilePath($copyPath);
}
}
return $success;
}
/**
* Get URLs of the files that are copies of the file.
*
* @return array An array of copy file URLs
* @since 1.8.0
*/
public function getCopyFileUrls() {
if (!$this->copyFilePaths) return [];
$urls = [];
foreach($this->copyFilePaths as $filePath) {
$url = FileService::getInstance()->getUrlForPathUnderUploadsDir($filePath);
if (!$url) continue;
$urls[] = $url;
}
return $urls;
}
/**
* @return Filesystem
* @since 1.8.0
*/
public function getFileSystem() {
return FileService::getInstance()->getFileSystem();
}
/**
* Clear copy file paths.
*
* @since 1.8.0
*/
private function clearCopyFilePaths() {
// Clear the copy file paths
$this->copyFilePaths = [];
}
/**
* @return int Size of the file in bytes
* @since 1.8.0
*/
private function getFileSize() {
$size = $this->getFileSystem()->size($this->getLocalPath());
return $size ? $size : 0;
}
/**
* Get unique file path under a directory.
*
* @param string $fileName File name without extension
* @param string $directory Directory path. The file name will be unique to this directory.
* @return string Absolute file path that is unique to the given directory
* @since 1.8.0
*/
private function getUniqueFilePath($fileName, $directory) {
return FileService::getInstance()->getUniqueFilePath(
$fileName . '.' . $this->getExtension(),
$directory,
$this->getLocalPath()
);
}
/**
* @param string $directoryPath Directory or file path.
* @return bool True if the directories of the file or the given path exist.
* @since 1.8.0
*/
private function makeDirectory($directoryPath) {
// Get the directory path of the given path.
$directoryPath = rtrim(FileService::getInstance()->forceDirectorySeparator($directoryPath), DIRECTORY_SEPARATOR);
$directoryPath = strlen($this->getFileSystem()->extension($directoryPath)) ? $this->getFileSystem()->dirname($directoryPath) : $directoryPath;
// If the directories do not exist, create them.
if (!$this->getFileSystem()->isDirectory($directoryPath)) {
$result = $this->getFileSystem()->makeDirectory($directoryPath, 0755, true);
// Stop if the directories could not be created.
if (!$result) {
//xxx directory could not be created.
return false;
}
}
return true;
}
} | true |
54a3ed328822b298f6eefcfe1db7978f3037b93c | PHP | ercancavusoglu/zagoo | /src/backend/app/Repositories/Eloquent/WalletRepository.php | UTF-8 | 1,168 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Repositories\Eloquent;
use App\Constant\WalletDefinitions;
use App\Contract\Repository\WalletRepositoryInterface;
use App\Models\Wallet;
use App\Service\Modules\Register\Parameters\WalletParameters;
class WalletRepository extends BaseRepository implements WalletRepositoryInterface
{
/**
* WalletRepository constructor.
*
* @param Wallet $model
*/
public function __construct(Wallet $model)
{
parent::__construct($model);
}
public function invitingReward(WalletParameters $parameters)
{
return $this->create([
'user_id' => $parameters->getUser()->id,
'amount' => WalletDefinitions::INVITING_USER_REWARD_AMOUNT,
'description' => $parameters->getCode() . ' invite code has used'
]);
}
public function invitedReward(WalletParameters $parameters)
{
return $this->create([
'user_id' => $parameters->getUser()->id,
'amount' => WalletDefinitions::INVITED_USER_REWARD_AMOUNT,
'description' => $parameters->getCode() . ' invite code has used by ' . $parameters->getFrom()
]);
}
}
| true |
8a688f53579b39db1d997cc70b4c03d74e9c3cd1 | PHP | DeBoerTool/validator | /src/Abstracts/Multi.php | UTF-8 | 325 | 2.671875 | 3 | [
"MIT"
] | permissive | <?php declare(strict_types=1);
namespace Dbt\Validator\Abstracts;
abstract class Multi
{
/** @var array */
protected $validators = [];
protected function setValidators (array $validators): void
{
foreach ($validators as $validator) {
$this->validators[] = $validator;
}
}
}
| true |
ac6c067839a4887b4f4ec0a232a826dad8e1a7ba | PHP | rjw57/findsorguk | /app/modules/analytics/controllers/ContentController.php | UTF-8 | 5,640 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | <?php
/** Query the Google analytics api by content
*
* @author Daniel Pett <dpett@britishmuseum.org>
* @copyright (c) 2014 Daniel Pett
* @category Pas
* @package Controller_Action
* @subpackage Admin
* @license
* @version 1
*/
class Analytics_ContentController extends Pas_Controller_Action_Admin {
/** The maximum number of results
*
*/
const MAX_RESULTS = 20;
/** Initialise the variables
* @access public
*/
public function init(){
$this->_helper->Acl->allow(null);
$this->_ID = $this->_helper->config()->webservice->google->username;
$this->_pword = $this->_helper->config()->webservice->google->password;
}
/** Retrieve the page number
* @access public
* @return integer
*/
public function getPage() {
$page = $this->_getParam('page');
if(!isset($page)){
$start = 1;
} else {
$start = $page;
}
return $start;
}
/** Get the start number
* @access public
* @return integer
*/
public function getStart() {
$p = $this->getPage();
if(is_null($p) || $p == 1){
$start = 1;
} else {
$start = (self::MAX_RESULTS) * ($p - 1) + 1;
}
return $start;
}
/** The index view
* @access public
*/
public function indexAction() {
$this->_helper->redirector('overview');
}
/** An overview of data
* @access public
*/
public function overviewAction(){
$analytics = new Pas_Analytics_Gateway($this->_ID, $this->_pword);
$analytics->setProfile(25726058);
$timeframe = new Pas_Analytics_Timespan();
$timeframe->setTimespan($this->_getParam('timespan'));
$dates = $timeframe->getDates();
$analytics->setStart($dates['start']);
$analytics->setEnd($dates['end']);
$analytics->setMetrics(
array(
Zend_Gdata_Analytics_DataQuery::METRIC_VISITORS,
Zend_Gdata_Analytics_DataQuery::METRIC_PAGEVIEWS,
Zend_Gdata_Analytics_DataQuery::METRIC_UNIQUE_PAGEVIEWS,
Zend_Gdata_Analytics_DataQuery::METRIC_AVG_TIME_ON_PAGE,
Zend_Gdata_Analytics_DataQuery::METRIC_ENTRANCES,
Zend_Gdata_Analytics_DataQuery::METRIC_EXITS,
Zend_Gdata_Analytics_DataQuery::METRIC_BOUNCES
));
$analytics->setDimensions(
array(
Zend_Gdata_Analytics_DataQuery::DIMENSION_PAGE_TITLE,
Zend_Gdata_Analytics_DataQuery::DIMENSION_PAGE_PATH,
));
if(is_null($this->_getParam('filter'))){
$analytics->setFilters(
array(
Zend_Gdata_Analytics_DataQuery::DIMENSION_PAGE_PATH
. Zend_Gdata_Analytics_DataQuery::REGULAR_NOT . 'forum'
));
} else {
$analytics->setFilters(
array(
Zend_Gdata_Analytics_DataQuery::DIMENSION_PAGE_PATH
. Zend_Gdata_Analytics_DataQuery::REGULAR . '/'
. $this->_getParam('filter')
));
}
$analytics->setMax(20);
$analytics->setSort(Zend_Gdata_Analytics_DataQuery::METRIC_VISITORS);
$analytics->setSortDirection(true);
$analytics->setStartIndex($this->getStart());
$this->view->results = $analytics->getData();
$paginator = Zend_Paginator::factory((int)$analytics->getTotal());
$paginator->setCurrentPageNumber((int)$this->getPage())
->setItemCountPerPage((int)self::MAX_RESULTS);
$this->view->paginator = $paginator;
}
/** The page query
* @access public
* @throws Pas_Analytics_Exception
*/
public function pageAction() {
$analytics = new Pas_Analytics_Gateway($this->_ID, $this->_pword);
$analytics->setProfile(25726058);
$timeframe = new Pas_Analytics_Timespan();
$timeframe->setTimespan($this->_getParam('timespan'));
$dates = $timeframe->getDates();
$analytics->setStart($dates['start']);
$analytics->setEnd($dates['end']);
$analytics->setMetrics(
array(
Zend_Gdata_Analytics_DataQuery::METRIC_VISITORS,
Zend_Gdata_Analytics_DataQuery::METRIC_PAGEVIEWS,
Zend_Gdata_Analytics_DataQuery::METRIC_UNIQUE_PAGEVIEWS,
Zend_Gdata_Analytics_DataQuery::METRIC_AVG_TIME_ON_PAGE,
Zend_Gdata_Analytics_DataQuery::METRIC_ENTRANCES,
Zend_Gdata_Analytics_DataQuery::METRIC_EXIT_RATE,
Zend_Gdata_Analytics_DataQuery::METRIC_BOUNCES
));
$analytics->setDimensions(
array(
Zend_Gdata_Analytics_DataQuery::DIMENSION_PAGE_TITLE,
Zend_Gdata_Analytics_DataQuery::DIMENSION_PAGE_PATH,
));
if(is_null($this->_getParam('url'))){
throw new Pas_Analytics_Exception('A path must be set');
} else {
$analytics->setFilters(
array(
Zend_Gdata_Analytics_DataQuery::DIMENSION_PAGE_PATH
. Zend_Gdata_Analytics_DataQuery::EQUALS
. base64_decode(rawurldecode($this->_getParam('url')))
));
}
$analytics->setMax(20);
$analytics->setSort(Zend_Gdata_Analytics_DataQuery::METRIC_VISITORS);
$analytics->setSortDirection(true);
$this->view->results = $analytics->getData();
$this->view->total = (int)$analytics->getTotal();
$this->view->path = $this->_getParam('url');
}
}
| true |
1319883996673f89cb43345b5d001e004782fa64 | PHP | buidaoanhvan/php_module | /includes/database.php | UTF-8 | 2,026 | 2.671875 | 3 | [] | no_license | <?php
if (!defined('_BLOCK_DEFAULT')) header("Location: ./?module=errors&action=404");
function query($sql, $data = [], $status = 0)
{
global $conn;
$query = false;
$statement = null;
try {
$statement = $conn->prepare($sql);
if (!empty($data)) {
$query = $statement->execute($data);
} else {
$query = $statement->execute();
}
} catch (Exception $e) {
require_once 'modules/errors/404.php';
die();
}
if ($status == 1) {
return $statement;
}
return $query;
}
//Hàm thêm dữ liệu (tên bảng, dữ liệu cần thêm array)
function insert($table, $data)
{
$value = implode(', :', array_keys($data));
$key = str_replace(':', '', $value);
$sql = "INSERT INTO " . $table . " (" . $key . ") VALUES (:" . $value . ")";
return query($sql, $data);
}
//Hàm câp nhật dữ liệu theo id (tên bảng, dữ liệu cần thêm array , id)
function update($table, $data, $id)
{
$value = "";
foreach ($data as $key => $val) {
$value .= $key . ' = :' . $key . ', ';
}
$value = rtrim($value, ', ');
$data['id'] = $id;
$sql = "UPDATE " . $table . " SET " . $value . " WHERE id = :id";
return query($sql, $data);
}
//Hàm xoá dữ liệu theo id (tên bảng, dữ liệu cần thêm array , id)
function delete($table, $id)
{
$data['id'] = $id;
$sql = "DELETE FROM " . $table . " WHERE id = :id";
return query($sql, $data);
}
//Hàm lấy dữ liệu theo bảng $field = "name, phone"
function show($table, $field = '*', $sort = 'asc')
{
$sql = "SELECT " . $field . " FROM " . $table . " ORDER BY id " . $sort;
return query($sql, null, 1)->fetchAll(PDO::FETCH_ASSOC);
}
//Hàm check duy nhất
function checkOnlyField($table, $field, $data)
{
$sql = "SELECT $field FROM $table WHERE $field = '$data'";
$data = query($sql, null, 1)->fetchAll(PDO::FETCH_ASSOC);
if (empty($data)) {
return true;
}
return false;
} | true |
7c1857ac96f3550e6d4d58e9a71871fd53ca78ab | PHP | Infernosquad/stackoverflow-driven | /src/ContentBundle/EntityListener/PostListener.php | UTF-8 | 552 | 2.625 | 3 | [] | no_license | <?php
namespace ContentBundle\EntityListener;
use ContentBundle\Entity\Post;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Psr\Log\LoggerInterface;
class PostListener
{
/**
* @var LoggerInterface
*/
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function prePersist(Post $post, LifecycleEventArgs $event)
{
if($post->getTitle() == '...'){
$this->logger->info(sprintf('Strange post #%d',$post->getId()));
}
}
} | true |
7271af6e0ef0fb3b46fa2f2dffe558284e8984c1 | PHP | ThomasA92/PHP | /03 _POST/exercice.php | UTF-8 | 721 | 2.5625 | 3 | [] | no_license | <?php
// Exercice :
// - Créer un formulaire avec les champs ville, code postal et un textarea adresse.
// - Afficher les valeurs saisies par l'internaute dans la page exercice_traitement quand le formulaire a été envoyé.
print_r($_POST);
?>
<h1>Formulaire exercice</h1>
<form action="exercice_traitement.php" method="post">
<div><label for="ville">Ville</label></div>
<div><input type="text" name="ville" id="ville"></div>
<div><label for="codepostal">Code Postal</label></div>
<div><input type="text" name="codepostal" id="codepostal"></div>
<div><label for="adresse">Adresse</label></div>
<div><textarea name="adresse" id="adresse" ></textarea></div>
<div><input type="submit" value="envoyer"></div>
</form> | true |
7f42cbd4f4915a926dd6e464087e481fa58a211e | PHP | rupeshmohanty/Book-My-Room | /admin/dashboard/scripts/deleteBooking.php | UTF-8 | 758 | 2.59375 | 3 | [] | no_license | <?php
// include db connection!
include('../../../scripts/db.php');
// session start!
session_start();
// get id of the booking!
$bookingId = $_GET['id'];
if($bookingId != 0) {
// delete booking!
$deleteBooking = "DELETE FROM `bookings` WHERE `id` = '$bookingId'";
$deleteBookingStatus = mysqli_query($conn,$deleteBooking) or die(mysqli_error($conn));
if($deleteBookingStatus) {
header('Location: ../index.php?message=Booking deleted successfully!');
} else {
header('Location: ../index.php?message=Unable to delete booking!');
}
} else {
header('Location: ../index.php?message=Some error occured! Try Again later!');
}
?> | true |
c787d7ca1973e6c27e9f7b2460f6ed817afe3395 | PHP | lat1992/EasyAPI-Framework | /lib/Db/DbMysql.php | UTF-8 | 772 | 2.921875 | 3 | [
"MIT"
] | permissive | <?php
class Db {
private $sql;
function __construct($host, $username, $password, $database, $charset) {
$this->sql = new mysqli($host, $username, $password, $database);
$this->sql->set_charset($charset);
//$this->sql->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
$this->sql->autocommit(FALSE);
}
function __destruct() {
$this->sql->close();
}
public function exec($sql) {
return $this->sql->query($sql);
}
public function realEscapeString($str) {
return $this->sql->real_escape_string($str);
}
public function getInsertDb() {
return $this->sql->insert_id;
}
public function commit() {
return $this->sql->commit();
}
public function rollback() {
return $this->sql->rollback();
}
}
?> | true |
c46067d3c7d4d33c866b92a6bf7d50d246949a50 | PHP | JeongJunPark/MyGitHub | /procject_celib/model/TradeModel.php | UTF-8 | 10,780 | 2.515625 | 3 | [] | no_license | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
class TradeModel extends CI_Model {
public $tablename="trades";
public $pk_fieldname="id";
public function __construct()
{
parent::__construct();
// Your own constructor code
$this->db2 = $this->load->database('wz', TRUE);
$this->tablename="trades";
$this->pk_fieldname="id";
}
public function totalcount($search_query = ''){
$ret = 0;
$query = " select count(t.id) as count
from ".$this->tablename." as t
join virtual_accounts as va on va.holder = 'CELIB' AND t.virtual_account_id = va.id
left join users as u on va.user_id = u.id
where 1 " . $search_query;
$q = $this->db2->query($query);
if($q->num_rows() == 1) {
foreach ($q->result() as $row) {
$ret= $row->count;
}
}
return $ret;
}
public function get_list($start, $order, $per_page, $search_query = '' ){
$rows = null;
$limit_sql = " limit ".$start.", ".$per_page;
$data = array();
$query = " select t.id, t.user_id, u.name as user_name, u.phone as user_phone, t.virtual_account_id, va.number, va.bank_code , tr_il ,tr_si ,
t.contract_id, t.iacct_no, t.iacct_nm, t.tr_amt, case when t.trade_type=0 then 'default' when t.trade_type=1 then 'manual' end trade_type,
CONCAT (date_format(tr_il , '%Y-%m-%d') ,' ',SUBSTRING(tr_si ,1,2),':',SUBSTRING(tr_si ,3,2),':',SUBSTRING(tr_si ,5,2) ) as deposit_time
from ".$this->tablename." as t
join virtual_accounts as va on va.holder = 'CELIB' AND t.virtual_account_id = va.id
left join users as u on va.user_id = u.id
where 1 " . $search_query . "
order by ".$order. $limit_sql;
$q = $this->db2->query($query);
if($q->num_rows() >= 1) {
$rows = array();
foreach ($q->result() as $row) {
$trade = array(
"id"=> $row->id,
"iacct_no"=> $row->iacct_no,
"iacct_nm"=> $row->iacct_nm,
"tr_amt"=> $row->tr_amt,
"trade_type"=> $row->trade_type,
"deposit_time"=> $row->deposit_time,
"contract_id"=> $row->contract_id,
"user_id"=> $row->user_id,
"user_name"=> $row->user_name,
"user_phone"=> $row->user_phone,
"number"=>$row->number
);
array_push($rows, $trade);
}
}else if($q->num_rows() ==1 ) {
//$rows =$q->result();
foreach ($q->result() as $row) {
$trade = array(
"id"=> $row->id,
"iacct_no"=> $row->iacct_no,
"iacct_nm"=> $row->iacct_nm,
"tr_amt"=> $row->tr_amt,
"trade_type"=> $row->trade_type,
"deposit_time"=> $row->deposit_time,
"contract_id"=> $row->contract_id,
"user_name"=> $row->user_name,
"user_phone"=> $row->user_phone,
"number"=>$row->number
);
$rows = $trade;
}
}
return $rows;
}
/*
* $vanumber : 계좌번호
* $iacctnm : 입금자명
* $username : 입주자명
*/
public function totalcount_search_by_vanumber_iacctnm_username($vanumber, $iacctnm, $username){
$ret = 0;
$query = " select count(trades.id) as count from trades join virtual_accounts on virtual_accounts.holder = 'CELIB' AND trades.virtual_account_id = virtual_accounts.id";
if($username != null && strlen($username) > 0){
$query .= " join users on users.name like '%".$username."%' and trades.user_id = users.id ";
}
if($vanumber != null && strlen($vanumber) > 0){
$query .= " join virtual_accounts on virtual_accounts.number like '%".$vanumber."%' and trades.virtual_account_id = virtual_accounts.id ";
}
$base_where = '';
if($vanumber != null && strlen($vanumber) > 0){
$base_where .= " where virtual_accounts.number like '%".$vanumber."%' ";
}
if($iacctnm != null && strlen($iacctnm) > 0){
$base_where .= (empty($base_where)?" where ": " and "). " trades.iacct_nm like '%".$iacctnm."%' ";
}
$q = $this->db2->query($query.$base_where);
if($q->num_rows() == 1) {
foreach ($q->result() as $row) {
$ret= $row->count;
}
}
return $ret;
}
/*
* $vanumber : 계좌번호
* $iacctnm : 입금자명
* $username : 입주자명
*/
public function search_by_vanumber_iacctnm_username($page, $order , $per_page, $vanumber, $iacctnm, $username){
$base_table = "(select trades.* from trades join virtual_accounts on virtual_accounts.holder = 'CELIB' AND trades.virtual_account_id = virtual_accounts.id";
if($order!=null && (strcasecmp($order,"user.name ASC")==0 || strcasecmp($order,"user.name DESC")==0) ){
$base_table = "(select trades.*,users.name user_name from trades ";
}
if($username != null && strlen($username) > 0){
$base_table .= " join users on users.name like '%".$username."%' and trades.user_id = users.id ";
}else if($order!=null && (strcasecmp($order,"user.name ASC")==0 || strcasecmp($order,"user.name DESC")==0) ) {
$base_table .= " left outer join users on trades.user_id = users.id ";
}
$base_where = '';
if($vanumber != null && strlen($vanumber) > 0){
$base_where .= " where virtual_accounts.number like '%".$vanumber."%' ";
}
if($iacctnm != null && strlen($iacctnm) > 0){
$base_where .= (empty($base_where)?" where ": " and "). " trades.iacct_nm like '%".$iacctnm."%' ";
}
$base_table .= $base_where . " ) trades ";
return $this->get_list_exec($page, $order , $per_page , $base_table );
}
public function get_list_exec($page, $order , $per_page , $base_table ){
$rows = null;
$orderby_sql=" use index (index_trades_idx1) order by tr_il desc , tr_si desc ";
$orderby_last=" order by deposit_time desc ";
if($order!=null && strcasecmp($order,"id ASC")==0 ) {
$orderby_sql=" order by trades.id asc";
$orderby_last=" order by id asc ";
}
if($order!=null && strcasecmp($order,"id DESC")==0 ) {
$orderby_sql=" order by trades.id desc";
$orderby_last=" order by id desc ";
}
if($order!=null && strcasecmp($order,"iacct_no ASC")==0 ) {
$orderby_sql=" order by trades.iacct_no asc";
$orderby_last=" order by iacct_no asc ";
}
if($order!=null && strcasecmp($order,"iacct_no DESC")==0 ) {
$orderby_sql=" order by trades.iacct_no desc";
$orderby_last=" order by iacct_no desc ";
}
if($order!=null && strcasecmp($order,"iacct_nm ASC")==0 ) {
$orderby_sql=" order by trades.iacct_nm asc";
$orderby_last=" order by iacct_nm asc ";
}
if($order!=null && strcasecmp($order,"iacct_nm DESC")==0 ) {
$orderby_sql=" order by trades.iacct_nm desc";
$orderby_last=" order by iacct_nm desc ";
}
if($order!=null && strcasecmp($order,"user.name ASC")==0 ) {
$orderby_sql=" order by user_name asc";
$orderby_last=" order by user_name asc ";
}
if($order!=null && strcasecmp($order,"user.name DESC")==0 ) {
$orderby_sql=" order by user_name desc";
$orderby_last=" order by user_name desc ";
}
if($order!=null && strcasecmp($order,"tr_amt ASC")==0 ) {
$orderby_sql=" order by trades.tr_amt asc";
$orderby_last=" order by tr_amt asc ";
}
if($order!=null && strcasecmp($order,"tr_amt DESC")==0 ) {
$orderby_sql=" order by trades.tr_amt desc";
$orderby_last=" order by tr_amt desc ";
}
if($order!=null && strcasecmp($order,"deposit_time ASC")==0 ) {
$orderby_sql=" order by trades.tr_il asc, trades.tr_si asc";
$orderby_last=" order by deposit_time asc ";
}
if($order!=null && strcasecmp($order,"deposit_time DESC")==0 ) {
$orderby_sql=" order by trades.tr_il desc, trades.tr_si desc";
$orderby_last=" order by deposit_time desc ";
}
$limit_sql=" limit ".$per_page;
if($page > 1 ) $limit_sql .= " limit ".(($page-1)*$per_page).", ".$per_page ;
$data = array();
$query ="select * from ( ".
" SELECT trades.id, trades.user_id, users.name as user_name, users.phone as user_phone, trades.virtual_account_id, virtual_accounts.number, virtual_accounts.bank_code , tr_il ,tr_si , ".
" trades.contract_id, trades.iacct_no, trades.iacct_nm, trades.tr_amt, case when trades.trade_type=0 then 'defalt' when trades.trade_type=1 then 'manual' end trade_type, ".
" CONCAT (date_format(tr_il , '%Y-%m-%d') ,' ',SUBSTRING(tr_si ,1,2),':',SUBSTRING(tr_si ,3,2),':',SUBSTRING(tr_si ,5,2) ) as deposit_time ".
" FROM ( ".
" select trades.* from ( SELECT trades.id FROM ".$base_table." ".$orderby_sql." ".$limit_sql." ) b ".
" join trades on b.id= trades.id ".
" ) trades ".
" left outer join users on trades.user_id = users.id ".
" left outer join virtual_accounts on trades.virtual_account_id = virtual_accounts.id ".
" ) a ".
" left outer join bank_code_map on a.bank_code = bank_code_map.code " ;
$query .= $orderby_last;
$q = $this->db2->query($query);
if($q->num_rows() >= 1) {
$rows = array();
foreach ($q->result() as $row) {
$trade = array(
"id"=> $row->id,
"iacct_no"=> $row->iacct_no,
"iacct_nm"=> $row->iacct_nm,
"tr_amt"=> $row->tr_amt,
"trade_type"=> $row->trade_type,
"deposit_time"=> $row->deposit_time,
"contract_id"=> $row->contract_id,
"user_id"=> $row->user_id,
"user"=> array( "id"=> $row->user_id,"name"=> $row->user_name, "phone" => $row->user_phone ) ,
"virtual_account"=>array("id"=> $row->virtual_account_id,"number"=> $row->number, "bank"=>$row->bank_name )
);
array_push($rows, $trade);
}
}else if($q->num_rows() ==1 ) {
//$rows =$q->result();
foreach ($q->result() as $row) {
$trade = array(
"id"=> $row->id,
"iacct_no"=> $row->iacct_no,
"iacct_nm"=> $row->iacct_nm,
"tr_amt"=> $row->tr_amt,
"trade_type"=> $row->trade_type,
"deposit_time"=> $row->deposit_time,
"contract_id"=> $row->contract_id,
"user"=> array( "id"=> $row->user_id,"name"=> $row->user_name, "phone" => $row->user_phone ) ,
"virtual_account"=>array("id"=> $row->virtual_account_id,"number"=> $row->number, "bank"=>$row->bank_name )
);
$rows = $trade;
}
}
return $rows;
}
}
| true |
786cd9f0c7c141d5cd50c4343d2966ccac0b82f6 | PHP | expouic/sapphire | /forms/GridField.php | UTF-8 | 3,755 | 3 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/**
* Displays a {@link SS_List} in a grid format.
*
* GridFIeld is a field that takes an SS_List and displays it in an table with rows
* and columns. It reminds of the old TableFields but works with SS_List types
* and only loads the necessary rows from the list.
*
* The minimum configuration is to pass in name and title of the field and a
* SS_List.
*
* <code>
* $gridField = new GridField('ExampleGrid', 'Example grid', new DataList('Page'));
* </code>
*
* If you want to modify the output of the grid you can attach a customised
* DataGridPresenter that are the actual Renderer of the data. Sapphire provides
* a default one if you chooses not to.
*
* @see GridFieldPresenter
* @see SS_List
*
* @package sapphire
* @subpackage forms
*/
class GridField extends FormField {
/**
* @var SS_List
*/
protected $list = null;
/**
* @var string
*/
protected $presenterClassName = "GridFieldPresenter";
/**
* @var GridFieldPresenter
*/
protected $presenter = null;
/**
* @var string - the classname of the DataObject that the GridField will display
*/
protected $modelClassName = '';
/**
* Url handlers
*
* @var array
*/
public static $url_handlers = array(
'$Action' => '$Action',
);
/**
* Creates a new GridField field
*
* @param string $name
* @param string $title
* @param SS_List $dataList
* @param Form $form
* @param string|GridFieldPresenter $dataPresenterClassName - can either pass in a string or an instance of a GridFieldPresenter
*/
public function __construct($name, $title = null, SS_List $dataList = null, Form $form = null, $dataPresenterClassName = 'GridFieldPresenter') {
parent::__construct($name, $title, null, $form);
if ($dataList) {
$this->setList($dataList);
}
$this->setPresenter($dataPresenterClassName);
}
/**
*
* @return string - HTML
*/
public function index() {
return $this->FieldHolder();
}
/**
* @param string $modelClassName
*/
public function setModelClass($modelClassName) {
$this->modelClassName = $modelClassName;
return $this;
}
/**
* @throws Exception
* @return string
*/
public function getModelClass() {
if ($this->modelClassName) {
return $this->modelClassName;
}
if ($this->list->dataClass) {
return $this->list->dataClass;
}
throw new Exception(get_class($this).' does not have a modelClassName');
}
/**
* @param string|GridFieldPresenter
*
* @throws Exception
*/
public function setPresenter($presenter) {
if(!$presenter){
throw new Exception('setPresenter() for GridField must be set with a class');
}
if(is_object($presenter)) {
$this->presenter = $presenter;
$this->presenter->setGridField($this);
return;
}
if(!class_exists($presenter)){
throw new Exception('DataPresenter for GridField must be set with an existing class, '.$presenter.' does not exists.');
}
if($presenter !='GridFieldPresenter' && !ClassInfo::is_subclass_of($presenter, 'GridFieldPresenter')) {
throw new Exception(sprintf(
'DataPresenter "%s" must subclass GridFieldPresenter', $presenter
));
}
$this->presenter = new $presenter;
$this->presenter->setGridField($this);
return $this;
}
/**
* @return GridFieldPresenter
*/
public function getPresenter(){
return $this->presenter;
}
/**
* Set the datasource
*
* @param SS_List $list
*/
public function setList(SS_List $list) {
$this->list = $list;
return $this;
}
/**
* Get the datasource
*
* @return SS_List
*/
public function getList() {
return $this->list;
}
/**
* @return string - html for the form
*/
function FieldHolder() {
return $this->getPresenter()->render();
}
}
| true |
fb69492331ef8bcf3896f8b108d4e7e814522158 | PHP | nanbando/core | /src/Core/Server/Command/Ssh/SshGetCommand.php | UTF-8 | 2,859 | 2.8125 | 3 | [
"MIT"
] | permissive | <?php
namespace Nanbando\Core\Server\Command\Ssh;
use Nanbando\Core\Server\Command\CommandInterface;
use Nanbando\Core\Storage\StorageInterface;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ChoiceQuestion;
/**
* Get a backup from a ssh connected server.
*/
class SshGetCommand implements CommandInterface
{
/**
* @var SshConnection
*/
private $connection;
/**
* @var StorageInterface
*/
private $storage;
/**
* @var OutputInterface
*/
private $output;
/**
* @param SshConnection $connection
* @param StorageInterface $storage
* @param OutputInterface $output
*/
public function __construct(SshConnection $connection, StorageInterface $storage, OutputInterface $output)
{
$this->connection = $connection;
$this->storage = $storage;
$this->output = $output;
}
/**
* {@inheritdoc}
*/
public function interact(InputInterface $input, OutputInterface $output)
{
if ($input->getArgument('name')) {
return;
}
$files = [];
$this->connection->executeNanbando(
'list:backups',
[],
function ($line) use (&$files) {
if (empty($line) || $line === "\n") {
return;
}
$files[] = $line;
}
);
if ($input->getOption('latest') && count($files) > 0) {
return $input->setArgument('name', end($files));
} elseif (count($files) === 1) {
return $input->setArgument('name', $files[0]);
}
$helper = new QuestionHelper();
$question = new ChoiceQuestion('Which backup', $files);
$question->setErrorMessage('Backup %s is invalid.');
$question->setAutocompleterValues([]);
$input->setArgument('name', $helper->ask($input, $output, $question));
$output->writeln('');
}
/**
* {@inheritdoc}
*/
public function execute(array $options = [])
{
$name = $options['name'];
$information = $this->connection->executeNanbando('information', [$name]);
$this->output->writeln($information);
preg_match('/path:\s*(?<path>\/([^\/\0]+(\/)?)+)\n/', $information, $matches);
$remotePath = $matches['path'];
$localPath = $this->storage->path($name);
$this->output->writeln(PHP_EOL . '$ scp ' . $remotePath . ' ' . $localPath);
// Try to display progress somehow.
$this->connection->get($remotePath, $localPath);
$this->output->writeln(PHP_EOL . sprintf('Backup "%s" downloaded successfully', $name));
return $name;
}
}
| true |
31e102973ed9bc96710e2cea84362850a9c1716e | PHP | kdambekalns/ApiGen | /src/Generator/NamespaceGenerator.php | UTF-8 | 2,761 | 2.6875 | 3 | [
"MIT"
] | permissive | <?php declare(strict_types=1);
namespace ApiGen\Generator;
use ApiGen\Configuration\Configuration;
use ApiGen\Contract\Generator\GeneratorInterface;
use ApiGen\Element\ReflectionCollector\NamespaceReflectionCollector;
use ApiGen\Templating\TemplateRenderer;
final class NamespaceGenerator implements GeneratorInterface
{
/**
* @var Configuration
*/
private $configuration;
/**
* @var TemplateRenderer
*/
private $templateRenderer;
/**
* @var NamespaceReflectionCollector
*/
private $namespaceReflectionCollector;
public function __construct(
NamespaceReflectionCollector $namespaceReflectionCollector,
Configuration $configuration,
TemplateRenderer $templateRenderer
) {
$this->namespaceReflectionCollector = $namespaceReflectionCollector;
$this->configuration = $configuration;
$this->templateRenderer = $templateRenderer;
}
public function generate(): void
{
foreach ($this->namespaceReflectionCollector->getNamespaces() as $namespace) {
$this->generateForNamespace($namespace, $this->namespaceReflectionCollector);
}
}
private function generateForNamespace(
string $namespace,
NamespaceReflectionCollector $namespaceReflectionCollector
): void {
$this->templateRenderer->renderToFile(
$this->configuration->getTemplateByName('namespace'),
$this->configuration->getDestinationWithPrefixName('namespace-', $namespace),
[
'activePage' => 'namespace',
'activeNamespace' => $namespace,
'childNamespaces' => $this->resolveChildNamespaces($namespace),
'classes' => $namespaceReflectionCollector->getClassReflections($namespace),
'exceptions' => $namespaceReflectionCollector->getExceptionReflections($namespace),
'interfaces' => $namespaceReflectionCollector->getInterfaceReflections($namespace),
'traits' => $namespaceReflectionCollector->getTraitReflections($namespace),
'functions' => $namespaceReflectionCollector->getFunctionReflections($namespace),
]
);
}
/**
* @return string[]
*/
private function resolveChildNamespaces(string $namespace): array
{
$prefix = $namespace . '\\';
$len = strlen($prefix);
$namespaces = [];
foreach ($this->namespaceReflectionCollector->getNamespaces() as $sub) {
if (substr($sub, 0, $len) === $prefix
&& strpos(substr($sub, $len), '\\') === false
) {
$namespaces[] = $sub;
}
}
return $namespaces;
}
}
| true |
f4fa8c3f2219ba324abf8407e679e27579a58252 | PHP | jaCUBE/roomba-test | /app/models/Roomba.class.php | UTF-8 | 1,357 | 3.09375 | 3 | [] | no_license | <?php
/**
* Glorious Roomba.
* @class Roomba
* @author Jakub Rychecký <jakub@rychecky.cz>
*/
class Roomba
{
/**
* @var Navigator $navigator Roomba's sense in the room
*/
public $navigator;
/**
* @var Battery $battery Roomba battery
*/
public $battery;
/**
* @var Commander Queue for Roomba commands
*/
public $commander;
/**
* @var Recorder $recorder Recorder for Roomba history
*/
public $recorder;
/**
* Roomba constructor.
* @param Commander $commander Commander for Roomba
* @param Navigator $navigator Navigator with map inside for roomba
* @param Battery $battery Battery for Roomba
*/
public function __construct(Commander $commander, Navigator $navigator, Battery $battery)
{
$this->commander = $commander;
$this->navigator = $navigator;
$this->battery = $battery;
// Initialize recorder with the first record
$this->recorder = new Recorder();
$this->record('START');
}
/**
* Makes one record for executed command.
* @param string $command Executed command
* @param bool $hit Roomba hit the wall?
* @return void
*/
public function record(string $command, bool $hit = false): void
{
$this->recorder->addRecord($command, $this, $hit);
}
} | true |
9858219c17fc6a4e2de6fafa4f8f536ff1175e89 | PHP | reyhannaufal/Cariin | /app/Http/Controllers/ThreadController.php | UTF-8 | 3,071 | 2.59375 | 3 | [] | no_license | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Thread;
class ThreadController extends Controller
{
public function index()
{
$threads = Thread::all();
return response()->json([
'success' => true,
'threads' => $threads
]);
}
public function show($id)
{
$thread = Thread::find($id);
if (!$thread) {
return response()->json([
'success' => false,
'message' => 'Thread not found'
], 404);
}
return response()->json([
'success' => true,
'thread' => $thread->toArray()
], 200);
}
public function store(Request $request)
{
$this->validate($request, [
'content' => 'required',
'team_id' => 'required',
]);
$thread = new Thread();
$thread->content = $request->content;
$thread->team_id = $request->team_id;
if (auth()->user()->threads()->save($thread)) {
return response()->json([
'success' => true,
'thread' => $thread->toArray()
]);
}
else {
return response()->json([
'success' => false,
'message' => 'Thread not added'
], 500);
}
}
public function update(Request $request, $id)
{
$threads = auth()->user()->threads()->find($id);
if (!$threads) {
return response()->json([
'success' => false,
'message' => 'Thread not found'
], 404);
}
$updated = $threads->fill($request->all())->save();
if ($updated){
return response()->json([
'success' => true
]);
}
else {
return response()->json([
'success' => false,
'message' => 'Thread can not be updated'
], 500);
}
}
public function delete($id)
{
$threads = auth()->user()->threads()->find($id);
if (!$threads) {
return response()->json([
'success' => false,
'message' => 'Thread not found'
], 404);
}
if ($threads->delete()) {
return response()->json([
'success' => true
]);
} else {
return response()->json([
'success' => false,
'message' => 'Thread can not be deleted'
], 500);
}
}
public function repliesById($id)
{
$thread = Thread::find($id);
if (!$thread) {
return response()->json([
'success' => false,
'message' => 'Thread not found'
], 404);
}
$replies = $thread->replies()->get();
return response()->json([
'success' => true,
'replies' => $replies
], 200);
}
}
| true |
b045904c61392711a007caccc66b8f3b0e356faa | PHP | khandu-shivam/crud | /taskview.php | UTF-8 | 1,163 | 2.640625 | 3 | [] | no_license | <!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
</head>
<body>
<?php
include 'dbcon.php';
$id=$_GET['id'];
$data="select * from task where id=$id";
$result=mysqli_query($con,$data);
$entry=mysqli_fetch_array($result);
// print_r($entry);
?>
<table class="table table-striped table-bordered">
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Address</th>
<th>City</th>
<th>Pincode</th>
<th>College</th>
<th>Department</th>
<th>Branch</th>
<th>Semester</th>
</tr>
<tr>
<td> <?php echo $entry['id'] ?> </td>
<td><?php echo $entry['name'] ?></td>
<td><?php echo $entry['email'] ?></td>
<td> <?php echo $entry['phone'] ?></td>
<td> <?php echo $entry['address'] ?></td>
<td> <?php echo $entry['city'] ?></td>
<td> <?php echo $entry['pincode'] ?></td>
<td> <?php echo $entry['college'] ?></td>
<td> <?php echo $entry['department'] ?></td>
<td> <?php echo $entry['branch'] ?></td>
<td> <?php echo $entry['semester'] ?></td>
</tr>
</body>
</html> | true |
b337a8abb3e86e6b1d09b3e427d60d4889eb2a93 | PHP | michalSolarz/symfony-shop | /src/AppBundle/Model/BackendProductSearch/StringCondition.php | UTF-8 | 835 | 2.84375 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: michal
* Date: 07.07.16
* Time: 07:11
*/
namespace AppBundle\Model\BackendProductSearch;
/**
* Class StringCondition
* @package AppBundle\Model
*/
class StringCondition implements SearchConditionInterface
{
/**
* @var string
*/
private $value;
/**
* StringCondition constructor.
* @param $value
*/
public function __construct($value)
{
$this->value = trim((string)$value);
}
/**
* @return bool
*/
public function conditionExists()
{
if (is_null($this->value))
return false;
if (!(strlen($this->value) > 0))
return false;
return true;
}
/**
* @return string
*/
public function getValue()
{
return $this->value;
}
} | true |
d7e2fb9ff98c264f796f73fd44be95cd47b62ac1 | PHP | pablojc12/Dog | /assets/server/uploadImagen.php | UTF-8 | 2,970 | 2.609375 | 3 | [] | no_license | <?php
require_once 'conection.php';
// Tiempo de espera del script
// Este lo usamos para emular mas o menos el comportamiento en un servidor web no local
// Ya que muchas veces al ejecutarlo de fomra local no se aprecia bien el funcionamiento.
//sleep(3);
// ini_set("display_errors", 1);
// Definimos variables generales
define("maxUpload", 1000500);
define("maxWidth", 1000);
define("maxHeight", 1000);
define("uploadURL", '../../images/upload/');
define("fileName", 'foto_');
// Tipos MIME
$fileType = array('image/jpeg', 'image/pjpeg', 'image/png');
// Bandera para procesar imagen
$pasaImgSize = false;
//bandera de error al procesar la imagen
$respuestaFile = false;
// nombre por default de la imagen a subir
$fileName = '';
// error del lado del servidor
$mensajeFile = 'ERROR EN EL SCRIPT';
// Obtenemos los datos del archivo
$tamanio = $_FILES['userfile']['size'];
$tipo = $_FILES['userfile']['type'];
$tmpImage = $_FILES['userfile']['tmp_name'];
// Tamaño de la imagen
$imageSize = getimagesize($_FILES['userfile']['tmp_name']);
// Verificamos la extension del archivo independiente del tipo mime
$extension = explode('.', $_FILES['userfile']['name']);
$num = count($extension) - 1;
// Creamos el nombre del archivo dependiendo la opcion
$imgFile = fileName . time() . '.' . $extension[$num];
// Verificamos el tamaño valido para los logotipos
if ($imageSize[0] <= maxWidth && $imageSize[1] <= maxHeight) {
$pasaImgSize = true;
}
// Verificamos el status de las dimensiones de la imagen a publicar
if ($pasaImgSize == true) {
// Verificamos Tamamo y extensiones
if (in_array($tipo, $fileType) && $tamanio > 0 && $tamanio <= maxUpload && ($extension[$num] == 'jpg' || $extension[$num] == 'png')) {
// Intentamos copiar el archivo
if (is_uploaded_file($tmpImage)) {
$ruta = uploadURL . $imgFile;
if (move_uploaded_file($tmpImage, $ruta)) {
$respuestaFile = 'done';
$fileName = $imgFile;
$mensajeFile = $imgFile;
} else {
// error del lado del servidor
$mensajeFile = 'No se pudo subir el archivo 1';
}
} else {
// error del lado del servidor
$mensajeFile = 'No se pudo subir el archivo 2';
}
} else {
// Error en el tamaño y tipo de imagen
$mensajeFile = 'Verifique el tamaño y tipo de imagen';
}
} else {
// Error en las dimensiones de la imagen
$mensajeFile = 'Verifique las dimensiones de la Imagen';
}
$salidaJson = array("respuesta" => $respuestaFile,
"mensaje" => $mensajeFile,
"fileName" => $fileName);
echo json_encode($salidaJson);
| true |
f8f362dc723abbc7a9becaba3aa80bb4efdc8af0 | PHP | netninja-scott/team-a | /src/TeamA/API/PlaxitudeBot.php | UTF-8 | 3,912 | 3.078125 | 3 | [] | no_license | <?php
namespace Netninja\TeamA\API;
use Netninja\TeamA\CommonAPI;
/**
* Class PlaxitudeBot
* @package Netninja\TeamA\API
*/
class PlaxitudeBot extends CommonAPI
{
/**
* @route /
*/
public function index()
{
$this->jsonResponse([
[
'method' =>
'GET',
'uri' =>
'/',
'description' =>
'API Summary',
'parameters' => []
],
[
'method' =>
'GET',
'uri' =>
'/send',
'description' =>
'Send a random plaxitude',
'parameters' => [
[
'name' =>
'name',
'type' =>
'string',
'required' =>
true,
'description' =>
'The name of the person to send a plaxitude. Magic value ("everybody") will send one to everybody.'
],
[
'name' =>
'category',
'type' =>
'string',
'required' =>
true,
'description' =>
'One of the following: SPORTS, EARLY YEARS, JOKES, KIDS'
]
]
]
]);
}
/**
* This is just a dummy Twilio callback.
*
* @route /callback
*/
public function callback()
{
$this->jsonResponse([
'ok' => true
]);
}
/**
* @route /send
*/
public function send()
{
try {
if (empty($_GET['name'])) {
$this->jsonResponse([
'ok' => false,
'error' => 'Parameter not passed: name'
]);
}
if (empty($_GET['category'])) {
/*
$this->jsonResponse([
'ok' => false,
'error' => 'Parameter not passed: category'
]);
*/
$_GET['category'] = $this->getRandomPlaxitudeCategory();
}
if (\is_array($_GET['name'])) {
$this->jsonResponse([
'ok' => false,
'error' => 'Parameter "name" cannot be an array.'
]);
}
if (\is_array($_GET['categoy'])) {
$this->jsonResponse([
'ok' => false,
'error' => 'Parameter "category" cannot be an array.'
]);
}
$this->handleSend($_GET['name'], $_GET['category']);
} catch (\Exception $ex) {
$this->jsonResponse([
'ok' => false,
'error' => $ex->getMessage()
]);
}
}
/**
* @param string $name
* @param string $category
*/
protected function handleSend($name = '', $category = '')
{
// MAGIC VALUE: SEND EVERYONE SOMETHING
$results = [];
if (\strtolower($name) === 'everyone') {
foreach ($this->getAllUsers() as $user) {
$results []= $this->sendPlaxitude(
$user,
$this->getRandomPlaxitude($category)
);
}
} else {
$results []= $this->sendPlaxitude(
$name,
$this->getRandomPlaxitude($category)
);
}
$this->jsonResponse(
[
'ok' => true,
'results' => $results
]
);
}
}
| true |
001d7b43c3d909fb5f3a0058f29b37fc0cac9178 | PHP | INET2005ITC2015/inet2005-fh | /inet2005Lab4 /rectangle.php | UTF-8 | 203 | 2.8125 | 3 | [] | no_license | <?php
abstract class rectangle extends shapes
{
var $width;
var $length;
var $name = 'rectangle';
function calculateSize()
{
$area = ($this->width * $this->length);
return $area;
}
} | true |
9ebc8ff65160537ccd2f1970fb4f5540212b1d1c | PHP | grateja/els-csi-offline_sync-v6 | /yii-ELS/framework/cli/views/webapp/protected/models/AccountTypes.php | UTF-8 | 7,822 | 2.65625 | 3 | [] | no_license | <?php
/**
* This is the model class for table "account_types".
*
* The followings are the available columns in table 'account_types':
* @property integer $id
* @property string $created_at
* @property string $updated_at
* @property string $name
* @property string $landing_module
* @property string $landing_controller
* @property string $landing_action
* @property integer $is_deleted
*/
class AccountTypes extends CActiveRecord {
protected $oldAttributes;
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'account_types';
}
public static function tbl()
{
return self::tableName();
}
public function beforeSave()
{
if ($this->isNewRecord)
$this->created_at = Settings::get_DateTime();
else
$this->updated_at = Settings::get_DateTime();
$changedArray = array_diff_assoc($this->attributes, $this->oldAttributes);
foreach ($changedArray as $key => $value) {
if (strcmp($key, 'updated_at'))
AuditTrails::newRecord(AuditTrails::TRANS_TYPE_UPDATE, self::tbl(), $key, $this->attributes['id'], $this->oldAttributes[$key], $value, Settings::get_UserID(), Settings::get_EmployeeID());
}
return parent::beforeSave();
}
public function afterFind()
{
$this->oldAttributes = $this->attributes;
return parent::afterFind();
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('created_at, name, landing_module, landing_controller, landing_action', 'required'),
array('is_deleted', 'numerical', 'integerOnly' => true),
array('name', 'length', 'max' => 255),
array('updated_at', 'safe'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, created_at, updated_at, name, landing_module, landing_controller, landing_action, is_deleted', 'safe', 'on' => 'search'),
array('id, created_at, updated_at, name, landing_module, landing_controller, landing_action, is_deleted', 'safe', 'on' => 'searchAdmin'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'created_at' => 'Date Created',
'updated_at' => 'Last Modified',
'name' => 'Name',
'landing_module' => 'Landing Module',
'landing_controller' => 'Landing Controller',
'landing_action' => 'Landing Action',
'is_deleted' => 'Is Deleted',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria = new CDbCriteria;
$criteria->compare('id', $this->id);
$criteria->compare('created_at', $this->created_at, true);
$criteria->compare('updated_at', $this->updated_at, true);
$criteria->compare('name', $this->name, true);
$criteria->compare('landing_module', $this->landing_module, true);
$criteria->compare('landing_controller', $this->landing_controller, true);
$criteria->compare('landing_action', $this->landing_action, true);
$criteria->compare('is_deleted', $this->is_deleted);
return new CActiveDataProvider('AccountTypes', array(
'criteria' => $criteria,
'pagination' => array(
'pageSize' => 18,
)
));
}
public function searchAdmin()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria = new CDbCriteria;
$criteria->compare('t.id', $this->id);
$criteria->compare('t.created_at', $this->created_at, true);
$criteria->compare('t.updated_at', $this->updated_at, true);
$criteria->compare('t.name', $this->name, true);
$criteria->compare('t.landing_module', $this->landing_module, true);
$criteria->compare('t.landing_controller', $this->landing_controller, true);
$criteria->compare('t.landing_action', $this->landing_action, true);
$criteria->compare('t.is_deleted', $this->is_deleted);
return new CActiveDataProvider('AccountTypes', array(
'criteria' => $criteria,
'pagination' => array(
'pageSize' => 18,
)
));
}
/**
* Returns the static model of the specified AR class.
* @return AccountTypes the static model class
*/
public static function model($className = __CLASS__)
{
return parent::model($className);
}
function getIsDeleted()
{
return Utilities::get_ActiveSelect($this->is_deleted);
}
public static function model_getData_byIsDeleted($isDeleted)
{
return self::model()->findAll('is_deleted = :isDeleted', array(':isDeleted' => $isDeleted));
}
public static function model_getData_byAccountTypeId($id)
{
return self::model()->findAll('id = :id', array(':id' => $id));
}
public static function model_getAllData_byDeleted($isDeleted)
{
return self::model()->findAll('is_deleted = :isDeleted', array(':isDeleted' => $isDeleted));
}
public static function setClassActive($value = null)
{
$_SESSION[self::tbl()]['classActive'] = $value;
}
public static function getClassActive()
{
return $_SESSION[self::tbl()]['classActive'];
}
public static function setClassOpen($value = null)
{
$_SESSION[self::tbl()]['classOpen'] = $value;
}
public static function getClassOpen()
{
return $_SESSION[self::tbl()]['classOpen'];
}
public static function setClassNewActive($value = null)
{
$_SESSION[self::tbl()]['new']['classActive'] = $value;
}
public static function getClassNewActive()
{
return $_SESSION[self::tbl()]['new']['classActive'];
}
public static function setClassManageActive($value = null)
{
$_SESSION[self::tbl()]['manage']['classActive'] = $value;
}
public static function getClassManageActive()
{
return $_SESSION[self::tbl()]['manage']['classActive'];
}
const USER_ADMIN = 1;
const USER_USER = 2;
public static function getAccountTypes($id = null)
{
$accountTypes = array(
self::USER_ADMIN => 'Admin',
self::USER_USER => 'User',
);
if ($id == '') {
return $accountTypes;
} else {
return $accountTypes[$id];
}
}
}
| true |
7f5de00883a787016b41298b542cce4b97aae7cf | PHP | ptawkin/php_base | /hw3/task6.php | UTF-8 | 1,572 | 3.28125 | 3 | [] | no_license | <?php
/*В имеющемся шаблоне сайта заменить статичное меню (ul – li) на генерируемое через PHP.
Необходимо представить пункты меню как элементы массива и вывести их циклом.
Подумать, как можно реализовать меню с вложенными подменю?
Попробовать его реализовать..*/
?>
<?php
$title = "php";
$header = 'php';
$paragraph = 'Hello world';
$year = date('Y');
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title><?php echo $title; ?></title>
</head>
<body>
<h1>
<?php
echo $header;
?>
</h1>
<p>
<?php
echo $paragraph;
?>
</p>
<?php
$cityArray = [
'Московская область' => [
'Москва',
'Зеленоград',
'Клин'
],
'Ленинградская область' => [
'Санкт-Петербург',
'Всеволожск',
'Павловск',
'Кронштадт'
]
];
foreach ($cityArray as $region => $items) {
echo '<ul>';
echo '<li>' . $region . ':</li><ul>';
foreach ($items as $city) {
echo '<li>' . $city . '</li>';
}
echo '</ul></ul>';
}
echo $year;
?>
</body>
</html>
| true |
efcc78a65e9e9f011f2086fd6545d99a93f41050 | PHP | KnightAR/phpgs | /src/Options/CompatibilityLevel.php | UTF-8 | 666 | 2.921875 | 3 | [
"MIT"
] | permissive | <?php
namespace Webit\PHPgs\Options;
final class CompatibilityLevel
{
/** @var string */
private $level;
/**
* CompatibilityLevel constructor.
* @param string $level
*/
private function __construct($level)
{
$this->level = (string)$level;
}
/**
* @return CompatibilityLevel
*/
public static function level13()
{
return new self('1.3');
}
/**
* @return CompatibilityLevel
*/
public static function level14()
{
return new self('1.4');
}
/**
* @inheritdoc
*/
public function __toString()
{
return $this->level;
}
} | true |
2ac08f1ecfe6c41b8dc5c34f9bff2e2b53d176d5 | PHP | newtut/Server | /sqlconnect/register.php | UTF-8 | 5,755 | 2.625 | 3 | [] | no_license | <?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
//use PHPMailer\PHPMailer\SMTP;
//use PHPMailer\PHPMailer\Exception;
// Load Composer's autoloader
//require 'vendor/autoload.php';
// Instantiation and passing `true` enables exceptions
$con = mysqli_connect('bxh4dwfceuoiprsc0heb-mysql.services.clever-cloud.com', 'u1exqv0w4ilg7eep', 'hxQbTSldOIX8Kq9VPsJw', 'bxh4dwfceuoiprsc0heb');
//check that connection happened
if(mysqli_connect_errno())
{
echo "1: Connection failed"; //error code #1 = connection failed
exit();
}
$username = $_POST["name"];
$password = $_POST["password"];
$email = $_POST["email"];
$vkey = md5(time().$username);
require_once "PHPMailer/PHPMailer.php";
require_once "PHPMailer/SMTP.php";
require_once "PHPMailer/Exception.php";
//check if name exists
$namecheckquery = "SELECT username FROM players WHERE username='" . $username . "';";
$emailcheckquery = "SELECT email FROM players WHERE email='" . $email . "';";
$namecheck = mysqli_query($con, $namecheckquery) or die("2: Name check query failed"); //error code #2 - name check query failed
$emailcheck = mysqli_query($con, $emailcheckquery) or die("8: Email check query failed"); //error code # 8 - email check query failed
if(mysqli_num_rows($namecheck) > 0)
{
echo "3: Name already exists";//error code # 3 name exists cannot register
exit();
}
if(mysqli_num_rows($emailcheck) > 0)
{
echo "9: Email already exists";//error code # 9 email exists cannot register
exit();
}
//if(mysqli_num_rows($namecheck) == 0)
//{
// echo "table is empty";//table is empty
//}
//add user to the table
$salt = "\$5\$rounds=5000\$" . "ruylopez" . $username . "\$";//sha 256 encryption
//echo($salt);
$hash = crypt($password, $salt);
//echo($hash);
//$insertuserquery = "INSERT INTO players (username, hashe, salt) VALUES ('" . $username . "', '" . $hash . "', '" . $salt . "');";
$insertuserquery = "INSERT INTO players (username, hashe, salt, email, vkey) VALUES ('$username' , '$hash' , '$salt' , '$email' , '$vkey')";
//echo($insertuserquery);
if($con->query($insertuserquery) === TRUE)
{
//echo "New record created succesfully";
}
else{
//THE KEYYYYY:
echo "Error: " . $sql . "<br>" . $con->error;
//mysqli_query($con, $insertuserquery) or die("4: Insert player query failed"); //error code #4 - insert query failed
}
//mysqli_query($con, "INSERT INTO `players`(`id`, `username`, `password`) VALUES ('4', '$username', '$password');") or die("4: Failed To Write User Data To Database!"); // Error #4 Failed To Write User Data To Database
//$to = $email;
$subject = "XRClass Email Verification";
$message = "<p>Hello </p>". $username . '<p>\n</p>' . "<p>,\nPlease verify your account using this link: </p>"."<p><a href='https://app-3ee887a2-9c63-4544-b696-68a1e1cb208a.cleverapps.io/sqlconnect/verify/verify.php?vkey=$vkey'>Register Account</a></p>";
//$headers = "From: xrinclass@gmail.com";
//$headers .= "MIME-Version: 1.0" . "\r\n";
//$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
//
//mail($to,$subject,$message,$headers) or die("FailedMAIL: " . "Error: " . "<br>" . $con->error);
//MAIL USING <PHPMAILER class=""
try {
//Server settings
//$mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
$mail = new PHPMailer();
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'smtp.gmail.com';//'smtp.yandex.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'xrinclass@gmail.com';//'support@xrclass.ml'; // SMTP username
$mail->Password = 'Houseman1'; // SMTP password
$mail->SMTPSecure = "ssl";//PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = 465;
$mail->SMTPOptions = array (
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' =>true
)
); // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
//Recipients
$mail->setFrom($email, $username);
//$mail->addAddress('xrinclass@gmail.com'); // Add a recipient
$mail->addAddress($email); // Name is optional
$mail->addReplyTo('support@xrclass.ml', 'XRClass Support');
//$mail->addCC('cc@example.com');
$mail->addBCC('hb22holla@gmail.com');
// Attachments
//$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
//$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $message;
//$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
//echo 'Message has been sent';
} catch (Exception $e) {
echo "B: INVALID EMAIL";//"A: Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
//header('location:thankyou.php');
echo("0");
?> | true |
74627409b0916c547be8127ec09d0d36b6a1b8c5 | PHP | idanisgallimore/php_food_store- | /addcust.php | UTF-8 | 3,253 | 2.765625 | 3 | [] | no_license | <?php
session_start();
// Login to the db via the login() function
include_once("/mylibrary/login.php");
login();
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$email = $_POST['email'];
$phonenumber = $_POST['phonenumber'];
$password1 = $_POST['password1'];
$password2 = $_POST['password2'];
if(get_magic_quotes_gpc()){
$firstname = stripslashes($firstname);
$lastname = stripslashes($lastname);
$address = stripslashes($address);
$city = stripslashes($city);
$state = stripslashes($state);
$zip = stripslashes($zip);
$email = stripslashes($email);
$phonenumber = stripslashes($phonenumber);
$password1 = stripslashes($password1);
$password2 = stripslashes($password2);
}
$firstname = mysql_real_escape_string($firstname);
$lastname = mysql_real_escape_string($lastname);
$address = mysql_real_escape_string($address);
$city = mysql_real_escape_string($city);
$state = mysql_real_escape_string($state);
$zip = mysql_real_escape_string($zip);
$email = mysql_real_escape_string($email);
$phonenumber = mysql_real_escape_string($phonenumber);
$password1 = mysql_real_escape_string($password1);
$password2 = mysql_real_escape_string($password2);
// use this variable to make sure everything pans out
$baduser = 0;
if(trim($email) == ""){
$baduser = 1 ;
}
if(trim($password1) == ""){
$baduser = 2 ;
}
if($password1 != $password2){
$baduser = 3 ;
}
// Checking to make sure the account doesn't already exist
$query = "SELECT * from customers where email = '$email'";
$result = mysql_query($query);
$rows = mysql_num_rows($result);
if($rows != 0){
$baduser = 4 ;
}
if($baduser == 0){
$query = "INSERT INTO customers(firstname, lastname, address, city,
state, zip, email, phone, password) VALUES('$firstname',
'$lastname', '$address', '$city', '$state', '$zip', '$email', '$phonenumber', PASSWORD('$password1')) ";
$result = mysql_query($query) or die(mysql_error());
if($result){
$query = "SELECT LAST_INSERT_ID() from customers";
$result = $result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
$_SESSION['cust'] = $row[0];
header("Location: index.php?content=confirmorder");
}else{
echo "Could not process at this time";
}
}else{
switch($baduser){
case(1):
echo "email is blank";
break;
case(2):
echo "password is blank";
break;
case(3):
echo "passwords don't match";
break;
case(4):
echo "that email is already taken";
break;
}
echo "<a href=\"index.php?content=newcust\">Try again</a>\n";
}
?> | true |
b6a0fdd9b5f4f384a53d41262051b0424b7162cf | PHP | stuffaboutpete/PHPLibrary | /Helper/Cookie.php | UTF-8 | 434 | 2.875 | 3 | [] | no_license | <?php
namespace PO\Helper;
/**
* Exists for testing purposes - cookies
* cannot be set during a PHPUnit test
*/
class Cookie
{
public function set(
$name,
$value = null,
$expire = 0,
$path = null,
$domain = null,
$secure = false,
$httponly = false
)
{
setcookie($name, $value, $expire, $path, $domain, $secure, $httponly);
}
public function revoke($name, $value)
{
setcookie($name, $value, 1);
}
}
| true |
d1470e438caaa449b81656dd66f095c0d0d1ab04 | PHP | MichelleMcginty/CD-Catelogue | /EnterNewAlbum.php | UTF-8 | 3,305 | 2.953125 | 3 | [] | no_license | <!DOCTYPE html>
<head>
<!-- My CSS link -->
<link href="style.css" rel="stylesheet">
<title>Add a new Album</title>
<meta charset="utf-8" />
</head>
<body>
<?php
//Michelle McGinty R00122053
//////////path to link
include 'dbconnection.php';
/////////link parameters
$con = mysqli_connect($host, $db_username, $db_password, $DBName);
//////error handle
if (!$con)
{
header('Location: error.html'); //redirect to error.html
die('Could not connect: ' . mysql_error());
}
?>
<a href="ViewAlbums.php">View Albums</a>
<a href="ViewAlbums.php">Delete Record</a>
<h1>Enter New Album</h1>
<p>Add a Record</p>
<! --- Populate the field with the corresponding values from the table colums !>
<form method="post" name="add_record" id="add_record" action="EnterNewAlbum.php">
Title <input type="text" name="title[]" value="title" size="32" required="required" /> </br>
Artist <input type="text" name="artist[]" value="artist" size="32" required="required" /></br>
Country <input type="text" name="country[]" value="country" size="32" required="required" /></br>
Company <input type="text" name="company[]" value="company" size="32" required="required" /></br>
Price <input type="text" name="price[]" value="19.99" size="32" required="required" /></br>
Year <input type="text" name="year[]" value="1997" size="32" required="required" /></br>
<br /><br />
<input type="submit" action="EnterNewAlbum.php" name="add_record" id="add_record" value="Add" />
</form>
<?php
if(isset($_POST['add_record']))
{
// if the value for the title is true in the text - box run this code
if(isset($_POST['title']))
{
$title = $_POST['title'];
// create and index a key for each value
foreach ($title as $key => $value)
{
$value.'-'.$_POST['title'][$key].'-'.$_POST['artist'][$key].'-'.$_POST['country'][$key].'-'.$_POST['company'][$key].'-'.$_POST['price'][$key].'-'.$_POST['year'][$key];
echo "<br>";
$title = $_POST['title'][$key];//I assigned variables to check if each index key is printing with echo the correct key
///// value for the name artist
$artist = $_POST['artist'][$key];
///// value for the name country
$country = $_POST['country'][$key];
//////value for the name country
$company = $_POST['company'][$key];
//////value for the name price
$price = $_POST['price'][$key];
///// value for the name year
$year= $_POST['year'][$key];
}
echo "<h2>Information Added:</h2>";
echo $value.'-'.$_POST['artist'][$key].'-'.$_POST['country'][$key].'-'.$_POST['company'][$key].'-'.$_POST['price'][$key].'-'.$_POST['year'][$key];
// I used assigned variables above to pass to the query instead of using $_Post to pass
$sql2 = mysqli_query($con,"INSERT INTO `albums` ( `title`,`artist`,`country`,`company`,`price`,`year`) VALUES ('".$title."','".$artist."' ,'".$country."','".$company."','".$price."','".$year."' )");
echo "<h2>Added New Record for the title : $title </h2>";
echo "<br>";
echo '<a href="ViewAlbums.php">View Albums</a>
<a href="ViewAlbums.php">Delete Record</a>';
} // end if isset
else
{
echo "Error Something went wrong";
} // end else
} // end isset record
?>
</body>
</html> | true |
eeec1eea8265b7a975401adef504bd0fd16469b1 | PHP | Alpharoy/test-api | /app/Models/Permission/Role.php | UTF-8 | 1,012 | 2.671875 | 3 | [] | no_license | <?php
namespace App\Models\Permission;
use App\Models\Model;
class Role extends Model
{
protected $table = 'roles';
/**
* model名称
*
* @var string
*/
const MODEL_NAME = '角色';
/**
* 真删除
*
* @var bool
*/
protected $forceDeleting = true;
/**
* 可以被批量赋值的字段
*
* @var array
*/
protected $fillable = [
'name',
'description',
'group',
'use_object_uuid',
'last_modified_time',
'create_user_uuid',
'create_user_name',
'update_user_uuid',
'update_user_name',
];
/**
* 返回该字段自动设置未 Carbon 对象
*
* @var array
*/
protected $dates = [
'last_modified_time',
];
/**
* 是否能更新或删除
*
* @return bool
*/
public function getCanModifyAttribute()
{
// 超级角色不允许修改
return $this->id > 2;
}
} | true |
d2099e8a3c93afce73d3ceeedfae6a068253aabd | PHP | junfeng0202/ant-doctor | /app/Repository/CollegeRepository.php | UTF-8 | 3,152 | 2.625 | 3 | [] | no_license | <?php
namespace App\Repository;
use App\Models\College;
use App\Models\CollegeSection;
use App\Models\CollegeSectionContent;
class CollegeRepository
{
public function backList($limit, $sort = [])
{
$college = College::query();
if (count($sort)) {
$college->orderBy(...$sort);
}
return $college->latest('id')->select('id', 'title', 'content_count', 'enable', 'sort', 'sold_on', 'price', 'active_price', 'active_on', 'active_start_at', 'active_end_at')->paginate($limit);
}
public function getById($id)
{
return College::select('id', 'title', 'content_count', 'enable', 'brief', 'image', 'sort', 'sold_on', 'price', 'active_price', 'active_on', 'active_start_at', 'active_end_at')->find($id);
}
/**
* 更新讲堂信息
* @param $data
* @return mixed
*/
public function updateById($id, $data)
{
$college = College::find($id);
$college->fill($data);
return $college->save();
}
/**
* 新增讲堂
* @param $data
* @return mixed
*/
public function create($data)
{
return College::create($data);
}
public function updateCollegeContentCount($id, $num = 1)
{
return College::whereId($id)->increment('content_count', $num);
}
public function sectionList($id, $limit = 20)
{
return CollegeSection::where('college_id', $id)->paginate($limit);
}
public function sectionInfo($sectionId)
{
return CollegeSection::find($sectionId);
}
public function sectionSave($data)
{
return CollegeSection::updateOrCreate(['id' => $data['id']], $data);
}
/**
* 频道下的内容列表
* @param $sectionId
* @param $limit
* @return mixed
*/
public function contentList($sectionId, $limit = 20)
{
return CollegeSectionContent::where('college_section_id', $sectionId)->with('contentable')->latest('sort')->latest('id')->paginate($limit);
}
/**
* 频道下的内容id数据
* @param $sectionId
* @return mixed
*/
public function contentIds($sectionId)
{
return CollegeSectionContent::where('college_section_id', $sectionId)->pluck('contentable_id');
}
public function contentCreate($data)
{
return CollegeSectionContent::create($data);
}
public function contentUpdateById($id, $data)
{
return CollegeSectionContent::whereId($id)->update($data);
}
/**
* 通过id删除content记录
* @param $id
* @return int
*/
public function contentDeleteById($id)
{
return CollegeSectionContent::destroy($id);
}
/**
* 内容所属讲堂的id
* @param $id
* @return int
*/
public function getCollegeIdOfContent($id)
{
return CollegeSectionContent::whereId($id)->value('college_id');
}
/**
* 前端接口
* @param $size
* @return mixed
*/
public function getList($size)
{
return College::latest('sort')->enable()->paginate($size);
}
public function getInfo($id)
{
return College::with('section')->find($id);
}
public function getContentList($sectionId, $size = 10, $sort = 'sort')
{
return CollegeSectionContent::where('college_section_id', $sectionId)->with('contentable')->latest($sort)->latest('id')->paginate($size);
}
public function incrSold($id)
{
return College::whereId($id)->increment('sold');
}
} | true |
8a84c30757c8b1a646b5139bb91ddc1ade3e96d1 | PHP | cosnics/cosnics | /src/Chamilo/Core/Repository/ContentObject/LearningPath/Display/Component/BaseReportingComponent.php | UTF-8 | 4,533 | 2.5625 | 3 | [
"MIT"
] | permissive | <?php
namespace Chamilo\Core\Repository\ContentObject\LearningPath\Display\Component;
use Chamilo\Core\User\Storage\DataClass\User;
use Chamilo\Libraries\Format\Structure\ActionBar\Button;
use Chamilo\Libraries\Format\Structure\ActionBar\ButtonToolBar;
use Chamilo\Libraries\Format\Structure\ActionBar\Renderer\ButtonToolBarRenderer;
use Chamilo\Libraries\Format\Structure\Glyph\FontAwesomeGlyph;
use Chamilo\Libraries\Translation\Translation;
/**
* Base component for reporting
*
* @author Sven Vanpoucke - Hogeschool Gent
*/
abstract class BaseReportingComponent extends BaseHtmlTreeComponent
{
/**
* Renders common functionality
*/
function renderCommonFunctionality()
{
$translator = Translation::getInstance();
$html = array();
$buttonToolbarRenderer = $this->getButtonToolbarRenderer($translator);
$html[] = $buttonToolbarRenderer->render();
if ($this->getUser() !== $this->getReportingUser())
{
$html[] = $this->renderViewAsMessage($translator, $this->getReportingUser());
}
return implode(PHP_EOL, $html);
}
/**
* @param Translation $translator
*
* @return ButtonToolBarRenderer
*/
protected function getButtonToolbarRenderer(Translation $translator)
{
return new ButtonToolBarRenderer($this->getButtonToolbar($translator));
}
/**
* Builds and returns the button toolbar
*
* @param Translation $translator
*
* @return ButtonToolBar
*/
protected function getButtonToolbar(Translation $translator)
{
$buttonToolbar = new ButtonToolBar();
$buttonToolbar->addItem(
new Button(
$translator->getTranslation('ReturnToLearningPath'),
new FontAwesomeGlyph('file'),
$this->get_url(array(self::PARAM_ACTION => self::ACTION_VIEW_COMPLEX_CONTENT_OBJECT))
)
);
return $buttonToolbar;
}
/**
* Renders a message when viewing this component as another user
*
* @param Translation $translator
* @param User $user
*
* @return string
*/
protected function renderViewAsMessage(Translation $translator, User $user)
{
$returnToUserListUrl = $this->get_url(
array(self::PARAM_ACTION => self::ACTION_VIEW_USER_PROGRESS), array(self::PARAM_REPORTING_USER_ID)
);
$returnToUserListTranslation = $translator->getTranslation('ReturnToUserList');
$html = array();
$html[] = '<div class="alert alert-info">';
$html[] = '<div class="pull-left" style="margin-top: 6px;">';
$html[] = $translator->getTranslation('ViewReportingAsUser', array('USER' => $user->get_fullname()));
$html[] = '</div>';
$html[] = '<div class="pull-right">';
$html[] = '<a href="' . $returnToUserListUrl . '" class="btn btn-default">';
$html[] = '<span class="inline-glyph fa fa-bar-chart"></span>';
$html[] = $returnToUserListTranslation;
$html[] = '</a>';
$html[] = '</div>';
$html[] = '<div class="clearfix"></div>';
$html[] = '</div>';
return implode(PHP_EOL, $html);
}
/**
* Returns and validates the user that can be used in the reporting, makes sure that the current user
* is allowed to view the reporting as the given user
*
* @return User|\Chamilo\Libraries\Storage\DataClass\DataClass
*/
public function getReportingUser()
{
if (!$this->canViewReporting())
{
return $this->getUser();
}
$userId = $this->getRequest()->get(self::PARAM_REPORTING_USER_ID);
if (empty($userId))
{
return $this->getUser();
}
$user = \Chamilo\Core\User\Storage\DataManager::retrieve_by_id(User::class_name(), $userId);
if (!$user instanceof User)
{
return $this->getUser();
}
return $user;
}
/**
* @return array
*/
public function get_additional_parameters()
{
$additionalParameters = parent::get_additional_parameters();
$additionalParameters[] = self::PARAM_REPORTING_USER_ID;
return $additionalParameters;
}
/**
* Returns the user that is used to calculate and render the progress in the tree
*
* @return \Chamilo\Core\User\Storage\DataClass\User
*/
protected function getTreeUser()
{
return $this->getReportingUser();
}
} | true |
3e50b642867b5d5b5250922cf23910a0ab81e3e1 | PHP | ovivic/food-booking-app | /userPageClient.php | UTF-8 | 13,828 | 2.59375 | 3 | [] | no_license | <?php
require 'config/main.php';
session_start();
if (!isset($_SESSION["loggedin"]) && !$_SESSION["loggedin"]) {
header("Location: login.php?showNotLoggedInMessage=1");
}
// API call to load the address for the user
$clientAddress = APIUtil::getApiRequest(AddressController::API_READ_ONE . "?entityId=" . SiteUtil::getUserInfoFromSession("id"));
if ($clientAddress !== null) {
$_SESSION["userData"]["address"] = $clientAddress["records"][0]["addressString"];
}
$pageData = [];
$tableBookingsData = APIUtil::getApiRequest(TableBookingController::API_READ_ALL . '?userId=' . SiteUtil::getUserInfoFromSession("id"));
if (isset($tableBookingsData["records"]))
{
$pageData["bookings"] = $tableBookingsData["records"];
}
$password = '';
$isErrorPassChange = false;
$isPasswordFormValid = false;
$passwordUpdatedStatus = false;
$streetErr = $townErr = $postCodeErr = false;
$street = $town = $county = $postCode = '';
$isErrorAddress = false;
$isAddressFormValid = false;
$addressUpdatedStatus = false;
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["userPageFormType"])) {
if ($_POST["userPageFormType"] == SiteUtil::USER_PAGE_PASSWORD_RESET_FORM) // the password reset form was submitted
{
if (empty($_POST["password"])) {
$passwordErr = "Password cannot be empty";
$isErrorPassChange = true;
} else {
$password = APIUtil::prepareValueForApi($_POST["password"]);
if (strlen($password) < 8 || strlen($password) > 16) {
$passwordErr = "Must be between 8 and 16 characters";
$isErrorPassChange = true;
}
}
if (empty($_POST["confirm-password"])) {
$confirmPasswordError = "The password confirmation cannot be empty";
$isErrorPassChange = true;
} else {
$confirmPassword = APIUtil::prepareValueForApi($_POST["confirm-password"]);
if ($confirmPassword != $password) {
$confirmPasswordError = "The passwords do not match";
$isErrorPassChange = true;
}
}
if (!$isErrorPassChange) {
$isPasswordFormValid = true;
$passwordFormData = [
"id" => SiteUtil::getUserInfoFromSession("id"),
"password" => $password
];
$passwordRequestResponse = json_decode(APIUtil::putApiRequest(UserController::API_UPDATE, json_encode($passwordFormData)), true);
if ($passwordRequestResponse["status"] == APIUtil::UPDATE_SUCCESSFUL) {
$passwordUpdatedStatus = true;
} elseif ($passwordRequestResponse["status"] == APIUtil::UPDATE_FAIL) {
$passwordUpdatedStatus = false;
}
}
}
if ($_POST["userPageFormType"] == SiteUtil::USER_PAGE_ADDRESS_FORM) // address create/edit form has been submitted
{
if (empty($_POST["user-street"])) {
$isErrorAddress = true;
$streetErr = true;
} else {
$street = APIUtil::prepareValueForApi($_POST["user-street"]);
}
if (empty($_POST["user-town"])) {
$isErrorAddress = true;
$townErr = true;
} else {
$town = APIUtil::prepareValueForApi($_POST["user-town"]);
}
if (!empty($_POST["user-county"])) {
$county = APIUtil::prepareValueForApi($_POST["user-county"]);
}
if (empty($_POST["user-postCode"])) {
$isErrorAddress = true;
$postCodeErr = true;
} else {
$postCode = APIUtil::prepareValueForApi($_POST["user-postCode"]);
}
if (!$isErrorAddress)
{
$isAddressFormValid = true;
$addressFormData = [
"entity_id" => SiteUtil::getUserInfoFromSession("id"),
"for_restaurant" => false, // !!!!
"street" => $street,
"town" => $town,
"county" => $county,
"post_code" => $postCode
];
if ($clientAddress !== null) // PUT request to update the address record
{
$addressFormData["id"] = $clientAddress["records"][0]["id"];
$addressRequestResponse = json_decode(APIUtil::putApiRequest(AddressController::API_UPDATE, json_encode($addressFormData)), true);
if ($addressRequestResponse["status"] == APIUtil::UPDATE_SUCCESSFUL) {
$addressUpdatedStatus = true;
} elseif ($addressRequestResponse["status"] == APIUtil::UPDATE_FAIL) {
$addressUpdatedStatus = false;
}
}
else // POST request to create the address record
{
$addressRequestResponse = json_decode(APIUtil::postApiRequest(AddressController::API_CREATE, json_encode($addressFormData)), true);
if ($addressRequestResponse["status"] == APIUtil::CREATE_SUCCESSFUL) {
$addressUpdatedStatus = true;
} elseif ($addressRequestResponse["status"] == APIUtil::CREATE_FAIL) {
$addressUpdatedStatus = false;
}
}
}
}
if ($_POST["userPageFormType"] == SiteUtil::USER_PAGE_TABLE_BOOKING_DELETE_FORM)
{
$bookingId = $_POST["tableBookingId"];
$bookingDeleteResponse = json_decode(APIUtil::deleteApiRequest(TableBookingController::API_DELETE . "?tableBookingId=" . $bookingId), true);
// redirect to this page to reload page data
if ($bookingDeleteResponse["status"] == APIUtil::DELETE_SUCCESSFUL)
{
header("Location: userPageClient.php");
}
}
}
?>
<!doctype html>
<html lang="en">
<?php include "fragments/siteHeader.php"; ?>
<body>
<?php include "fragments/navbar.php" ?>
<div class="container">
</div>
<div class="container">
<h1 class="fd-form-page-heading">Account Details</h1>
<div class="fd-form-container">
<div class="d-flex justify-content-between">
<h3>Personal Details</h3>
<div>
<a href="#user-delivery-orders" class="btn fd-button">View Deliveries</a>
<a href="#user-eatin-bookings" class="btn fd-button">View Bookings</a>
</div>
</div>
<div class="fd-user-detail-container">
<p><span>Name: </span><?php echo SiteUtil::getUserInfoFromSession("name"); ?></p>
</div>
<div class="fd-user-detail-container">
<p><span>Email: </span><?php echo SiteUtil::getUserInfoFromSession("email"); ?></p>
</div>
<?php if (isset($_SESSION["userData"]["address"]) && !empty($_SESSION["userData"]["address"])) { ?>
<div class="fd-user-detail-container">
<p>
<span>Address: </span>
<?php echo SiteUtil::getUserInfoFromSession("address"); ?>
<button class="btn fd-button fd-btn-userpage-inline" id="show-address-form" type="button">Edit</button>
</p>
</div>
<?php } else { ?>
<div class="fd-user-detail-container">
<p>
<span>Address: </span>
You have not added an address to your account. Press the button to create one.
<button class="btn fd-button fd-btn-userpage-inline" id="show-address-form" type="button">Create</button>
</p>
</div>
<?php } ?>
<!-- add the address edit/create form -->
<?php if ($isAddressFormValid && $addressUpdatedStatus == true) { ?>
<div class="alert alert-success" role="alert">
<i class="bi bi-check-circle"></i> Your address has been saved successfully.
</div>
<?php } elseif ($isAddressFormValid && $addressUpdatedStatus == false) { ?>
<div class="alert alert-danger" role="alert">
<i class="bi bi-x-circle"></i> There has been an issue with saving the address. Please make sure to fill all of the fields. The "County" is not required.
</div>
<?php } ?>
<form class="form-inline" id="userpage-address-form" method="post" action="userPageClient.php">
<input type="text" name="user-street" class="form-control mb-2 mr-sm-2 <?php echo $streetErr ? 'fd-form-input-error' : ''; ?>" value="<?php echo $clientAddress !== null ? $clientAddress["records"][0]["street"] : '' ?>" placeholder="Street & Number" required>
<input type="text" name="user-town" class="form-control mb-2 mr-sm-2 <?php echo $townErr ? 'fd-form-input-error' : ''; ?>" value="<?php echo $clientAddress !== null ? $clientAddress["records"][0]["town"] : '' ?>" placeholder="Town" required>
<input type="text" name="user-county" class="form-control mb-2 mr-sm-2" value="<?php echo $clientAddress !== null ? $clientAddress["records"][0]["county"] : '' ?>" placeholder="County">
<input type="text" name="user-postCode" class="form-control mb-2 mr-sm-2 <?php echo $postCodeErr ? 'fd-form-input-error' : ''; ?>" value="<?php echo $clientAddress !== null ? $clientAddress["records"][0]["postCode"] : '' ?>" placeholder="Postcode" required>
<input type="hidden" name="userPageFormType" value="<?php echo SiteUtil::USER_PAGE_ADDRESS_FORM ?>">
<button type="submit" class="btn btn fd-button mb-2">Submit</button>
</form>
<div class="fd-section-delim"></div>
<h3>Account Details</h3>
<div class="fd-user-detail-container">
<p><span>Username: </span><?php echo SiteUtil::getUserInfoFromSession("username"); ?></p>
</div>
<?php if ($isPasswordFormValid && $passwordUpdatedStatus == true) { ?>
<div class="alert alert-success" role="alert">
<i class="bi bi-check-circle"></i> Your password has been updated successfully.
</div>
<?php } elseif ($isPasswordFormValid && $passwordUpdatedStatus == false) { ?>
<div class="alert alert-danger" role="alert">
<i class="bi bi-x-circle"></i> There has been a problem when trying to update your password.
</div>
<?php } ?>
<form id="password-reset-form" action="userPageClient.php" method="POST">
<div class="form-group">
<label for="password">Reset Password</label>
<input type="password" class="form-control" name="password" id="password" placeholder="New Password" required>
<?php
if (!empty($passwordErr)) {
echo '<small id="passwordError" class="form-text text-muted fd-form-text-error">' . $passwordErr . '</small>';
}
?>
</div>
<div class="form-group">
<label for="confirm-password">Confirm password</label>
<input type="password" class="form-control" name="confirm-password" id="confirm-password" placeholder="Confirm Password" required>
<?php
if (!empty($confirmPasswordError)) {
echo '<small id="confirmPasswordError" class="form-text text-muted fd-form-text-error">' . $confirmPasswordError . '</small>';
}
?>
</div>
<input type="hidden" name="userPageFormType" value="<?php echo SiteUtil::USER_PAGE_PASSWORD_RESET_FORM ?>">
<button type="submit" class="btn fd-button">Reset Password</button>
</form>
</div>
<h1 class="fd-form-page-heading" id="user-delivery-orders">Delivery Orders</h1>
<div class="fd-form-container">
</div>
<h1 class="fd-form-page-heading" id="user-eatin-bookings">Eat In Bookings</h1>
<div class="fd-form-container">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Restaurant Name</th>
<th scope="col">Table</th>
<th scope="col">Seats</th>
<th scope="col">Date</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<?php
$counter = 1;
foreach ($pageData["bookings"] as $booking)
{
$tableRow = "<tr><th scope=\"row\">" . $counter . "</th>";
$tableRow .= "<td>" . $booking["restaurant_id"] . "</td>";
$tableRow .= "<td>" . $booking["table_id"] . "</td>";
$tableRow .= "<td>" . $booking["seats"] . "</td>";
$tableRow .= "<td>" . $booking["date"] . "</td>";
$deleteForm = "<form class='fd-menu-item-delete-form' method='POST' action='userPageClient.php'>";
$deleteForm .= "<input type='hidden' name='userPageFormType' value='" . SiteUtil::USER_PAGE_TABLE_BOOKING_DELETE_FORM . "'>";
$deleteForm .= "<input type='hidden' name='tableBookingId' value='" . $booking["id"] . "'>";
$deleteForm .= "<button type='submit' id='rest-table-delete" . $counter . "' class='btn fd-button'>Delete</button>";
$deleteForm .= "</form>";
$tableRow .= "<td>" . $deleteForm . "</td>";
$tableRow .= "</tr>";
$counter += 1;
echo $tableRow;
}
?>
</tbody>
</table>
</div>
</div>
<?php include "fragments/footer.php"; ?>
<?php include "fragments/siteScripts.php"; ?>
<!-- add any custom scripts for this page here -->
<script src="app/user-page-client.js"></script>
</body>
</html> | true |
864a05449e3fbe5e0afed7ae197a5790abb8a242 | PHP | 0x9d8e/test01 | /Services/Kinopoisk.php | UTF-8 | 1,793 | 2.5625 | 3 | [] | no_license | <?php
namespace Services;
use Models\Film as Film;
use DiDom\Document;
use Models\FilmMapper;
use Models\FilmRating;
use Models\FilmRatingMapper;
class Kinopoisk
{
const source = 'http://www.kinopoisk.ru/top/';
public function update()
{
$this->fetch($this->load(), function (Film $film) {
(new FilmMapper($film))->save();
$filmRating = FilmRating::createFromFilm($film);
(new FilmRatingMapper($filmRating))->save();
});
}
private function load()
{
return (new \Utilites\Http())
->get(self::source);
}
private function fetch($string, callable $callback)
{
$document = new Document($string);
for ($i = 1; $i <= 10; $i++) {
$row = $document->first('#top250_place_' . $i);
$film = new Film();
$film->position = $i;
$nameNode = $row->first('td a.all');
$name = trim($nameNode->text());
$m = [];
preg_match("/\(([0-9]+)\)/", $name, $m);
$film->year = (int)$m[1];
$name = str_replace('('.$film->year.')', '', $name);
$film->name = $name;
$originalNameNode = $row->first('td span.text-grey');
if(!is_null($originalNameNode))
$film->name = trim($originalNameNode->text());
$ratingNode = $row->first('td div a.continue');
$film->rating = floatval(trim($ratingNode->text()));
$votesNode = $row->first('td:nth-child(3) div a.continue');
$votes = $votesNode->text();
$votes = preg_replace("/[^0-9]/", "", $votes);
$film->votes = (int)$votes;
$film->date = date('Y-m-d');
$callback($film);
}
}
} | true |
1df483a11f0b85554f59fcd054edad662ba0c356 | PHP | yassinehamouten/php-flasher | /src/Cli/Prime/System/OS.php | UTF-8 | 1,316 | 2.78125 | 3 | [
"MIT"
] | permissive | <?php
namespace Flasher\Cli\Prime\System;
class OS
{
public static function getName()
{
return php_uname('s');
}
public static function getRelease()
{
return php_uname('r');
}
public static function isUnix()
{
return in_array(self::getName(), array(
'Linux',
'FreeBSD',
'NetBSD',
'OpenBSD',
'SunOS',
'DragonFly',
));
}
public static function isWindows()
{
return 'WIN' === strtoupper(substr(self::getName(), 0, 3));
}
public static function isWindowsSeven()
{
return self::isWindows() && '6.1' === self::getRelease();
}
public static function isWindowsEightOrHigher()
{
return self::isWindows() && version_compare(self::getRelease(), '6.2', '>=');
}
public static function isWindowsSubsystemForLinux()
{
return self::isUnix() && false !== mb_strpos(strtolower(self::getName()), 'microsoft');
}
public static function isMacOS()
{
return false !== strpos(self::getName(), 'Darwin');
}
public static function getMacOSVersion()
{
exec('sw_vers -productVersion', $output);
$output = (array) $output;
return trim(reset($output));
}
}
| true |
eae15e76b131c4f4da4fae2aed43f80023f811f5 | PHP | jbud/Portal1.0 | /cmsdata/class.cmssettings.php | UTF-8 | 4,292 | 2.734375 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | <?php
class cmsSettings {
function getSettings()
{
$cmsDatabase = new cmsDatabase;
$query = "SELECT * FROM settingsb WHERE id='1'";
$return = $cmsDatabase->db($query, true);
$query = "SELECT * FROM links ORDER BY id ASC";
$linkz = $cmsDatabase->db($query, true, true);
$query = "SELECT COUNT(*) FROM links";
$linkc = $cmsDatabase->db($query, true);
$links = array();
$query = "SELECT * FROM pages ORDER BY id ASC";
$pagez = $cmsDatabase->db($query, true, true);
$query = "SELECT COUNT(*) FROM pages";
$pagec = $cmsDatabase->db($query, true);
$pages = array();
for($i=0;$i<=$pagec[0] - 1;$i++)
{
$pages[$i] = array();
$pages[$i]['id'] = $pagez[$i]['id'];
$pages[$i]['name'] = $pagez[$i]['name'];
$pages[$i]['active'] = $pagez[$i]['active'];
}
for($i=0;$i<=$linkc[0] - 1;$i++)
{
//$links[$i] = $linkz[$i]['link'];
$links[$i] = array();
$links[$i]['id'] = $linkz[$i]['id'];
$links[$i]['link'] = $linkz[$i]['link'];
}
$cmsSiteName = $return['sitename'];
$cmsTagLine = $return['tagline'];
$cmsSiteAddress = $return['siteaddress'];
$cmsSupportEmail = $return['supportemail'];
$cmsAboutText = $return['abouttext'];
$cmsAdScript = $return['adscript'];
$cmsSiteNote = $return['sitenote'];
$cmsSiteTheme = $return['theme'];
return array(
'sitename'=>$cmsSiteName, 'tagline'=>$cmsTagLine, 'siteaddress'=>$cmsSiteAddress,
'supportemail'=>$cmsSupportEmail, 'abouttext'=>$cmsAboutText, 'adscript'=>$cmsAdScript,
'sitenote'=>$cmsSiteNote, 'theme'=>$cmsSiteTheme, 'links'=>$links, 'pages'=>$pages
);
}
function editSettings($settingsSiteName, $settingsAboutText, $settingsAdScript, $settingsSiteNote, $settingsTagLine, $settingsSiteAddress, $settingsSupportEmail, $settingsSiteTheme)
{
$cmsDatabase = new cmsDatabase;
$query = "UPDATE settingsb SET sitename='$settingsSiteName', abouttext='".$settingsAboutText."', adscript='".$settingsAdScript."', sitenote='".$settingsSiteNote."', tagline = '".$settingsTagLine."', siteaddress = '".$settingsSiteAddress."', supportemail = '".$settingsSupportEmail."', theme = '".$settingsSiteTheme."' WHERE id='1'";
$d = $cmsDatabase->db($query);
return !$d ? false : true;
}
function editLink($update, $i)
{
$cmsDatabase = new cmsDatabase;
$query = "UPDATE links SET link='$update' WHERE id='$i'";
$d = $cmsDatabase->db($query);
return !$d ? false : true;
}
function addLink($update)
{
$cmsDatabase = new cmsDatabase;
$query = "INSERT INTO links (link) VALUES ('$update')";
$d = $cmsDatabase->db($query);
return !$d ? false : true;
}
function addPage($name, $content, $php, $active)
{
$cmsDatabase = new cmsDatabase;
$query = "INSERT INTO pages (name, page, isphp, active) VALUES ('$name', '$content', '$php', '$active')";
$d = $cmsDatabase->db($query);
return !$d ? false : true;
}
function editPage($name, $content, $php, $active, $id)
{
$cmsDatabase = new cmsDatabase;
$query = "UPDATE pages SET name='$name', page='$content', isphp='$php', active='$active' WHERE id='$id'";
$d = $cmsDatabase->db($query);
return !$d ? false : true;
}
function remPage($id)
{
$cmsDatabase = new cmsDatabase;
$query = "DELETE FROM pages WHERE id='$id'";
$d = $cmsDatabase->db($query);
return !$d ? false : true;
}
function remLink($id)
{
$cmsDatabase = new cmsDatabase;
$query = "DELETE FROM links WHERE id='$id'";
$d = $cmsDatabase->db($query);
return !$d ? false : true;
}
function getPage($id)
{
$cmsDatabase = new cmsDatabase;
$query = "SELECT * FROM pages WHERE id='$id'";
$d = $cmsDatabase->db($query, true);
return $d;
}
function isPhp($id)
{
$cmsDatabase = new cmsDatabase;
$query = "SELECT isphp FROM pages WHERE id='$id'";
$d = $cmsDatabase->db($query, true);
if ($d['isphp'] == '1')
{
return true;
}
else
{
return false;
}
}
function getLinkId($link)// Deprecated!
{
$cmsDatabase = new cmsDatabase;
$query = "SELECT id FROM links WHERE link='$link'";
$return = $cmsDatabase->db($query, true);
return $return['id'];
}
function getCurrTheme()
{
$cmsDatabase = new cmsDatabase;
$query = "SELECT theme FROM settingsb WHERE id='1'";
$return = $cmsDatabase->db($query, true);
return $return['theme'];
}
}
?>
| true |
88384030ab0e4dcdfe2d34a0665b503991a035ad | PHP | kranack/frmwrk | /app/framework/modules/Form/class/Form.php | UTF-8 | 1,392 | 2.765625 | 3 | [] | no_license | <?php
namespace Modules\Form;
/* TODO: FOR LIE A L'ID PUTAIN DE MERDE T'ES CON OU QUOI?!!! */
class Form {
private $_objs = array();
private $__template_path;
public function __construct ($type, $action) {
$this->_type = $type;
$this->_action = $action;
$this->__module_path = dirname(__DIR__);
$this->__template_path = $this->__module_path . DIRECTORY_SEPARATOR . '_templates/';
return $this;
}
public function add_obj ($obj) {
$classname = get_class($obj);
if (!isset($this->_objs[strtolower($classname)])) {
$this->_objs [strtolower($classname)] = array();
}
$this->_objs [strtolower($classname)][] = $obj;
return $this;
}
public function add ($input, $name, $type = "text", $id = null, $class = null) {
$classname = ucfirst($input);
if (!Core::is_loaded($classname)) {
return null;
}
if (!isset($this->_objs[$input])) {
$this->_objs [$input] = array();
}
$this->_objs [$input][] = new $classname($name, $type, $id, $class);
return $this;
}
public function display () {
return $this->render();
}
public function check () {
$r = false;
foreach ($this->_objs as $obj) {
$r |= $obj->check();
}
return $r;
}
private function render () {
ob_start();
require ($this->__template_path . 'form.tpl');
return ob_get_clean();
}
}
| true |
64387308393323401b1952ce37962c10283173c6 | PHP | vinhnguyen13/krp | /source/apps/backend/protected/modules/news/controllers/ArticleController.php | UTF-8 | 15,093 | 2.703125 | 3 | [] | no_license | <?php
class ArticleController extends Controller
{
/**
* @var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='//layouts/column2';
/**
* Displays a particular model.
* @param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'article'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$this->layout='//layouts/column1';
$model= new Article();
$model->public_time = time();
$model->author_name = Yii::app()->user->data()->username;
if(isset($_POST['Article']))
{
$model->attributes = $_POST['Article'];
$model->tmp_sections = isset($_POST['Article']['sections']) ? $_POST['Article']['sections'] : array();
$model->tmp_categories = isset($_POST['Article']['categories']) ? $_POST['Article']['categories'] : array();
$model->created = time();
$model->last_modify = time();
$model->creator = Yii::app()->user->getId();
$model->public_time = strtotime($_POST['Article']['public_time']);
$model->setTags($_POST['tags']);
$model->validate();
if($model->save()){
/**
* save traslate default
*/
$languageDefault = Language::model()->find("is_default = 1");
$articleTrans = ArticleTranslation::model()->findByAttributes(array('article_id'=>$model->id, 'language_code'=>$languageDefault->code));
if(empty($articleTrans)){
$articleTrans = new ArticleTranslation();
}
$articleTrans->article_id = $model->id;
$articleTrans->language_code = $languageDefault->code;
$articleTrans->attributes = $model->attributes;
$articleTrans->validate();
if(!$articleTrans->hasErrors()){
$articleTrans->save();
}
/**
* save traslate
*/
if(isset($_POST['ArticleTranslation']))
{
foreach ($_POST['ArticleTranslation'] as $lang => $article){
$articleTrans = ArticleTranslation::model()->findByAttributes(array('article_id'=>$model->id, 'language_code'=>$lang));
if(empty($articleTrans)){
$articleTrans = new ArticleTranslation();
}
$articleTrans->article_id = $model->id;
$articleTrans->language_code = $lang;
$articleTrans->attributes = $article;
$articleTrans->validate();
if(!$articleTrans->hasErrors()){
$articleTrans->save();
}
}
}
$this->redirect(array('admin'));
}
}
$this->render('create',array(
'model'=>$model,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$this->layout='//layouts/column1';
$model = $this->loadModel($id);
if(isset($_POST['Article']))
{
$model->attributes= $_POST['Article'];
$model->featured = $_POST['Article']['featured'];
$model->tmp_sections = isset($_POST['Article']['sections']) ? $_POST['Article']['sections'] : array();
$model->tmp_categories = isset($_POST['Article']['categories']) ? $_POST['Article']['categories'] : array();
$model->last_modify = time();
//$model->creator = Yii::app()->user->getId();
$model->public_time = strtotime($_POST['Article']['public_time']);
$model->setTags($_POST['tags']);
$model->validate();
if($model->save()){
/**
* save traslate default
*/
$languageDefault = Language::model()->find("is_default = 1");
$articleTrans = ArticleTranslation::model()->findByAttributes(array('article_id'=>$model->id, 'language_code'=>$languageDefault->code));
if(empty($articleTrans)){
$articleTrans = new ArticleTranslation();
}
$articleTrans->article_id = $model->id;
$articleTrans->language_code = $languageDefault->code;
$articleTrans->attributes = $model->attributes;
$articleTrans->validate();
if(!$articleTrans->hasErrors()){
$articleTrans->save();
}
/**
* save traslate
*/
if(isset($_POST['ArticleTranslation']))
{
foreach ($_POST['ArticleTranslation'] as $lang => $article){
$articleTrans = ArticleTranslation::model()->findByAttributes(array('article_id'=>$model->id, 'language_code'=>$lang));
if(empty($articleTrans)){
$articleTrans = new ArticleTranslation();
}
$articleTrans->article_id = $model->id;
$articleTrans->language_code = $lang;
$articleTrans->attributes = $article;
$articleTrans->validate();
if(!$articleTrans->hasErrors()){
$articleTrans->save();
}
}
}
$this->redirect(array('admin'));
}
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* @param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
if(Yii::app()->request->isPostRequest)
{
$model = $this->loadModel($id);
$model->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
else
throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('Article');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new Article('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Article']))
$model->attributes=$_GET['Article'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* @param integer the ID of the model to be loaded
*/
public function loadModel($id)
{
$model=Article::model()->loadFullArticle($id);
if(empty($model->public_time))
$model->public_time = time();
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* @param CModel the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='article-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
public function actionTags(){
$tags = Article::model()->getAllTags();
$tmp = array();
if ($tags){
foreach ($tags as $t)
{
$tmp[] = $t;
}
}
echo implode("\n", $tmp);
Yii::app()->end();
}
public function actionGetEvents()
{
//{ "date": "1337594400000", "type": "meeting", "title": "Project A meeting", "description": "Lorem Ipsum dolor set", "url": "http://www.event1.com/" },
$return[] = array(
'date'=>'1358395228000',
'type'=>'meeting',
'title'=>'1 Project A meeting',
'description'=>'Lorem Ipsum dolor set',
'url'=>'http://www.event1.com/',
);
$return[] = array(
'date'=>'1358568048000',
'type'=>'meeting',
'title'=>'2 Project A meeting',
'description'=>'Lorem Ipsum dolor set',
'url'=>'http://www.event1.com/',
);
$return[] = array(
'date'=>'1358740861000',
'type'=>'meeting',
'title'=>'3 Project A meeting',
'description'=>'Lorem Ipsum dolor set',
'url'=>'http://www.event1.com/',
);
echo CJSON::encode($return);
}
private function getThumbnailPath() {
return Yii::app()->basePath.'/../../../../'.Yii::app()->params->news['thumbnail_path'];
}
public function actionLoadFiles($folder) {
$list = Article::loadFiles(Yii::getPathOfAlias('pathroot'). DS . 'themes' . DS . $folder . DS . 'views/layouts' . DS , array());
echo CJSON::encode($list);
exit();
}
public function actionLoadCategories($id) {
$list = Category::model()->getCategories($id);
$result = array();
foreach($list as $item) {
$result[$item->id] = $item->title;
}
echo CJSON::encode($result);
exit();
}
public function actionProducts() {
$models = ProProducts::model()->findAll();
$arr = array();
foreach($models as $model) {
$arr[] = array(
'label'=>$model->title, // label for dropdown list
'value'=>$model->title, // value for input field
'id'=>$model->id, // return value from autocomplete
);
}
echo CJSON::encode($arr);
Yii::app()->end();
}
public function actionBrands() {
$lid = Yii::app()->request->getParam('lid');
$cri = new CDbCriteria();
$cri->addCondition("company_id IN(SELECT id FROM `pro_companies` WHERE city_id = :city)");
$cri->params = array(':city'=>$lid);
$models = ProBrands::model()->findAll($cri);
$data = CHtml::listData( $models, 'id', 'title');
$location = ProLocation::model()->findByPk($lid);
if(!empty($data)){
echo '<div class="listBrand_'.$lid.'">'.CHtml::dropDownList(null, null, $data, array('id'=>"brand_$lid", 'class'=>'lstBrand', 'data-location'=>$lid, 'empty' => '-- Select Brand --')).'</div>';
}
Yii::app()->end();
}
public function actionShops() {
$bid = Yii::app()->request->getParam('bid');
$lid = Yii::app()->request->getParam('lid');
$cri = new CDbCriteria();
$cri->addCondition("brand_id = :brand");
$cri->params = array(':brand'=>$bid);
$models = ProShops::model()->findAll($cri);
$data = CHtml::listData( $models, 'id', 'title');
$location = ProLocation::model()->findByPk($lid);
if(!empty($data)){
echo '<div class="location_'.$lid.' brand_'.$bid.'"><h4>'.$location->city_name.'</h4><ul>'.CHtml::checkBoxList('shop_id', array(), $data, array('class'=>'CBShop', 'template' => '<li>{label} {input}</li>', 'separator'=>false, 'container'=>false)).'</ul></div>';
}
Yii::app()->end();
}
public function actionGalleries() {
$term = Yii::app()->request->getParam('term');
$cri = new CDbCriteria();
$cri->addCondition("name LIKE :term");
$cri->params = array(':term'=> "%$term%");
$cri->limit = 20;
$models = Gallery::model()->findAll($cri);
$arr = array();
foreach($models as $model) {
$arr[] = array(
'label'=>$model->name, // label for dropdown list
'value'=>$model->name, // value for input field
'id'=>$model->id, // return value from autocomplete
);
}
echo CJSON::encode($arr);
Yii::app()->end();
}
public function actionUsers() {
$term = Yii::app()->request->getParam('term');
$cri = new CDbCriteria();
$cri->addCondition("username LIKE :term");
$cri->params = array(':term'=> "%$term%");
$cri->limit = 10;
$models = Member::model()->findAll($cri);
$arr = array();
foreach($models as $model) {
$arr[] = array(
'label'=>$model->username, // label for dropdown list
'value'=>$model->username, // value for input field
'id'=>$model->id, // return value from autocomplete
);
}
echo CJSON::encode($arr);
Yii::app()->end();
}
/**
* Upload File Controller
* Nam Le
*/
public function actionUpload($id = null){
if(Yii::app()->request->isPostRequest && Yii::app()->request->isAjaxRequest){
$id = isset($id) ? $id : 0;
/*if($id > 0){
$model = $this->loadModel($id);
if(count($model->images) == 4){
$result = array('error' => 'Too many items would be uploaded. Item limit is 4.') ;
$result=htmlspecialchars(json_encode($result), ENT_NOQUOTES);
echo $result;
Yii::app()->end();
}
}*/
$params = CParams::load();
$thumb300x0 = $params->params->uploads->article->thumb300x0;
$detail960x0 = $params->params->uploads->article->detail960x0;
$origin = $params->params->uploads->article->origin;
$thumb300x0_folder = $this->setPath ( $thumb300x0->p );
$detail960x0_folder = $this->setPath ( $detail960x0->p );
$origin_folder = $this->setPath ( $origin->p );
$path_folder = $this->setPath ( $params->params->uploads->article->path, false );
Yii::import("backend.extensions.EFineUploader.qqFileUploader");
$uploader = new qqFileUploader();
$uploader->allowedExtensions = array('jpg','jpeg','png');
$uploader->sizeLimit = $params->params->uploads->article->size;//maximum file size in bytes
$uploader->chunksFolder = $origin_folder;
$result = $uploader->handleUpload($origin_folder);
$origin_uploaded_path = $origin_folder . DS . $uploader->getUploadName ();
$resize_large_img = false;
list ( $width, $height ) = getimagesize ( $origin_uploaded_path );
if ($width < $thumb300x0->w || $height < $thumb300x0->h) {
$result ['success'] = false;
$result ['error'] = "Please choose a image file with minimum weight size is {$thumb300x0->w}px and minimum height size is{$thumb300x0->h}px";
} else {
Yii::import("backend.extensions.image.Image");
if ($width > $height) {
$resize_type = Image::HEIGHT;
} else {
$resize_type = Image::WIDTH;
}
if (isset ( $result ['success'] )) {
// begin resize and crop for thumbnail
//Yii::app()->image->load($origin_uploaded_path)->resize($thumb300x0->w, $thumb300x0->h, $resize_type)->crop ( $thumb300x0->w, $thumb300x0->h )->save($thumb300x0_folder.DS.$uploader->getUploadName());
Yii::app()->image->load($origin_uploaded_path)->resize($thumb300x0->w, $thumb300x0->h)->crop ( $thumb300x0->w, $thumb300x0->h )->save($thumb300x0_folder.DS.$uploader->getUploadName());
// resize for detail (width 600)
Yii::app ()->image->load ( $origin_uploaded_path )->resize ( $detail960x0->w, $detail960x0->w, Image::WIDTH )->save ( $detail960x0_folder . DS . $uploader->getUploadName () );
//save to database
$image = new ArticleImage();
$image->article_id = $id;
$image->image = $uploader->getUploadName();
$image->path = $path_folder;
$image->save();
$result['image_id'] = $image->id;
}
}
$result['filename'] = $uploader->getUploadName();
$result['filepath'] = $path_folder;
header("Content-Type: text/plain");
$result=htmlspecialchars(json_encode($result), ENT_NOQUOTES);
echo $result;
Yii::app()->end();
}
}
private function setPath($path, $full = true) {
if (isset ( $path )) {
$path = str_replace ( '{year}', date ( 'Y' ), $path );
$path = str_replace ( '{month}', date ( 'm' ), $path );
$path = str_replace ( '{day}', date ( 'd' ), $path );
$folder = ($full) ? Yii::app()->params['upload_path'] . DS . $path : $path;
if (VHelper::checkDir ( $folder )) {
return $folder;
} else {
return false;
}
} else {
return false;
}
}
}
| true |
57dfb6410ac9ce974158e55b9a8e441849b968ea | PHP | caominhquan/learning | /laravel/app/Http/Controllers/NotesAPIController.php | UTF-8 | 796 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use App\Note;
use Illuminate\Http\Request;
class NotesAPIController extends Controller
{
public function index()
{
return Note::get();
}
public function store(Request $request) {
$post = new Note();
$post->title = $request->title;
$post->description = $request->input('description');
$post->save();
}
public function show($id) {
return Note::findOrFail($id);
}
public function update(Request $request, $id) {
$post = Note::findOrFail($id);
$post->update($request->all());
return $post;
}
public function destroy($id) {
if($id != null) {
$post = Note::findOrFail($id);
$post->delete();
}
}
}
| true |
39bc8db3061b812558cc38611a355aa86acc9556 | PHP | gunelism/task | /q01.php | UTF-8 | 507 | 3.359375 | 3 | [] | no_license | <?php
// Neticesi aşağıdakılar olan funksiya yazın
/*
ekranaYaz(); -->Boş
ekranaYaz('salam'); -->arg1: salam
ekranaYaz('salam', 'heci', 'necesen'); -->arg1: salam,arg2: heci,arg3: necesen
*/
function fun($yaz=null, $h=null, $c=null){
if ($yaz==null) {
echo "bos";
}
elseif($h==null){
echo $yaz;
}elseif($c==null){
echo $yaz . $h;
}else{
echo $yaz . $h . $c;
}
}
$a="hello1 ";
$b="hello ";
$d="ddd";
fun($a,$b,$d);
?> | true |
9cb9348976534bc6bac0e346f59f6580db9308cb | PHP | julienBreem/mvc-fromScratch | /index.php | UTF-8 | 850 | 2.5625 | 3 | [] | no_license | <?php
require __DIR__ . '/vendor/autoload.php';
include('config.php');
//Initializes the request abstraction
//$request = new base\core\request();
$request = new base\core\http\Request();
//getting the view class from the request
$viewFactory = new base\view\ViewFactory();
$view = $viewFactory->getView($request);
$view->setDefaultTemplateLocation($config["view"]["defaultTemplateLocation"]);
$modelService = new base\model\Service($config["model"]);
//getting controller and feeding it the view, the request and the modelFactory.
$controllerFactory = new base\controller\ControllerFactory();
$controller = $controllerFactory->getController($request,$view,$modelService);
//Execute the necessary command on the controller
$command = $request->getActionName();
$controller->{$command}($request);
//Produces the response
echo $view->render();
| true |
a489d1c0cada7ac19da94a39982c47d18332883b | PHP | 1PilotApp/oc-client-plugin | /classes/ComposerUpdateManager.php | UTF-8 | 3,670 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
namespace OnePilot\Client\Classes;
use ApplicationException;
use Artisan;
use Exception;
use Illuminate\Support\Arr;
class ComposerUpdateManager
{
/** @var ComposerProcess */
private $process;
public function __construct()
{
$this->process = new ComposerProcess;
}
/**
* @param string[] $plugins Vendor.Plugin
*
* @return string|null
* @throws ApplicationException
*/
public function updatePlugin(array $plugins)
{
if (empty($packages = $this->composerPackagesFromPluginsCode($plugins))) {
throw new ApplicationException("Plugin not found", 400);
}
return $this->updatePackages($packages);
}
/**
* @return string|null
* @throws ApplicationException
*/
public function updatePackages(array $packages)
{
$this->checkComposerVersion();
$installedPackages = Arr::pluck($this->process->listPackages(), 'name');
if (!empty($diff = array_diff($packages, $installedPackages))) {
throw new ApplicationException('Packages "' . implode(", ", $diff) . '" is not installed');
}
return $this->process->updatePackages($packages);
}
/**
* @return string|null
* @throws ApplicationException
*/
public function updateCore()
{
$this->checkComposerVersion();
return $this->process->updatePackages(['october/*', 'laravel/framework']);
}
/**
* Run composer install to ensure all works properly in case of issue during update
*/
public function install()
{
return $this->process->install();
}
/**
* @return string
*/
public function runDatabaseMigrations()
{
try {
retry(2, function () {
Artisan::call('october:migrate');
});
} catch (\Throwable $e) {
//
}
return Artisan::output();
}
/**
* @param string[] $plugins Vendor.Plugin
*
* @return string[]
*/
public function composerPackagesFromPluginsCode(array $plugins)
{
$updateManager = UpdateManager::instance();
$packages = [];
foreach ($plugins as $plugin) {
try {
$pluginDetails = $updateManager->requestPluginDetails($plugin);
$packages[] = array_get($pluginDetails ?? [], 'composer_code');
} catch (Exception $e) {
//
}
}
return array_filter($packages);
}
/**
* @throws ApplicationException
*/
public function checkComposerVersion()
{
if (version_compare($this->process->version(), '2.0.0', '<')) {
throw new ApplicationException('Require composer 2');
}
}
public function setOctoberCMSVersion()
{
if (empty($octoberSystemVersion = $this->process->getComposerOctoberSystemVersion())) {
return null;
}
if (!empty($build = $this->getBuildFromVersion($octoberSystemVersion))) {
UpdateManager::instance()->setBuild($build);
}
}
/**
* Return the patch version of a semver string
* eg: 1.2.3 -> 3, 1.2.3-dev -> 3
*/
protected function getBuildFromVersion(string $version)
{
$parts = explode('.', $version);
if (count($parts) !== 3) {
return null;
}
$lastPart = $parts[2];
if (!is_numeric($lastPart)) {
$lastPart = explode('-', $lastPart)[0];
}
if (!is_numeric($lastPart)) {
return null;
}
return $lastPart;
}
}
| true |
e1910017e4e3b7342c0ea0f71ed3a83ef5659fd2 | PHP | LiXiaoYaoGG/Ephp | /Core/Core.php | UTF-8 | 2,247 | 2.90625 | 3 | [] | no_license | <?php
namespace Core;
use Core\Core;
use Components\Console\Console;
class Core{
private static $instance;
private $pool = [];
public function __construct(){
self::$instance = &$this;
}
/**
* 获取单例
* @return ControllerFactory
*/
public static function getInstance(){
if (self::$instance == null) {
new Core();
}
return self::$instance;
}
/**
* 执行控制方法
* @param type $controller_name 控制器名称
* @param string $method_name 控制器方法
* @param type $params 参数
* @return type
*/
public function run(&$controller_name,&$method_name,&$client_data,&$request, &$response){
//定义默认方法
if ($controller_name == null) $controller_name = 'index';
if($method_name == null) $method_name = 'index';
$controller_names = $this->pool[$controller_name] ?? null;
if ($controller_names == null) {
$controller_names = $this->pool[$controller_name] = new \SplQueue();
}
if ($controller_names->isEmpty()) {
$class_name = "Controllers\\$controller_name";
if (class_exists($class_name)) {
$obj = new $class_name;
$obj->core_name = $controller_name;
if(method_exists($obj, $method_name)){
try {
$obj->before($client_data,$request,$response);
$obj->$method_name();
$obj->after();
//归还到池中
$this->pool[$obj->core_name]->push($obj);
} catch (\Exception $exc) {
Console::warning($exc->getMessage(),33);
}
}else{
throw new \Exception("Not find the method \"{$method_name}\"");
}
} else {
throw new \Exception("Not find the controller \"{$controller_name}\"");
}
}else{
//从池中获取
$obj = $controller_names->shift();
$obj->core_name = $controller_name;
if(method_exists($obj, $method_name)){
try {
$obj->before($client_data,$request,$response);
$obj->$method_name();
$obj->after();
//归还到池中
$this->pool[$obj->core_name]->push($obj);
} catch (\Exception $exc) {
Console::warning($exc->getMessage(),33);
}
}else{
throw new \Exception("Not find the method \"{$method_name}\"");
}
}
}
} | true |
ba74792a0ef7c10d381854c7294f34bbe649aee8 | PHP | mrloc2015/ITV | /order.php | UTF-8 | 1,510 | 3.5625 | 4 | [] | no_license | <?php
$order = new Order();
$order->setPrice(4000);
var_dump($order);
echo $order->getTotalHtml();
class Order
{
const MINIMUM_PRICE_FREE_SHIPPING = 5000;
const TAX_VALUE = 0.05;
protected $tax = 0 ;
protected $shipping = 0;
protected $price = 0;
public function setPrice($price)
{
$this->price = $price;
$this->calculateShipping($price);
$this->calculateTax($price);
return $this;
}
protected function validatePrice($price)
{
return is_numeric($price);
}
protected function calculateTotal()
{
$result = false;
if($this->validatePrice($this->price)){
$result = $this->price + $this->tax + $this->shipping;
}
return $result;
}
protected function calculateShipping($price)
{
if($price && $price < self::MINIMUM_PRICE_FREE_SHIPPING){
$this->shipping = 60;
}
return $this->shipping;
}
protected function calculateTax($price)
{
$this->tax = $this->price * self::TAX_VALUE;
return $this->tax;
}
public function getTotalHtml()
{
$result = 'Please enter right number format.';
$total = $this->calculateTotal();
if($total){
$result = $this->printHTML('Price',$this->price);
$result .= $this->printHTML('Shipping',$this->shipping);
$result .= $this->printHTML('Tax',$this->tax);
$result .= $this->printHTML('Total', $total);
}
return $result;
}
protected function printHTML($title, $value)
{
return $title . ': '. $value. '<br>';
}
} | true |
ac406eaba8b512adea46f029f7418bbf3b127aa5 | PHP | leomazzolin/mysocialarea | /application/objects/Object.php | UTF-8 | 8,143 | 2.640625 | 3 | [] | no_license | <?php
abstract class Object_Object
{
/**
* PRIVATE DATA
*/
private $_TblName = NULL;
private $_errors = array();
private $_DataTblName = '_data';
private $_db = NULL;
private $_CategoryValues = array( 'id', 'tbl', 'ref_id', 'category', 'description', 'value', 'created', 'modified' );
/*
* PROTECTED DATA
*/
protected $_object = array(
'general' => array(),
'data' => array()
);
function __construct($obj = NULL, $search = NULL){
$config = Zend_Registry::get('appOptions');
$this->_db = Zend_Db::factory($config['resources']['db']['adapter'], $config['resources']['db']['params']);
if($obj != NULL){
$this->_TblName = $obj;
if($search != NULL){
$this->_populate($search);
}
}
}
/*
* ABSTRACT FUNCTIONS
*/
abstract public function _sanitize();
/*
* PRIVATE FUNCTIONS
*/
private function _read($read){
$payload = array();
$this->_db->beginTransaction();
try {
$select = $this->_db->select()
->from($this->_TblName);
foreach($read as $key => $value){
$select->where( $key . ' = ?', $value );
}
$stmt = $this->_db->query($select);
$payload = $stmt->fetchAll();
switch(count($payload)){
case 0:
$payload = NULL;
break;
case 1:
$this->_db->commit();
break;
default:
throw new Exception("Object_Object->_read()<br />Invalid number of rows returned...can only be 1 ");
break;
}
return $payload;
} catch (Exception $e) {
$this->_db->rollBack();
return $this->_error($e);
}
}
private function _insert($insert){
$payload = array();
$this->_db->beginTransaction();
try {
$created = new Zend_Db_Expr('NOW()');
$insert['created'] = $created;
$this->_db->insert($this->_TblName, $insert);
$insertID = $this->_db->lastInsertId();
$this->_db->commit();
return $insertID;
} catch (Exception $e) {
$this->_db->rollBack();
return $this->_error($e);
}
}
private function _update($update){
$payload = array();
$this->_db->beginTransaction();
try {
$this->_db->update($this->_TblName, $update, 'id = ' . $this->_object['general']['id']);
$this->_db->commit();
$payload = $this->_read(array('id' => $this->_object['general']['id']));
$this->_object['general'] = $this->_toRow($payload);
return $payload;
} catch (Exception $e) {
$this->_db->rollBack();
return $this->_error($e);
}
}
private function _delete(){
$payload = array();
$this->_db->beginTransaction();
try {
$payload = $this->_db->delete($this->_TblName, 'id = ' . $this->_object['general']['id']);
$this->_db->commit();
if(is_numeric(count($payload))){
$this->_object['general'] = array();
}
return $payload;
} catch (Exception $e) {
$this->_db->rollBack();
return $this->_error($e);
}
}
private function _readData($data){
$payload = array();
$this->_db->beginTransaction();
try {
$select = $this->_db->select()
->from($this->_TblName . $this->_DataTblName);
$select->where('ref_id = ?', $this->_object['general']['id']);
$select->order(array('category ASC', 'description ASC'));
$stmt = $this->_db->query($select);
$result = $stmt->fetchAll();
$this->_db->commit();
$payload = $result;
return $payload;
} catch (Exception $e) {
$this->_db->rollBack();
return $this->_error($e);
}
}
private function _editData($edit){
$payload = array();
$editType = 'insert';
$this->_db->beginTransaction();
try {
if(array_key_exists('data', $this->_object)){
if(array_key_exists($edit['category'], $this->_object['data'])){
if(array_key_exists($edit['description'], $this->_object['data'][$edit['category']])){
$editType = 'update';
}
}
}
if($editType == 'insert'){
$created = new Zend_Db_Expr('NOW()');
$item['created'] = $created;
$item['ref_id'] = $this->_object['general']['id'];
$item['category'] = $edit['category'];
$item['description'] = $edit['description'];
$item['value'] = $edit['value'];
$this->_db->insert($this->_TblName . $this->_DataTblName, $item);
$insertID = 0;
$insertID = $this->_db->lastInsertId();
if($insertID > 0 && is_numeric($insertID)){
$this->_object['data'][$edit['category']][$edit['description']] = $edit['value'];
}
}
else{
$where = array(
'ref_id = ?' => $this->_object['general']['id'],
'category = ?' => $edit['category'],
'description = ?' => $edit['description'],
);
$result = $this->_db->update($this->_TblName . $this->_DataTblName, array('value' => $edit['value']), $where);
if($result == 1){
$this->_object['data'][$edit['category']][$edit['description']] = $edit['value'];
}
}
$this->_db->commit();
return $payload;
} catch (Exception $e) {
$this->_db->rollBack();
return $this->_error($e);
}
}
private function _deleteData(){
$payload = array();
$this->_db->beginTransaction();
try {
$payload = $this->_db->delete($this->_TblName . $this->_DataTblName, 'ref_id = ' . $this->_object['general']['id']);
$this->_db->commit();
if(is_numeric(count($payload))){
$this->_object['data'] = array();
}
return $payload;
} catch (Exception $e) {
$this->_db->rollBack();
return $this->_error($e);
}
}
private function _toRow($rowset){
$payload = array();
if(count($rowset) == 1){
foreach($rowset[0] as $key =>$value){
$payload[$key] = $value;
}
}
return $payload;
}
protected function _error($e){
return array( 'errors' => array(
'message' => $e->getMessage(),
'exception' => $e->getTraceAsString(),
'request' => 'NONE'
)
);
}
/*
* PROTECTED FUNCTIONS
*/
protected function _setTblName($name){
$this->_TblName = $name;
}
protected function _populate($search){
$payload = array();
$rowset = $this->_read($search);
if($rowset != NULL){
$this->_object['general'] = $this->_toRow($rowset);
$search = array(
'ref_id' => $this->_object['general']['id'],
);
$rowset = $this->_readData($search);
$categories= array();
$i = 0;
foreach($rowset as $row){
$this->_object['data'][$row['category']][$row['description']] = $row['value'];
$rowset[$i] = NULL;
$i++;
}
}
}
/*
* PUBLIC FUNCTIONS
*/
public function _getObject(){
return $this->_object;
}
public function _newObject($insert){
$id = $this->_insert($insert);
if(is_numeric($id) && $id > 0){
$search = array( 'id' => $id );
$this->_populate($search);
return $id;
}
else{
return NULL;
}
}
public function _updateObject($edit){
if(array_key_exists('general', $edit)){
$result = $this->_update($edit['general']);
}
if(array_key_exists('data', $edit)){
foreach($edit['data'] as $data){
$this->_editData($data);
}
}
}
public function _deleteObject(){
$this->_deleteData();
$this->_delete();
}
public function _getGeneralData(){
return $payload = $this->_object['general'];
}
public function _getDataValue($category, $description){
$payload = NULL;
if($this->_object == NULL){
return $payload;
}else{
foreach($this->_object['data'] as $row){
if($row['category'] == $category && $row['description'] == $description){
$payload = trim($row['value']);
break;
}
}
return $payload;
}
}
public function _getCategory($category){
$payload = array();
if($this->_object == NULL){
return $payload;
}
else{
foreach($this->_object['data'] as $row){
if($row['category'] == $category){
$payload[trim($row['description'])] = trim($row['value']);
}
}
return $payload;
}
}
public function _overview(){
$payload = array();
$this->_db->beginTransaction();
try{
$select = $this->_db->select()
->from(array('item' => $this->_TblName), array('COUNT(item.id) AS count', 'MAX(item.created) AS latest'));
$stmt = $this->_db->query($select);
$overview = $stmt->fetch();
$payload = $overview;
$this->_db->commit();
return $payload;
}catch (Exception $e){
$this->_db->rollBack();
return $this->_error($e);
}
}
}
?> | true |
abaec93b962e6aaad637b4a45b906755a63b7af3 | PHP | slince/composer-registry-manager | /src/Command/ResetCommand.php | UTF-8 | 1,119 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
/*
* This file is part of the slince/composer-registry-manager package.
*
* (c) Slince <taosikai@yeah.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Slince\Crm\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
class ResetCommand extends Command
{
/**
* {@inheritdoc}
*/
public function configure()
{
$this->setName('repo:reset')
->setDescription('Remove custom repositories and reset to default');
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
$style = new SymfonyStyle($input, $output);
if ($style->ask('This command will remove custom repositories. Are you sure to do this?')) {
$this->repositoryManager->resetRepositories();
$style->success('Successfully reset');
}
return 0;
}
} | true |
114a62afdfb0b51c20028b35a23ff204ed8d5f58 | PHP | dougblackjr/ee-json-ld | /addon/json_ld/vendor/spatie/schema-org/src/Menu.php | UTF-8 | 1,454 | 2.875 | 3 | [
"MIT"
] | permissive | <?php
namespace Spatie\SchemaOrg;
/**
* A structured representation of food or drink items available from a
* FoodEstablishment.
*
* @see http://schema.org/Menu
*/
class Menu extends CreativeWork
{
/**
* A food or drink item contained in a menu or menu section.
*
* @param \Spatie\SchemaOrg\MenuSection $hasMenuItem
*
* @return static
*
* @see http://schema.org/hasMenuItem
*/
public function hasMenuItem($hasMenuItem)
{
return $this->setProperty('hasMenuItem', $hasMenuItem);
}
/**
* A subgrouping of the menu (by dishes, course, serving time period, etc.).
*
* @param \Spatie\SchemaOrg\MenuSection $hasMenuSection
*
* @return static
*
* @see http://schema.org/hasMenuSection
*/
public function hasMenuSection($hasMenuSection)
{
return $this->setProperty('hasMenuSection', $hasMenuSection);
}
/**
* Additional menu item(s) such as a side dish of salad or side order of
* fries that can be added to this menu item. Additionally it can be a menu
* section containing allowed add-on menu items for this menu item.
*
* @param \Spatie\SchemaOrg\MenuItem|\Spatie\SchemaOrg\MenuSection $menuAddOn
*
* @return static
*
* @see http://schema.org/menuAddOn
*/
public function menuAddOn($menuAddOn)
{
return $this->setProperty('menuAddOn', $menuAddOn);
}
} | true |
736b26a35306d8c4bdb39ddba401095c1841de64 | PHP | snamper/pms | /src/Validation/Validator/transactionValidator.php | UTF-8 | 1,059 | 2.53125 | 3 | [] | no_license | <?php
namespace pms\Validation\Validator;
/**
* 事务验证
* Class transactionValidator
* @package pms\Validation\Validator
*/
class transactionValidator extends \pms\Validation\Validator
{
/**
* 进行验证
* @param \Phalcon\Validation $validation
* @param type $attribute
* @return boolean
*/
public function validate(\Phalcon\Validation $validation, $attribute)
{
$transaction = $this->get_transactionManager();
if (!$transaction->has()) {
# 没有启动事务
$validation->appendMessage(
new \Phalcon\Validation\Message($this->getOption("message", 'no-start-transaction'), $attribute, 'transaction')
);
return false;
}
return true;
}
/**
* 获取事务管理器
* @return \Phalcon\Mvc\Model\Transaction\Manager
*/
private function get_transactionManager(): \Phalcon\Mvc\Model\Transaction\Manager
{
return \Phalcon\Di::getDefault()->getShared('transactionManager');
}
} | true |
a6684e7bae97ebe73033e34b9f533fad16243179 | PHP | jordanrynard/Code-Examples | /PHP Application - Autodownloader/classes/ImdbList.class.php | UTF-8 | 1,738 | 2.859375 | 3 | [] | no_license | <?
namespace MediaCenter;
require_once('./libraries/simple_html_dom.php'); // http://simplehtmldom.sourceforge.net/manual.htm
class ImdbList {
function __construct(){
}
static function get_results($url){
// User Agent seems to be required by The Pirate Bay
ini_set('user_agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.9) Gecko/20071025 Firefox/2.0.0.9');
$html = file_get_html($url);
if (empty($html)){
Error::warning("Could not reach IMDB to retrieve this list ".$url);
return;
}
return self::parse_results($html);
}
static function parse_results($html){
$shows = array();
$list = $html->find("div.list",0);
if (empty($list)){
Error::notice("Empty list page on IMDB.");
return;
}
$list_items = $list->children();
foreach ($list_items as $list_item){
$a_link = $list_item->find("a",0);
$link = $a_link->getAttribute("href");
$_link = explode("/",$link);
$shows[]['imdb_id'] = (string)$_link[2];
$shows[]['tvdb_id'] = (string)$_link[2]; // It's actually IMDB_ID but we're passing it to a Trakt function that reads tvdb_id
}
return $shows;
}
static function get_ids($url){
// http://www.imdb.com/list/y6ZxAmYH5VY/ (2013-2014 new shows)
$shows = self::get_results($url);
return $shows;
}
// Does this belong here? This is all kinda wonky
static function update_shows_new(){
$shows = self::get_ids('http://www.imdb.com/list/y6ZxAmYH5VY/');
Debug::msg("Updating IMDB List shows New");
DB::query('TRUNCATE TABLE `list_shows_new`');
$_shows = Trakt::get_shows($shows);
foreach ($_shows as $_show){
DB::insert('list_shows_new', array(
'tvdb_id'=>$_show['tvdb_id']
));
}
Trakt::update_show_database($shows);
}
}
?> | true |
0f3e2207f227ec45af0a98bc5fb68d17cfb699d1 | PHP | ProgressoRU/plasticode | /src/Models/Traits/CachedDescription.php | UTF-8 | 1,959 | 2.671875 | 3 | [] | no_license | <?php
namespace Plasticode\Models\Traits;
use Plasticode\Util\Date;
trait CachedDescription
{
protected static function getDescriptionField()
{
return 'description';
}
protected static function getDescriptionCacheField()
{
return 'cache';
}
protected static function getDescriptionTTL()
{
return '1 hour';
}
public function parsedDescription()
{
return $this->lazy(function () {
$descriptionField = static::getDescriptionField();
$cacheField = static::getDescriptionCacheField();
$description = $this->{$descriptionField};
$cache = $this->{$cacheField};
if (strlen($description) > 0) {
if (strlen($cache) > 0) {
$parsed = @json_decode($cache, true);
}
if (is_array($parsed)) {
$updatedAt = $parsed['updated_at'] ?? null;
if (!$updatedAt || Date::expired($updatedAt, static::getDescriptionTTL())) {
unset($parsed);
}
}
if (!is_array($parsed)) {
$parsed = self::$parser->parse($description);
$parsed['updated_at'] = Date::dbNow();
$this->{$cacheField} = json_encode($parsed);
$this->save();
}
if (is_array($parsed)) {
$parsed['text'] = self::$parser->renderLinks($parsed['text']);
}
}
return $parsed ?? [];
});
}
public function resetDescription()
{
$cacheField = static::getDescriptionCacheField();
$this->{$cacheField} = null;
$this->save();
$this->resetLazy('parsedDescription');
}
}
| true |
4eff62972df6809ca7c19dfbda65a6c08edea62c | PHP | anggadarkprince/angga-ari.com | /app/Taxonomy.php | UTF-8 | 1,788 | 2.546875 | 3 | [] | no_license | <?php
namespace App;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
class Taxonomy extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'term', 'slug', 'type', 'category', 'description'
];
/**
* Scope a query to sort latest post by published date.
*
* @param Builder $query
* @param $category
* @return Builder
*/
public function scopeCategory($query, $category)
{
return $query->where('category', $category);
}
/**
* Scope a query to sort latest post by published date.
*
* @param Builder $query
* @param $type
* @return Builder
*/
public function scopeType($query, $type)
{
return $query->where('type', $type);
}
/**
* Get the owner that owns the taxonomy.
*/
public function user()
{
return $this->belongsTo(User::class);
}
/**
* Get all of the posts that are assigned this tag.
*/
public function posts()
{
return $this->morphedByMany(Post::class, 'taggable', 'taxonomy_relationships')->withTimestamps();
}
/**
* Get all of the showcase that are assigned this tag.
*/
public function showcases()
{
return $this->morphedByMany(Portfolio::class, 'taggable', 'taxonomy_relationships')->withTimestamps();
}
/**
* Get categories by user id and type.
*
* @param $userId
* @param $type
* @return mixed
*/
public function categories($userId, $type)
{
return $this->where('user_id', $userId)
->orWhere('slug', 'uncategories')
->category($type)
->get();
}
}
| true |
64ff7b6be896f82beaf0a484377860967e15546a | PHP | chaplean/coding-standard | /phpcs/ChapleanStandard/Sniffs/File/DisallowDoubleEmptyLineSniff.php | UTF-8 | 2,019 | 3.046875 | 3 | [] | no_license | <?php
/**
* Disallow double consecutive empty lines in file.
*
* @author Tom - Chaplean <tom@chaplean.coop>
* @copyright 2014 - 2017 Chaplean (http://www.chaplean.coop)
* @since 1.1.0
*/
class ChapleanStandard_Sniffs_File_DisallowDoubleEmptyLineSniff implements PHP_CodeSniffer_Sniff
{
protected $consecutiveLines = 0;
/**
* Returns the token types that this sniff is interested in.
*
* @return array
*/
public function register()
{
return array(
T_WHITESPACE
);
}
/**
* Processes the tokens that this sniff is interested in.
*
* @param PHP_CodeSniffer_File $phpcsFile The file where the token was found.
* @param integer $stackPtr The position in the stack where
* the token was found.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$token = $tokens[$stackPtr];
/**
* We want only spaces or endlines on our lines
*/
$containsNewLineCharacter = preg_match('/\n/', $token['content']);
$nextLine = $token['column'] == 1 && $containsNewLineCharacter;
// Cause it's really annoying to show something... [For test purpuse only]
// $msg = $this->consecutiveLines . ' ' . json_encode($token['content']) . ' ' . (int) $containsNewLineCharacter . ' ' . $token['line'] . '-' . $token['column'] . ' ' .
// var_export($nextLine, true);
// $phpcsFile->addWarning($msg, $stackPtr, 'Test');
if ($nextLine) {
$this->consecutiveLines++;
if ($this->consecutiveLines >= 2) {
$this->consecutiveLines = 0;
$error = 'You can\'t have two consecutives empty lines or more.';
$phpcsFile->addError($error, $stackPtr);
}
return;
}
$this->consecutiveLines = 0;
}
}
| true |
8ae742c03d34c96f9aa06bd073be7ba8fe86a3f6 | PHP | handylim/SlidingPuzzle | /login.php | UTF-8 | 2,252 | 2.59375 | 3 | [] | no_license | <?php
session_start();
function testInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$response['connected'] = null;
$response['error'] = null;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$userEmail = testInput($_POST["email"]);
$userPassword = sha1($_POST["password"]);
$serverName = "ap-cdbr-azure-southeast-b.cloudapp.net";
$databaseName = "Default Database";
$userName = "b7c4a56e485de0";
$password = "4ed752a1";
try {
$conn = new PDO ("mysql:host=$serverName;dbname=$databaseName",$userName,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
if ($_POST["signUp"] == "false") { // login
$sql = "SELECT COUNT(*) FROM PlayerData WHERE email='$userEmail'";
if ($rslt = $conn->query($sql)) {
if ($rslt->fetchColumn() >= 1) {
$sql = "SELECT password FROM PlayerData WHERE email='$userEmail'";
foreach ($conn->query($sql) as $row) {
if ($row['password'] == $userPassword) {
$response['connected']=true;
$_SESSION['email'] = $userEmail;
}
}
if ($response['connected'] == null) {
$response['error'] = "Email and password not match";
}
}
else {
$response['error'] = "Email not found in the database";
}
}
}
else { // Sign up
$sql = "SELECT email FROM PlayerData";
$result = $conn->query($sql);
$isEmailExist=false;
foreach($result as $row){
if($row['email'] == $userEmail){
$isEmailExist=true;
$response['error'] = "Email has been used";
}
}
if($isEmailExist == false){
$sql=$conn->prepare("INSERT INTO PlayerData (email, password)
VALUES (:useremail, :userpassword)");
$sql->bindParam(':useremail',$userEmailParam);
$sql->bindParam(':userpassword',$userPasswordParam);
$userEmailParam=$userEmail;
$userPasswordParam=$userPassword;
$sql->execute();
$response['connected'] = true;
$_SESSION['email'] = $userEmail;
}
}
}
catch (PDOException $e) {
$response['error'] = "Connection failed: " . $e->getMessage();
$response['connected'] = false;
}
$conn = null;
}
echo json_encode($response);
?>
| true |
d691b0cf8a8dff6f99ba6a6dabb8f12e019d564d | PHP | codertiu/city-edu | /console/migrations/m180511_154840_create_member_salary_table.php | UTF-8 | 886 | 2.53125 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
use yii\db\Migration;
/**
* Handles the creation of table `member_salary`.
*/
class m180511_154840_create_member_salary_table extends Migration
{
/**
* {@inheritdoc}
*/
public function safeUp()
{
$this->createTable('member_salary', [
'id' => $this->primaryKey(),
'member_id'=>$this->integer()->notNull(),
'sum'=>$this->decimal(10,2)->notNull(),
'date'=>$this->date()->notNull(),
'comment'=>$this->string(150)->null(),
'type_pay'=>$this->integer(1)->notNull(),
'currency_id'=>$this->integer(1)->notNull(),
'create_date'=>$this->dateTime()->notNull(),
'update_date'=>$this->dateTime()->notNull()
]);
}
/**
* {@inheritdoc}
*/
public function safeDown()
{
$this->dropTable('member_salary');
}
}
| true |
d60471b59ab47cd933f7cda3b90953411546c5ec | PHP | Rahim12345/barcode | /seller/rightBorder.php | UTF-8 | 1,740 | 2.59375 | 3 | [
"MIT"
] | permissive | <?php ?>
<table class="table table-dark" style="width: 100%;font-size: 10px;">
<thead style="background-color: #1c4b79;">
<tr>
<th scope="col">№</th>
<th scope="col">İstehsalçı</th>
<th scope="col">Ünvan</th>
<th scope="col">Model</th>
<th scope="col">Kateqoriya</th>
<th scope="col">Seria(və ya Say)</th>
<th scope="col">N/S qiyməti ($)</th>
<th scope="col">K/S qiyməti ($)</th>
</tr>
</thead>
<tbody style="background-color: #1c4b79;">
<?php
$n=0;
foreach($rowscategory as $rowcategory)
{
if($rowcategory["selling"]<$max)
{
$n++;
?>
<tr>
<th scope="row"><?php echo $n; ?></th>
<td><?php echo $rowcategory["manufacturer"]; ?></td>
<td><?php echo $rowcategory["warehouse"]; ?></td>
<td><?php echo $rowcategory["model"]; ?></td>
<td><?php echo $rowcategory["category"]; ?></td>
<td>
<?php
if($rowcategory["seria"]!="")
{
echo $rowcategory["seria"];
}
else
{
echo $rowcategory["dimension"];
}
?>
</td>
<td><?php echo $rowcategory["selling"]; ?></td>
<td><?php echo $rowcategory["credit"]; ?></td>
</tr>
<?php
}
}
?>
<tr>
<td colspan="8" style="text-align: center;font-size: 20px;color:orange;font-weight: bold;">
<?php
if($n==0)
{
echo "Heç bir nəticə tapılmadı";
}
else
{
echo $max." AZN dən ucuz məhsul sayı ".$n;
}
?>
</td>
</tr>
</tbody>
</table> | true |
99f8575047927c59918ffe16219f7404bd2a56aa | PHP | octfx/WebProgrammierungShop | /app/SparkPlug/Config.php | UTF-8 | 1,143 | 2.828125 | 3 | [] | no_license | <?php declare(strict_types = 1);
/**
* User: Hannes
* Date: 20.11.2017
* Time: 18:37
*/
namespace App\SparkPlug;
/**
* Class Config
* Lädt PHP Dateien aus config Ordner
*/
class Config
{
private $configFolder;
private $config = [];
/**
* Config constructor.
*/
public function __construct()
{
$this->configFolder = app()->getBasePath().'/config/';
$files = glob($this->configFolder.'*.php');
foreach ($files as $file) {
$key = str_replace(['.php', $this->configFolder], '', $file);
$this->config[$key] = require $file;
}
}
/**
* @param string $key Der zu suchende Key in Dot notaion
*
* @return array|mixed
*/
public function get(string $key)
{
$config = $this->config;
$keys = explode('.', $key);
foreach ($keys as $key) {
if (!is_array($config) || !array_key_exists($key, $config)) {
throw new \InvalidArgumentException("No config with key {$key} found!");
}
$config = &$config[$key];
}
return $config;
}
}
| true |
60b0a727c306414b4c95caae6fba899dc6db7885 | PHP | rpistoresi/ilr | /rand.php | UTF-8 | 665 | 3.015625 | 3 | [] | no_license | <?php
// seed with microseconds
function make_seed()
{
list($usec, $sec) = explode(' ', microtime());
return $sec + $usec * 1000000;
}
srand(make_seed());
$randval = rand();
//echo $randval;
echo '<br>';
// $fileTempName = "raytest.jpg";
// $fileName = substr($fileName, 0, strpos($fileName, "test"));
// $ext2 = pathinfo($fileTempName, PATHINFO_EXTENSION);
// $num = 12;
// echo $fileName . (string) $num . "." . $ext2;
$path_parts = pathinfo('raytest.jpg');
// echo $path_parts['dirname'], "\n";
// echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // filename is only since PHP 5.2.0
?>
| true |
80500de22a629beea619a73665299fa8269597e4 | PHP | JanekRoos/gs1-barcode-parser | /src/Parser/ParserConfig.php | UTF-8 | 1,754 | 2.734375 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace Lamoda\GS1Parser\Parser;
use Lamoda\GS1Parser\Barcode;
use Lamoda\GS1Parser\Constants;
final class ParserConfig
{
/**
* @var bool
*/
private $fnc1SequenceRequired = true;
/**
* @var array
*/
private $fnc1PrefixMap = [
Constants::FNC1_GS1_DATAMATRIX_SEQUENCE => Barcode::TYPE_GS1_DATAMATRIX,
Constants::FNC1_GS1_128_SEQUENCE => Barcode::TYPE_GS1_128,
Constants::FNC1_GS1_QRCODE_SEQUENCE => Barcode::TYPE_GS1_QRCODE,
Constants::FNC1_GS1_EAN_SEQUENCE => Barcode::TYPE_EAN,
];
/**
* @var string
*/
private $groupSeparator = Constants::GROUP_SEPARATOR_SYMBOL;
/**
* @var array of strings
*/
private $knownAIs = [];
public function isFnc1SequenceRequired(): bool
{
return $this->fnc1SequenceRequired;
}
public function setFnc1SequenceRequired(bool $fnc1SequenceRequired): self
{
$this->fnc1SequenceRequired = $fnc1SequenceRequired;
return $this;
}
public function getFnc1PrefixMap(): array
{
return $this->fnc1PrefixMap;
}
public function setFnc1PrefixMap(array $fnc1PrefixMap): self
{
$this->fnc1PrefixMap = $fnc1PrefixMap;
return $this;
}
public function getGroupSeparator(): string
{
return $this->groupSeparator;
}
public function setGroupSeparator(string $groupSeparator): self
{
$this->groupSeparator = $groupSeparator;
return $this;
}
public function getKnownAIs(): array
{
return $this->knownAIs;
}
public function setKnownAIs(array $knownAIs): self
{
$this->knownAIs = $knownAIs;
return $this;
}
} | true |
1398bcfa83232313f19067b1014b06b9cb96270e | PHP | RegioneER/sirer | /html/html/xCDMProtocolloLib_PROD/Archiflow/soapClient/Card/Type/KeyVersion.php | UTF-8 | 6,321 | 2.796875 | 3 | [] | no_license | <?php
namespace ArchiflowWSCard\Type;
use Phpro\SoapClient\Type\RequestInterface;
class KeyVersion implements RequestInterface
{
/**
* @var string
*/
private $Digest = null;
/**
* @var \ArchiflowWSCard\Type\ArrayOfField
*/
private $Indexes = null;
/**
* @var \DateTime
*/
private $ModificationDate = null;
/**
* @var string
*/
private $NomeAllegato = null;
/**
* @var int
*/
private $OperationalOfficeCode = null;
/**
* @var string
*/
private $OperationalOfficeName = null;
/**
* @var int
*/
private $TipoDato = null;
/**
* @var int
*/
private $TipoOperazione = null;
/**
* @var int
*/
private $UserCode = null;
/**
* @var string
*/
private $UserName = null;
/**
* @var int
*/
private $Version = null;
/**
* Constructor
*
* @var string $Digest
* @var \ArchiflowWSCard\Type\ArrayOfField $Indexes
* @var \DateTime $ModificationDate
* @var string $NomeAllegato
* @var int $OperationalOfficeCode
* @var string $OperationalOfficeName
* @var int $TipoDato
* @var int $TipoOperazione
* @var int $UserCode
* @var string $UserName
* @var int $Version
*/
public function __construct($Digest, $Indexes, $ModificationDate, $NomeAllegato, $OperationalOfficeCode, $OperationalOfficeName, $TipoDato, $TipoOperazione, $UserCode, $UserName, $Version)
{
$this->Digest = $Digest;
$this->Indexes = $Indexes;
$this->ModificationDate = $ModificationDate;
$this->NomeAllegato = $NomeAllegato;
$this->OperationalOfficeCode = $OperationalOfficeCode;
$this->OperationalOfficeName = $OperationalOfficeName;
$this->TipoDato = $TipoDato;
$this->TipoOperazione = $TipoOperazione;
$this->UserCode = $UserCode;
$this->UserName = $UserName;
$this->Version = $Version;
}
/**
* @return string
*/
public function getDigest()
{
return $this->Digest;
}
/**
* @param string $Digest
* @return KeyVersion
*/
public function withDigest($Digest)
{
$new = clone $this;
$new->Digest = $Digest;
return $new;
}
/**
* @return \ArchiflowWSCard\Type\ArrayOfField
*/
public function getIndexes()
{
return $this->Indexes;
}
/**
* @param \ArchiflowWSCard\Type\ArrayOfField $Indexes
* @return KeyVersion
*/
public function withIndexes($Indexes)
{
$new = clone $this;
$new->Indexes = $Indexes;
return $new;
}
/**
* @return \DateTime
*/
public function getModificationDate()
{
return $this->ModificationDate;
}
/**
* @param \DateTime $ModificationDate
* @return KeyVersion
*/
public function withModificationDate($ModificationDate)
{
$new = clone $this;
$new->ModificationDate = $ModificationDate;
return $new;
}
/**
* @return string
*/
public function getNomeAllegato()
{
return $this->NomeAllegato;
}
/**
* @param string $NomeAllegato
* @return KeyVersion
*/
public function withNomeAllegato($NomeAllegato)
{
$new = clone $this;
$new->NomeAllegato = $NomeAllegato;
return $new;
}
/**
* @return int
*/
public function getOperationalOfficeCode()
{
return $this->OperationalOfficeCode;
}
/**
* @param int $OperationalOfficeCode
* @return KeyVersion
*/
public function withOperationalOfficeCode($OperationalOfficeCode)
{
$new = clone $this;
$new->OperationalOfficeCode = $OperationalOfficeCode;
return $new;
}
/**
* @return string
*/
public function getOperationalOfficeName()
{
return $this->OperationalOfficeName;
}
/**
* @param string $OperationalOfficeName
* @return KeyVersion
*/
public function withOperationalOfficeName($OperationalOfficeName)
{
$new = clone $this;
$new->OperationalOfficeName = $OperationalOfficeName;
return $new;
}
/**
* @return int
*/
public function getTipoDato()
{
return $this->TipoDato;
}
/**
* @param int $TipoDato
* @return KeyVersion
*/
public function withTipoDato($TipoDato)
{
$new = clone $this;
$new->TipoDato = $TipoDato;
return $new;
}
/**
* @return int
*/
public function getTipoOperazione()
{
return $this->TipoOperazione;
}
/**
* @param int $TipoOperazione
* @return KeyVersion
*/
public function withTipoOperazione($TipoOperazione)
{
$new = clone $this;
$new->TipoOperazione = $TipoOperazione;
return $new;
}
/**
* @return int
*/
public function getUserCode()
{
return $this->UserCode;
}
/**
* @param int $UserCode
* @return KeyVersion
*/
public function withUserCode($UserCode)
{
$new = clone $this;
$new->UserCode = $UserCode;
return $new;
}
/**
* @return string
*/
public function getUserName()
{
return $this->UserName;
}
/**
* @param string $UserName
* @return KeyVersion
*/
public function withUserName($UserName)
{
$new = clone $this;
$new->UserName = $UserName;
return $new;
}
/**
* @return int
*/
public function getVersion()
{
return $this->Version;
}
/**
* @param int $Version
* @return KeyVersion
*/
public function withVersion($Version)
{
$new = clone $this;
$new->Version = $Version;
return $new;
}
}
| true |
ff65c41b35393438811f65c7340fb72b250387aa | PHP | saadadel/simple-todo | /app/Http/Requests/TasksStoreRequest.php | UTF-8 | 797 | 2.53125 | 3 | [] | no_license | <?php
namespace App\Http\Requests;
use App\Task;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
class TasksStoreRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'title' => 'required|min:2|max:100',
'description' => 'nullable|min:2|max:65535',
'status' => 'nullable|in:todo,in-progress,done'
];
}
public function storeTask()
{
return Auth::user()->tasks()->create($this->all());
}
}
| true |
d00c14c1109161a0838dffec6d6290a9f3c3da05 | PHP | chhetry-abhishek/abhishek_component2 | /abhishek-component2/app/Http/Controllers/ProductController.php | UTF-8 | 4,095 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function index(){
$data = file_get_contents('products.json');
$productdata = json_decode($data, true);
return view('welcome',[
'productdata' =>$productdata
]);
}
public function add(Request $request){
$request -> validate([
'type' => 'required',
'title' =>'required',
'fname' => 'required',
'sname' => 'required',
'price' =>'required',
'pages' =>'required',
]);
$type = $request->input('type');
$title = $request->input('title');
$fname = $request->input('fname');
$sname = $request->input('sname');
$price = $request->input('price');
$pages = $request->input('pages');
$string = file_get_contents('products.json');
$productsJson = json_decode($string, true);
$ids = [];
foreach ($productsJson as $product ){
$ids[] = $product['id'];
}
rsort($ids);
$newId = $ids[0] + 1;
$products = [];
foreach ($productsJson as $product) {
$products[] = $product;
}
$newProduct = [];
$newProduct['id'] = $newId;
$newProduct['type'] = $type;
$newProduct['title'] = $title;
$newProduct['firstname'] = $fname;
$newProduct['mainname'] = $sname;
$newProduct['price'] = $price;
if($type=='cd') $newProduct['playlength'] = $pages;
if($type=='book') $newProduct['numpages'] = $pages;
$products[] = $newProduct;
$json = json_encode($products);
if(file_put_contents('products.json',$json))
return back()->with('success',"Product Added Successfully");
else
return back()->with('fail',"Product Listing failed");
}
public function edit($id){
$string = file_get_contents('products.json');
$productsJson = json_decode($string, true);
$products = [];
foreach ($productsJson as $product){
if($product['id']==$id){
$products[] = $product;
break;
}
}
return view('product',[
'products'=>$products
]);
}
public function update(Request $request,$id){
$type = $request->input('type');
$title = $request->input('title');
$fname = $request->input('fname');
$sname = $request->input('sname');
$price = $request->input('price');
$pages = $request->input('pages');
$string = file_get_contents('products.json');
$products = [];
$productsJson = json_decode($string, true);
foreach ($productsJson as $product){
if($product['id']==$id){
$product['title'] = $title;
$product['firstname'] = $fname;
$product['mainname'] = $sname;
$product['price'] = $price;
if($product['type']=='cd') $product['playlength'] =$pages;
if($product['type']=='book') $product['numpages'] =$pages;
}
$products[] = $product;
}
$json = json_encode($products);
if(file_put_contents('products.json',$json))
return back()->with('success',"Product Updated Successfully");
else
return back()->with('fail',"Product Updating failed");
}
public function destroy($id){
$string = file_get_contents('products.json');
$productsJson = json_decode($string,true);
$products = [];
foreach($productsJson as $product){
if($product['id'] != $id){
$products[] = $product;
}
}
$json = json_encode($products);
if(file_put_contents('products.json',$json))
return back()->with('success',"Product Deleted Successfully");
else
return back()->with('fail',"Product Deletion failed");
}
}
| true |
6a8a8f31c0c600007e46335b6e6d4a9c480a30c7 | PHP | netzmensch/hurricane | /sys/classes/parsers/image.php | UTF-8 | 394 | 2.65625 | 3 | [] | no_license | <?php
namespace redcross\hurricane\classes\parsers;
use redcross\hurricane\classes\abstractParser;
/**
* Class image
* @package redcross\hurricane\classes\parsers
*/
class image extends abstractParser
{
/**
* @return void
*/
public function parseContent()
{
$this->replaceContentElement('/\[\[(.*)\]\]/', '<img class="img-responsive" src="page/$1">');
}
} | true |
9c6324484bf6c6bf74d090107ae6f041fe0c0204 | PHP | signifly/travy-schema | /tests/Unit/SchemaTest.php | UTF-8 | 2,096 | 2.5625 | 3 | [
"MIT"
] | permissive | <?php
namespace Signifly\Travy\Schema\Tests\Unit;
use PHPUnit\Framework\TestCase;
use Signifly\Travy\Schema\Fields\Text;
use Signifly\Travy\Schema\Schema;
class SchemaTest extends TestCase
{
/** @test */
public function it_serializes_attributes_to_json()
{
$schema = new Schema([
'name' => 'name',
'field' => Text::make('Test'),
'items' => [
Text::make('Name'),
],
'nested' => [
'nested' => [
Text::make('Other'),
],
'item' => Text::make('Something'),
],
]);
$expected = [
'name' => 'name',
'field' => [
'name' => 'Test',
'fieldType' => [
'id' => 'text',
'props' => [
'text' => '{test}',
],
],
],
'items' => [
[
'name' => 'Name',
'fieldType' => [
'id' => 'text',
'props' => [
'text' => '{name}',
],
],
],
],
'nested' => [
'nested' => [
[
'name' => 'Other',
'fieldType' => [
'id' => 'text',
'props' => [
'text' => '{other}',
],
],
],
],
'item' => [
'name' => 'Something',
'fieldType' => [
'id' => 'text',
'props' => [
'text' => '{something}',
],
],
],
],
];
$this->assertEquals($expected, $schema->jsonSerialize());
}
}
| true |
5c7172d7edb8afbd4f6474d502a3861312b81a7a | PHP | jgleiser/simple-php-smarty-blog | /create_new_blog.php | UTF-8 | 811 | 2.84375 | 3 | [
"MIT"
] | permissive | <?php
session_start();
require_once "includes/functions.php";
// check if user is logged
if(!isset($_SESSION['uid'])){
header("Location: index.php");
exit;
}
// Check if it was called from the form
if(!isset($_POST['create'])){
header("Location: index.php");
exit;
}
// blogid stores the id of the new blog or an error message
$blogid = createNewBlog($_POST);
// If error code
if((int)$blogid <= 0){
$referer = $_SERVER['HTTP_REFERER'];
// strip previous error codes if there is any
$referer = preg_replace("/([&\\?]?)(error=)([-+]\\d+)/", "", $referer);
header("Location: $referer?error=$blogid");
exit;
}
// else, redirect to the blog page
else {
$_SESSION['userhasblog'] = true; // set that the user has at least 1 blog, for the menu
header("Location: blog.php?id=$blogid");
exit;
}
?>
| true |
5e075978cd2bfd741e9336ff1c13f90881603fff | PHP | wangti1/priceFindsystem | /index.php | UTF-8 | 3,875 | 2.625 | 3 | [] | no_license | <?php require_once('Connections/pricefind.php'); ?>
<?php
$currentPage = $_SERVER["PHP_SELF"];
$maxRows_rsdbprice = 3;
$pageNum_rsdbprice = 0;
if (isset($_GET['pageNum_rsdbprice'])) {
$pageNum_rsdbprice = $_GET['pageNum_rsdbprice'];
}
$startRow_rsdbprice = $pageNum_rsdbprice * $maxRows_rsdbprice;
mysql_select_db($database_pricefind, $pricefind);
$query_rsdbprice = "SELECT * FROM webprice";
$query_limit_rsdbprice = sprintf("%s LIMIT %d, %d", $query_rsdbprice, $startRow_rsdbprice, $maxRows_rsdbprice);
$rsdbprice = mysql_query($query_limit_rsdbprice, $pricefind) or die(mysql_error());
$row_rsdbprice = mysql_fetch_assoc($rsdbprice);
if (isset($_GET['totalRows_rsdbprice'])) {
$totalRows_rsdbprice = $_GET['totalRows_rsdbprice'];
} else {
$all_rsdbprice = mysql_query($query_rsdbprice);
$totalRows_rsdbprice = mysql_num_rows($all_rsdbprice);
}
$totalPages_rsdbprice = ceil($totalRows_rsdbprice/$maxRows_rsdbprice)-1;
$queryString_rsdbprice = "";
if (!empty($_SERVER['QUERY_STRING'])) {
$params = explode("&", $_SERVER['QUERY_STRING']);
$newParams = array();
foreach ($params as $param) {
if (stristr($param, "pageNum_rsdbprice") == false &&
stristr($param, "totalRows_rsdbprice") == false) {
array_push($newParams, $param);
}
}
if (count($newParams) != 0) {
$queryString_rsdbprice = "&" . htmlentities(implode("&", $newParams));
}
}
$queryString_rsdbprice = sprintf("&totalRows_rsdbprice=%d%s", $totalRows_rsdbprice, $queryString_rsdbprice);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>价格查询系统</title>
<style type="text/css">
<!--
body,td,th {
font-family: 新宋体;
}
-->
</style></head>
<body>
<table width="703" height="151" border="1">
<caption>
价格查询
</caption>
<tr>
<th width="112" scope="col">主键id</th>
<th width="217" scope="col">商品名称</th>
<th width="138" scope="col">商品数量</th>
<th width="208" scope="col">商品价格</th>
</tr>
<?php do { ?>
<tr>
<td><a href="detail.php?id=<?php echo $row_rsdbprice['id']; ?>"><?php echo $row_rsdbprice['id']; ?> </a></td>
<td><?php echo $row_rsdbprice['product_name']; ?></td>
<td><?php echo $row_rsdbprice['product_number']; ?></td>
<td><?php echo $row_rsdbprice['product_price']; ?></td>
</tr>
<?php } while ($row_rsdbprice = mysql_fetch_assoc($rsdbprice)); ?>
<tr>
<td>
<?php if ($pageNum_rsdbprice > 0) { // Show if not first page ?>
[第一页]
<?php } // Show if not first page ?> </td>
<td><?php if ($pageNum_rsdbprice > 0) { // Show if not first page ?>
<a href="<?php printf("%s?pageNum_rsdbprice=%d%s", $currentPage, max(0, $pageNum_rsdbprice - 1), $queryString_rsdbprice); ?>">[上一页]</a>
<?php } // Show if not first page ?></td>
<td><?php if ($pageNum_rsdbprice < $totalPages_rsdbprice) { // Show if not last page ?>
<a href="<?php printf("%s?pageNum_rsdbprice=%d%s", $currentPage, min($totalPages_rsdbprice, $pageNum_rsdbprice + 1), $queryString_rsdbprice); ?>">[下一页]</a>
<?php } // Show if not last page ?></td>
<td><?php if ($pageNum_rsdbprice < $totalPages_rsdbprice) { // Show if not last page ?>
<a href="<?php printf("%s?pageNum_rsdbprice=%d%s", $currentPage, $totalPages_rsdbprice, $queryString_rsdbprice); ?>">[最后一页]</a>
<?php } // Show if not last page ?></td>
</tr>
</table>
<p>共有<?php echo $totalRows_rsdbprice ?> 记录,目前查询<?php echo ($startRow_rsdbprice + 1) ?>至<?php echo min($startRow_rsdbprice + $maxRows_rsdbprice, $totalRows_rsdbprice) ?>记录</p>
</body>
</html>
<?php
mysql_free_result($rsdbprice);
?>
| true |
254fdf3e874d536fbb36d7a3728f260edf6437c9 | PHP | winky007/SwooleCustomerService | /class/Utils.php | UTF-8 | 523 | 2.765625 | 3 | [] | no_license | <?PHP
class Utils
{
public static function debug($input, $tag = '')
{
if ($tag) echo "{$tag} start\n";
echo json_encode($input, JSON_UNESCAPED_UNICODE) . "\n";
if ($tag) echo "{$tag} end\n";
}
public static function h($text)
{
return htmlentities($text, ENT_COMPAT | ENT_HTML401, 'utf-8');
}
public static function redis()
{
$redis = new Redis();
$redis->connect(REDIS_HOST, REDIS_PORT);
return $redis;
}
} | true |
f77ea0129c6b4ba917b0b004d508c64bb6f277bf | PHP | zitivapo/php-druid-query | /src/DruidFamiliar/Interval.php | UTF-8 | 3,906 | 3.359375 | 3 | [
"MIT"
] | permissive | <?php
namespace DruidFamiliar;
use DateTime;
use DruidFamiliar\Exception\MissingParametersException;
use DruidFamiliar\Exception\UnexpectedTypeException;
use RuntimeException;
/**
* Class Interval represents Web ISO style date ranges for use in Druid queries.
*
* @package DruidFamiliar
*/
class Interval
{
/**
* ISO Time
* @var DruidTime
*/
public $intervalStart;
/**
* ISO Time
* @var DruidTime
*/
public $intervalEnd;
/**
* @param string|DateTime|DruidTime $intervalStart
* @param string|DateTime|DruidTime $intervalEnd
*/
function __construct($intervalStart = "1970-01-01 01:30:00", $intervalEnd = "3030-01-01 01:30:00")
{
$this->setInterval($intervalStart, $intervalEnd);
}
/**
* @param string|DateTime|DruidTime $intervalStart
* @param string|DateTime|DruidTime $intervalEnd
*/
public function setInterval($intervalStart = "1970-01-01 01:30:00", $intervalEnd = "3030-01-01 01:30:00")
{
$this->setStart($intervalStart);
$this->setEnd($intervalEnd);
}
/**
* @param string|DateTime|DruidTime $intervalStart
*/
public function setStart($intervalStart = "1970-01-01 01:30:00")
{
if ( is_string($intervalStart ) )
{
$intervalStart = new DateTime( $intervalStart );
}
if ( is_a($intervalStart, 'DateTime') )
{
$intervalStart = new DruidTime( $intervalStart );
}
if ( is_a($intervalStart, 'DruidFamiliar\DruidTime') )
{
$this->intervalStart = $intervalStart;
}
else
{
throw new RuntimeException('Encountered unexpected start time. Expected either string, DateTime, or DruidTime.');
}
}
/**
* @param string|DateTime|DruidTime $intervalEnd
*/
public function setEnd($intervalEnd = "3030-01-01 01:30:00")
{
if ( is_string($intervalEnd ) )
{
$intervalEnd = new DateTime( $intervalEnd );
}
if ( is_a($intervalEnd, 'DateTime') )
{
$intervalEnd = new DruidTime( $intervalEnd );
}
if ( is_a($intervalEnd, 'DruidFamiliar\DruidTime') )
{
$this->intervalEnd = $intervalEnd;
}
else
{
throw new RuntimeException('Encountered unexpected end time. Expected either string, DateTime, or DruidTime.');
}
}
/**
* @return string
* @throws MissingParametersException
* @throws UnexpectedTypeException
*/
function __toString()
{
return $this->getIntervalsString();
}
/**
* @return string
* @throws MissingParametersException
* @throws UnexpectedTypeException
*/
public function getIntervalsString()
{
// Missing params
$missingParams = array();
if ( !isset( $this->intervalStart ) ) { $missingParams[] = 'intervalStart'; }
if ( !isset( $this->intervalEnd ) ) { $missingParams[] = 'intervalEnd'; }
if ( count( $missingParams ) > 0 ) { throw new MissingParametersException($missingParams); }
// Invalid params
if ( !$this->intervalStart instanceof DruidTime ) {
throw new UnexpectedTypeException($this->intervalStart, 'DruidTime', 'For parameter intervalStart.');
}
if ( !$this->intervalEnd instanceof DruidTime ) {
throw new UnexpectedTypeException($this->intervalEnd, 'DruidTime', 'For parameter intervalEnd.');
}
// Format
return $this->intervalStart . '/' . $this->intervalEnd;
}
/**
* @return DruidTime
*/
public function getStart()
{
return $this->intervalStart;
}
/**
* @return DruidTime
*/
public function getEnd()
{
return $this->intervalEnd;
}
}
| true |
d0305977a2031abb7f1de60cea92ae298365635c | PHP | GlZM0/phpBubbleSort | /WriteArrays.php | UTF-8 | 338 | 3.1875 | 3 | [] | no_license | <?php
include_once ("BubbleSort.php");
class WriteArrays
{
function writer($tablicaL) {
$bubbleSort = new BubbleSort();
echo "Liczby przed sortowaniem :\n";
print_r($tablicaL);
echo "<br>";
echo "\nLiczby po sortowaniu\n:";
print_r($bubbleSort->sortowanieBabelkowe($tablicaL));
}
} | true |
dbf00f702e82809f3e9ef24ce126ef29335f65b0 | PHP | tan-yuki/agora-recording-sample-php-server | /src/AgoraServer/Domain/Agora/Entity/RestfulAPI/AuthCredentialKeyFactory.php | UTF-8 | 629 | 2.65625 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace AgoraServer\Domain\Agora\Entity\RestfulAPI;
class AuthCredentialKeyFactory
{
private CustomerId $customerId;
private CustomerSecret $customerSecret;
public function __construct(CustomerIdFactory $customerIdFactory,
CustomerSecretFactory $customerSecretFactory)
{
$this->customerId = $customerIdFactory->create();
$this->customerSecret = $customerSecretFactory->create();
}
public function create(): AuthCredentialKey
{
return new AuthCredentialKey($this->customerId, $this->customerSecret);
}
} | true |
73dff8c1219da5c5e2e28ff322d35ec4fb04dc4e | PHP | map2u/cobas_react | /react/Model/ReportInterface.php | UTF-8 | 4,186 | 2.5625 | 3 | [] | no_license | <?php
namespace Map2u\CoreBundle\Model;
/**
* ReportInterface
*/
interface ReportInterface {
/**
* Get id
*
* @return guid
*/
public function getId();
/**
* Set id
*
* @param guid $id
* @return Report
*/
public function setId($id);
/**
* Set userId
*
* @param guid $userId
* @return mixed
*/
public function setUserId($userId);
/**
* Get userId
*
* @return guid
*/
public function getUserId();
/**
* Set name
*
* @param string $name
* @return mixed
*/
public function setName($name);
/**
* Get name
*
* @return string
*/
public function getName();
/**
* Set sessionid
*
* @param string $sessionid
* @return mixed
*/
public function setSessionid($sessionid);
/**
* Get sessionid
*
* @return string
*/
public function getSessionid();
/**
* Set deleted
*
* @param boolean $deleted
* @return mixed
*/
public function setDeleted($deleted);
/**
* Get deleted
*
* @return boolean
*/
public function getDeleted();
/**
* Set createdAt
*
* @param \DateTime $createdAt
* @return mixed
*/
public function setCreatedAt($createdAt);
/**
* Get createdAt
*
* @return \DateTime
*/
public function getCreatedAt();
/**
* Set updatedAt
*
* @param \DateTime $updatedAt
* @return Report
*/
public function setUpdatedAt($updatedAt);
/**
* Get updatedAt
*
* @return \DateTime
*/
public function getUpdatedAt();
/**
* Set description
*
* @param string $description
* @return Report
*/
public function setDescription($description);
/**
* Get description
*
* @return string
*/
public function getDescription();
/**
* Set user
*
* @param \Application\Sonata\UserBundle\Entity\User $user
* @return Report
*/
public function setUser(\Application\Sonata\UserBundle\Entity\User $user = null);
/**
* Get user
*
* @return \Application\Sonata\UserBundle\Entity\User
*/
public function getUser();
/**
* Add tags
*
* @param \Map2u\CoreBundle\Entity\Tag $tags
* @return Report
*/
public function addTag(\Map2u\CoreBundle\Entity\Tag $tags);
/**
* Remove tags
*
* @param \Map2u\CoreBundle\Entity\Tag $tags
*/
public function removeTag(\Map2u\CoreBundle\Entity\Tag $tags);
/**
* Get tags
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getTags();
/**
* Add categories
*
* @param \Map2u\CoreBundle\Entity\Category $categories
* @return mixed
*/
public function addCategory(\Map2u\CoreBundle\Entity\Category $categories);
/**
* Remove categories
*
* @param \Map2u\CoreBundle\Entity\Category $categories
*/
public function removeCategory(\Map2u\CoreBundle\Entity\Category $categories);
/**
* Get categories
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getCategories();
/**
* Set project
*
* @param \Map2u\CoreBundle\Entity\Project $project
* @return mixed
*/
public function setProject(\Map2u\CoreBundle\Entity\Project $project = null);
/**
* Get project
*
* @return \Map2u\CoreBundle\Entity\Project
*/
public function getProject();
/**
* Set reportTitle
*
* @param string $reportTitle
* @return mixed
*/
public function setReportTitle($reportTitle);
/**
* Get reportTitle
*
* @return string
*/
public function getReportTitle();
/**
* Set reportType
*
* @param string $reportType
* @return mixed
*/
public function setReportType($reportType);
/**
* Get reportType
*
* @return string
*/
public function getReportType();
}
| true |
79e56c4b5e9f1e0754905a277c7cdf8801af8c40 | PHP | danalextronic/gocare | /app/Http/Controllers/API/ApiController.php | UTF-8 | 2,078 | 2.84375 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Apikey;
use Crypt;
use Auth;
use App\User;
class ApiController extends Controller
{
private $_key;
public $user;
/**
* ApiController constructor. Grabs the API key, assigns it to the private class value, and fires the api_key_exists
* function.
*
* @param Request $request
*/
public function __construct(Request $request)
{
$this->_key = $request->header('X-Api-Key');
$this->user = $this->getUserByApiKey($this->_key);
if (!$this->_api_key_exists()) {
echo $this->errorResponse('Invalid API Key');
die();
};
}
/**
* A quick and dirty way to make sure, at least, the API key exists. If so, we'll let the API scripts continue,
* otherwise, we just echo some JSON and die.
*/
private function _api_key_exists()
{
$apikey = Apikey::where('secret', '=', $this->_key)->first();
if (!$apikey) {
return false;
}
return true;
}
public function getUserByApiKey($key)
{
$apikey = Apikey::where('secret', '=', $this->_key)->first();
$user = User::find($apikey->user_id);
return $user;
}
protected function jsonResponse(array $json, $code = 200) {
return response()->make(json_encode($json, JSON_NUMERIC_CHECK), $code, ['Content-Type' => 'application/json']);
}
protected function successResponse(array $data = [], $code = 200) {
return $this->jsonResponse(['result' => 'success'] + (!empty($data) ? ['data' => $data] : []), $code);
}
protected function errorResponse($error, $code = 200, array $data = []) {
return $this->jsonResponse(['result' => 'error', 'error' => $error] + $data, $code);
}
protected function customResponse($data, $code = 200, $contentType = 'text/html') {
return response()->make($data, $code, ['Content-Type' => $contentType]);
}
}
| true |
45e5d43efa778b52ebba30a75bf1add3541c63e3 | PHP | CampanL/mof-maf | /controllers/Controllers.php | UTF-8 | 3,372 | 2.78125 | 3 | [] | no_license | <?php
namespace Controllers;
use Symfony\Component\HttpFoundation\Request;
use Silex\Application as App;
use Models;
use Symfony\Component\Validator\Constraints as Assert;
use Utils\Utils as Utils;
class Controllers{
protected $table;
protected $model;
protected $app;
protected $utils;
protected $constraint;
protected $access = [];
public function __construct( App $app, $table ){
$this->table = $table;
//Chemin de la class du model;
$modelPath = '\Models\\'.$table;
//Instance dynamique du model
$this->model = new $modelPath($app);
$this->app = $app;
$this->utils = new Utils($app);
}
/**
* Affiche tout les administrateurs de la BDD
* @return [view] Retourne la vue associé avec les datas
*/
public function index(){
$this->utils->accessVerif($this->access);
$data = $this->model->index();
return $this->app['twig']->render('fronts/backOffice/'.$this->table.'/index.twig',['data'=>$data]);
}
/**
* Sert le formulaire de création d'un admin
* @return [view] Retourne la vue associé
*/
public function create(){
$this->utils->accessVerif($this->access);
return $this->app['twig']->render('fronts/backOffice/'.$this->table.'/creer.twig');
}
/**
* Enregistre l'utilisateur dans la base de donnée.
* @param [Request $request] Donnée issus du formulaire
* @return [view] Retourne la vue associés² avec les datas
*/
public function save(Request $request){
$this->utils->accessVerif($this->access);
$request = $request->request->all();
$this->model->create($request);
return $this->app->redirect('/'.'admin/'.$this->table);
}
/**
* Supprime un utilisateur de la base
* @param [Request $request Donnée transmise dans la requete
* @return [view] Redirige vers la page de gestiopn des admins avec un message de succes
*/
public function delete(Request $request){
$this->utils->accessVerif($this->access);
$id = $request->attributes->all()['id'];
$this->model->delete($id);
$this->app['session']->getFlashBag()->add('alert', 'Utilisateur supprimé');
return $this->app->redirect('/'.'admin/'.$this->table);
}
/**
* Sert le formulaire de mise a jour des admins
* @param [int] $id Id de l'admin a afficher
* @return [view] Retoune la vue avec les datas associées
*/
public function edit($id){
$this->utils->accessVerif($this->access);
$user = $this->model->read($id);
return $this->app['twig']->render('fronts/backOffice/'.$this->table.'/edit.twig',['data'=>$user]);
}
/**
* Enregistré les modifications dans la base de donnée
* @param [Request $request] Donnée issus du formulaire
* @return [view] Redirige vers la page d'administration des admins avec un message
*/
public function update(Request $request){
$this->utils->accessVerif($this->access);
$request = $request->request->all();
foreach ($request as $key => $value) {
if ($value == '') {
unset($request[$key]);
}
}
$this->model->update($request);
$this->app['session']->getFlashBag()->add('alert', 'Utilisateur modifié');
return $this->app->redirect('/'.'admin/'.$this->table);
}
public function read($id){
$this->utils->accessVerif($this->access);
$data = $this->news->read($id);
return $this->app['twig']->render('fronts/backOffice/'.$this->table.'/read.twig',['data'=>$data]);
}
} | true |
f1932083fe42486cd7b5e7452250c3a8d4878391 | PHP | wilcarllopez/PHPexercises | /solution41.php | UTF-8 | 375 | 3.46875 | 3 | [] | no_license | <!DOCTYPE html>
<html>
<head>
<title>Solution #41</title>
</head>
<body>
<div class="container">
<?php
for ($i = 1; $i < 7; $i++) {
for ($j = 1; $j < 7; $j++) {
if ($j == 1) {
echo str_pad($i*$j, 2, " ", STR_PAD_LEFT);
} else {
echo str_pad($i*$j, 4, " ", STR_PAD_LEFT);
}
}
echo "\n";
}
?>
</div>
</body>
</html> | true |
0ad7f74fb97ae5be9ce1d6b60d12ee3735b600a1 | PHP | meza/P-PEX | /tests/Http/HttpParamsTest.php | UTF-8 | 1,659 | 2.5625 | 3 | [] | no_license | <?php
/**
* HttpParamsTest.php
*
* Holds the test cases for the HttpParams class
*
* PHP Version: 5
*
* @category File
* @package Test
*
* @author meza <meza@meza.hu>
* @license GPL3.0
* GNU GENERAL PUBLIC LICENSE
* Version 3, 29 June 2007
*
* Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
* Everyone is permitted to copy and distribute verbatim copies
* of this license document, but changing it is not allowed.
* @link http://www.assembla.com/spaces/p-pex
**/
namespace Pex;
/**
* The test class of the HttpParams class
*
* PHP Version: 5
*
* @category Class
* @package Test
* @author meza <meza@meza.hu>
* @license GPLv3 <http://www.gnu.org/licenses/>
* @link http://www.assembla.com/spaces/p-pex
*/
class HttpParamsTest extends PexTestBase
{
/**
* @var HttpParams instance
*/
protected $object;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*
* @return void
*/
protected function setUp()
{
$this->object = new HttpParams();
}//end setUp()
/**
* We need to make sure the preparedUrl is set
*
* @return void
*/
public function testSetPreparedUrl()
{
$this->assertNull($this->readAttribute($this->object, 'preparedUrl'));
$expected = "foo.bar";
$this->object->setPreparedUrl($expected);
$actual = $this->readAttribute($this->object, 'preparedUrl');
$this->assertEquals($expected, $actual);
}//end testSetPreparedUrl()
}//end class
?>
| true |
c82aa7940d9a6198a8caef5b9bf7d1408a135546 | PHP | 1g0rbm/eventhub | /api/src/Auth/Entity/User/Status.php | UTF-8 | 813 | 2.953125 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace App\Auth\Entity\User;
use Webmozart\Assert\Assert;
class Status
{
public const WAIT = 'wait';
public const ACTIVE = 'active';
private string $value;
public function __construct(string $value)
{
Assert::oneOf($value, [self::WAIT, self::ACTIVE]);
$this->value = $value;
}
public static function wait(): self
{
return new self(self::WAIT);
}
public static function active(): self
{
return new self(self::ACTIVE);
}
public function isWait(): bool
{
return $this->value === self::WAIT;
}
public function isActive(): bool
{
return $this->value === self::ACTIVE;
}
public function getValue(): string
{
return $this->value;
}
}
| true |
8fde53d7a360d6bed3bfa21d7ea1ffe698c089d1 | PHP | codesk90/backOrder | /database/api.php | UTF-8 | 2,025 | 2.921875 | 3 | [] | no_license | <?php
//Connection
include("../dbconnect.php");
if (isset($_POST['done'])) {
//Assign variables
$styleNumber = $_POST['style_number'];
$customerName = $_POST['customer_name'];
$phoneNumber = $_POST['phone_number'];
$email = $_POST['email'];
$date = date("Y-m-d");
//Insert into database
$sql = "INSERT INTO db_back_order (style_number, customer_name, phone_number, email, date) VALUES ('$styleNumber', '$customerName', '$phoneNumber', '$email', '$date')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
if (isset($_POST['display'])) {
if ($_POST['style_number'] != '') {
$sql = "SELECT * FROM db_back_order WHERE style_number = '".$_POST['style_number']."'";
}
$result = mysqli_query($conn, $sql);
echo "<tr>
<th>Style #</th>
<th>Customer Name</th>
<th>Phone #</th>
<th>Email</th>
<th>Date</th>
<th>Edit</th>
</tr>";
while ($row = mysqli_fetch_array($result)) {
$id = $row["id"];
$style = $row["style_number"];
$customer = $row["customer_name"];
$phone = $row["phone_number"];
$email = $row["email"];
$date = $row["date"];
echo "<tr>
<td> {$style} </td>
<td> {$customer} </td>
<td> {$phone} </td>
<td> {$email} </td>
<td> {$date} </td>
<td><a href='./database/api.php?del={$id}'>Delete
</td>
</tr>";
}
}
if (isset($_GET['del'])) {
$id = $_GET['del'];
$sql = "DELETE FROM db_back_order WHERE id = '$id'";
$result = mysqli_query($conn, $sql) or die("Failed".mysqli_error());
echo "<meta http-equiv='refresh' content='0;url=../index.php'>";
}
/*
if (isset($_GET['del'])) {
$id = $_GET['del'];
$sql = "DELETE FROM db_back_order WHERE id = '$id'";
$result = mysqli_query($conn, $sql) or die("Failed" .mysqli_error());
echo "<meta http-equiv='refresh' content='0;url=../index.php'>";
}
*/
$conn->close();
?> | true |
1a4e5e8a9552608ac690534ed47e1e26a1c8c965 | PHP | wikimedia/oauth2-server | /src/Entities/ClaimEntityInterface.php | UTF-8 | 478 | 2.5625 | 3 | [
"MIT"
] | permissive | <?php
/**
* @author Sebastian Kroczek <me@xbug.de>
* @copyright Copyright (c) Alex Bilbie
* @license http://mit-license.org/
*
* @link https://github.com/thephpleague/oauth2-server
*/
namespace League\OAuth2\Server\Entities;
interface ClaimEntityInterface
{
/**
* Get the claim's name.
*
* @return string
*/
public function getName();
/**
* Get the claim's value
*
* @return mixed
*/
public function getValue();
}
| true |
016b5ffcd328739c798bb6edcd6732913d0d4841 | PHP | alesancor1/IISSI-AutoescuelaTrafico | /app/models/AnunciosModel.php | UTF-8 | 1,083 | 2.796875 | 3 | [
"MIT"
] | permissive | <?php
class AnunciosModel extends BaseModel{
private $table;
public function __construct($adapter){
$this-> table = "Anuncios";
parent::__construct($this -> table, $adapter);
}
public function getAll($first = 0, $last = -1){
$query="SELECT * FROM Anuncios ORDER BY Fecha DESC";
$res = $this->consultaPaginada($query,$first,$last);
if($res != null){
foreach($res as $num=>$anuncio){
$res[$num] = Anuncios::__parse("Anuncios",$anuncio);
$res[$num]->setTexto($this->getLOB("Anuncios","Texto","OID_ANUN",$res[$num]->getID()));
}
}
else
$res=array();
return $res;
}
/*si la consulta es paginada debe implementarse rownum*/
public function rows(){
return $this->rowNum("SELECT * FROM Anuncios");
}
public function insert($titulo, $texto){
$this->db()->beginTransaction();
$this->ejecutaSql("INSERT INTO Anuncios (Fecha,Titulo,Texto) VALUES (sysdate,'$titulo','$texto')");
$this->db()->commit();
}
}
?> | true |
966e97fe8faa1e8b365f95a9fe0478aa3f7d6ee9 | PHP | Engrev/P5_vergne_thomas | /core/Route.php | UTF-8 | 3,050 | 3.453125 | 3 | [] | no_license | <?php
namespace Blog\Core;
/**
* Class Route
* @package Blog\Core
*
* Represents a route.
*/
class Route
{
/**
* @var string The path.
*/
private $path;
/**
* @var mixed The closure.
*/
private $callable;
/**
* @var array URL matches.
*/
private $matches = [];
/**
* @var array URL constraints.
*/
private $params = [];
/**
* Route constructor.
*
* @param string $path
* @param mixed $callable Function.
*/
public function __construct($path, $callable)
{
$this->path = trim($path, '/');
$this->callable = $callable;
}
/**
* Checks if the URL typed matches one of the saved routes by transforming the URL.
* e.g : get('/posts/:id-:slug').
* If so, matches are saved.
* And check if the match is not in the constraint parameters.
*
* @param string $url
*
* @return bool
*/
public function match($url)
{
$url = trim($url, '/');
$path = preg_replace_callback('#:([\w]+)#', [$this, 'paramMatch'], $this->path);
$regexp = "#^$path$#i";
if (!preg_match($regexp, $url, $matches)) {
return false;
}
array_shift($matches);
$this->matches = $matches;
return true;
}
/**
* If the match is in the constraint parameters, a regexp with match is returned.
* The parentheses are useful for capturing in $matches in match() method.
*
* @param array $match
*
* @return string
*/
private function paramMatch($match)
{
if (isset($this->params[$match[1]])) {
return '('.$this->params[$match[1]].')';
}
return '([^/]+)';
}
/**
* Call the method related to matches.
*
* @return mixed
*/
public function call()
{
if (is_string($this->callable)) {
$params = explode('#', $this->callable);
$controller = 'Blog\\Controllers\\'.$params[0].'Controller';
$Controller = new $controller();
return call_user_func_array([$Controller, $params[1]], $this->matches);
} else {
return call_user_func_array($this->callable, $this->matches);
}
}
/**
* Save constraints.
* '(?:' is useful for parentheses in $regexp in this method. Like that, the parentheses are not captivating.
*
* @param string $param
* @param string $regexp
*
* @return $this For others with().
*/
public function with($param, $regexp)
{
$this->params[$param] = str_replace('(', '(?:', $regexp);
return $this;
}
/**
* Displays the URL corresponding to the name.
*
* @param array $params
*
* @return string|string[]
*/
public function getUrl($params)
{
$path = $this->path;
foreach ($params as $key => $value) {
$path = str_replace(":$key", $value, $path);
}
return $path;
}
} | true |
df901d19eed7a021bb81900e2687b6e895403603 | PHP | Rolice/Laravel-LangSync | /src/services/LabelsCollection.php | UTF-8 | 543 | 2.78125 | 3 | [
"MIT"
] | permissive | <?php namespace Rolice\LangSync;
/**
* Class LabelsCollection
* @package Rolice\LangSync
*/
class LabelsCollection
{
/**
* @var array
*/
private $collection = [];
/**
* Set collection items
*
* @param $collection
* @return $this
*/
public function set($collection)
{
$this->collection = $collection;
return $this;
}
/**
* Get collection items
*
* @return array
*/
public function get()
{
return $this->collection;
}
} | true |
241f6222154b9a55def44d94bf845ae85212ef54 | PHP | PatBradley88/ThoroughbredSmartTrainerHMS | /admin/includes/editFarrier.php | UTF-8 | 3,411 | 2.875 | 3 | [] | no_license | <?php
if(isset($_GET['f_id'])) {
$the_farrier_id = $_GET['f_id'];
}
$query = "SELECT * FROM farrier WHERE farrier_id = {$the_farrier_id}";
$select_farrier_by_id = mysqli_query($con, $query);
while($row = mysqli_fetch_assoc($select_farrier_by_id)) {
$farrier_id = $row['farrier_id'];
$farrier_horse_id = $row['farrier_horse_id'];
$farrier_name = $row['farrier_name'];
$farrier_note = $row['farrier_note'];
$farrier_note_poster = $row['farrier_note_poster'];
$farrier_date = $row['farrier_date'];
}
if(isset($_POST['update_farrier'])) {
$farrier_horse_id = $_POST['farrier_horse_id'];
$farrier_name = $_POST['farrier_name'];
$farrier_note = $_POST['farrier_note'];
$farrier_note_poster = $_POST['farrier_poster'];
$farrier_date = date('m.d.y');
$farrier_name = mysqli_real_escape_string($con, $_POST['farrier_name']);
$farrier_note = mysqli_real_escape_string($con, $_POST['farrier_note']);
$farrier_note_poster = mysqli_real_escape_string($con, $_POST['farrier_poster']);
$query = "UPDATE farrier SET ";
$query .="farrier_horse_id = '{$farrier_horse_id}', ";
$query .="farrier_name = '{$farrier_name}', ";
$query .="farrier_note = '{$farrier_note}', ";
$query .="farrier_note_poster = '{$farrier_note_poster}', ";
$query .="farrier_date = now() ";
$query .= "WHERE farrier_id = {$the_farrier_id} ";
$update_farrier = mysqli_query($con, $query);
if (!$update_farrier) {
die ("Query Failed" . mysqli_error($con));
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<div class="horseDetails">
<div class="container borderBottom">
<h2>FARRIER </h2>
<div>
<label for="farrier_horse_id">Name of Horse</label>
<select name="farrier_horse_id" id="horse_dropdown">
<?php
$query = "SELECT * FROM horses";
$select_horse = mysqli_query($con, $query);
if (!$select_horse) {
die ("Query Failed" . mysqli_error($con));
}
while($row = mysqli_fetch_assoc($select_horse)) {
$horse_id = $row['horse_id'];
$horse_name = $row['horse_name'];
if ($farrier_horse_id == $horse_id) {
echo "<option value='{$horse_id}' selected>{$horse_name}</option>";
} else {
echo "<option value='{$horse_id}'>{$horse_name}</option>";
}
}
?>
</select>
</div>
<label for="farrier_name">Name of Farrier</label>
<input type="text" name="farrier_name" placeholder="Farrier Name" value="<?php echo $farrier_name; ?>">
<label for="farrier_note">Farrier's note</label>
<input type="text" name="farrier_note" placeholder="Duties carried out" value="<?php echo $farrier_note; ?>">
<div>
<label for="farrier_poster">Posted By</label>
<select name="farrier_poster" id="horse_dropdown">
<?php
$query = "SELECT * FROM users";
$select_user = mysqli_query($con, $query);
if (!$select_user) {
die ("Query Failed" . mysqli_error($con));
}
while($row = mysqli_fetch_assoc($select_user)) {
$id = $row['id'];
$firstName = $row['firstName'];
$lastName = $row['lastName'];
if ($vet_note_poster == $id) {
echo "<option value='{$id}' selected>{$firstName} {$lastName}</option>";
} else {
echo "<option value='{$id}'>{$firstName} {$lastName}</option>";
}
}
?>
</select>
</div>
<button class="button" onclick="" name="update_farrier">UPDATE</button>
</div>
</div>
</form> | true |
c0f52436ede387930d1712b7235866a8944cd264 | PHP | Mordavius/nw3-dierenambulance | /app/Console/Commands/CrontTest.php | UTF-8 | 1,292 | 2.734375 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Console\Commands;
use App\User;
use Illuminate\Console\Command;
use App\Ticket;
class CrontTest extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'crontest';
/**
* The console command description.
*
* @var string
*/
protected $description = 'cron test written to test on mark his server';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
//return view('crontest.index');
$userdate = strtotime(User::all()->first()->created_at);
$checkdate = strtotime('-1 minute');
if ($userdate <= $checkdate){
echo User::all();
}
else{
echo "niks is kleiner dan een minuut";
}
echo "\n". strtotime(User::all()->first()->created_at);
//echo "\n". strtotime('now');
echo "\n". strtotime('-1 minute');
echo "\n". date('r', strtotime(User::all()->first()->created_at));
echo "\n". date('r', strtotime('now'));
}
}
| true |
5c9be3ea16dd5f94e13fe5cc3a6553dcf75ee184 | PHP | jacerider/code_challenges | /easy/fibonacci_series/php/fibonacci_series.php | UTF-8 | 1,020 | 4.09375 | 4 | [] | no_license | <?php
/**
* Fibonacci Series Code Challenge
*
* The Fibonacci series is defined as:
*
* F(0) = 0; F(1) = 1; F(n) = F(n-1) + F(n-2) when n > 1;
*
* Given a positive integer 'n', print out the F(n).
*
* -- Example Input:
*
* 5
* 12
*
*
* -- Example Output:
*
* 5
* 144
*
* To access the text file you can either hard code it in here
* or make it a command line argument like so:
*
* $ php fibonacci_series.php list.txt
*
* so $argv[1] would equal 'list.txt'
*
* $lines = file($argv[1]);
*
* OR
*
* $lines = file('list.txt');
*/
function main(){
$lines = file('list.txt');
foreach($lines as $n){
fibonacci($n);
}
exit(0);
}
function fibonacci($n){
$a = 0;
$b = 1;
$output = array();
for ($i = 0; $i < $n; $i++){
$output[$a] = (integer) $a;
$sum = $a+$b;
$a = $b;
$b = $sum;
}
$last = end($output);
print implode(', ', $output);
print "\n\n";
print '-----------ANSWER:' . $last . '-----------';
print "\n\n\n";
}
main();
?> | true |
4d99571d8df6eae3c55b5f9383b3ab8837898f25 | PHP | ondraczsk/MCPELANDCore | /src/legionpe/command/team/TeamRankChangeSubcommand.php | UTF-8 | 2,807 | 2.734375 | 3 | [] | no_license | <?php
namespace legionpe\command\team;
use legionpe\command\sublib\SessionSubcommand;
use legionpe\session\Session;
use legionpe\team\Team;
use pocketmine\utils\TextFormat;
class TeamRankChangeSubcommand extends SessionSubcommand{
/** @var bool */
private $promote;
/**
* @param bool $promote
*/
public function __construct($promote){
$this->promote = $promote;
}
protected function onRun(Session $ses, array $args){
$team = $ses->getTeam();
if(!($team instanceof Team)){
return TextFormat::RED . "You are not in a team!";
}
if(!isset($args[0])){
return TextFormat::RED . "Usage: " . $this->getUsage();
}
$target = $this->getSession(array_shift($args));
if(!($target instanceof Session)){
return TextFormat::RED . "There is no player online by that name!";
}
if(!isset($team->members[$target->getUID()])){
return TextFormat::RED . $target->getRealName() . " is not in your team!";
}
$myRank = $ses->getTeamRank();
$lightPurple = TextFormat::LIGHT_PURPLE;
$red = TextFormat::RED;
$aqua = TextFormat::AQUA;
if($myRank < Team::RANK_CO_LEADER){
return $red . "You must be$lightPurple a team leader or co-leader$red to promote/demote players!";
}
$hisRank = $ses->getTeamRank();
if($hisRank === Team::RANK_CO_LEADER and $this->promote){
return TextFormat::RED . "There can only be one leader per team, and the leadership cannot be transferred. \n$aqua" . "You can contact an$lightPurple admin$aqua, a$lightPurple developer$aqua or an$lightPurple owner$aqua if you have special reasons.";
}
if($hisRank === Team::RANK_JUNIOR and !$this->promote){
return TextFormat::RED . "Junior-Member is already the lowest rank. \n$aqua" . "Use $lightPurple/t k$aqua if you wish to kick the player.";
}
if($hisRank >= $myRank){
return TextFormat::RED . "You can only promote/demote members of lower rank than you!";
}
$team->members[$target->getUID()] = $target->getMysqlSession()->data["teamrank"] = ($this->promote ? ++$hisRank : --$hisRank);
$rankName = Team::$RANK_NAMES[$hisRank];
$target->tell(TextFormat::AQUA . "You have been " . $this->getName() . "d to a$lightPurple $rankName$aqua by " . $ses->getRealName() . ". \n" . TextFormat::GREEN . "If you wish to have your nametag updated, please rejoin.\n$aqua" . "If you don't mind, you don't need to rejoin; your nametag will be updated the next time you join."); // TODO $session->recalculateNametag()
return TextFormat::GREEN . $target->getRealName() . " has been " . $this->getName() . "d to a$lightPurple $rankName.";
}
public function getName(){
return $this->promote ? "promote":"demote";
}
public function getDescription(){
return ucfirst($this->getName()) . " a team member";
}
public function getUsage(){
return "/t " . $this->getName() . " <member>";
}
}
| true |
25fe8b7e57ec5acc6e778166e2f125a22eae80ae | PHP | Bephometh/TBD-tugas-besar | /TugasBesar 3/UI Baru/Second.php | UTF-8 | 10,553 | 2.53125 | 3 | [] | no_license |
<html>
<?php
include ("../connection.php");
// print_r($conn);
// return;
session_start();
?>
<head>
<title>Diagnosis 2</title>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<div class="w3-container w3-display-container w3-black w3-padding">
<h1>Diagnosis</h1>
</div>
<div class="w3-container w3-display-container w3-red w3-padding">
<a href="Histogram.php">Cek Histogram</a>
</div>
<div class="w3-content w3-center w3-large">
<p>Apa saja Gejala mu?</p>
</div>
<div class="w3-container w3-padding" style="height:80%">
<?php
//Menghitung nama gejala
$sql_num_of_gejala = "SELECT COUNT(Gejala.idGejala) FROM Gejala";
$num_of_gejala = sqlsrv_query($conn,$sql_num_of_gejala);
$number = sqlsrv_fetch_array($num_of_gejala, SQLSRV_FETCH_NUMERIC);
//Mempartisi jumlah gejala menjadi 3
// $part1 = floor($number[0] / 3);
//$part2 = $number[0] - ($part1+1);
//$part3 = $number[0] ;
$j = 0;
$part = $number[0];
//query nama gejala
$sql_nama_gejala = "SELECT Gejala.namaGejala FROM Gejala";
$hasil_nama_gejala = sqlsrv_query($conn,$sql_nama_gejala);
//Memasukkan hasil query ke array
$row1 = array();
while( $row = sqlsrv_fetch_array( $hasil_nama_gejala, SQLSRV_FETCH_NUMERIC) ) {
array_push($row1, $row[0]);
}
?>
<form method="GET" action="Second.php">
<fieldset class="w3-content w3-padding" style="width:40%">
<legend>Gejala</legend>
<div style="padding-left: 10%; padding-top:2%;">
Gejala 1 :
<select name="gej1" id="gj1" style="width:60% ">
<?php
//Populate select
for($j = 0; $j < $part; $j++){
echo '<option value="'.$row1[$j].'">'.$row1[$j].'</option>';
}
?>
</select>
<p>
Gejala 2 :
<select name="gej2" id="gj2" style="width:60% ">
<?php
//Populate select
for($j = 0; $j < $part; $j++){
echo '<option value="'.$row1[$j].'">'.$row1[$j].'</option>';
}
?>
</select>
<p>
Gejala 3 :
<select name="gej3" id="gj3" style="width:60% ">
<?php
//Populate select
for($j = 0; $j < $part; $j++){
echo '<option value="'.$row1[$j].'">'.$row1[$j].'</option>';
}
?>
</select>
<p>
<input class="w3-button w3-border w3-border-red w3-round-xlarge w3-hover-red" type="submit" name="action" value="Kembali">
<input class="w3-button w3-border w3-border-red w3-round-xlarge w3-hover-red" type="submit" name="action" value="Cek">
</p>
<?php
if(isset($_GET['action'])){
//Go back one page
if($_GET['action'] == 'Kembali'){
echo '<meta http-equiv="refresh" content="0; URL=first.php">';
}
//Check Diagnose
else if($_GET['action'] == 'Cek'){
//Memasukkan Value ke table checkup
$date_now = date("Ymd H:i:s A");
$sql_checkUp = "INSERT INTO CheckUp VALUES ('$date_now')";
$query_checkUp = sqlsrv_query($conn, $sql_checkUp);
//Mendapatkan idCheckUp
$sql_idCheckUp = "SELECT idCheckUp FROM CheckUp WHERE Tanggal = '$date_now' ";
$query_idCheckUp = sqlsrv_query($conn,$sql_idCheckUp);
if( sqlsrv_fetch( $query_idCheckUp ) === false) {
echo"id check up tidak ditemukan."."</br>";
}
$idCheckUp = sqlsrv_get_field($query_idCheckUp,0);
//Mendapatkan id pasien
$nama = $_SESSION['namaPasien'];
$sql_idPasien = "SELECT idPasien FROM Pasien WHERE namaPasien = '$nama' ";
$quer_idPasien = sqlsrv_query($conn, $sql_idPasien);
if( sqlsrv_fetch( $quer_idPasien ) === false) {
echo"id pasien tidak dietmukan."."</br>";
}
$idPasien = sqlsrv_get_field($quer_idPasien,0);
//Memasukkan data ke dalam tabel hasil
$sql_insertHasil = "exec insRoundRobinHasil $idCheckUp, $idPasien";
$query_insertHasil = sqlsrv_query($conn, $sql_insertHasil);
//Menyimpan gejala yang dialami
$gejala1 = $_GET['gej1'];
$gejala2 = $_GET['gej2'];
$gejala3 = $_GET['gej3'];
//Mencari id dari gejala2 yang dialami
$sql_gej1 = "SELECT idGejala FROM Gejala WHERE namaGejala = '$gejala1'";
$sql_gej2 = "SELECT idGejala FROM Gejala WHERE namaGejala = '$gejala2'";
$sql_gej3 = "SELECT idGejala FROM Gejala WHERE namaGejala = '$gejala3'";
//gejala 1
$query_gej1 = sqlsrv_query($conn, $sql_gej1);
if( sqlsrv_fetch( $query_gej1 ) === false) {
echo"id gejala tidak dietmukan.";
}
$idGejala1 = sqlsrv_get_field($query_gej1,0);
//gejala2
$query_gej2 = sqlsrv_query($conn, $sql_gej2);
if( sqlsrv_fetch( $query_gej2 ) === false) {
echo"id gejala tidak dietmukan.";
}
$idGejala2 = sqlsrv_get_field($query_gej2,0);
//gejala 3
$query_gej3 = sqlsrv_query($conn, $sql_gej3);
if( sqlsrv_fetch( $query_gej3 ) === false) {
echo"id gejala tidak dietmukan.";
}
$idGejala3 = sqlsrv_get_field($query_gej3,0);
//Memasukkan id gejala kedalam array
$idGejala = array();
array_push($idGejala, $idGejala1,$idGejala2,$idGejala3);
//Memasukkan ke dalam table record
$length = sizeof($idGejala);
for($i = 0; $i < $length; $i++){
$sql_insertRecord = "exec insRoundRobinGejala $idCheckUp, $idGejala[$i] ";
//echo "$sql_insertRecord";
sqlsrv_query($conn, $sql_insertRecord);
}
//Mencari penyakit yang dialami pasien
$sql_diagnos = "exec Diag $idCheckUp";
$query_diagnosis = sqlsrv_query($conn, $sql_diagnos);
if( $query_diagnosis === false) {
echo "This aint it chief";
}
echo "<table>";
echo "<tr>
<th> Penyakit </th>
</tr>";
while( $row = sqlsrv_fetch_array($query_diagnosis, SQLSRV_FETCH_NUMERIC)) {
//array_push($penyakit, $row[0]);
echo "<tr>";
echo '<td>'.$row[0].'</td>';
echo "</tr>";
}
echo "</table>";
}
}
else{
}
?>
</div>
</fieldset>
</form>
</div>
</body>
</html>
| true |
61d9215d89c1a842d261cee97eb84cccfcf659b6 | PHP | ozzyrod/cis047 | /assignment12/inc/viewBlog.php | UTF-8 | 1,785 | 3.3125 | 3 | [] | no_license | <?php
$connection = dbConnect();
$sql = "SELECT * FROM `blogging_tool` . `blog`";
$dosql = mysqli_query( $connection, $sql ) or die ( 'Query failed: ' . mysqli_error( $connection ) );
// for each row in the database, grab the episode, title, director, and year
// and create a new form to edit the data. When you click "Edit", you'll update the database!
$count = 0;
while( $row = mysqli_fetch_array( $dosql ) ) {
$count++;
$columns = 'one-half';
if ( $count == 0 || $count % 2 == 0 ) {
$columns .= ' last';
}
$id = $row['id'];
$subject = stripslashes( $row['subject'] );
$name = stripslashes( $row['name'] );
$email = stripslashes( $row['email'] );
$message = stripslashes( $row['message'] );
$str_date = strtotime( $row['date'] );
$date = date('j F Y', $str_date );
?>
<div class="entry <?php echo $columns; ?>">
<?php if ( $subject ) : ?>
<h2 class="entry-title"><?php echo $subject; ?></h2>
<?php endif; ?>
<p class="date">Posted on: <?php echo $date; ?></p>
<?php if ( $email && $name ) : ?>
<p class="email">Email: <a href="mailto:<?php echo $email; ?>"><?php echo $name; ?></a></p>
<?php endif; ?>
<?php if ( $message ) : ?>
<p class="message"><?php echo $message; ?></p>
<?php endif; ?>
<form method="post" action="editEntry.php">
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="hidden" name="subject" value="<?php echo $subject; ?>">
<input type="hidden" name="name" value="<?php echo $name; ?>">
<input type="hidden" name="email" value="<?php echo $email; ?>">
<input type="hidden" name="message" value="<?php echo $message; ?>">
<input class="button" type="submit" value="Edit">
</form>
</div>
<?php
}
// Close the connection.
mysqli_close( $connection ); | true |
56ba232a220198e14d13ab7be59f762d48b9798f | PHP | codekandis/easypwgen-api | /src/Http/UriBuilders/ApiUriBuilderInterface.php | UTF-8 | 513 | 2.625 | 3 | [] | no_license | <?php declare( strict_types = 1 );
namespace CodeKandis\EasyPwGenApi\Http\UriBuilders;
/**
* Represents the interface of all API URI builders.
* @package codekandis/easypwgen-api
* @author Christian Ramelow <info@codekandis.net>
*/
interface ApiUriBuilderInterface
{
/**
* Builds the URI of the index.
* @return string The URI of the index.
*/
public function buildIndexUri(): string;
/**
* Builds the URI of the password.
* @return string The URI of the password.
*/
public function buildPasswordUri(): string;
}
| true |
70fef6eac99d1d8d820702829716673942e17ba3 | PHP | Laisbat/scgm | /src/Model/Malote.php | UTF-8 | 4,824 | 2.75 | 3 | [] | no_license | <?php
namespace src\Model;
/**
* Classe de Malote
*
* @author Lais
*/
class Malote extends \src\Model\Db {
private $name = 'malote';
public function get($id)
{
$sql = "SELECT id_malote, dt_envio, valor_recebido, valor_receber, observacao, fk_operadora, status, dt_recebimento FROM {$this->name} WHERE id_malote = ?";
$statement = self::$db->prepare($sql);
$statement->bindParam(1, $id);
$statement->execute();
return $statement->fetch(\PDO::FETCH_OBJ);
}
public function getAll()
{
$sql = "SELECT m.id_malote, m.dt_envio, m.dt_recebimento, m.valor_recebido, m.valor_receber, m.status, o.operadora FROM {$this->name} m "
. "INNER JOIN operadora o on m.fk_operadora = o.id_operadora ORDER BY 1 DESC";
$statement = self::$db->prepare($sql);
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_OBJ);
}
public function getAllConfirmado()
{
$sql = "SELECT id_malote FROM {$this->name} WHERE status = 'C' ";
$statement = self::$db->prepare($sql);
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_OBJ);
}
/**
*
* Executa uma inserção no banco, e retorna o ID gerado, OU, falso para erro.
* @param array $params
* @return boolean
*/
public function insert(array $params)
{
$sql = "INSERT INTO {$this->name} SET dt_envio = ?, valor_receber = ?, valor_recebido = ?, observacao = ?, fk_operadora = ?, dt_recebimento = ?";
$statement = self::$db->prepare($sql);
$statement->bindParam(1, $params['dt_envio']);
$statement->bindParam(2, $params['valor_receber']);
$statement->bindParam(3, $params['valor_recebido']);
$statement->bindParam(4, $params['observacao']);
$statement->bindParam(5, $params['fk_operadora']);
$statement->bindParam(6, $params['dt_recebimento']);
if ($statement->execute()) {
return self::$db->lastInsertId();
}
return false;
}
public function delete($id)
{
$sql = "UPDATE {$this->name} SET status = 'I' WHERE id_malote = ?";
$statement = self::$db->prepare($sql);
$statement->bindParam(1, $id);
return $statement->execute();
}
public function update(array $params)
{
$sql = "UPDATE {$this->name} SET valor_receber = ?, valor_recebido = ?, observacao = ?, fk_operadora = ?, status = ?, dt_envio = ?, dt_recebimento = ? WHERE id_malote = ?";
$statement = self::$db->prepare($sql);
$statement->bindParam(1, $params['valor_receber']);
$statement->bindParam(2, $params['valor_recebido']);
$statement->bindParam(3, $params['observacao']);
$statement->bindParam(4, $params['fk_operadora']);
$statement->bindParam(5, $params['status']);
$statement->bindParam(6, $params['dt_envio']);
$statement->bindParam(7, $params['dt_recebimento']);
$statement->bindParam(8, $params['id_malote']);
return $statement->execute();
}
public function updateValorRecebido($valorRecebido, $idMalote)
{
$sql = "UPDATE {$this->name} SET valor_recebido = ? WHERE id_malote = ?";
$statement = self::$db->prepare($sql);
$statement->bindParam(1, $valorRecebido);
$statement->bindParam(2, $idMalote);
return $statement->execute();
}
public function updatesStatus($idMalote, $status = 'C')
{
$sql = "UPDATE {$this->name} SET status = ? WHERE id_malote = ?";
$statement = self::$db->prepare($sql);
$statement->bindParam(1, $status);
$statement->bindParam(2, $idMalote);
return $statement->execute();
}
public function getEstatistica($idMalote){
$sql = "SELECT m.id_malote, f.funcionario, SUM(p.valor) AS valor, o.operadora, COUNT(p.id_procedimento) AS qtd_procedimentos
FROM sgm.malote m
INNER JOIN sgm.guia g ON g.fk_malote = m.id_malote
INNER JOIN sgm.guia_has_procedimento gp ON g.id_guia = gp.id_guia
INNER JOIN sgm.dentista d ON d.id_dentista = gp.fk_dentista
INNER JOIN sgm.funcionario f ON f.id_funcionario = d.fk_funcionario
INNER JOIN sgm.procedimento p ON gp.id_procedimento = p.id_procedimento
INNER JOIN sgm.operadora o ON m.fk_operadora = o.id_operadora
WHERE m.id_malote = ? and g.status = 'P' and m.status = 'C'
GROUP BY m.id_malote, f.funcionario, o.operadora;";
$statement = self::$db->prepare($sql);
$statement->bindParam(1, $idMalote);
$statement->execute();
return $statement->fetchAll(\PDO::FETCH_OBJ);
}
}
| true |