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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
f0e82d42e9cd12fadc96f18364598bf89d12b496 | PHP | AmazeeLabs/cypress | /src/CypressRuntime.php | UTF-8 | 5,392 | 2.65625 | 3 | [] | no_license | <?php
namespace Drupal\cypress;
use Symfony\Component\Filesystem\Filesystem;
/**
* Manages the Cypress runtime directory.
*
* Responsible for directory creation, config file updates and collection of
* test requirements across different test suites.
*
* @package Drupal\cypress
*/
class CypressRuntime implements CypressRuntimeInterface {
/**
* A filesystem component for various operations.
*
* @var \Symfony\Component\Filesystem\Filesystem
*/
protected $fileSystem;
/**
* The root directory where config files and tests should be collected.
* @var string
*/
protected $cypressRoot;
/**
* List of paths to support files.
*
* @var string[]
*/
protected $support = [];
/**
* List of paths to plugin files.
*
* @var string[]
*/
protected $plugins = [];
/**
* List of npm dependencies and versions.
*
* @var string[]
*/
protected $dependencies = [];
/**
* A npm project manager to install test suite dependencies.
*
* @var \Drupal\cypress\NpmProjectManagerInterface
*/
protected $npmProjectManager;
/**
* Generate the filesystem instance.
*
* @return \Symfony\Component\Filesystem\Filesystem
*/
protected function getFileSystem() {
return new Filesystem();
}
/**
* CypressRuntime constructor.
*
* @param string $cypressRoot
* The absolute path the Cypress runtime should reside in.
*/
public function __construct($cypressRoot, NpmProjectManagerInterface $npmProjectManager) {
$this->cypressRoot = $cypressRoot;
$this->npmProjectManager = $npmProjectManager;
$this->fileSystem = $this->getFileSystem();
}
/**
* {@inheritDoc}
*/
public function initiate(CypressOptions $options) {
if (!$this->fileSystem->exists($this->cypressRoot)) {
$this->fileSystem->mkdir($this->cypressRoot);
}
if ($this->fileSystem->exists($this->cypressRoot . '/integration')) {
$this->fileSystem->remove($this->cypressRoot . '/integration');
}
if ($this->fileSystem->exists($this->cypressRoot . '/suites')) {
$this->fileSystem->remove($this->cypressRoot . '/suites');
}
if ($this->fileSystem->exists($this->cypressRoot . '/support')) {
$this->fileSystem->remove($this->cypressRoot . '/support');
}
if ($this->fileSystem->exists($this->cypressRoot . '/plugins')) {
$this->fileSystem->remove($this->cypressRoot . '/plugins');
}
$this->fileSystem->mkdir($this->cypressRoot . '/integration');
$this->fileSystem->mkdir($this->cypressRoot . '/integration/common');
$this->fileSystem->mkdir($this->cypressRoot . '/suites');
$this->fileSystem->dumpFile($this->cypressRoot . '/cypress.json', $options->getCypressJson());
$this->fileSystem->dumpFile($this->cypressRoot . '/plugins.js', $this->generatePluginsJs());
$this->fileSystem->dumpFile($this->cypressRoot . '/support.js', $this->generateSupportJs());
}
/**
* {@inheritDoc}
*/
public function addSuite($name, $path) {
if (!$this->fileSystem->exists($path)) {
return FALSE;
}
if ($this->fileSystem->exists($path)) {
$this->fileSystem->symlink(
$path,
$this->cypressRoot . '/suites/' . $name
);
}
if ($this->fileSystem->exists($path . '/integration')) {
$this->fileSystem->symlink(
$path . '/integration',
$this->cypressRoot . '/integration/' . $name
);
}
if ($this->fileSystem->exists($path . '/steps')) {
$this->fileSystem->symlink(
$path . '/steps',
$this->cypressRoot . '/integration/common/' . $name
);
}
if ($this->fileSystem->exists($path . '/support/index.js')) {
$this->support[] = $name;
$this->fileSystem->mirror($path . '/support', $this->cypressRoot . '/support/' . $name);
$this->fileSystem->dumpFile($this->cypressRoot . '/support.js', $this->generateSupportJs());
}
if ($this->fileSystem->exists($path . '/plugins/index.js')) {
$this->plugins[] = $name;
$this->fileSystem->mirror($path . '/plugins', $this->cypressRoot . '/plugins/' . $name);
$this->fileSystem->dumpFile($this->cypressRoot . '/plugins.js', $this->generatePluginsJs());
}
if ($this->fileSystem->exists($path . '/package.json')) {
$this->npmProjectManager->merge($path . '/package.json');
}
}
/**
* Generate a javascript file that imports plugins.
*
* @return string
* The content for a local plugins/index.js.
*/
private function generatePluginsJs() {
$plugins = array_map(
function ($file) {
return " require('./plugins/{$file}/index.js')(on, config);";
},
$this->plugins
);
array_unshift($plugins,
'// Automatically generated by the Cypress module for Drupal.',
'module.exports = (on, config) => {'
);
$plugins[] = '};';
return implode("\n", $plugins);
}
/**
* Generate a javascript file that imports `index` from given folders.
*
* @return string
* The content for a local index.js.
*/
protected function generateSupportJs() {
$index = array_map(function ($name) {
return "require('./support/$name/index.js');";
}, $this->support);
array_unshift(
$index,
'// Automatically generated by the Cypress module for Drupal.'
);
return implode("\n", $index);
}
}
| true |
28863308473955ca397d46d426b3f5302d64bd28 | PHP | luoshengming/MyReadings | /books/html5-ia/src/main/resources/ch4/sse-chat/close-session.php | UTF-8 | 515 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | <?php
session_start();
include_once "credentials.php";
//remove it from the database
try {
$dbh = new PDO($db, $user, $pass);
$preparedStatement = $dbh->prepare('DELETE FROM `sessions`WHERE `session_id` =:sid');
$preparedStatement->execute(array(':sid' => session_id()));
$rows = $preparedStatement->fetchAll();
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
session_destroy();
//redirect to index.php
header("Location: index.php");
?> | true |
ad71f68d1775f65bf5f8e8cb594ae2953e1022fa | PHP | medalidridi/trade-line | /trade_line/accueil/model/client.php | UTF-8 | 2,589 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
class client {
public $id;
public $nom;
public $prenom;
public $photo;
public $email;
public $confmail;
public $login;
public $pwd;
public $tel;
public $adresse;
public $civilite;
public $dnc;
public function Addclient(client $client)
{
include("config.php");
$q=$db->prepare('insert into client set nom= :nom ,prenom= :prenom ,email= :email ,login= :login ,pwd= :pwd ,tel= :tel ,adresse= :adresse ,civilite= :civilite ,dnc= :dnc');
$q->bindValue(':nom',$client->nom);
$q->bindValue(':prenom',$client->prenom);
$q->bindValue(':email',$client->email);
$q->bindValue(':login',$client->login);
$q->bindValue(':pwd',$client->pwd);
$q->bindValue(':tel',$client->tel);
$q->bindValue(':adresse',$client->adresse);
$q->bindValue(':civilite',$client->civilite);
$q->bindValue(':dnc',$client->dnc);
$q->execute();
}
public function Affclient()
{
include("config.php");
$tab=array();
$q=$db->prepare('select * from client');
$q->execute();
while ($donnees=$q->fetch($db::FETCH_ASSOC))
{
$tab[]=$donnees;}
if ($tab){
return $tab;}
else
{ return; }
}
public function suppclientbyid($id)
{
include("config.php");
$q=$db->prepare('delete from client where id = :id');
$q->execute(array(':id'=>$id));
}
public function affclientbyid($id)
{
include("config.php");
$q=$db->prepare('select * from client where id= :id');
$q->execute(array(':id'=>$id));
$donnees=$q->fetch($db::FETCH_ASSOC); //affichage de la base de donnee
return $donnees;
}
public function affclientbyidclient($id_client)
{
include("config.php");
$q=$db->prepare('select * from client where id= :id_client');
$q->execute(array(':id_client'=>$id_client));
$donnees=$q->fetch($db::FETCH_ASSOC); //affichage de la base de donnee
return $donnees;
}
public function modifclient(client $client)
{
include("config.php");
$q=$db->prepare('update client set nom= :nom ,prenom= :prenom ,telm= :telm ,telf= :telf ,adresse= :adresse ,ville= :ville ,code_postal= :code_postal ,pays= :pays ,description= :description where id= :id');
$q->bindValue(':id',$client->id);
$q->bindValue(':nom',$client->nom);
$q->bindValue(':prenom',$client->prenom);
$q->bindValue(':telm',$client->telm);
$q->bindValue(':telf',$client->telf);
$q->bindValue(':adresse',$client->adresse);
$q->bindValue(':ville',$client->ville);
$q->bindValue(':code_postal',$client->code_postal);
$q->bindValue(':pays',$client->pays);
$q->bindValue(':description',$client->description);
$q->execute();
}
}
?> | true |
697ee38928da7eb320733909e5614032f53f7648 | PHP | hobocta/patterns | /src/Hobocta/Patterns/Behavioral/Observer/Observer.php | UTF-8 | 262 | 2.53125 | 3 | [] | no_license | <?php
namespace Hobocta\Patterns\Behavioral\Observer;
/**
* Interface Observer
* @package Hobocta\Patterns\Behavioral\Observer
*/
interface Observer
{
/**
* @param JobPost $jobPosting
*/
public function onJobPosted(JobPost $jobPosting);
}
| true |
1f888577bf716df241369a890f084632a29d39c8 | PHP | TallAndSassy/livewire-friends | /tests/Feature/Http/Controllers/LivewireFriendsControllerTest.php | UTF-8 | 2,400 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace TallAndSassy\LivewireFriends\Tests\Feature\Http\Controllers;
class LivewireFriendsControllerTest extends \TallAndSassy\LivewireFriends\Tests\TestCase
{
/** @test */
public function global_urls_returns_ok()
{
// Test hard-coded routes...
$this
->get('/grok/TallAndSassy/LivewireFriends/sample_string')
->assertOk()
->assertSee('Hello LivewireFriends string via global url.');
$this
->get('/grok/TallAndSassy/LivewireFriends/sample_blade')
->assertOk()
->assertSee('Hello LivewireFriends from blade in TallAndSassy/LivewireFriends/groks/sample_blade');
$this
->get('/grok/TallAndSassy/LivewireFriends/controller')
->assertOk()
->assertSee('Hello LivewireFriends from: TallAndSassy\LivewireFriends\Http\Controllers\LivewireFriendsController::sample');
}
/** @test */
public function prefixed_urls_returns_ok()
{
// Test user-defined routes...
// Reproduce in routes/web.php like so
// Route::tassylivewirefriends('staff');
// http://test-tallandsassy.test/staff/TallAndSassy/LivewireFriends/string
// http://test-tallandsassy.test/staff/TallAndSassy/LivewireFriends/blade
// http://test-tallandsassy.test/staff/TallAndSassy/LivewireFriends/controller
$userDefinedBladePrefix = $this->userDefinedBladePrefix; // user will do this in routes/web.php Route::tassylivewirefriends('url');
// string
$this
->get("/$userDefinedBladePrefix/TallAndSassy/LivewireFriends/sample_string")
->assertOk()
#->assertSee('hw(TallAndSassy\LivewireFriends\Http\Controllers\LivewireFriendsController)');
->assertSee('Hello LivewireFriends string via blade prefix');
// blade
$this
->get("/$userDefinedBladePrefix/TallAndSassy/LivewireFriends/sample_blade")
->assertOk()
->assertSee('Hello LivewireFriends from blade in TallAndSassy/LivewireFriends/groks/sample_blade');
// controller
$this
->get("/$userDefinedBladePrefix/TallAndSassy/LivewireFriends/controller")
->assertOk()
->assertSee('Hello LivewireFriends from: TallAndSassy\LivewireFriends\Http\Controllers\LivewireFriendsController::sample');
}
}
| true |
8debfef5d2a088d37c271290105bb9aa8a8611d6 | PHP | Erryk20/mini-framework | /migrations/20200506102923_create_category_table.php | UTF-8 | 635 | 2.609375 | 3 | [] | no_license | <?php
use Phinx\Migration\AbstractMigration;
class CreateCategoryTable extends AbstractMigration
{
public function up()
{
$table = $this->table('category');
$table->addColumn('parent_id', 'integer', ['null' => true])
->addIndex('parent_id')
->addColumn('name', 'string', ['limit' => 100])
->save();
$table->addForeignKey('parent_id', 'category', 'id', ['delete'=>'CASCADE', 'update'=>'NO ACTION'])
->save();
}
public function down()
{
$table = $this->table('category');
$table->dropForeignKey('parent_id')
->removeIndex('parent_id')
->save();
$table->drop()->save();
}
}
| true |
6cf3dcb1f77102f6f5c294696ae29637635cfa73 | PHP | rutgerkirkels/DomoticzPHP | /src/Hardware/AbstractHardware.php | UTF-8 | 1,771 | 3.21875 | 3 | [
"MIT"
] | permissive | <?php
namespace rutgerkirkels\DomoticzPHP\Hardware;
abstract class AbstractHardware
{
/**
* @var int
*/
protected $id;
/**
* @var string
*/
protected $name;
/**
* @var string
*/
protected $type;
/**
* @var array
*/
protected $devices;
public function __construct(int $id, string $name, array $devices, string $type = null)
{
$this->id = $id;
$this->name =$name;
$this->devices = $devices;
$this->type = $type;
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @param int $id
*/
public function setId(int $id): void
{
$this->id = $id;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @param string $name
*/
public function setName(string $name): void
{
$this->name = $name;
}
/**
* @return string
*/
public function getType(): string
{
return $this->type;
}
/**
* @param string $type
*/
public function setType(string $type): void
{
$this->type = $type;
}
/**
* @return array
*/
public function getDevices(): array
{
return $this->devices;
}
/**
* @param array $devices
*/
public function setDevices(array $devices): void
{
$this->devices = $devices;
}
public function getDeviceByIdx(int $idx) {
foreach ($this->devices as $key => $device) {
if ($device->getIdx() === $idx) {
return $this->devices[$key];
}
}
return false;
}
} | true |
84249afb2fa8ac208abf75ca25a5cf1a786f46c7 | PHP | DSim0111/ProjekatPSI_MTS | /faza6/app/Models/DeliveryRequestsModel.php | UTF-8 | 1,608 | 2.625 | 3 | [] | no_license | <?php
namespace App\Models;
use CodeIgniter\Model;
/**
* Description of CategoriesModel
*
* @author Simona
*/
class DeliveryRequestsModel extends Model {
//put your code here
protected $table = 'deliveryrequest';
protected $primaryKey = 'idDelReq';
protected $returnType = 'object';
protected $allowedFields = ['idUser', 'idProduct', 'idShop', 'state', 'submitDate', 'payment', 'notes', 'address', 'submitTime', 'receiverName', 'receiverSurname', 'deliverDate', 'deliverTime'];
public function handledRequestForShopWithID($idShop) {
return $this->builder()->select("*, DeliveryRequest.address as dAddress, User.address as UserAddress")->where("idShop", $idShop)->where("state!=", "A")->join("user", "user.id=deliveryrequest.idUser")->join("systemuser", "systemuser.id=deliveryrequest.idUser")->get()->getResultObject();
}
public function unhandledRequestForShopWithID($idShop) {
return $this->builder()->select("*, DeliveryRequest.address as dAddress, User.address as UserAddress")->where("idShop", $idShop)->where("state", "A")->join("user", "user.id=deliveryrequest.idUser")->join("systemuser", "systemuser.id=deliveryrequest.idUser")->get()->getResultObject();
}
public function existsRequestForShop($idReq, $idShop) {
$obj = $this->builder()->select()->where("idDelReq", $idReq)->where("idShop", $idShop)->where("state", "A")->get()->getRow();
if ($obj != null)
return true;
else
return false;
}
public function insertData($data) {
return $this->insert($data);
}
}
| true |
50398af44f10e285eb6069f9db847cc58b0f5e16 | PHP | decole/planka-php-sdk | /src/Actions/Card/CardCreateAction.php | UTF-8 | 1,011 | 2.671875 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace Planka\Bridge\Actions\Card;
use Planka\Bridge\Contracts\Actions\ResponseResultInterface;
use Planka\Bridge\Contracts\Actions\AuthenticateInterface;
use Planka\Bridge\Contracts\Actions\ActionInterface;
use Planka\Bridge\Traits\AuthenticateTrait;
use Planka\Bridge\Traits\CardHydrateTrait;
final class CardCreateAction implements ActionInterface, AuthenticateInterface, ResponseResultInterface
{
use AuthenticateTrait, CardHydrateTrait;
public function __construct(
private readonly string $listId,
private readonly string $name,
private readonly int $position,
string $token
) {
$this->setToken($token);
}
public function url(): string
{
return "api/lists/{$this->listId}/cards";
}
public function getOptions(): array
{
return [
'body' => [
'name' => $this->name,
'position' => $this->position,
],
];
}
} | true |
1d320bcb43dcff03310e7ae94bdf2b45ac77e283 | PHP | Sete7/3sturismo | /admin/View/Admin/AdminView.php | UTF-8 | 6,219 | 2.625 | 3 | [] | no_license | <?php
//require_once '../Controller/UsuarioController.php';
//require_once '../Model/Usuario.php';
$nome = "";
$resultado = "";
$usuarioController = new UsuarioController();
$btnCadastrar = filter_input(INPUT_POST, 'btnCadastrar', FILTER_SANITIZE_STRING);
if ($btnCadastrar) {
$usuario = new Usuario();
$usuario->setNome(filter_input(INPUT_POST, 'txtNome', FILTER_SANITIZE_STRING));
$usuario->setEmail(filter_input(INPUT_POST, 'txtEmail', FILTER_SANITIZE_STRING));
$usuario->setUsuario(filter_input(INPUT_POST, 'txtUsuario', FILTER_SANITIZE_STRING));
$usuario->setSenha(filter_input(INPUT_POST, 'txtSenha', FILTER_SANITIZE_STRING));
$usuario->setPermissao(filter_input(INPUT_POST, 'slSexo', FILTER_SANITIZE_NUMBER_INT));
$usuario->setStatus(filter_input(INPUT_POST, 'slStatus', FILTER_SANITIZE_NUMBER_INT));
if($usuarioController->Cadastrar($usuario)){
$resultado = "<div class=\"bg-success\">O usuário <b> {$usuario->getUsuario()}</b> foi cadastrado com sucesso</div>";
}else{
$resultado = "<div class=\"bg-danger\"> Não foi possível cadastrada o usuário</div>";
}
}
?>
<div id="page-wrapper">
<div class="container-fluid">
<!-- Page Heading -->
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">
Usuário
</h1>
<ol class="breadcrumb">
<li>
<i class="fa fa-dashboard"></i> <a href="painel.php">Dashboard</a>
</li>
<li class="active">
<i class="fa fa-user"></i> Usuário
</li>
</ol>
</div>
</div>
<form method="post">
<div class="row">
<div class="col-lg-6 col-xs-12">
<div class="form-group">
<label for="txtNome">Nome Completo</label>
<input type="text" class="form-control" id="txtNome" name="txtNome" placeholder="Nome Completo" value="<?= $nome; ?>">
<span class="msg-error msg-nome"></span>
</div>
</div>
<div class="col-lg-6 col-xs-12">
<div class="form-group">
<label for="txtEmail">Email</label>
<input type="email" class="form-control" id="txtNome" name="txtEmail" placeholder="email" value="">
<span class="msg-error msg-nome"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6 col-xs-12">
<div class="form-group">
<label for="txtUsuario">Usuário</label>
<input type="text" class="form-control" id="txtUsuario" name="txtUsuario" placeholder="Informe o usuário" value="">
<span class="msg-error msg-nome"></span>
</div>
</div>
<div class="col-lg-6 col-xs-12">
<div class="form-group">
<label for="txtThumb">Selecione uma imagem</label>
<input type="file">
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6 col-xs-12">
<div class="form-group">
<label for="txtSenha">Senha (mínimo 6 caracteres)</label>
<input type="password" class="form-control" id="txtSenha" name="txtSenha" placeholder="Informe a senha" value="">
<span class="msg-error msg-nome"></span>
</div>
</div>
<div class="col-lg-6 col-xs-12">
<div class="form-group">
<label for="txtSenha">Repita a Senha</label>
<input type="password" class="form-control" id="txtSenha" name="txtSenha" placeholder="Repita a senha" value="">
<span class="msg-error msg-nome"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6 col-xs-12">
<div class="form-group">
<label for="slPermissao">Permissão</label>
<select class="form-control" name="slSexo" id="slPermissao">
<option value="1">Administrador</option>
<option value="2">Editor</option>
</select>
<span class="msg-error msg-sexo"></span>
</div>
</div>
<div class="col-lg-6 col-xs-12">
<div class="form-group">
<label for="slStatus">Status</label>
<select class="form-control" name="slStatus" id="slStatus">
<option value="1">Ativo</option>
<option value="2">Bloqueado</option>
</select>
<span class="msg-error msg-sexo">2 </span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="form-group">
<?php echo $resultado; ?>
</div>
</div>
</div>
<input class="btn btn-primary" type="submit" value="Cadastrar" name="btnCadastrar">
<input class="btn btn-danger" type="submit" value="Cancelar">
</form>
</div>
<!-- /.container-fluid -->
</div>
<!-- /#page-wrapper -->
| true |
8e0ee83e7b426488c9d4d2ab587879d927d65b74 | PHP | ProklUng/framework-tools-bundle | /Services/Wordpress/Context.php | UTF-8 | 9,240 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
namespace Prokl\FrameworkExtensionBundle\Services\Wordpress;
use JsonSerializable;
/**
* Class Context
* @package Prokl\FrameworkExtensionBundle\Services\Wordpress
*
* @since 10.06.2021
* @see https://github.com/inpsyde/wp-context
*/
class Context implements JsonSerializable
{
public const AJAX = 'ajax';
public const BACKOFFICE = 'backoffice';
public const CLI = 'wpcli';
public const CORE = 'core';
public const CRON = 'cron';
public const FRONTOFFICE = 'frontoffice';
public const INSTALLING = 'installing';
public const LOGIN = 'login';
public const REST = 'rest';
public const XML_RPC = 'xml-rpc';
private const ALL = [
self::AJAX,
self::BACKOFFICE,
self::CLI,
self::CORE,
self::CRON,
self::FRONTOFFICE,
self::INSTALLING,
self::LOGIN,
self::REST,
self::XML_RPC,
];
/**
* @var array $data
*/
private $data;
/**
* @var array<string, callable>
*/
private $actionCallbacks = [];
/**
* @return self
*/
final public static function new(): self
{
return new self(array_fill_keys(self::ALL, false));
}
/**
* @return self
*/
final public static function determine(): self
{
$installing = defined('WP_INSTALLING') && WP_INSTALLING;
$xmlRpc = defined('XMLRPC_REQUEST') && XMLRPC_REQUEST;
$isCore = defined('ABSPATH');
$isCli = defined('WP_CLI');
$notInstalling = $isCore && !$installing;
$isAjax = $notInstalling ? wp_doing_ajax() : false;
$isAdmin = $notInstalling ? (is_admin() && !$isAjax) : false;
$isCron = $notInstalling ? wp_doing_cron() : false;
$undetermined = $notInstalling && !$isAdmin && !$isCron && !$isCli && !$xmlRpc && !$isAjax;
$isRest = $undetermined ? static::isRestRequest() : false;
$isLogin = ($undetermined && !$isRest) ? static::isLoginRequest() : false;
// When nothing else matches, we assume it is a front-office request.
$isFront = $undetermined && !$isRest && !$isLogin;
/*
* Note that when core is installing **only** `INSTALLING` will be true, not even `CORE`.
* This is done to do as less as possible during installation, when most of WP does not act
* as expected.
*/
$instance = new self(
[
self::CORE => ($isCore || $xmlRpc) && !$installing,
self::FRONTOFFICE => $isFront,
self::BACKOFFICE => $isAdmin,
self::LOGIN => $isLogin,
self::AJAX => $isAjax,
self::REST => $isRest,
self::CRON => $isCron,
self::CLI => $isCli,
self::XML_RPC => $xmlRpc && !$installing,
self::INSTALLING => $installing,
]
);
$instance->addActionHooks();
return $instance;
}
/**
* @param array $data Данные.
*/
private function __construct(array $data)
{
$this->data = $data;
}
/**
* @param string $context Контекст.
*
* @return self
*/
final public function force(string $context): self
{
if (!in_array($context, self::ALL, true)) {
throw new \LogicException("'{$context}' is not a valid context.");
}
$this->removeActionHooks();
$data = array_fill_keys(self::ALL, false);
$data[$context] = true;
if ($context !== self::INSTALLING && $context !== self::CORE && $context !== self::CLI) {
$data[self::CORE] = true;
}
$this->data = $data;
return $this;
}
/**
* @return self
*/
final public function withCli(): self
{
$this->data[self::CLI] = true;
return $this;
}
/**
* @param string $context Контекст.
* @param string ...$contexts Все контексты.
*
* @return boolean
*/
final public function is(string $context, string ...$contexts): bool
{
array_unshift($contexts, $context);
foreach ($contexts as $context) {
if ($this->data[$context] ?? null) {
return true;
}
}
return false;
}
/**
* @return boolean
*/
public function isCore(): bool
{
return $this->is(self::CORE);
}
/**
* @return boolean
*/
public function isFrontoffice(): bool
{
return $this->is(self::FRONTOFFICE);
}
/**
* @return boolean
*/
public function isBackoffice(): bool
{
return $this->is(self::BACKOFFICE);
}
/**
* @return boolean
*/
public function isAjax(): bool
{
return $this->is(self::AJAX);
}
/**
* @return boolean
*/
public function isLogin(): bool
{
return $this->is(self::LOGIN);
}
/**
* @return boolean
*/
public function isRest(): bool
{
return $this->is(self::REST);
}
/**
* @return boolean
*/
public function isCron(): bool
{
return $this->is(self::CRON);
}
/**
* @return boolean
*/
public function isWpCli(): bool
{
return $this->is(self::CLI);
}
/**
* @return boolean
*/
public function isXmlRpc(): bool
{
return $this->is(self::XML_RPC);
}
/**
* @return boolean
*/
public function isInstalling(): bool
{
return $this->is(self::INSTALLING);
}
/**
* @return array
*/
public function jsonSerialize(): array
{
return $this->data;
}
/**
* When context is determined very early we do our best to understand some context like
* login, rest and front-office even if WordPress normally would require a later hook.
* When that later hook happen, we change what we have determined, leveraging the more
* "core-compliant" approach.
*
* @return void
*/
private function addActionHooks(): void
{
$this->actionCallbacks = [
'login_init' => function (): void {
$this->resetAndForce(self::LOGIN);
},
'rest_api_init' => function (): void {
$this->resetAndForce(self::REST);
},
'template_redirect' => function (): void {
$this->resetAndForce(self::FRONTOFFICE);
},
'current_screen' => function (\WP_Screen $screen): void {
$screen->in_admin() && $this->resetAndForce(self::BACKOFFICE);
},
];
foreach ($this->actionCallbacks as $action => $callback) {
add_action($action, $callback, PHP_INT_MIN);
}
}
/**
* When "force" is called on an instance created via `determine()` we need to remove added hooks
* or what we are forcing might be overridden.
*
* @return void
*/
private function removeActionHooks(): void
{
foreach ($this->actionCallbacks as $action => $callback) {
remove_action($action, $callback, PHP_INT_MIN);
}
$this->actionCallbacks = [];
}
/**
* @param string $context
*
* @return void
*/
private function resetAndForce(string $context): void
{
$cli = $this->data[self::CLI];
$this->data = array_fill_keys(self::ALL, false);
$this->data[self::CORE] = true;
$this->data[self::CLI] = $cli;
$this->data[$context] = true;
$this->removeActionHooks();
}
/**
* @return boolean
*/
private static function isRestRequest(): bool
{
if (defined('REST_REQUEST') && REST_REQUEST) {
return true;
}
if (!get_option('permalink_structure')) {
return !empty($_GET['rest_route']); // phpcs:ignore
}
/*
* This is needed because, if called early, global $wp_rewrite is not defined but required
* by get_rest_url(). WP will reuse what we set here, or in worst case will replace, but no
* consequences for us in any case.
*/
if (empty($GLOBALS['wp_rewrite'])) {
$GLOBALS['wp_rewrite'] = new \WP_Rewrite();
}
$currentPath = trim((string)parse_url((string)add_query_arg([]), PHP_URL_PATH), '/') . '/';
$restPath = trim((string)parse_url((string)get_rest_url(), PHP_URL_PATH), '/') . '/';
return strpos($currentPath, $restPath) === 0;
}
/**
* @return boolean
*/
private static function isLoginRequest(): bool
{
if (!empty($_REQUEST['interim-login'])) { // phpcs:ignore
return true;
}
$pageNow = (string)($GLOBALS['pagenow'] ?? '');
if ($pageNow && (basename($pageNow) === 'wp-login.php')) {
return true;
}
$currentPath = (string)parse_url(add_query_arg([]), PHP_URL_PATH);
$loginPath = (string)parse_url(wp_login_url(), PHP_URL_PATH);
return rtrim($currentPath, '/') === rtrim($loginPath, '/');
}
} | true |
0fa97f9648c92964cd179813c10ba1f33f06297b | PHP | dindakhrsm/absenv2-1 | /app/Models/Room.php | UTF-8 | 725 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
/**
* Created by PhpStorm.
* User: eka
* Date: 22/01/16
* Time: 15:24
*/
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class Room extends Model
{
protected $table = 'rooms';
/**
* The database table primary key.
*
* @var string
*/
protected $primaryKey = 'id_ruang';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'nama_ruang',
'lokasi',
'daya_tampung'
];
public static function room_name(){
$room = DB::table('rooms')
->select('id_ruang','nama_ruang')
->get();
return $room;
}
} | true |
be53b8e7964c5569c0d5b88badae33fea5500ccb | PHP | jotamolas/att | /src/att/attBundle/Services/WorkFlowService.php | UTF-8 | 1,707 | 2.84375 | 3 | [] | no_license | <?php
namespace att\attBundle\Services;
use Doctrine\ORM\EntityManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
use att\attBundle\Entity\Atworkflow;
use att\attBundle\Entity\Atworkflowmsg;
class WorkFlowService {
protected $em;
protected $container;
public function __construct(EntityManager $em, ContainerInterface $container)
{
$this->em = $em;
$this->container = $container;
}
public function persistWorkFlow(Atworkflow $workflow){
$this->em->persist($workflow);
$this->em->flush();
return ($workflow);
}
/**
* Cast an object to another class, keeping the properties, but changing the methods
*
* @param string $class Class name
* @param object $object
* @return object
*/
public function castToClass($class, $object)
{
return unserialize(preg_replace('/^O:\d+:"[^"]++"/', 'O:' . strlen($class) . ':"' . $class . '"', serialize($object)));
}
/**
*
* @param Atworkflow $workflow
* @param type $message
*/
public function createWorkflowMessage(Atworkflow $workflow, $message){
$msg = new Atworkflowmsg();
$msg->setDetails($message)
->setWorkflow($workflow)
->setWfstate($workflow->getStatekey());
return $this->persistWorkflowMessage($msg);
}
/**
*
* @param Atworkflowmsg $msg
* @return Atworkflowmsg
*/
public function persistWorkflowMessage(Atworkflowmsg $msg){
$this->em->persist($msg);
$this->em->flush();
return $msg;
}
} | true |
8128bbd8eca54423a92f72d5658e681e6f8e4469 | PHP | jackieluper/csp_portal_style | /htm/controllers/products.db.php | UTF-8 | 2,402 | 2.65625 | 3 | [] | no_license | <?php
require 'config.php';
require 'email.php';
require '../classes/offers.class.php';
//setting initial variables/objects
$entity = $_SESSION['entity'];
$offers = new offers();
try {
//query to get offer details and to determine if it is a top offer or not
$getOfferDetails = "SELECT top_offer, offer.id, offer.display_name, offer.license_agreement_type, offer.purchase_unit, offer.secondary_license_type, offer.sku, offer_price.erp_price FROM offer, offer_price WHERE offer.id=offer_id AND offer.license_agreement_type='$entity' AND active='1'";
$offerDetailsRes = $conn->query($getOfferDetails);
$index = 0;
if ($offerDetailsRes->num_rows > 0) {
while ($row = $offerDetailsRes->fetch_assoc()) {
$addon = $row['secondary_license_type'];
if ($addon != 'ADDON') {
$name = $row['display_name'];
$erp = $row['erp_price'];
$purchase_unit = $row['purchase_unit'];
$id = $row['id'];
$topOffer = $row['top_offer'];
//setting DB data to offers object
$offers->setOfferName($index, $name);
$offers->setOfferPrice($index, $erp);
$offers->setOfferUnit($index, $purchase_unit);
$offers->setOfferId($index, $id);
$offers->setTopOffer($index, $topOffer);
//setting the img to the name of the corresponding offer
$getImgSet = "SELECT img_tag, details FROM image WHERE offer_name='$name'";
$imgSetRes = $conn->query($getImgSet);
if ($imgSetRes->num_rows > 0) {
while ($row1 = $imgSetRes->fetch_assoc()) {
$tag = $row1['img_tag'];
$caption = $row1['details'];
$offers->setOfferImg($index, $tag);
$offers->setOfferCaption($index, $caption);
}
//if img not in DB grab no image available and send email notifying us
} else {
$tag = "noImage.png";
$offers->setOfferImg($index, $tag);
}
$index++;
}
}
} else {
throw new Exception("MySql Error: " . $getOfferDetails . "<br>" . $conn->error);
}
} catch (Exception $e) {
echo $e->getMessage();
} | true |
d78be80f5a2f481d0fa61acba7999b78717bfc73 | PHP | dominx99/poly-backend | /src/Map/Application/Handlers/RemoveCurrentMapObjectHandler.php | UTF-8 | 1,009 | 2.546875 | 3 | [] | no_license | <?php declare(strict_types=1);
namespace App\Map\Application\Handlers;
use App\Map\Application\Commands\RemoveCurrentMapObject;
use Doctrine\ORM\EntityManagerInterface;
use App\Map\Domain\Map\MapObject;
final class RemoveCurrentMapObjectHandler
{
/** @var \Doctrine\ORM\EntityManagerInterface */
private $entityManager;
/**
* @param \Doctrine\ORM\EntityManagerInterface $entityManager
*/
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
/**
* @param \App\Map\Application\Commands\RemoveCurrentMapObject $command
* @return void
*/
public function handle(RemoveCurrentMapObject $command): void
{
if (! $mapObject = $this->entityManager->getRepository(MapObject::class)->findOneBy([
'field' => $command->fieldId(),
])) {
return;
}
$this->entityManager->remove($mapObject);
$this->entityManager->flush();
}
}
| true |
5a36e134afe4b51e36562521ff35636dade78b26 | PHP | paoim/PHPDemo | /stringdemo/app/StringDemo.php | UTF-8 | 1,800 | 3.046875 | 3 | [] | no_license | <?php
class StringDemo
{
public function __construct() {
$this->display();
}
private function display() {
echo "<pre>"; print_r(substr('Welcome', 0, 1)); echo "</pre>";
echo "<pre>"; print_r($this->_getXXXSSN('0487')); echo "</pre>";
echo "<pre>"; print_r($this->_getXXXSSN('72-0487')); echo "</pre>";
echo "<pre>"; print_r($this->_getXXXSSN('536-72-0487')); echo "</pre>";
echo "<pre>"; print_r(($this->makeMd5('LMD0ma!n') == '369c5a2b79b61284f7574828a3141327') ? 'Yes' : 'No'); echo "</pre>";
echo "<pre>"; print_r($this->getSirvaShipmentID('REG 123456')); echo "</pre>";
}
private function makeMd5($password) {
return md5($password);
}
private function getSirvaShipmentID($description) {
$description = $this->cleanContent($description);
$description = strtoupper($description);
if ($this->isContentStartWith($description, 'REG')) {
$description = $this->replace($description, 'REG');
}
return $description;
}
private function replace($content, $filter) {
$content = str_replace($filter, '', $content);
$content = $this->cleanContent($content);
return $content;
}
private function isContentStartWith($content, $filter) {
$position = strpos($content, $filter, 0);//find from index zero
return ($position === 0);
}
private function cleanContent($line) {
return ($this->isValidStr($line) ? trim($line) : "");
}
private function isValidStr($str) {
return (isset($str) && strlen($str) > 0);
}
private function _getXXXSSN($input) {
$strSSN = "XXX-XXX-$input";
$strArray = explode('-', $input);
if (!count($strArray)) {
return $input;
}
if (count($strArray) == 3) {
$strSSN = "XXX-XXX-" . $strArray[2];
} else if (count($strArray) == 2) {
$strSSN = "XXX-XXX-" . $strArray[1];
}
return $strSSN;
}
}
| true |
5749c7d70de1ef146c2f1a3ade1dc4d83405445b | PHP | DrexelSeniorDesign2016Team8/Middleware | /getUser.php | UTF-8 | 376 | 2.53125 | 3 | [] | no_license | <?php
require_once 'setup.php';
require_once 'session.class.php';
$json = array();
$sid = $_GET['sid'];
$user_name = Session::fetchName($sid);
if($user_name == false) {
$json['status'] = 'error';
$json['error'] = 'No user found for this session';
} else {
$json['status'] = 'success';
$json['response'] = array('userName' => $user_name);
}
echo json_encode($json);
?>
| true |
a6bdb9ccca14de3b0de7caeb95a0945388654a75 | PHP | gregoriohc/argentum-common | /src/Common/Document/Invoice.php | UTF-8 | 2,126 | 3.28125 | 3 | [
"MIT"
] | permissive | <?php
namespace Argentum\Common\Document;
use Argentum\Common\Exception\InvalidDocumentException;
use Argentum\Common\Person;
/**
* Invoice class
*
* Invoice document type
*
* Example:
*
* <code>
* // Define document parameters, which should look like this
* $parameters = [
* 'id' => 'A-123',
* 'from' => new Person(...),
* 'to' => new Person(...),
* 'items' => new Bag(...),
* ];
*
* // Create a invoice object
* $invoice = new Invoice($parameters);
* </code>
*
* The full list of document attributes that may be set via the parameter to
* *new* is as follows:
*
* * id
* * series
* * date
* * from
* * to
* * items
* * currency
*
* If any unknown parameters are passed in, they will be ignored. No error is thrown.
*/
class Invoice extends Ticket
{
/**
* Create a new Document object using the specified parameters
*
* @param array $parameters An array of parameters to set on the new object
*/
public function __construct($parameters = array())
{
parent::__construct($parameters);
$this->addParametersRequired(array('to'));
$this->setType('invoice');
}
/**
* Validate this invoice. If the invoice is invalid, InvalidDocumentException is thrown.
*
* @throws InvalidDocumentException
* @return void
*/
public function validate()
{
parent::validate();
$to = $this->getTo();
if (!($to instanceof Person)) {
throw new InvalidDocumentException("The to parameter must be a Person object");
}
$to->validate();
}
/**
* Get document 'to'
*
* @return Person
*/
public function getTo()
{
return $this->getParameter('to');
}
/**
* Set document 'to'
*
* @param array|Person $value Parameter value
* @return Invoice provides a fluent interface.
*/
public function setTo($value)
{
if (is_array($value)) {
$value = new Person($value);
}
return $this->setParameter('to', $value);
}
}
| true |
795de1e722b99ba2befba4aa31f76e3ba72b8f80 | PHP | lingpj/jiu | /application/command/Export.php | UTF-8 | 2,470 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | <?php
namespace app\command;
use think\console\input\Argument;
use think\console\Input;
use think\console\Output;
use think\Db;
/**
* Created by PhpStorm.
* Author: zjh
* Date: 2017-7-4 004
* Time: 8:25
*/
class Export extends \think\console\Command
{
function configure()
{
$this->setName('export')->setDescription('export province,city,area info to js file');
$this->addArgument('args', Argument::OPTIONAL);
}
private function address(){
/**
* 北京,河南省
* 郑州市,洛阳市
*/
$provinces = Db::name('provinces')->field('province,provinceid')->select();
//sort
$prefix = [];
$rest = [];
foreach($provinces as $p){
$name = $p['province'];
if(in_array($name,['北京','河南省'])){
$prefix[] = $p;
}else{
$rest[] = $p;
}
}
if($prefix[0]['province'] == '河南省'){
$first = array_pop($prefix);
array_unshift($prefix,$first);
}
$provinces = array_merge($prefix,$rest);
$map_provinces = [];
foreach($provinces as &$p){
$cities = Db::name('cities')->where('provinceid',$p['provinceid'])->field('city,cityid')->select();
if($p['province'] == '河南省'){
$prefix = [];
$rest = [];
foreach($cities as $c){
$name = $c['city'];
if(in_array($name,['郑州市','洛阳市'])){
$prefix[] = $c;
}else{
$rest[] = $c;
}
}
if($prefix[0]['city'] == '洛阳市'){
$first = array_pop($prefix);
array_unshift($prefix,$first);
}
$cities = array_merge($prefix,$rest);
}
$p['children'] = $cities;
$map_provinces[$p['provinceid']] = $p;
}
$cities = Db::name('cities')->field('city,cityid')->select();
$map_cities = [];
foreach($cities as &$c){
$areas = Db::name('areas')->where('cityid',$c['cityid'])->field('area,areaid')->select();
$c['children'] = $areas;
$map_cities[$c['cityid']] = $c;
}
//export to file
$map_provinces = json_encode($map_provinces);
$map_cities = json_encode($map_cities);
$str = "var bao_provinces = '{$map_provinces}';var bao_cities = '{$map_cities}';";
$bytes = file_put_contents('areas.js',$str);
dump("done,write $bytes");
}
function execute(Input $input, Output $output)
{
$args = $input->getArguments()['args'];
$args = empty($args) ? 'help' : $args;
switch($args) {
case 'address':
$this->address();
break;
case 'help':
$output->writeln('-h');
break;
default:
$output->writeln('Wrong arguments!');
}
}
} | true |
1b96a2f72bfc66f0b55dfc4f6a6369ef50292b08 | PHP | human-programmer/portfolio-warehouse | /lib/services/services/accounts/AmocrmAccounts.php | UTF-8 | 1,598 | 2.828125 | 3 | [] | no_license | <?php
namespace Services;
use Services\General\iAccount;
trait AmocrmAccounts {
function findAmocrmById(int $amocrm_account_id): iAccount|null {
$query = self::createFindAmocrmByIdQuery($amocrm_account_id);
return $this->singleGetMethod($query);
}
private static function createFindAmocrmByIdQuery(int|array $amocrm_account_id): array {
$filter = ['amocrm_account_id' => $amocrm_account_id];
return self::createQueryWithFilter($filter);
}
function findAmocrmBySubdomain(string $subdomain): iAccount|null {
$referer = "$subdomain.amocrm.ru";
return $this->findAmocrmByReferer($referer);
}
function findAmocrmByReferer(string $referer): iAccount|null {
$query = self::createFindAmocrmByReferer($referer);
return $this->singleGetMethod($query);
}
private static function createFindAmocrmByReferer(string|array $amocrm_referer): array {
$filter = ['amocrm_referer' => $amocrm_referer];
return self::createQueryWithFilter($filter);
}
function findBitrix24ByMemberId(string $member_id): iAccount|null {
// throw new \Exception("Method findBitrix24ByMemberId is not implemented");
return null;
}
private function singleGetMethod(array $query): iAccount|null {
$answer = $this->amocrmGetMethod($query);
return $answer[0] ?? null;
}
private function amocrmGetMethod(array $query): array {
$answer = $this->amocrmRequest('get', $query);
return self::createStructs($answer['result']);
}
private function amocrmRequest(string $method, array $query): array {
$path = "/amocrm/accounts/$method";
return $this->servicesRequest($path, $query);
}
} | true |
1211255424c37ae68146181c87999b2069841e2a | PHP | hackerlank/php-webserver | /cls/dao/lock.php | UTF-8 | 2,965 | 2.734375 | 3 | [] | no_license | <?php
/**
* @author guoyunfeng
*/
class cls_dao_lock extends sys_daoabs
{
private static $pid;
private static $lock_dir = 'tmp/';
private static $lock_array = array();
public function __construct()
{
parent::__construct();
self::$pid = getmypid();
self::$lock_dir = ROOT_PATH.'/filelock/';
}
/*
* 增加一个事务锁
*/
public function Lock($club_id,$key, $update_interval = 3)
{
for ($i = 1; $i <= $update_interval * 2; $i++) {
$ret = self::addLock($club_id,$key,$update_interval);
if($ret){
return true;
}
else{
usleep(500000); // wait for 0.5 seconds
}
}
}
/*
* 删除一个事务锁
*/
public function unLock($club_id,$key)
{
return self::deleteLock($club_id,$key);
}
private static function _getFileName($club_id,$key)
{
return $club_id.$key.'.lock';
}
private static function addLock($club_id,$key,$lock_time){
$fileName = self::_getFileName($club_id,$key);
$fileHandle = self::_getFileHandle($fileName);
$lock = flock($fileHandle, LOCK_EX | LOCK_NB);
if($lock === TRUE){
self::$lock_array[$fileName] = array('file' => $fileHandle);
$content = self::$pid . PHP_EOL . microtime(true). PHP_EOL . $club_id.PHP_EOL . $key . PHP_EOL . $lock_time;
if(fwrite($fileHandle, $content) === FALSE) {
flock($handle, LOCK_UN); // 释放锁定
return false;
}
fflush($fileHandle);
return true;
}
return false;
}
private static function deleteLock($club_id,$key){
$fileName = self::_getFileName($club_id,$key);
$lock_file = self::_getPath($fileName);
if(!file_exists($lock_file)){
return true;
}
$fileHandle = self::_getFileHandle($fileName);
$success = flock($fileHandle, LOCK_UN);
ftruncate($fileHandle, 0);
fclose($fileHandle);
unset(self::$lock_array[$fileName]);
return true;
}
private static function _getFileHandle($name){
$fileHandle = null;
if(isset(self::$lock_array[$name])) {
$fileHandle = self::$lock_array[$name]['file'];
}
if($fileHandle == null) {
$fileHandle = fopen(self::_getPath($name), 'c');
}
return $fileHandle;
}
private static function _getPath($name)
{
return self::$lock_dir.$name;
}
function __destruct()
{
foreach (self::$lock_array as $key => $value) {
flock($value['file'], LOCK_UN);
}
}
} | true |
bb19c7c25737e3eaf16212b26e112e3bb548b96f | PHP | alberto234/wurrd-client-interface-plugin | /Classes/ThreadProcessor.php | UTF-8 | 6,297 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | <?php
/*
* This file is a part of Wurrd ClientInterface Plugin.
*
* Copyright 2015 Eyong N <eyongn@scalior.com>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Wurrd\Mibew\Plugin\ClientInterface\Classes;
use Mibew\RequestProcessor\ThreadProcessor as CoreThreadProcessor;
use Mibew\RequestProcessor\Exception\ThreadProcessorException;
use Wurrd\Mibew\Plugin\ClientInterface\Classes\Thread;
/**
* Extends the Mibew core ThreadProcessor
*
* TODO: This extension is needed to override the apiPost() method
* so that it returns the postedId for every message that is
* posted. The recommendation is for this enhancement to be
* implemented in the core ThreadProcessor itself
*/
class ThreadProcessor extends CoreThreadProcessor
{
/**
* Post message to thread. API function
*
* @param array $args Associative array of arguments. It must contains the
* following keys:
* - 'threadId': Id of the thread related to chat window
* - 'token': last thread token
* - 'user': TRUE if window used by user and FALSE otherwise
* - 'message': posted message
* @throws ThreadProcessorException
*/
protected function apiPost($args)
{
// Load thread
$thread = self::getThread($args['threadId'], $args['token']);
// Check variables
self::checkParams($args, array('user', 'message'));
// Get operator's array
if (!$args['user']) {
$operator = $this->checkOperator();
// Operators can post messages only to own threads.
$can_post = ($operator['operatorid'] == $thread->agentId);
} else {
// Users can post messages only when a thread is open.
$can_post = $thread->state != Thread::STATE_CLOSED;
}
if (!$can_post) {
throw new ThreadProcessorException(
"Cannot send",
ThreadProcessorException::ERROR_CANNOT_SEND
);
}
// Set fields
$kind = $args['user'] ? Thread::KIND_USER : Thread::KIND_AGENT;
if ($args['user']) {
$msg_options = array('name' => $thread->userName);
} else {
$msg_options = array(
'name' => $thread->agentName,
'operator_id' => $operator['operatorid'],
);
}
// Post message
$posted_id = $thread->postMessage($kind, $args['message'], $msg_options);
// Update shownMessageId
if ($args['user'] && $thread->shownMessageId == 0) {
$thread->shownMessageId = $posted_id;
$thread->save();
}
// Everything in this method up to this point is from mibew-2.0.0-beta.2
return array('postedId' => $posted_id);
}
/**
* Send new messages to window. API function
* -- Overriding this so that we can use our Thread subclass.
*
* @param array $args Associative array of arguments. It must contains the
* following keys:
* - 'threadId': Id of the thread related to chat window
* - 'token': last thread token
* - 'user': TRUE if window used by user and FALSE otherwise
* - 'lastId': last sent message id
*/
protected function apiUpdateMessages($args)
{
// Load thread
$thread = $this->getWurrdThread($args['threadId'], $args['token']);
// Check variables
self::checkParams($args, array('user', 'lastId'));
// Check access
if (!$args['user']) {
$operator = $this->checkOperator();
// Check for reassign here. Normally this is done by the apiUpdate() method.
$thread->checkForReassign($operator);
}
// Send new messages
$last_message_id = $args['lastId'];
$messages = array_map(
'sanitize_message',
$thread->getMessages($args['user'], $last_message_id)
);
// Ping the thread here. Normally this is done by the apiUpdate() method.
// However this method will be called when checking for updates for multiple threads
// at the same time in the background process when the operator is not actively engaged in this thread.
// At this time the operator can't indicate that they are typing or not.
// It is also not satisfactory to say the operator is not typing because the background operation could be
// triggered even when the operator is actively chatting.
$thread->operatorPing(null);
return array(
'messages' => $messages,
'lastId' => $last_message_id,
);
}
/**
* Loads thread by id and token and checks if thread loaded
*
* @param int $thread_id Id of the thread
* @param int $last_token Last token of the thread
* @return \Mibew\Thread
* @throws \Mibew\RequestProcessor\ThreadProcessorException
*/
public function getWurrdThread($thread_id, $last_token)
{
// Load thread
$thread = Thread::ovLoad($thread_id, $last_token);
// Check thread
if (!$thread) {
throw new ThreadProcessorException(
'Wrong thread',
ThreadProcessorException::ERROR_WRONG_THREAD
);
}
// Return thread
return $thread;
}
/**
* Gets a new instance of the ThreadProcessor. The getInstance() method returns
* a singleton which makes it difficult to use a ThreadProcessor and a UsersProcessor
* within the same request. The NotificationController calls both when checking if a
* particular client needs to be notified of new activity
*
* @return ThreadProcessor A new ThreadProcessor instance
*/
public static function getNewInstance() {
return new static();
}
}
| true |
73e29d79bd2d811b90de05637f0d39dba77d05b6 | PHP | root-tongue/root-tongue | /vvv/www/root-tongue/content/mu-plugins/library/root-tongue/email-messages.php | UTF-8 | 2,272 | 2.78125 | 3 | [
"MIT"
] | permissive | <?php
namespace Root_Tongue;
class Email_Messages extends Abstracts\Hooks {
protected function hook() {
add_filter( 'retrieve_password_title', array( $this, 'retrieve_password_title' ) );
add_filter( 'retrieve_password_message', array( $this, 'retrieve_password_message' ), 10, 3 );
add_filter( 'rt_new_user_email_title', array( $this, 'new_user_email_title' ) );
add_filter( 'rt_new_user_email_message', array( $this, 'new_user_email_message' ), 10, 3 );
add_filter( 'rt_submit_later_title', array( $this, 'submit_later_title' ) );
add_filter( 'rt_submit_later_message', array( $this, 'submit_later_message' ), 10, 2 );
}
public function retrieve_password_title( $title ) {
return __( 'Root Tongue: Password Reset', 'rt' );
}
public function retrieve_password_message( $message, $key, $user_login ) {
// Assemble the URL for resetting the password
$reset_url = add_query_arg( array(
'action' => 'rp',
'key' => $key,
'login' => rawurlencode( $user_login )
), wp_login_url() );
// Create and return the message
$message = sprintf( __( "You have requested that your Root Tongue password be reset for the following account:
Username: %s
If this was a mistake, just ignore this email and no action will be taken.
To reset your password, go to the following address:
%s
All the best,
The Root Tongue Team
", 'rt' ), $user_login, $reset_url );
return $message;
}
public function new_user_email_title() {
return __( 'Root Tongue: Registration Information', 'rt' );
}
public function new_user_email_message( $message, $username, $password ) {
return sprintf( __( "
Thank you for registering for Root Tongue! We very happy to have you here. Here is your username and password:
username: %s
password: %s
Please keep this login info for future reference.
All the best,
The Root Tongue Team", 'rt' ), $username, $password );
}
public function submit_later_title( $title ) {
return __( 'Root Tongue: Come Back Later', 'rt' );
}
public function submit_later_message( $message, $link ) {
return sprintf( __( "
You requested to come back to Root Tongue and participate later. Here is the link to return to where you left off:
%s
Thanks for viewing and sharing,
The Root Tongue Team
", 'rt' ), $link );
}
} | true |
2b868c7c3aff4f8c262dd3676791adecf6c081f3 | PHP | AttafMohammed/briefphp | /Les tableaux/EX6.php | UTF-8 | 433 | 2.671875 | 3 | [] | no_license | <?php
/*
5 départements en Hauts-de-France
Aisne (02)
Nord (59)
Oise (60)
Pas-de-Calais (62)
Somme (80)
*/
$departement = array( "2"=>"Aisne", "59"=> "Nord", "60"=>"Oise","80"=>"pasDeCalais");
// echo '<pre>'; print_r($mois); echo '</pre>';
// $departement['41']='cc';
$departement['51']= 'Reims';
echo $departement["51"];
ksort($departement); pour faire un ordre
echo '<pre>'; print_r($departement); echo '</pre>';
?>
| true |
0a75c01ec5d00ba6da8354c48fbeb171b593b575 | PHP | newfulin/fu-cloud | /app/Modules/Finance/Repository/RedPacketRepository.php | UTF-8 | 1,877 | 2.59375 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: wqb
* Date: 2018/3/9
* Time: 15:49
*/
namespace App\Modules\Finance\Repository;
use App\Common\Models\RedPacket;
use Illuminate\Support\Facades\DB;
use App\Common\Contracts\Repository;
class RedPacketRepository extends Repository
{
public function __construct(RedPacket $model)
{
$this->model = $model;
}
//根据用户ID查询红包
public function getRedPacketListByUserId($request)
{
$ret = optional($this->model
->select('id','packet_name','packet_amount','granting_object','desr','granting_time','status')
->where('granting_object',$request['user_id'])
->paginate($request['pageSize']))
->toArray();
return $ret['data'];
}
/**
* 获取红包类型
*/
public function getPacketManage($name='VIP红包')
{
$ret = DB::select("SELECT `id`, `packet_name`, `packet_amount`, `granting_type`, `greeting`, `limit_amount`, `desr`, `granting_amount`, `status` FROM packet_manage WHERE packet_name = '$name'");
return json_decode(json_encode($ret[0]),true);
}
/**
* 获取指定用户的红包数量
*/
public function getHBCountByUserId($userId,$packetAmount){
$ret = $this->model->where('granting_object','=',$userId)->where('packet_amount','=',$packetAmount)->count();
return $ret;
}
/**
* 获取定用户的红包列表信息
*/
public function getMyPacket($where){
$ret = $this->model->where('granting_object','=',$where['granting_object'])
->where('status','=',$where['status'])->where('packet_amount','=',$where['packet_amount'])->orderby('id')->get();
return $ret;
}
/**
* 插入红包流水
*/
public function save($data)
{
$this->model->insert($data);
}
} | true |
0878d6d06f7a385a90cb45f0cc03914394763385 | PHP | jalfcolombia/nogal.se | /core/NQL.php | UTF-8 | 5,727 | 3.171875 | 3 | [
"MIT"
] | permissive | <?php
/**
* This file is part of the NogalSE package.
*
* (c) Julian Lasso <jalasso69@misena.edu.co>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace NogalSE;
use NogalSE\Interfaces\IDriver;
/**
* Nogal Query Language (NQL) proporciona algunos métodos para realizar
* operaciones básicas sobre entidades tales como la creación, borrado, carga,
* filtrado y ordenación.
* En ocasiones, sin embargo, es necesario realizar
* consultas más complejas que no pueden resolverse con estos métodos.
*
* @author Julián Andrés Lasso Figueroa <jalasso69@misena.edu.co>
*/
class NQL implements IDriver
{
/**
* Valor para condicional AND de SQL
*/
const _AND = 'AND';
/**
* Valor para condicional OR de SQL
*/
const _OR = 'OR';
/**
* Valor para orden ascendente
*/
const ASC = 'ASC';
/**
* Valor para orden descendente
*/
const DESC = 'DESC';
/**
* Controlador de PDO a usar, Ejemplo: pgsql, mysql
*
* @var string
*/
private $driver;
/**
* Variable contenedora del objeto referente a la clase del motor de
* bases de datos para NQL
*
* @var object
*/
private $driver_class;
public function __construct(string $driver)
{
$this->driver = $driver;
$class = 'NogalSE\\Drivers\\' . $this->driver;
$this->driver_class = new $class();
}
/**
* Agrega una condición AND u OR según la necesidad
*
* @param string $typeCondition
* Condicionales NQL::_AND u NQL::_OR
* @param string $condition
* Condición a utilizar. Ejemplo id = 33
* @param bool $raw
* true: "id = 69" o false: "id" = "id = :id" esta última
* opción permite enlazar (bind) con la clase PDOStatement
* @return $this
*/
public function Condition(string $typeCondition, string $condition, bool $raw = true)
{
$this->driver_class->Condition($typeCondition, $condition, $raw);
return $this;
}
/**
* Inicializa un SQL con la palabra clave DELETE
*
* @param string $table
* Tabla de donde se borrará la información
* @return $this
*/
public function delete(string $table)
{
$this->driver_class->delete($table);
return $this;
}
/**
* Complementa el uso de las palabra clave SELECT
*
* @param string $table
* Tabla en la cual se realizará la consulta
* @return $this
*/
public function from(string $table)
{
$this->driver_class->from($table);
return $this;
}
/**
* Inicializa un SQL con la palabra clave INSERT INTO
*
* @param string $table
* @param string $columns
* @return $this
*/
public function insert(string $table, string $columns)
{
$this->driver_class->insert($table, $columns);
return $this;
}
/**
* Agrega a la consulta SQL la clausula LIMIT
*
* @param float $limit
* @return $this
*/
public function limit(float $limit)
{
$this->driver_class->limit($limit);
return $this;
}
/**
* Agrega a la consulta SQL la clausula OFFSET (Clusula complementaria de LIMIT)
*
* @param int $offset
* @return $this
*/
public function offset(int $offset)
{
$this->driver_class->offset($offset);
return $this;
}
/**
* Finaliza una consulta SQL con la clausula ORDER BY
*
* @param string $columns
* @param string $typeOrder
* @return $this
*/
public function orderBy(string $columns, string $typeOrder)
{
$this->driver_class->orderBy($columns, $typeOrder);
return $this;
}
/**
* Inicializa un SQL con la palabra clave SELECT
*
* @param string $columns
* @return $this
*/
public function select(string $columns)
{
$this->driver_class->select($columns);
return $this;
}
/**
* Complementa una sentencia SQL inicializada con la palabra clave UPDATE
*
* @param string $columnsAndValues
* @param bool $raw
* @return $this
*/
public function set(string $columnsAndValues, bool $raw = true)
{
$this->driver_class->set($columnsAndValues, $raw);
return $this;
}
/**
* Inicializa un SQL con la palabra clave UPDATE
*
* @param string $table
* @return $this
*/
public function update(string $table)
{
$this->driver_class->update($table);
return $this;
}
/**
* Complementa una sentencia SQL inicializada con la palabra clave INSERT INTO
*
* @param string $values
* @return $this
*/
public function values(string $values)
{
$this->driver_class->values($values);
return $this;
}
/**
* Complementa una sentencia SQL con la clausula WHERE
*
* @param string $condition
* @param bool $raw
* @return $this
*/
public function where(string $condition, bool $raw = true)
{
$this->driver_class->where($condition, $raw);
return $this;
}
/**
* Retorna la consulta creada con NQL
*
* @return string
*/
public function __toString(): string
{
return $this->driver_class->__toString();
}
}
| true |
9d862745e5c50b7b8fff33978b1f1e910b98eec2 | PHP | DavyJones8/eNubesPrueba | /application/helpers/fecha_helper.php | UTF-8 | 809 | 2.71875 | 3 | [
"MIT"
] | permissive | <?php
function fechaEspCorta( $fecha ){
$fecha = trim(substr($fecha, 0, 20));
$numeroDia = date('d', strtotime($fecha));
$mes = date('m', strtotime($fecha));
$anio = date('Y', strtotime($fecha));
$fecha_modificada = $numeroDia . '/' . $mes . '/' . $anio;
return $fecha_modificada;
}
function fechaEsp( $fecha ){
$fecha = trim(substr($fecha, 0, 20));
$numeroDia = date('d', strtotime($fecha));
$mes = date('m', strtotime($fecha));
$anio = date('Y', strtotime($fecha));
$hora = date('H', strtotime($fecha));
$minuto = date('i', strtotime($fecha));
$segundo = date('s', strtotime($fecha));
$fecha_modificada = $numeroDia . '/' . $mes . '/' . $anio . ' ' . $hora . ':' . $minuto . ':' . $segundo;
return $fecha_modificada;
}
?> | true |
b864881a0afe57aa603d21c52a5de29b8cb48168 | PHP | olakunlevpn/Php-Contact-Form | /incl/config.php | UTF-8 | 1,684 | 2.59375 | 3 | [
"BSD-2-Clause"
] | permissive | <?php
// Maximum file size in MB.
$max_file_size = 1;
// Allowed file types. On the left side is user friendly file type presentation, on the right side is mime type presentation (you can found almost all mime types on this site: http://www.freeformatter.com/mime-types-list.html).
// You can add as many file types as you want. If array is empty ( $file_types = array(); ), than all file types will be accepted.
$file_types = array(
"jpg, jpeg" => "image/jpeg",
"gif" => "image/gif",
);
// Text for file types - this text appear in file input so user can see which file types are allowed in attachment. If you leave this string empty, left values from $file_types will be shown (if even $file_types is empty than "All" will be shown).
$file_types_text = "";
// Text that is shown before submit button
$submit_label = "We Provide Your Logo in: PSD & AI (Adobe logos)";
// Write in address where the mail is sent.
$recipient = "test@example.com";
// E-mail address that is shown in received mail. Write in "contact_form" if you want that user e-mail from contact form is shown in received mail.
$send_from = "contact_form";
// Name that is shown in received mail. Write in "contact_form" if you want that user first name and last name from contact form is shown in received mail.
$send_from_name = "contact_form";
// E-mail subject.
$subject = "Email from www.example.com";
// Text displayed if mail was successfully sent.
$message_success = "<div class='alert alert-success top40'>Mail was sent successfully.</div>";
// Text displayed if there was a problem sending mail.
$message_fail = "<div class='alert alert-danger top40'>There was a problem to send a mail.</div>";
?> | true |
c7e99f6d6009913ccd9a6565c9e42161d20fca8f | PHP | ZgeZh/shishangqiyi | /src/php/base.php | UTF-8 | 1,256 | 2.984375 | 3 | [] | no_license | <?php
//初始化连接对象方法
function connect(){
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "shishangqiyi";
$con = mysqli_connect($servername,$username,$password,$dbname);
//获取连接对象的错误信息
if (mysqli_connect_error($con)) {
echo "连接 MySQL 失败:".mysqli_connect_error();
return null;
}
return $con;
};
//执行查询数据方法
function query($sql){
$con = connect();
$result = mysqli_query($con,$sql);//返回结果集
$jsonData = array();
// print_r($result);
if ($result) {
while($obj = mysqli_fetch_object($result)){//将结果级
// print_r($obj);
$jsonData[] = $obj;
}
// 将经过处理后的数组转换成字符串,等同于JSON.stringify()
// $jsonData = json_encode($jsonData,JSON_UNESCAPED_UNICODE);
mysqli_free_result($result);//释放结果集
}
mysqli_close($con);//关闭连接
// print_r($jsonData);
return $jsonData;
};
//执行修改数据的方法
function excute($sql){
$con = connect();
$result = mysqli_query($con,$sql);//返回布尔值 true||false
mysqli_close($con);
return $result;
};
//insert into, update, delete 返回一个布尔值 true||false 不用释放
?> | true |
6d5318ee503ae5678c351fd200b4fe7d8479288e | PHP | luis-luciano/workBrigades | /app/helpers.php | UTF-8 | 2,767 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
use Carbon\Carbon;
function plural($name = null)
{
if (str_contains($name, '.')) {
return trans_choice($name, 2);
}
return trans_choice($name.'.'.str_singular($name), 2);
}
function singular($name = null)
{
if (str_contains($name, '.')) {
return trans_choice($name, 1);
}
return trans_choice($name.'.'.str_singular($name), 1);
}
function getChoice($elements = null)
{
return ($$elements->total()>1)? plural($elements) :singular($elements);
}
function optionalCollection($collection)
{
return ['' => 'No tiene'] + $collection->all();
}
function normalizeCharacters($string)
{
$normalizeChars = [
'Š' => 'S', 'š' => 's', 'Ð' => 'Dj', 'Ž' => 'Z', 'ž' => 'z', 'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'A',
'Å' => 'A', 'Æ' => 'A', 'Ç' => 'C', 'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I',
'Ï' => 'I', 'Ñ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ö' => 'O', 'Ø' => 'O', 'Ù' => 'U', 'Ú' => 'U',
'Û' => 'U', 'Ü' => 'U', 'Ý' => 'Y', 'Þ' => 'B', 'ß' => 'Ss', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'a',
'å' => 'a', 'æ' => 'a', 'ç' => 'c', 'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i',
'ï' => 'i', 'ð' => 'o', 'ñ' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'o', 'ø' => 'o', 'ù' => 'u',
'ú' => 'u', 'û' => 'u', 'ý' => 'y', 'ý' => 'y', 'þ' => 'b', 'ÿ' => 'y', 'ƒ' => 'f',
'ă' => 'a', 'î' => 'i', 'â' => 'a', 'ș' => 's', 'ț' => 't', 'Ă' => 'A', 'Î' => 'I', 'Â' => 'A', 'Ș' => 'S', 'Ț' => 'T',
];
return trim(strtolower(strtr($string, $normalizeChars)));
}
function splitWhiteSpaces($string)
{
return preg_split('/\s+/', $string);
}
function str_randomNumbers($length = 16)
{
$pool = '0123456789';
return substr(str_shuffle(str_repeat($pool, $length)), 0, $length);
}
function getDateRange($dateRange)
{
if (!str_contains($dateRange, '-') || substr_count($dateRange, '-') > 1) {
return '';
}
$dateRange = [
'start' => substr($dateRange, 0, strpos($dateRange, '-') - 1),
'end' => substr($dateRange, strpos($dateRange, '-') + 2, strlen($dateRange)),
];
try {
$dateRange['start'] = Carbon::createFromFormat('d/m/Y', $dateRange['start'])->startOfDay();
$dateRange['end'] = Carbon::createFromFormat('d/m/Y', $dateRange['end'])->endOfDay();
} catch (Exception $e) {
return '';
}
return $dateRange;
}
function dateToday($format)
{
if ($format) {
return Carbon::now()->format($format);
}
return Carbon::now();
}
| true |
1b0df098ebea1e0b81bca609b74fd16a892f6045 | PHP | arman-arif/pbss_testimonial | /libraries/Controller.php | UTF-8 | 230 | 2.578125 | 3 | [] | no_license | <?php
namespace libraries;
interface Controller
{
public function __construct();
public function get_view();
public function get_title();
public function get_script();
public function get_style();
} | true |
eab13ac40af6e3d9c7bf4337551d3835d55f7985 | PHP | JoaoASousa/Hoaloha | /includes/session.php | UTF-8 | 241 | 2.609375 | 3 | [] | no_license | <?php
function generate_random_token(){
return bin2hex(openssl_random_pseudo_bytes(32));
}
if (session_status() == PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['csrf'])) $_SESSION['csrf'] = generate_random_token();
?> | true |
89b1e323b0c174c7fa3fbc0c07d821a0da3e9d80 | PHP | jamilcse13/design-pattern-in-action | /Strategy Pattern/index.php | UTF-8 | 880 | 3.4375 | 3 | [] | no_license | <?php
/**
* Created by Anonymous
* Date: 2/5/20
* Time: 1:34 am
*/
interface PaymentGateway{
public function pay($amount);
}
class DCC implements PaymentGateway{
public function pay($amount)
{
echo "Paying $amount using Debit/Credit card\n";
}
}
class Stripe implements PaymentGateway {
public function pay($amount)
{
echo "Paying $amount using Stripe\n";
}
}
class Order {
private PaymentGateway $paymentGateway;
public function setPaymentGateway(PaymentGateway $paymentGateway)
{
$this->paymentGateway = $paymentGateway;
}
public function payBill($amount)
{
return $this->paymentGateway->pay($amount);
}
}
$order = new Order();
$order2 = clone $order;
$order->setPaymentGateway(new DCC());
$order2->setPaymentGateway(new Stripe());
$order->payBill(200);
$order2->payBill(500); | true |
c3b229c00617e44d35a28fba13263f9dbf5b6667 | PHP | Lidemy/mentor-program-4th-YongChenSu | /homeworks/week11/hw1/admin.php | UTF-8 | 2,237 | 2.703125 | 3 | [] | no_license | <?php
session_start();
require_once('./conn.php');
require_once('./utils.php');
$username = NULL;
$user = NULL;
if (!empty($_SESSION['username'])) {
$username = $_SESSION['username'];
$user = getUserFromUsername($username);
}
if ($user === NULL || $user['role'] !== 'ADMIN') {
header('Location: ./index.php');
exit;
}
$stmt = $conn->prepare(
"SELECT id, role, nickname, username FROM
yongchen_users3 ORDER BY id DESC
");
$result = $stmt->execute();
if (!$result) {
die('Error:' . $conn->error);
}
$result = $stmt->get_result();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>後臺管理</title>
<link href="https://fonts.googleapis.com/css2?family=Pangolin&display=swap" rel="stylesheet">
<link href="./style.css" rel="stylesheet">
</head>
<body>
<header class="warning">
<strong>WARNING! THIS SITE IS FOR PHP PRACTICING AND UNSECURED. PLS DONT'T USE REAL-LIFE USERNAME AND PASSWORD.</strong>
</header>
<main class="board">
<div class="board__title">
<h1>ADMIN</h1>
</div>
<section>
<table border>
<tr>
<th>id</th>
<th>role</th>
<th>nickname</th>
<th>username</th>
<th>調整身分</th>
</tr>
<?php while($row = $result->fetch_assoc()) { ?>
<tr>
<td><?php echo escape($row['id']) ?></td>
<td><?php echo escape($row['role']) ?></td>
<td><?php echo escape($row['nickname']) ?></td>
<td><?php echo escape($row['username']) ?></td>
<td>
<a href="handle_update_role.php?role=ADMIN
&id=<?php echo escape($row['id'])?>">管理員
</a>
<a href="handle_update_role.php?role=NORMAL
&id=<?php echo escape($row['id'])?>">使用者
</a>
<a href="handle_update_role.php?role=BANNED
&id=<?php echo escape($row['id'])?>">停權
</a>
</td>
</tr>
<?php } ?>
</table>
</section>
</main>
<script>
</script>
</body>
</html> | true |
82eeb6153dbfca6a459301d7f2f2bb436bc2d6c8 | PHP | Malcolm-soubdhan/TP_mini_jeu | /class/Mage.php | UTF-8 | 228 | 2.625 | 3 | [] | no_license | <?php
class Mage extends Perso
{
public function __construct(){
$this->PV = 100;
$this->MP = 5;
$this->defense = 0;
$this->attack = rand(5, 10);
$this->image = "hat.png";
}
} | true |
c53becb9baced33448b5b265cdc7e762e2f0eedb | PHP | realchief/Symfony-wonderly | /src/AppBundle/DataFixtures/ORM/EventFixture.php | UTF-8 | 4,957 | 2.625 | 3 | [] | no_license | <?php
namespace AppBundle\DataFixtures\ORM;
use CrEOF\Spatial\PHP\Types\Geometry\Point;
use Doctrine\Common\Persistence\ObjectManager;
use FrontendBundle\Entity\Age;
use FrontendBundle\Entity\Category;
use FrontendBundle\Entity\Event;
use UserBundle\Entity\Organize;
/**
* Class EventFixture
* @package AppBundle\DataFixtures\ORM
*/
class EventFixture extends AbstractFixture
{
/**
* Load data fixtures with the passed EntityManager
*
* @param ObjectManager $manager A ObjectManager instance.
*
* @return void
*/
public function load(ObjectManager $manager)
{
if (! $this->checkEnvironment('test')) {
return;
}
/** @var Organize $organize */
$organize = $this->getReference('organize1');
/** @var Category $arts */
$arts = $this->getReference('arts');
/** @var Category $animals */
$animals = $this->getReference('animals');
/** @var Category $dance */
$dance = $this->getReference('dance');
// Event 1
$event = new Event();
$event
->setOrganize($organize)
->setName('event1')
->setEmail('event1@mail.dev')
->setAddress('event1 address')
->setPoint(new Point(55.9931214, 82.9763641))
->setAppointment(false)
->setZip('11111')
->setSite('http://event1.com')
->setPhonenumber('11111')
->setOutdoor('indoor')
->setDescription('some')
->setOrigin(date_create()->setTime(12, 30))
->setPrice(12.3)
->addCategory($arts)
->addCategory($animals);
$this->addAges($event, [ 0, 1, 2, 4, 5, 6 ]);
$manager->persist($event);
// Event 2
$event = new Event();
$event
->setOrganize($organize)
->setName('event2')
->setEmail('event2@mail.dev')
->setAddress('event2 address')
->setPoint(new Point(55.968597, 82.970374))
->setAppointment(false)
->setZip('22222')
->setSite('http://event2.com')
->setPhonenumber('22222')
->setOutdoor('indoor')
->setDescription('some')
->setOrigin(date_create()->setTime(14, 30))
->addCategory($animals);
$this->addAges($event, [ 4, 5, 6 ]);
$manager->persist($event);
// Event 3
$event = new Event();
$event
->setOrganize($organize)
->setName('event3')
->setEmail('event3@mail.dev')
->setAddress('event3 address')
->setPoint(new Point(55.994599, 82.674763))
->setAppointment(false)
->setZip('33333')
->setSite('http://event3.com')
->setPhonenumber('33333')
->setOutdoor('indoor')
->setDescription('some')
->setOrigin(date_create()->setTime(18, 30))
->addCategory($arts);
$this->addAges($event, range(0, 21));
$manager->persist($event);
// Event 4
$event = new Event();
$event
->setOrganize($organize)
->setName('event4')
->setEmail('event4@mail.dev')
->setAddress('event4 address')
->setPoint(new Point(56.222035, 83.831074))
->setAppointment(false)
->setZip('44444')
->setSite('http://event4.com')
->setPhonenumber('44444')
->setOutdoor('indoor')
->setDescription('some')
->setOrigin(date_create()->setTime(15, 30))
->addCategory($dance);
$this->addAges($event, [ 4, 5, 6, 7, 8, 9, 10 ]);
$manager->persist($event);
// Event 5
$event = new Event();
$event
->setOrganize($organize)
->setName('event5')
->setEmail('event5@mail.dev')
->setAddress('event5 address')
->setPoint(new Point(56.800935, 84.781391))
->setAppointment(false)
->setZip('55555')
->setSite('http://event5.com')
->setPhonenumber('55555')
->setOutdoor('indoor')
->setDescription('some')
->setOrigin(date_create()->setTime(15, 30))
->addCategory($animals)
->addCategory($dance);
$this->addAges($event, [ 4, 5, 6, 7, 8, 9, 10 ]);
$manager->persist($event);
$manager->flush();
}
/**
* @param Event $event A Event entity instance.
* @param array $ages Array of required ages.
*
* @return void
*/
private function addAges(Event $event, array $ages)
{
foreach ($ages as $age) {
$event->addAge(new Age($age));
}
}
/**
* Get the order of this fixture
*
* @return integer
*/
public function getOrder()
{
return 1;
}
}
| true |
7082cd1b8ffff722afe78e4b96f6cecb032e0840 | PHP | aizuyan/PHP-Migration | /src/Changes/v5dot4/IncompHashAlgo.php | UTF-8 | 1,446 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
namespace PhpMigration\Changes\v5dot4;
use PhpMigration\Changes\AbstractChange;
use PhpMigration\SymbolTable;
use PhpParser\Node\Expr;
use PhpParser\Node\Scalar;
class IncompHashAlgo extends AbstractChange
{
protected static $version = '5.4.0';
protected $funcTable = [
'hash',
'hash_file',
'hash_hmac',
'hash_hmac_file',
'hash_init',
];
public function __construct()
{
$this->funcTable = new SymbolTable($this->funcTable, SymbolTable::IC);
}
public function leaveNode($node)
{
/*
* {Description}
* The Salsa10 and Salsa20 hash algorithms have been removed.
*
* {Reference}
* http://php.net/manual/en/migration54.incompatible.php
*/
if ($node instanceof Expr\FuncCall && $this->funcTable->has($node->name)) {
$affected = true;
$certain = false;
if (!isset($node->args[0])) {
return;
}
$param = $node->args[0]->value;
if ($param instanceof Scalar\String_) {
$certain = $affected = (strcasecmp($param->value, 'salsa10') === 0 ||
strcasecmp($param->value, 'salsa20') === 0);
}
if ($affected) {
$this->addSpot('WARNING', $certain, 'Salsa10 and Salsa20 hash algorithms have been removed');
}
}
}
}
| true |
32456f08621f3c17dd44283dfb250d5718610fbf | PHP | suzondas/quiz-app-vendor | /cmed-admin/vendor/myclabs/deep-copy/src/DeepCopy/deep_copy.php | UTF-8 | 268 | 3.015625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | <?php
namespace DeepCopy;
/**
* Deep copies the given value.
*
* @param mixed $value
* @param bool $useCloneMethod
*
* @return mixed
*/
function deep_copy( $value, $useCloneMethod = FALSE )
{
return ( new DeepCopy( $useCloneMethod ) )->copy( $value );
}
| true |
4c2fb9c27f925af4f317618383accd69b2336e42 | PHP | Thibok/tc-blog | /lib/Components/StringField.php | UTF-8 | 2,363 | 3.203125 | 3 | [] | no_license | <?php
/*
* This file is part of the Tc-blog project.
*
* (c) Thibault Cavailles <tcblog@tc-dev.ovh>
*
* First blog in PHP
*/
namespace Components;
class StringField extends Field
{
/**
*
* @var int
* @access private
*/
private $maxLength;
/**
*
* @var string
* @access private
*/
private $placeHolder;
/**
*
* @var string
* @access private
*/
private $type;
/**
* {@inheritDoc}
* @return string
*/
public function buildField()
{
$label = '<label class="control-label text-white" for="'
.$this->name.'">'.$this->label.'</label>';
$field = '<input type="'.$this->type.'" class="form-control" id="'
.$this->name.'" name="'.$this->name.'"';
if (!empty($this->value)) {
$field .= ' value="'.htmlspecialchars($this->value).'"';
}
if (!empty($this->maxLength)) {
$field .= ' maxlength="'.$this->maxLength.'"';
}
if (!empty($this->placeHolder)) {
$field .= ' placeholder="'.$this->placeHolder.'"';
}
if (!empty($this->required) && $this->required === true) {
$field .= ' required';
}
$field .= ' />';
if (!empty($this->errorMessage)) {
$field = '<div class="alert alert-danger">'.$this->errorMessage.$field.'</div>';
}
$field = '<div class="'.$this->class.'">'.$label.$field.'</div>';
return $field;
}
/**
* @access public
* @return int
*/
public function getMaxLength()
{
return $this->maxLength;
}
/**
* @access public
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* @access public
* @return string
*/
public function getPlaceHolder()
{
return $this->placeHolder;
}
/**
* @access public
* @param string $type
* @return void
*/
public function setType($type)
{
if (is_string($type)) {
$this->type = $type;
}
}
/**
* @access public
* @param string $placeHolder
* @return void
*/
public function setPlaceHolder($placeHolder)
{
if (is_string($placeHolder)) {
$this->placeHolder = $placeHolder;
}
}
/**
* @access public
* @param int $maxLength
* @return void
* @throws RuntimeException If maxLength < 1
*/
public function setMaxLength($maxLength)
{
$maxLength = (int) $maxLength;
if ($maxLength > 0) {
$this->maxLength = $maxLength;
} else {
throw new \RuntimeException('La longueur maximale doit être supérieur à 0 !');
}
}
} | true |
a022adcb05cb20591c3c5c2bdd2bcf7035811bba | PHP | Fizax/project-fifa-php | /admin.php | UTF-8 | 1,288 | 2.859375 | 3 | [] | no_license | <?php
require 'config.php';
$sql = "SELECT * FROM teams"; //string even opslaan die we later gaan gebruiken
$query = $db->query($sql); //qurey verzoek data base sla ik op in variablke
$teams = $query->fetchAll(PDO::FETCH_ASSOC); //multie demensionale array //alle colomen wil ik fetchen -> binnen halen
session_start();
if($_SESSION['sid']==session_id())
{
echo "Je bent admin";
echo '<ul>';
foreach ($teams as $team){
$name = htmlentities($team['name']);
$coach= htmlentities($team ['maker']);
echo "<li><a href='delete_controler.php?id={$team['id']}'>$name, $coach</a></li>";
}
echo '</ul>';
echo "<a href='logout.php'>Logout</a>";
}
else {
header("location:index.php");
}
?>
<div class="index">
<div class="description">
<form action="competitieController.php" method="post">
<input type="hidden" name="type" value="team">
<div class="button">
<input type="submit" value="schema">
</div>
</form>
<div>
<a href="team.php">maak een team</a>
</div>
<div>
<a href="players.php">speler aan team toevoegen</a>
</div>
</div>
| true |
2e79c40fce0856c935fc1fa413b3bd2954a0b0f8 | PHP | VrushaliBhosale/registration | /UserRegistration/update_user.php | UTF-8 | 1,384 | 3 | 3 | [] | no_license | <?php
require_once "vendor/autoload.php";
use UserRegistration\Activity\User;
$obj=new User();
$row=$obj->getRecord($_GET['u_id']);
echo $id;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Edit User</h1>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
Name: <input name="name" type="text" required value="<?php echo $row["fname"]?>"><br><br>
Email: <input name="email" type="email" required value="<?php echo $row["email"]?>"><br><br>
Role: <input name="role" type="text" required value="<?php echo $row["roles"]?>"><br><br>
<input type="submit" name="update" value="Update">
<!-- <?php echo '<a href="update_user.php?u_id='. $_GET["u_id"]. '"><input type="submit" name="delete" value="Delete"></a>'?> -->
<input type="submit" name="delete" value="Delete">
</form><br>
<a href="admin.php">Home</a>
</body>
</html>
<?php
if($_POST['update'])
{
if($obj->updateUser($_POST['name'],$_POST['role'],$_POST['email']))
{
echo "Record Updated Successfully";
}
}
if($_POST['delete'] == 'Delete')
{
if($obj->deleteUser($_POST['email']))
{
echo "Record deleted successfully";
}
}
?> | true |
dbf38ff346ee8915ee465ba485c3a16996085850 | PHP | fidus/api | /Fidus/Api/RechargeCredit.php | UTF-8 | 882 | 3.03125 | 3 | [] | no_license | <?php
namespace Fidus\Api;
class RechargeCredit implements IRequest {
const TYPE = 'recharge-credit';
/**
* @var
*/
private $customerId;
/**
* @var
*/
private $rechargeCredit;
/**
* @var \DateTime
*/
private $date;
/**
* @param $customerId
* @param $rechargeCredit
* @param \DateTime $date
*/
public function __construct($customerId, $rechargeCredit, \DateTime $date = NULL)
{
$this->customerId = $customerId;
$this->rechargeCredit = $rechargeCredit;
$this->date = $date ? $date : new \DateTime();
}
/**
* @return array
*/
public function getData()
{
$data = array();
$data['customerId'] = $this->customerId;
$data['rechargeCredit'] = $this->rechargeCredit;
$data['date'] = $this->date->format('Y-m-d H:i:s');
return $data;
}
/**
* @return string
*/
public function getType()
{
return self::TYPE;
}
}
| true |
ca0c50f971237acdb610811ca4d540c6fb075003 | PHP | SagarNaliyapara/order-product-test-demo | /tests/Feature/ProductsApiTest.php | UTF-8 | 2,257 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace Tests\Feature;
use App\Product;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class ProductsApiTest extends TestCase
{
use RefreshDatabase;
public function testProductList()
{
// create products with quantity greater than 1
factory(Product::class, 7)->create([
'quantity' => rand(2, 8),
]);
// create products with quantity 0 or 1
factory(Product::class, 4)->create([
'quantity' => rand(0, 1),
]);
// should only return products with quantity > 1
$this->getJson(route('products.index'))
->assertStatus(200)
->assertJsonCount(7, 'data');
}
public function testProductDetail()
{
$product = factory(Product::class)->create([
'name' => 'test name',
'quantity' => 11,
'dimensions' => [
'weight' => 11.0,
'length' => 10.0,
'width' => 10.2,
],
]);
$this->getJson(route('products.show', $product->id))
->assertJson([
'data' => [
'id' => $product->id,
'name' => 'test name',
'quantity' => 11,
'dimensions' => [
'weight' => 11.0,
'length' => 10.0,
'width' => 10.2,
],
]
]);
}
public function testProductUpdate()
{
$product = factory(Product::class)->create([
'quantity' => 0,
]);
$this->putJson(route('products.update', $product->id))
->assertJsonValidationErrors(['quantity']);
$this->putJson(route('products.update', $product->id), [
'quantity' => 9
])
->assertStatus(200)
->assertJson([
'data' => [
'id' => $product->id,
'quantity' => 9,
],
]);
// check in database, quantity should be updated to 9
$this->assertDatabaseHas('products', [
'id' => $product->id,
'quantity' => 9,
]);
}
}
| true |
5bcc5148fa1ef2ef53a0055cb5fdaa58b6ca7dca | PHP | sharpless/ridcully | /src/CObject/CObject.php | UTF-8 | 1,867 | 2.96875 | 3 | [] | no_license | <?php
/**
* Base class for enabling access to Ridcully through $this
*
* @package RidcullyCore
* @author Fredrik Larsson <fredrik@sharpless.se>
*
*/
class CObject {
public $config;
public $data;
public $request;
public $database;
public $views;
public $session;
protected function __construct($r=null) {
if (!$r) {
$r = CRidcully::Instance();
}
$this->r = &$r;
$this->config = &$r->config;
$this->data = &$r->data;
$this->request = &$r->request;
$this->database = &$r->database;
$this->views = &$r->views;
$this->session = &$r->session;
$this->user = &$r->user;
}
/**
* A wrapper for CRidcully::RedirectTo
*/
protected function RedirectTo($urlOrController=null, $method=null) {
$this->r->RedirectTo($urlOrController=null, $method=null);
}
/**
* A wrapper for CRidcully::RedirectToController
*
* @param string method name the method, default is index method.
*/
protected function RedirectToController($method=null) {
$this->r->RedirectToController($method);
}
/**
* A wrapper for CRidcully::RedirectToControllerMethod
*
* @param string controller name the controller or null for current controller.
* @param string method name the method, default is current method.
*/
protected function RedirectToControllerMethod($controller=null, $method=null) {
$this->r->RedirectToControllerMethod($controller, $method);
}
/**
* A wrapper for CRidcully::AddMessage
*
* @param $type string the type of message, for example: notice, info, success, warning, error.
* @param $message string the message.
* @param $alternative string the message if the $type is set to false, defaults to null.
*/
protected function AddMessage($type, $message, $alternative=null) {
$this->r->AddMessage($type, $message, $alternative=null);
}
}
?>
| true |
653453defb5021ef8954899cd698a204aedd7dc7 | PHP | T3hArco/skeyler-site | /index.php | UTF-8 | 1,428 | 2.71875 | 3 | [] | no_license | <?php
require '_.php';
$page = new Page();
$page->header('test');
function parseForums()
{
$out = "";
$resp = curlGet("showboards");
$boardArray = json_decode($resp, true);
for ($i = 0; $i < count($boardArray); $i++) {
for ($j = 0; $j < count($boardArray[$i]) / 2; $j++) {
if ($j == 0) {
$out .= "<a href='?act=viewforum&id=" . $boardArray[$i][$j] . "'>";
} else if ($j == count($boardArray[$i]) / 2) {
$out .= $boardArray[$i][$j] . " ";
} else {
$out .= $boardArray[$i][$j] . "</a>";
}
}
$out .= "<br />";
}
return $out;
}
function parsePosts($id)
{
$out = "";
$resp = curlGet("showposts&id=" . $id);
$postArray = json_decode($resp, true);
for ($i = 0; $i < count($postArray); $i++) {
for ($j = 0; $j < count($postArray[$i]) / 2; $j++) {
if ($j == 0) {
$out .= "<a href='?act=viewpost&id=" . $postArray[$i][$j] . "'>";
} else if ($j == count($postArray[$i]) / 2) {
$out .= $postArray[$i][$j] . " ";
} else {
$out .= $postArray[$i][$j] . "</a>";
}
}
}
return $out;
}
if (!isset($_GET['act'])) $_GET['act'] = "";
switch ($_GET['act']) {
case 'viewforum':
if (!isset($_GET['id'])) header("Location: index.php");
$id = mysql_real_escape_string($_GET['id']);
echo parsePosts($id);
break;
case 'home':
default:
echo parseForums();
break;
}
?> | true |
c787dd0f6252bc2b96150ef38f8dbfefb98beb6d | PHP | joaovmorais00/TP---CLP | /tp_CLP_PHP/Produto.php | UTF-8 | 611 | 3.25 | 3 | [] | no_license | <?php
class Produto{
private $nome;
private $codigo;
private $valor;
public function __construct($nome, $codigo, $valor){
$this->nome = $nome;
$this->codigo = $codigo;
$this->valor = $valor;
}
public function get_nome(){
return $this->nome;
}
public function get_codigo(){
return $this->codigo;
}
public function get_valor(){
return $this->valor;
}
public function set_nome($nome){
$this->nome = $nome;
}
public function set_codigo($codigo){
$this->codigo = $codigo ;
}
public function set_valor($valor){
$this->valor = $valor;
}
}
?> | true |
22c0b4c40909296cbf48ffe0b567f2ee2a33b129 | PHP | tflori/dependency-injector | /tests/Examples/AdvancedSingleton.php | UTF-8 | 525 | 2.90625 | 3 | [] | no_license | <?php
namespace DependencyInjector\Test\Examples;
class AdvancedSingleton
{
/** @var AdvancedSingleton[] */
protected static $instances = [];
public $name;
private function __construct(string $name)
{
$this->name = $name;
}
private function __clone()
{
}
public static function getInstance(string $name)
{
if (!isset(self::$instances[$name])) {
self::$instances[$name] = new self($name);
}
return self::$instances[$name];
}
}
| true |
e926568bdd7224325a8dc426faee884b4472e879 | PHP | ip2location/ip2proxy-php | /examples/example.php | UTF-8 | 758 | 2.609375 | 3 | [
"MIT",
"LicenseRef-scancode-other-permissive"
] | permissive | <?php
error_reporting(\E_ALL);
ini_set('display_errors', 1);
require 'vendor/autoload.php';
// Lookup by local BIN database
$db = new \IP2Proxy\Database('./data/PX11.SAMPLE.BIN', \IP2PROXY\Database::FILE_IO);
echo 'Module Version: ' . $db->getModuleVersion() . \PHP_EOL . \PHP_EOL;
echo 'Package: PX' . $db->getPackageVersion() . \PHP_EOL;
echo 'Database Date: ' . $db->getDatabaseVersion() . \PHP_EOL;
echo '$records = $db->lookup(\'1.0.0.8\', \IP2PROXY\Database::ALL);' . \PHP_EOL;
$records = $db->lookup('1.0.0.8', \IP2PROXY\Database::ALL);
print_r($records);
echo \PHP_EOL . \PHP_EOL;
echo 'Web Service' . \PHP_EOL;
// Lookup by Web API
$ws = new \IP2Proxy\WebService('demo', 'PX11', false);
$results = $ws->lookup('1.0.0.8');
print_r($results);
| true |
4a0585d53e424d138431d9ec8076946aff03659b | PHP | moelj/sqli-eztoolbox | /Entity/Doctrine/Parameter.php | UTF-8 | 2,648 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace SQLI\EzToolboxBundle\Entity\Doctrine;
use Doctrine\ORM\Mapping as ORM;
use SQLI\EzToolboxBundle\Annotations\Annotation as SQLIAdmin;
use stdClass;
/**
* @ORM\Table(name="eboutique_parameter")
* @ORM\Entity(repositoryClass="SQLI\EzToolboxBundle\Repository\Doctrine\ParameterRepository")
* @SQLIAdmin\Entity(update=true,create=true,delete=true,description="Paramètrage",tabname="Param")
*/
class Parameter
{
/**
* @var int
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
* @SQLIAdmin\EntityProperty(readonly=true)
*/
private $id;
/**
* @var string
* @ORM\Column(name="name", type="string", length=255)
* @SQLIAdmin\EntityProperty(description="Nom du paramètre")
*/
private $name;
/**
* @var string
* @ORM\Column(name="value", type="string", length=255)
* @SQLIAdmin\EntityProperty(
* choices={"Activé": "enabled", "Désactivé": "disabled"},
* description="Paramètre activé ou non ?")
*/
private $value;
/**
* @var stdClass
*
* @ORM\Column(name="params", type="object", nullable=true)
* @SQLIAdmin\EntityProperty(
* visible=true,
* description="Données complémentaires sérialisées.
* S'assurer de la validité avant sauvegarde avec https://fr.functions-online.com/unserialize.html")
*/
private $params;
/**
* @return int
*/
public function getId(): ?int
{
return $this->id;
}
/**
* @param int $id
* @return Parameter
*/
public function setId(int $id): Parameter
{
$this->id = $id;
return $this;
}
/**
* @return string
*/
public function getName(): ?string
{
return $this->name;
}
/**
* @param string $name
* @return Parameter
*/
public function setName(string $name): Parameter
{
$this->name = $name;
return $this;
}
/**
* @return string
*/
public function getValue(): ?string
{
return $this->value;
}
/**
* @param string $value
* @return Parameter
*/
public function setValue(string $value): Parameter
{
$this->value = $value;
return $this;
}
/**
* @return mixed
*/
public function getParams(): stdClass
{
return $this->params;
}
/**
* @param mixed $params
* @return Parameter
*/
public function setParams($params): Parameter
{
$this->params = $params;
return $this;
}
}
| true |
30e0d3e33bdd03949de4c256201d3641ac438a78 | PHP | vera-yxu/Website | /myfav.php | UTF-8 | 1,855 | 2.515625 | 3 | [] | no_license | <html>
<head>
<link rel="stylesheet" href="main_style.css" type="text/css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.del_btn').click(function(){
var homeid = $(this).attr('id');
//alert('You clicked on ' + homeid);
$.ajax({
url: 'myfav.php',
type: 'POST',
data: {
homeid: homeid
},
datatype: 'json',
success: function(result){
alert("Deleted home" + homeid);
}
});
});
});
</script>
</head>
<body>
<?php include("header.php"); ?>
<?php
include "db_connection.php";
$fname = $_SESSION['username'];
$conn = OpenCon();
$sql_name = "SELECT * FROM Users WHERE FirstName = '$fname'";
$result_name = mysqli_query($conn, $sql_name);
$rows_name = mysqli_fetch_array($result_name);
$userid = $rows_name['UserID'];
$sql = "SELECT * FROM Myfav WHERE UserID = '$userid'";
$likes = mysqli_query($conn, $sql);
?>
<div class="container">
<?php while ($rows = mysqli_fetch_array($likes)) {
echo "You liked home" ."". $rows['HomeID'] . " ". "."; ?>
<span><a style="text-decoration:none;" href="" class="del_btn" id="<?php echo $rows['HomeID']; ?>">delete</a></span><br>
<?} ?>
</div>
<?php
if (isset($_POST['homeid'])) {
$homeid = $_POST['homeid'];
$sql = "DELETE FROM Myfav WHERE UserID='$userid' AND HomeID='$homeid' ";
if ($conn->query($sql) === TRUE) {
header("location:myfav.php");
} else echo "Error: ". $sql . "<br>" . $conn->error;
}
CloseCon($conn);
?>
</body>
</html> | true |
11292224aad814a5db654620909449c8b9f87cd9 | PHP | anandsm08/phpmysqlworkshopiitb | /DAY1/Q1_evenodd.php | UTF-8 | 147 | 3.953125 | 4 | [] | no_license | //Even or Odd numbers
<?php
$input = readline('Enter a Number');
if ($input%2)
{
echo $input.('is odd');
}
else {
echo $input.('is even');
}
?>
| true |
569de74c7d761cc87b2dcd8a788804fb5a9d6be2 | PHP | Malek23923/fakoli | /cms/components/svg_charts/pages/test_morphing_histogram.inc | UTF-8 | 850 | 2.53125 | 3 | [] | no_license | <?php
Fakoli::using("svg_charts");
$chart = new Histogram("histogram", 600, 400, 50, 50, 400, 300, "standard");
$chart->setLabels(array("First", "Second", "Third", "Fourth"));
$chart->ticks = 5;
$chart->max = 100;
$chart->morphing = true;
$series = new HistogramSeries("block", "Series 1", array(10, 40, 20, 80));
$chart->addSeries($series);
$series2 = new HistogramSeries("block", "Series 2", array(30, 20, 40, 90));
$chart->addSeries($series2);
$series3 = new HistogramSeries("block", "Series 3", array(20, 50, 40, 30));
$chart->addSeries($series3);
$series4 = new HistogramSeries("block", "Series 4", array(90, 20, 10, 50));
$chart->addSeries($series4);
//$pie->setRadius(150);
//$pie->setCenter(180,180);
//$pie->setLabelSize(16);
//$pie->setStrokeWidth(2);
//$pie->showLegend(true, 350, 20);
$chart->draw();
?> | true |
57b9055cb20519d61a4c7ec0bfe8031d05f7c0ee | PHP | Calinou/godot-asset-library-laravel | /app/AssetPreview.php | UTF-8 | 2,548 | 2.921875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
declare(strict_types=1);
namespace App;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* An externally-hosted asset preview (can be an image or a video).
* It can optionally have a caption defined.
*
* @property int $preview_id The preview's unique ID.
* @property int $type_id The preview's type (see the `TYPE_*` constants).
* @property string $link The preview's full-size URL.
* @property ?string $thumbnail The preview's thumbnail URL.
* @property ?string $caption The preview's caption (displayed below the preview and used as `alt` text).
* @property int $asset_id The asset the preview belongs to.
*/
class AssetPreview extends Model
{
use HasFactory;
public const TYPE_IMAGE = 0;
public const TYPE_VIDEO = 1;
public const TYPE_MAX = 2;
/**
* Indicates if the model should be timestamped.
*
* @var bool
*/
public $timestamps = false;
/**
* The primary key associated with the table.
* This value has been changed from the default for compatibility with the
* existing asset library API.
*
* @var string
*/
protected $primaryKey = 'preview_id';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'type_id',
'link',
'thumbnail',
'caption',
'asset_id',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'preview_id',
'type_id',
'asset_id',
];
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = [
'type',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'type_id' => 'integer',
];
/**
* Return the given type's name.
*/
public static function getType(int $type): string
{
$typeNames = [
self::TYPE_IMAGE => 'image',
self::TYPE_VIDEO => 'video',
];
if (array_key_exists($type, $typeNames)) {
return $typeNames[$type];
} else {
throw new \Exception("Invalid asset preview type: $type");
}
}
/**
* Non-static variant of `getType` (used in serialization).
*/
public function getTypeAttribute(): string
{
return self::getType($this->type_id);
}
}
| true |
fdaca23b7585db2d5b411d9b293ad40f8d96da55 | PHP | SviatoslavSheludchenko/bintime | /models/User.php | UTF-8 | 3,044 | 2.71875 | 3 | [] | permissive | <?php
namespace app\models;
use DateTime;
use Yii;
use yii\db\ActiveRecord;
/**
* @property int $id
* @property string $login
* @property string $password
* @property string $first_name
* @property string $last_name
* @property int $gender
* @property string $date
* @property string $email
*/
class User extends ActiveRecord {
const GENDER_FEMALE = 'female';
const GENDER_MALE = 'male';
const GENDER_UNKNOWN = 'unknown';
public static function tableName()
{
return 'user';
}
public function rules()
{
return [
[['login', 'password', 'first_name', 'last_name', 'gender', 'email'], 'required'],
[['login'], 'string', 'min' => 4, 'max' => 20],
[['password'], 'string', 'min' => 6, 'max' => 20],
[['first_name', 'last_name', 'email'], 'string', 'max' => 30],
[['gender'], 'string', 'max' => 15],
[['date'], 'safe'],
[['login', 'password'], 'string', 'max' => 20],
[['login'], 'unique'],
[['email'], 'unique'],
];
}
public function attributeLabels()
{
return [
'id' => 'ID',
'login' => 'Login',
'password' => 'Password',
'first_name' => 'First Name',
'last_name' => 'Last Name',
'gender' => 'Gender',
'date' => 'Date',
'email' => 'Email',
];
}
public function beforeSave($insert)
{
parent::beforeSave($insert);
if ($this->isNewRecord) {
$this->date = Yii::$app->formatter->asDate(new DateTime(), 'yyyy-MM-dd HH:mm:ss');
$this->first_name = self::ucfirst($this->first_name, $e = 'utf-8');
$this->last_name = self::ucfirst($this->last_name, $e = 'utf-8');
}
return true;
}
public static function ucfirst($string, $e = 'utf-8')
{
if (function_exists('mb_strtoupper') && function_exists('mb_substr') && !empty($string)) {
$string = mb_strtolower($string, $e);
$upper = mb_strtoupper($string, $e);
preg_match('#(.)#us', $upper, $matches);
$string = $matches[1] . mb_substr($string, 1, mb_strlen($string, $e), $e);
} else {
$string = ucfirst($string);
}
return $string;
}
public static function listGenders()
{
return [
self::GENDER_UNKNOWN => Yii::t('app', 'No Information'),
self::GENDER_FEMALE => Yii::t('app', 'Female'),
self::GENDER_MALE => Yii::t('app', 'Male'),
];
}
public function getUserAddresses()
{
return $this->hasMany(Address::className(), ['user_id' => 'id']);
}
public function beforeDelete()
{
$addresses = $this->userAddresses;
foreach ($addresses as $address) {
$address->delete();
}
// call the parent implementation so that this event is raise properly
return parent::beforeDelete();
}
}
| true |
71064344a029040603eea1476795efb8a567fc46 | PHP | edb-gjengen/inside | /includes/payex2/payex_pxpartner.php | UTF-8 | 2,629 | 2.65625 | 3 | [] | no_license | <?php
require_once('payex.php');
/**
* Class for using the PxPartner Payex webservice.
* Please report bugs to support.solutions@payex.no
*
* @author Jon Helge Stensrud, Keyteq AS
* @version 5.3
*
*/
class PayexPxPartner extends Payex
{
var $ivrCode;
var $transactionStatus;
var $transactionRef;
var $transactionNumber;
function PayexPxPartner($setup = false)
{
$this->__setup($setup);
$this->__createClient($this->__setup->getPxPartnerWSDL());
$this->ivrCode = '';
$this->transactionStatus = '';
$this->transactionRef = '';
$this->transactionNumber = '';
}
function ReserveIVRCode($identifierRef, $ivrPhoneNumber, $clientPhoneNumber)
{
$hash = $this->__generateHash($this->__accountNumber, $identifierRef, $ivrPhoneNumber, $clientPhoneNumber);
$params = array(
'accountNumber' => $this->__accountNumber,
'identifierRef' => $identifierRef,
'ivrPhoneNumber' => $ivrPhoneNumber,
'clientPhoneNumber' => $clientPhoneNumber,
'hash' => $hash
);
$return_data = $this->client->ReserveIVRCode($params);
return $this->__processResponse($return_data);
}
function IssueReservedIVRCode($identifierRef, $ivrPhoneNumber, $clientPhoneNumber, $ivrCode)
{
$hash = $this->__generateHash($this->__accountNumber, $identifierRef, $ivrPhoneNumber, $clientPhoneNumber, $ivrCode);
$params = array(
'accountNumber' => $this->__accountNumber,
'identifierRef' => $identifierRef,
'ivrPhoneNumber' => $ivrPhoneNumber,
'clientPhoneNumber' => $clientPhoneNumber,
'ivrCode' => $ivrCode,
'hash' => $hash
);
$return_data = $this->client->IssueReservedIVRCode($params);
return $this->__processResponse($return_data);
}
function IsValidIVRCode($ivrCode)
{
$hash = $this->__generateHash($this->__accountNumber, $ivrCode);
$params = array(
'accountNumber' => $this->__accountNumber,
'ivrCode' => $ivrCode,
'hash' => $hash
);
$return_data = $this->client->IsValidIVRCode($params);
return $this->__processResponse($return_data);
}
function getIvrCode()
{
return $this->ivrCode;
}
function setIvrCode($ivrCode)
{
$this->ivrCode = $ivrCode;
}
function getTransactionStatus()
{
return $this->transactionStatus;
}
function setTransactionStatus($transactionStatus)
{
$this->transactionStatus = $transactionStatus;
}
function getTransactionRef()
{
return $this->transactionRef;
}
function setTransactionRef($transactionRef)
{
$this->transactionRef = $transactionRef;
}
function getTransactionNumber()
{
return $this->transactionNumber;
}
function setTransactionNumber($transactionNumber)
{
$this->transactionNumber = $transactionNumber;
}
}
?> | true |
584b2159b21e47a07fdee774539c89ce263f38c2 | PHP | inetstudio/dummy_package | /src/Mail/NewDummyMail.php | UTF-8 | 1,465 | 2.671875 | 3 | [] | no_license | <?php
namespace InetStudio\Dummies\Mail;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use InetStudio\Dummies\Contracts\Mail\NewDummyMailContract;
use InetStudio\Dummies\Contracts\Models\DummyModelContract;
/**
* Class NewDummyMail.
*/
class NewDummyMail extends Mailable implements NewDummyMailContract
{
use SerializesModels;
protected $dummy;
/**
* NewDummyMail constructor.
*
* @param DummyModelContract $dummy
*/
public function __construct(DummyModelContract $dummy)
{
$this->dummy = $dummy;
}
/**
* Build the message.
*
* @return $this
*/
public function build(): self
{
$subject = config('app.name').' | '.((config('dummies.mails.subject')) ? config('dummies.mails.subject') : 'Новый dummy');
$headers = (config('dummies.mails.headers')) ? config('dummies.mails.headers') : [];
return $this->from(config('mail.from.address'), config('mail.from.name'))
->to(config('dummies.mails.to'), '')
->subject($subject)
->withSwiftMessage(function ($message) use ($headers) {
$messageHeaders = $message->getHeaders();
foreach ($headers as $header => $value) {
$messageHeaders->addTextHeader($header, $value);
}
})
->view('admin.module.dummies::mails.dummy', ['dummy' => $this->dummy]);
}
}
| true |
1d2f28895581b5801ab9ef6660ea73a573d64730 | PHP | zupaazhai/simpler | /app/Enum/MediaEnum.php | UTF-8 | 1,121 | 2.875 | 3 | [] | no_license | <?php
namespace App\Enum;
class MediaEnum
{
const DIR = 'dir';
const FILE = 'file';
const ROOT = 'root';
/**
* Allowed mimes
*
* @return array
*/
public static function allowedMimes()
{
return array(
'image/jpeg' => 'jpg',
'image/pjpeg' => 'jpeg',
'image/jpg' => 'jpg',
'image/png' => 'png',
'image/gif' => 'gif',
'image/svg+xml' => 'svg',
'video/mp4' => 'mp4',
'audio/mpeg' => 'mp3',
'application/zip' => 'zip',
'application/x-compressed' => 'zip',
'application/x-gzip' => 'zip'
);
}
/**
* Get allowed mimes
*
* @return array
*/
public static function getAllowedMimes()
{
$mimes = self::allowedMimes();
return array_keys($mimes);
}
/**
* Get allowed file extension
*
* @return array
*/
public static function getFileExtension()
{
$mimes = self::allowedMimes();
return array_unique(array_values($mimes));
}
} | true |
de8b1b4b019c1bf2e6a092a8c61fc0348b996596 | PHP | Shofiul-Alam/magento-app | /src/vendor/magento/framework/Setup/Declaration/Schema/Operations/CreateTable.php | UTF-8 | 5,285 | 2.59375 | 3 | [
"OSL-3.0",
"LicenseRef-scancode-unknown-license-reference",
"AFL-2.1",
"AFL-3.0",
"MIT"
] | permissive | <?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\Setup\Declaration\Schema\Operations;
use Magento\Framework\Setup\Declaration\Schema\Db\DbSchemaWriterInterface;
use Magento\Framework\Setup\Declaration\Schema\Db\DDLTriggerInterface;
use Magento\Framework\Setup\Declaration\Schema\Db\DefinitionAggregator;
use Magento\Framework\Setup\Declaration\Schema\Db\Statement;
use Magento\Framework\Setup\Declaration\Schema\Dto\Column;
use Magento\Framework\Setup\Declaration\Schema\Dto\Constraint;
use Magento\Framework\Setup\Declaration\Schema\Dto\ElementInterface;
use Magento\Framework\Setup\Declaration\Schema\Dto\Index;
use Magento\Framework\Setup\Declaration\Schema\Dto\Table;
use Magento\Framework\Setup\Declaration\Schema\ElementHistory;
use Magento\Framework\Setup\Declaration\Schema\ElementHistoryFactory;
use Magento\Framework\Setup\Declaration\Schema\OperationInterface;
/**
* Create table operation.
*/
class CreateTable implements OperationInterface
{
/**
* Operation name.
*/
const OPERATION_NAME = 'create_table';
/**
* @var DbSchemaWriterInterface
*/
private $dbSchemaWriter;
/**
* @var DefinitionAggregator
*/
private $definitionAggregator;
/**
* @var DDLTriggerInterface[]
*/
private $columnTriggers;
/**
* @var DDLTriggerInterface[]
*/
private $triggers;
/**
* @var ElementHistoryFactory
*/
private $elementHistoryFactory;
/**
* @param DbSchemaWriterInterface $dbSchemaWriter
* @param DefinitionAggregator $definitionAggregator
* @param ElementHistoryFactory $elementHistoryFactory
* @param array $columnTriggers
* @param array $triggers
*/
public function __construct(
DbSchemaWriterInterface $dbSchemaWriter,
DefinitionAggregator $definitionAggregator,
ElementHistoryFactory $elementHistoryFactory,
array $columnTriggers = [],
array $triggers = []
) {
$this->dbSchemaWriter = $dbSchemaWriter;
$this->definitionAggregator = $definitionAggregator;
$this->columnTriggers = $columnTriggers;
$this->triggers = $triggers;
$this->elementHistoryFactory = $elementHistoryFactory;
}
/**
* {@inheritdoc}
*/
public function getOperationName()
{
return self::OPERATION_NAME;
}
/**
* {@inheritdoc}
*/
public function isOperationDestructive()
{
return false;
}
/**
* Setup callbacks for newely created columns
*
* @param array $columns
* @param Statement $createTableStatement
* @return void
*/
private function setupColumnTriggers(array $columns, Statement $createTableStatement)
{
foreach ($columns as $column) {
foreach ($this->columnTriggers as $trigger) {
if ($trigger->isApplicable((string) $column->getOnCreate())) {
$elementHistory = $this->elementHistoryFactory->create([
'new' => $column,
'old' => $column
]);
$createTableStatement->addTrigger(
$trigger->getCallback($elementHistory)
);
}
}
}
}
/**
* Setup triggers for entire table
*
* @param Table $table
* @param Statement $createTableStatement
* @return void
*/
private function setupTableTriggers(Table $table, Statement $createTableStatement)
{
foreach ($this->triggers as $trigger) {
if ($trigger->isApplicable((string) $table->getOnCreate())) {
$elementHistory = $this->elementHistoryFactory->create([
'new' => $table,
'old' => $table
]);
$createTableStatement->addTrigger(
$trigger->getCallback($elementHistory)
);
}
}
}
/**
* {@inheritdoc}
*/
public function doOperation(ElementHistory $elementHistory)
{
/** @var Table $table */
$table = $elementHistory->getNew();
$definition = [];
$data = [
Column::TYPE => $table->getColumns(),
Constraint::TYPE => $table->getConstraints(),
Index::TYPE => $table->getIndexes()
];
foreach ($data as $type => $elements) {
/**
* @var ElementInterface $element
*/
foreach ($elements as $element) {
//Make definition as flat list.
$definition[$type . $element->getName()] = $this->definitionAggregator->toDefinition($element);
}
}
$createTableStatement = $this->dbSchemaWriter
->createTable(
$table->getName(),
$elementHistory->getNew()->getResource(),
$definition,
$table->getDiffSensitiveParams()
);
$this->setupTableTriggers($table, $createTableStatement);
$this->setupColumnTriggers($table->getColumns(), $createTableStatement);
return [$createTableStatement];
}
}
| true |
4fe68feaddaed19e6d3c0a4b2120b54b50b43124 | PHP | Enas1998/Web_Page_Robot_Arm_control | /update.php | UTF-8 | 920 | 2.59375 | 3 | [] | no_license | <?php
ini_set ('display_errors', 1);
error_reporting (E_ALL & ~E_NOTICE);
$dbc=mysqli_connect('localhost', 'root', '');
@mysqli_select_db($dbc, 'new_data');
$query = "SELECT * FROM handles_values ORDER BY ID DESC LIMIT 1;";
$result = mysqli_query($dbc, $query);
echo "<br>";
echo "<table border='1'>";
while($row = mysqli_fetch_row($result)) {
echo "<tr><td>ID</td><td>v1</td><td>v2</td><td>v3</td><td>v4</td><td>v5</td><td>v6</td></tr>
<tr><td> $row[0]</td><td>$row[1]</td><td>$row[2]</td><td>$row[3]</td><td>$row[4]</td><td>$row[5]</td><td>$row[6]</td></tr>";
}
echo "</table>";
echo "<br>";
$query = "SELECT * FROM on_values ORDER BY ID DESC LIMIT 1;";
$result = mysqli_query($dbc, $query);
echo "<br>";
echo "<table border='1'>";
while($row = mysqli_fetch_row($result)) {
echo "<tr><td>ID</td><td>handle on</td></tr>
<tr><td>$row[0]</td><td>$row[1]</td></tr>";
}
echo "</table>";
?> | true |
0e17ede181e0e08bc806bf0546da35198af9867f | PHP | sundaravadivel1980/fleetsu-service | /src/DBO/ServiceDBO.php | UTF-8 | 537 | 2.671875 | 3 | [] | no_license | <?php
namespace src\DBO {
use \PDO, \PDOException, src\Logger\Logger, src\endpoints;
class ServiceDBO {
const QUERY_LOADALL_DEVICELIST = 'SELECT device_id, device_label, device_reported_datetime, device_status FROM devices';
private $_dbh;
public function __construct($dbh) {
$this->_dbh = $dbh;
}
public function getDeviceList(){
$stm = $this->_dbh->prepare(self::QUERY_LOADALL_DEVICELIST);
$stm->execute();
Logger::log("Query Executed","DEBUG");
return $stm->fetchAll(PDO::FETCH_CLASS);
}
}
} | true |
08d3ff550a57a2fd2b989e741baf42034678be95 | PHP | gizmore/gdo6 | /GDO/Javascript/Method/DetectNode.php | UTF-8 | 2,865 | 2.6875 | 3 | [
"MIT"
] | permissive | <?php
namespace GDO\Javascript\Method;
use GDO\Core\GDT_Response;
use GDO\Core\Website;
use GDO\Core\MethodAdmin;
use GDO\Util\Process;
use GDO\Javascript\Module_Javascript;
use GDO\Form\GDT_Form;
use GDO\Form\MethodForm;
use GDO\Form\GDT_Submit;
/**
* Auto-detect nodejs_path, uglifyjs_path and ng_annotate_path.
*
* To install:
*
* $ aptitude install nodejs
*
* $ npm -g install ng-annotate-patched
* $ npm -g install uglify-js
*
* @author gizmore
*/
final class DetectNode extends MethodForm
{
use MethodAdmin;
public function getPermission() { return 'staff'; }
public function showInSitemap() { return false; }
public function getTitleLangKey() { return 'cfg_link_node_detect'; }
public function createForm(GDT_Form $form)
{
$form->info(t('info_detect_node_js'));
$form->actions()->addField(GDT_Submit::make());
}
public function formValidated(GDT_Form $form)
{
$response = $this->detectNodeJS();
$response->addField($this->detectAnnotate());
$response->addField($this->detectUglify());
$url = href('Admin', 'Configure', '&module=Javascript');
return $response->addField(Website::redirect($url, 12));
}
/**
* Detect node/nodejs binary and save to config.
* @return GDT_Response
*/
public function detectNodeJS()
{
$path = null;
if ($path === null)
{
$path = Process::commandPath("nodejs");
}
if ($path === null)
{
$path = Process::commandPath("node");
}
if ($path === null)
{
return $this->error('err_nodejs_not_found');
}
Module_Javascript::instance()->saveConfigVar('nodejs_path', $path);
return $this->message('msg_nodejs_detected', [htmlspecialchars($path)]);
}
/**
* Detect node/nodejs binary and save to config.
* @return GDT_Response
*/
public function detectAnnotate()
{
$path = null;
if ($path === null)
{
$path = Process::commandPath("ng-annotate-patched", '.cmd');
}
if ($path === null)
{
$path = Process::commandPath("ng-annotate", '.cmd');
}
if ($path === null)
{
return $this->error('err_annotate_not_found');
}
Module_Javascript::instance()->saveConfigVar('ng_annotate_path', $path);
return $this->message('msg_annotate_detected', [htmlspecialchars($path)]);
}
/**
* Detect node/nodejs binary and save to config.
* @return GDT_Response
*/
public function detectUglify()
{
$path = null;
if ($path === null)
{
$path = Process::commandPath("uglify-js", '.cmd');
}
if ($path === null)
{
$path = Process::commandPath("uglifyjs", '.cmd');
}
if ($path === null)
{
$path = Process::commandPath("uglify", '.cmd');
}
if ($path === null)
{
return $this->error('err_uglify_not_found');
}
Module_Javascript::instance()->saveConfigVar('uglifyjs_path', $path);
return $this->message('msg_uglify_detected', [htmlspecialchars($path)]);
}
}
| true |
f6d6d93b53c7e000ad5b56c61a1c90325397806a | PHP | felipe-gerula/Ejercicios-Laboratorio-IV | /tp N°5/Models/BattleShip.php | UTF-8 | 452 | 3.15625 | 3 | [] | no_license | <?php
namespace Models;
use Models\Ship as Ship;
class BattleShip extends Ship{
//Attributes
private $armament;
//Constructors
function __construct(){
}
//Get
public function getArmament(){
return $this->armament;
}
//SET
public function setArmament($armament){
$this->armament = $armament;
}
}
?> | true |
1a652fdf761918676bf42d845bb0c3927aa78c06 | PHP | BryanLizana/project_one_senati-school_stark | /views/root/del-user.php | UTF-8 | 736 | 2.53125 | 3 | [] | no_license | <?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ( is_numeric($_POST['id_user']) && $_POST['id_user'] !== '0') {
$user = new Users();
$user->id_user = $_POST['id_user'];
$user->delete_user();
header('location:/root/detail/');//redireccionar a la lista de usuarios una vez eliminado el que se ha solicitado
}
}
?>
<div class="main">
<h2>Desea eliminar al usuario de ID: <?php echo $_GET['id'] ?> ?</h2>
<form action="" method="POST">
<a href="<?php echo '/root/detail/' ?>"> <button type="button">Cancelar</button> </a>
<input type="hidden" name="id_user" value="<?php echo $_GET['id'] ?>">
<input type="submit" name="" value="Eliminar">
</form>
</div> | true |
3fdac3ad31c6cda27a8f7e02b6d35b3f3084393a | PHP | SEOService2020/phpmorphy | /src/phpMorphy/Dict/Source/Mrd.php | UTF-8 | 2,303 | 2.515625 | 3 | [
"LGPL-2.1-only"
] | permissive | <?php
/*
* This file is part of phpMorphy project
*
* Copyright (c) 2007-2012 Kamaev Vladimir <heromantor@users.sourceforge.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
class phpMorphy_Dict_Source_Mrd implements phpMorphy_Dict_Source_SourceInterface {
protected
$manager;
function __construct($mwzFilePath) {
$this->manager = $this->createMrdManager($mwzFilePath);
}
protected function createMrdManager($mwzPath) {
$manager = new phpMorphy_Aot_MrdManager();
$manager->open($mwzPath);
return $manager;
}
function getName() {
return 'mrd';
}
// phpMorphy_Dict_Source_SourceInterface
function getLanguage() {
$lang = strtolower($this->manager->getLanguage());
switch($lang) {
case 'russian':
return 'ru_RU';
case 'english':
return 'en_EN';
case 'german':
return 'de_DE';
default:
return $this->manager->getLanguage();
}
}
function getDescription() {
return 'Dialing dictionary file for ' . $this->manager->getLanguage() . ' language';
}
function getAncodes() {
return $this->manager->getGramInfo();
}
function getFlexias() {
return $this->manager->getMrd()->flexias_section;
}
function getPrefixes() {
return $this->manager->getMrd()->prefixes_section;
}
function getAccents() {
return $this->manager->getMrd()->accents_section;
}
function getLemmas() {
return $this->manager->getMrd()->lemmas_section;
}
} | true |
0e4867e2f59162156c2577bb1af4ba66543ce0ee | PHP | Lalama1982/PHPStuff | /PHP_Practise/displayValuesSent.php | UTF-8 | 544 | 2.8125 | 3 | [] | no_license | <?php
// Retrieve data from POST String
$name = $_GET['name'];
$email = $_GET['email'];
$gender = $_GET['gender'];
$course = $_GET['course'];
$class = $_GET['class'];
$subject = $_GET['subject'];
$display_string = "<p>Your name is $name</p>";
$display_string .= "<p> your email address is $email</p>";
$display_string .= "<p>Your class time at $course</p>";
$display_string .= "<p>your class info $class </p>";
$display_string .= "<p>your gender is $gender</p>";
$display_string .= "<p>your gender is $subject</p>";
echo $display_string;
?>
| true |
07aef2a6d95137df77967e232b807978c26ec056 | PHP | queicherius/stockphoto-crawler | /application/Console/Progressbar.php | UTF-8 | 1,329 | 3.390625 | 3 | [
"MIT"
] | permissive | <?php namespace Console;
class Progressbar
{
private $color = '32';
private $blocks = 20;
private $current_element = 0;
private $max_elements;
public function __construct($max_elements)
{
$this->max_elements = $max_elements;
$this->setProgress(0);
}
public function increase($amount = 1)
{
$this->current_element += $amount;
$percent = ($this->current_element / $this->max_elements) * 100;
$this->setProgress($percent);
}
private function setProgress($percent)
{
$blocks = $this->calculateBlocks($percent);
$string = $this->renderBar($blocks) . $this->renderText($percent);
$end_of_line = ($percent === 100) ? "\n" : "\r";
Console::info($string, $end_of_line);
}
private function calculateBlocks($percent)
{
return floor($percent * ($this->blocks / 100));
}
private function renderText($percent)
{
return ' ' . floor($percent) . '% (' . $this->current_element . '/' . $this->max_elements . ')';
}
private function renderBar($blocks)
{
$done = Console::colorString($this->color, str_repeat('#', $blocks));
$not_done = str_repeat(' ', $this->blocks - $blocks);
return 'Progress: [' . $done . $not_done . ']';
}
} | true |
a2ad567d64d454f4f7bb96cff198e8e3511e11a7 | PHP | ogorzalka/Commentatic | /pi.commentatic.php | UTF-8 | 13,009 | 2.640625 | 3 | [] | no_license | <?php
class Plugin_commentatic extends Plugin {
public $meta = array(
'name' => 'Commentatic',
'version' => '1.0',
'author' => 'Olivier Gorzalka', // form part inspired by Eric Barnes (https://github.com/ericbarnes/Statamic-email-form)
'author_url' => 'http://clearideaz.com'
);
public $total_items = false; // total comments
public $total_pages = false; // total pages of comments
public $user_datas = false; // data of logged user
protected $comment_folder = ''; // comment path from _content
protected $raw_comment_folder = ''; // raw comment path including base path
protected $comment_file = ''; // path relative to the comment file
protected $form_datas;
protected $app;
protected $config = array(); // plugin config
protected $options = array(); // options
protected $validation = array(); // validation errors
/**
* init the Slim App and setup the paths
*/
protected function init() {
$this->config = Spyc::YAMLLoad('_config/add-ons/commentatic.yaml');
$this->app = \Slim\Slim::getInstance(); // app instance
if (!array_key_exists('email_field', $this->config)) {
throw new Exception('Hey, don\'t forget to copy the commentatic.yaml file from the plugin folder to _config/add-ons/commentatic.yaml');
}
// comment locations
$this->get_comment_path();
$this->options['class'] = $this->fetch_param('class', '');
$this->options['id'] = $this->fetch_param('id', '');
$this->options['required'] = $this->fetch_param('required');
$this->options['honeypot'] = $this->fetch_param('honeypot', true); #boolen param
}
/**
* Default methods
*/
// comment form
public function form() {
$this->init();
// Set up some default vars.
$output = '';
$vars = array(array());
$flash = $this->app->view()->getData('flash');
if ($flash['success']) {
$vars = array(array('success' => true));
}
// If the page has post data process it.
if ($this->app->request()->isPost()) {
$this->form_datas = (object)$this->app->request()->post();
if ($this->logged_in()) {
$this->form_datas->{$this->config['username_field']} = $this->username();
$this->form_datas->{$this->config['email_field']} = $this->email();
}
if ($this->config['comment_field'] != 'content') {
$this->form_datas->content = $this->form_datas->{$this->config['comment_field']};
unset($this->form_datas->{$this->config['comment_field']});
}
if ( ! $this->validate()) {
$vars = array(array('error' => true, 'errors' => $this->validation));
} elseif ($this->save()) {
$this->app->flash('success', 'Comment sent successfully !');
$url_redirect = rtrim(Statamic::get_site_root(), '/').$this->app->request()->getResourceUri();
if ($this->page_count() > 0 && $this->fetch_param('sort_dir', 'asc') != 'desc') {
$url_redirect .= '?page='.$this->page_count();
}
if( $this->options['id'] != '') {
$url_redirect .= '#'.$this->options['id'];
}
$this->app->redirect($url_redirect, 302);
} else {
$vars = array(array('error' => true, 'errors' => 'Could not send comment'));
}
}
// Display the form on the page.
$output .= '<form method="post"';
$output .= ' action="' . rtrim(Statamic::get_site_root(), '/').$this->app->request()->getResourceUri().'"';
if ( $this->options['class'] != '') { $output .= ' class="' . $this->options['class'] . '"'; }
if ( $this->options['id'] != '') { $output .= ' id="' . $this->options['id'] . '"'; }
$output .= '>';
//inject the honeypot if true
if ($this->options['honeypot']) {
$output .= '<input type="text" class="honeypot" name="wearetherobot" value="" />';
}
$output .= $this->parse_loop($this->content, $vars);
$output .= '</form>';
//inject the honeypot if true
if ($this->options['honeypot']) {
$output .= '<style>.honeypot { display:none; }</style>';
}
return $output;
}
// Comment listing method
public function listing() {
$this->init();
$folder = $this->fetch_param('folder', $this->comment_folder); // defaults to null
if ($folder != $this->comment_folder) {
$this->get_comment_path();
$folder = $this->comment_folder; // resolve new folder path
}
$limit = $this->config['comment_per_page']; // defaults to none
$offset = $this->fetch_param('offset', 0, 'is_numeric'); // defaults to zero
$sort_by = $this->fetch_param('sort_by', 'date'); // defaults to date
$sort_dir = $this->fetch_param('sort_dir', 'asc'); // defaults to desc
$conditions = $this->fetch_param('conditions', null, false, false, false); // defaults to null
$switch = $this->fetch_param('switch', null); // defaults to null
$since = $this->fetch_param('since', null); // defaults to null
$until = $this->fetch_param('until', null); // defaults to null
$paginate = $this->fetch_param('paginate', true, false, true); // defaults to true
if ($this->config['comment_per_page'] && $paginate) {
// override limit/offset if paging
$pagination_variable = Statamic::get_pagination_variable();
$page = $this->app->request()->get($pagination_variable) ? $this->app->request()->get($pagination_variable) : 1;
$offset = (($page * $this->config['comment_per_page']) - $this->config['comment_per_page']) + $offset;
}
if ($this->comment_folder) {
$list = Statamic::get_content_list($folder, $limit, $offset, false, true, $sort_by, $sort_dir, $conditions, $switch, false, false, $since, $until);
if (sizeof($list)) {
foreach ($list as $key => $item) {
/* Begin Gravatar Support */
$gravatar_src = 'http://www.gravatar.com/avatar/';
$gravatar_href = 'http://www.gravatar.com/';
$gravatar_alt = '';
if (array_key_exists($this->config['email_field'], $item)) {
$gravatar_src .= md5( strtolower( trim( $item[$this->config['email_field']] ) ) );
$gravatar_href .= md5( strtolower( trim( $item[$this->config['email_field']] ) ) );
$gravatar_alt = $item[$this->config['email_field']].'\'s Gravatar';
}
$list[$key]['avatar'] = "<img src=\"$gravatar_src\" alt=\"$gravatar_alt\" />";
$list[$key]['gravatar_profile'] = $gravatar_href;
/* End Gravatar Support */
$list[$key]['content'] = Statamic::parse_content($item['content'], $item);
}
return $this->parse_loop($this->content, $list);
} else {
return array('no_results' => true);
}
}
return array();
}
// Pagination method
public function pagination() {
$this->init();
$folder = $this->fetch_param('folder', $this->comment_folder); // defaults to null
if ($folder != $this->comment_folder) {
$this->get_comment_path();
$folder = $this->comment_folder; // resolve new folder path
}
$limit = $this->config['comment_per_page']; // defaults to none
$conditions = $this->fetch_param('conditions', null, false, false, false); // defaults to null
$since = $this->fetch_param('since', null); // defaults to null
$until = $this->fetch_param('until', null); // defaults to null
$style = $this->fetch_param('style', 'prev_next'); // defaults to date
$count = Statamic::get_content_count($this->comment_folder, false, true, $conditions, $since, $until);
$pagination_variable = Statamic::get_pagination_variable();
$page = $this->app->request()->get($pagination_variable) ? $this->app->request()->get($pagination_variable) : 1;
$arr = array();
$arr['total_items'] = (int) max(0, $count);
$arr['items_per_page'] = (int) max(1, $limit);
$arr['total_pages'] = (int) ceil($count / $limit);
$arr['current_page'] = (int) min(max(1, $page), max(1, $page));
$arr['current_first_item'] = (int) min((($page - 1) * $limit) + 1, $count);
$arr['current_last_item'] = (int) min($arr['current_first_item'] + $limit - 1, $count);
$arr['previous_page'] = ($arr['current_page'] > 1) ? "?{$pagination_variable}=".($arr['current_page'] - 1) : FALSE;
$arr['next_page'] = ($arr['current_page'] < $arr['total_pages']) ? "?{$pagination_variable}=".($arr['current_page'] + 1) : FALSE;
$arr['first_page'] = ($arr['current_page'] === 1) ? FALSE : "?{$pagination_variable}=1";
$arr['last_page'] = ($arr['current_page'] >= $arr['total_pages']) ? FALSE : "?{$pagination_variable}=".$arr['total_pages'];
$arr['offset'] = (int) (($arr['current_page'] - 1) * $limit);
return $this->parser->parse($this->content, $arr);
}
/**
* Helpers
*/
// Total comment count
public function comment_count()
{
$this->init();
$folder = $this->fetch_param('folder', $this->comment_folder); // defaults to null
if ($folder != $this->comment_folder) {
$this->get_comment_path();
$folder = $this->comment_folder; // resolve new folder path
}
if (!$this->total_items) {
$this->total_items = Statamic::get_content_count($this->comment_folder, false, true, null, null, null);
}
return $this->total_items;
}
/**
* protected Methods
*/
protected function get_comment_path($folder=false)
{
if (!$folder) {
$folder = $this->app->request()->getResourceUri();
}
$this->comment_folder = '_comments'.Statamic_helper::resolve_path($folder);
$this->raw_comment_folder = '_content/'.$this->comment_folder;
$this->comment_file = $this->raw_comment_folder . '/' . date('Y-m-d').'_'.time().'.md';
}
// Check if logged in
protected function logged_in() {
return Statamic_Auth::is_logged_in();
}
protected function user_datas() {
if (!$this->user_datas) {
$this->user_datas = Statamic_Auth::get_current_user(); // retrieve user datas
}
return $this->user_datas;
}
/**
* Print the username when logged in
*/
protected function username() {
$username = '';
if ($current_user = $this->user_datas()) {
$username = $current_user->get_name(); // username is used by default
// if there's a last name, great !
if ($last_name = $current_user->get_last_name()) {
$username = $last_name;
}
// ok there's a first name, go for it !
if ($first_name = $current_user->get_first_name()) {
$username .= ' '.$first_name;
}
}
return $username;
}
// User email
protected function email() {
if ($current_user = $this->user_datas()) {
return $this->app->config['contact_email'];
}
return '';
}
// Comment page count
protected function page_count() {
if (!$this->total_pages) {
$this->total_pages = (int) ceil(($this->comment_count()) / $this->config['comment_per_page']);
}
return $this->total_pages;
}
// Validate the submitted form data
protected function validate() {
$input = $this->form_datas;
$required = explode('|', str_replace(array('comment',$this->config['email_field'], $this->config['username_field']), '', $this->options['required']));
if ( !isset($input->content) or trim($input->content) === '') {
$this->validation[]['error'] = 'Comment is required';
}
// Email is always required
if ( !$this->logged_in() && ( ! isset($input->{$this->config['email_field']}) or ! filter_var($input->email, FILTER_VALIDATE_EMAIL) ) ) {
$this->validation[]['error'] = 'Email is required';
}
// Username is always required
if ( !$this->logged_in() && ( ! isset($input->{$this->config['username_field']}) ) ) {
$this->validation[]['error'] = 'Username is required';
}
// Honeypot !
if ($this->options['honeypot'] && $input->wearetherobot != '' ) {
$this->validation[]['error'] = 'Hello robot !';
}
foreach ($required as $key => $value) {
if ($value != '' and $input->$value == '') {
$this->validation[]['error'] = ucfirst($value).' is required';
}
}
return empty($this->validation) ? true : false;
}
// Save the comment
protected function save() {
$file_content = "";
$file_content .= "---\n";
foreach($this->form_datas as $key=>$data) {
if ($key != 'content' && $key != 'wearetherobot') {
$file_content .= "{$key}: {$data}\n";
}
}
$file_content .= "---\n";
$file_content .= $this->form_datas->content;
$file_content .= "\n";
if (!file_exists($this->raw_comment_folder)) {
mkdir($this->raw_comment_folder, 0777, true);
}
return file_put_contents($this->comment_file, $file_content);
}
} | true |
2699fa408acc0d179e97d4c06c0b66ce88ea5292 | PHP | fossabot/flight-routing | /src/Middlewares/ResponseMiddleware.php | UTF-8 | 4,177 | 2.671875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | <?php
declare(strict_types=1);
/*
* This code is under BSD 3-Clause "New" or "Revised" License.
*
* PHP version 7 and above required
*
* @category RoutingManager
*
* @author Divine Niiquaye Ibok <divineibok@gmail.com>
* @copyright 2019 Biurad Group (https://biurad.com/)
* @license https://opensource.org/licenses/BSD-3-Clause License
*
* @link https://www.biurad.com/projects/routingmanager
* @since Version 0.1
*/
namespace Flight\Routing\Middlewares;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use BiuradPHP\Http\Exceptions\ClientException;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
/**
* Default response dispatch middleware.
*
* Checks for a composed route result in the request. If none is provided,
* delegates request processing to the handler.
*
* Otherwise, it delegates processing to the route result.
*/
class ResponseMiddleware implements MiddlewareInterface
{
/**
* {@inheritDoc}
*
* @param Request $request
* @param RequestHandler $handler
*
* @return \Psr\Http\Message\ResponseInterface
*/
public function process(Request $request, RequestHandler $handler): ResponseInterface
{
$response = $handler->handle($request);
// Set the cache control to no cache
// disable caching of potentially sensitive data
if (!$response->hasHeader('Cache-Control')) {
$response = $response
->withHeader('Cache-Control', 'private, no-cache, must-revalidate, no-store')
;
}
// prevent content sniffing (MIME sniffing)
if (!$response->hasHeader('X-Content-Type-Options')) {
//$response = $response
// ->withHeader('X-Content-Type-Options', 'nosniff')
//;
}
// Fix Content-Type
if (!$response->hasHeader('Content-Type')) {
$response = $response
->withHeader('Content-Type', 'text/html; charset=UTF-8');
} elseif (
0 === stripos($response->getHeaderLine('Content-Type'), 'text/') &&
false === stripos($response->getHeaderLine('Content-Type'), 'charset')) {
// add the charset
$response = $response
->withHeader('Content-Type', $response->getHeaderLine('Content-Type').'; charset=UTF-8');
}
// Check if we need to send extra expire info headers
if (
$response->getProtocolVersion() &&
false !== strpos($response->getHeaderLine('Cache-Control'), 'no-cache')
) {
$response = $response
->withHeader('Pragma', 'no-cache')
->withHeader('expires', 'Thu, 19 Nov 1981 00:00:00 GMT');
}
// Redirection header
if ($response->getStatusCode() === 302) {
$response = $response
->withoutHeader('Cache-Control')
->withAddedHeader('Cache-Control', 'no-cache, must-revalidate');
}
// Incase response is empty
if ($this->isResponseEmpty($response)) {
$response = $response
->withoutHeader('Allow')
->withoutHeader('Content-MD5')
->withoutHeader('Content-Type')
->withoutHeader('Content-Length');
}
// Handle Headers Error
if ($response->getStatusCode() >= 400) {
for ($i = 400; $i < 600; $i++) {
if ($response->getStatusCode() === $i) {
throw new ClientException($i);
}
};
}
// remove headers that MUST NOT be included with 304 Not Modified responses
return $response;
}
/**
* Asserts response body is empty or status code is 204, 205 or 304
*
* @param ResponseInterface $response
* @return bool
*/
private function isResponseEmpty(ResponseInterface $response): bool
{
$contents = (string) $response->getBody();
return empty($contents) || in_array($response->getStatusCode(), [204, 205, 304], true);
}
}
| true |
2902ba1813175c68f6c4a262b934a1a9ffc8c847 | PHP | Sherif-nasser/larvel-insightCRM | /app/Http/Controllers/Admin/CRUDController.php | UTF-8 | 2,134 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class CRUDController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
/// AMIT WOORK START//
$data = $request->all();
$rules =[
'name' =>['required', 'min:4', 'max:25'],
'email'=> ['required' , 'unique:users', 'email'],
'password' => ['required', 'min:8']
];
$validator = Validator::make($data,$rules);
if($validator->fails()){
return redirect()->back()->withErrors($validator)->withInput($data);
}
User::create([
'name' =>$request->_token,
]);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$user = User::findorFail($id); //find the id if exists or not from the User table
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
| true |
a2ac3e3d72f1d0b06607267ae0336a1ded59cba2 | PHP | julianamayercardoso/public_html | /index.php | UTF-8 | 1,641 | 2.609375 | 3 | [] | no_license | <!DOCTYPE html>
<html>
<head>
<title>Testes de html 5, ecmascript 6, css 3 e php 5</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#CCEEFF">
<ul>
<li> <h2>Programacao para internet</h2></li>
<li><h3>Engenharia de software</h3></li>
</ul>
<form>
De que frutas você gosta? <br />
<input type="checkbox" name="uva" value="uva"/>Uva <br />
<input type="checkbox" name="maca" value="maca"/>Maçã <br />
<input type="checkbox" name="melancia" value="melancia"/>Melancia
</form>
<h1>Faça login</h1>
<form action="index.html" method="post">
<table>
<tr>
<td>
Nome:
</td>
</tr>
<tr>
<td>
<input type="text" name="nome_do_usuario"/>
</td>
</tr>
<tr>
<td>
Senha:
</td>
</tr>
<tr>
<td>
<input type="password" name="senha_do_usuario"/>
</td>
</tr>
<tr>
<td>
<input type="submit" name="botao" value="Entrar"/>
</td>
</tr>
</table>
</form>
<?php
echo "Juliana e alexsandro Stefenon<br>";
echo "1,2,3,4,5,<br>";
echo "6,7,8,9,10<br>";
echo "11<br>";
echo "alexsandro<br>";
echo "20<br>";
echo "Geovana Mayer Cardoso<br>";
echo "paolla<br>";
echo "chuva<br>";
echo "23<br>";
?>
</body>
</html>
| true |
ecbaa8a5b32c43468a668a4c9fc81afb5c62a784 | PHP | healars/testNew | /uploader.php | UTF-8 | 1,794 | 2.703125 | 3 | [] | no_license | <?php
// get the q parameter from URL
$q = $_REQUEST ["q"];
if(empty($q)){
$q="client1";
}
$target_dir= "/home/maxprodisplays/public_html/client/clientImages/" . $q ."/";
//$target_dir="D:/xampp/htdocs/client/clientImages/" . $q ."/";
if (!is_dir ( $target_dir)) {
mkdir( $target_dir);
echo "directory created as didn't existed before";
}
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check file size
if ($_FILES["file"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
$uploadOk = 0;
header ( 'HTTP/1.1 400 Internal Server' );
header ( 'Content-Type: application/json; charset=UTF-8' );
die ( json_encode ( array (
'message' => 'File type not supported',
'code' => 400
) ) );
} else {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
} else {
header ( 'HTTP/1.1 400 Internal Server' );
header ( 'Content-Type: application/json; charset=UTF-8' );
die ( json_encode ( array (
'message' => 'Error uploading image',
'code' => 400
) ) );
}
}
?>
| true |
3e3f9fe7dd5184a5a22bf36c9e1f3a4bccae3331 | PHP | Vitvik/TestSoftGroup | /decision6.php | UTF-8 | 461 | 2.890625 | 3 | [] | no_license | <?php
ini_set('display_errors',1);
error_reporting(E_ALL ^E_NOTICE);
//Передаємо дані в масив
$arr = file('upload/protokol.txt');
unset($arr[0]);
$arr_as = array();
foreach ($arr as &$val) {
$data = explode(" ", $val);
foreach ($arr_as as $key_as => $val_as){
$key_as = $data[0];
$val_as = $data[1];
}
unset($val);
}
foreach ($arr as $key => $value) {
echo "{$key} => {$value} "."\n <br />";
}
?>
| true |
0546784183f710903487c69064f5bf98866cf86b | PHP | Meuons/REST | /config/database.php | UTF-8 | 629 | 3.3125 | 3 | [] | no_license | <?php
class database{
//Store the database connection as properties
private $host = //host address goes here;
private $db_name = //database name goes here;
private $username = //username goes here;
private $password = //password goes here;
private $conn;
public function connect(){
//Create a database connection
$this->conn = new mysqli($this->host, $this->username, $this->password, $this->db_name );
if($this->conn->connect_errno > 0){
die("Error connecting: " . $this->conn->connect_error);
}
return $this->conn;
}
public function close(){
$this->conn = null;
}
}
| true |
1dfbcc86b96fe4e7ac4a9ee323ee589fb6104304 | PHP | zk45145/Collectionist | /api/app/Models/Collection.php | UTF-8 | 570 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Collection extends Model
{
use HasFactory;
const CREATED_AT = 'createdAt';
const UPDATED_AT = 'updatedAt';
protected $fillable = ['name', 'description', 'collection_type_id', 'image'];
protected $casts = ['image' => 'array'];
public function type(){
return $this->belongsTo(CollectionType::class);
}
public function elements () {
return $this->hasMany(CollectionElement::class);
}
}
| true |
319d9ff7761517f68e649024989cbe1cb3e8a4c7 | PHP | rickywrwn/titipankuAPI | /GetAllRequest.php | UTF-8 | 5,165 | 2.546875 | 3 | [] | no_license | <?php
include("DbConnect.php");
$email = $_GET["email"];
$sql = "SELECT * FROM user WHERE email = '$email'";
$result = mysqli_query($conn,$sql);
$user=array();
if(mysqli_num_rows($result) > 0)
{
while($row = $result->fetch_assoc()) {
$berat = $row["berat"];
$ukuran = $row["ukuran"];
}
}
if ($berat == '1'){
if ($ukuran == "Kecil (20x20x20 CM)"){
$sql = "SELECT * FROM postRequest WHERE status != '0' AND berat = '1' AND ukuran = 'Kecil (20x20x20 CM)' ORDER BY id DESC";
$result = mysqli_query($conn,$sql);
}else if ($ukuran == "Sedang ( 30x25x20 CM)"){
$sql = "SELECT * FROM postRequest WHERE status != '0' AND berat = '1' AND ukuran = 'Kecil (20x20x20 CM)' OR ukuran = 'Sedang ( 30x25x20 CM)' ORDER BY id DESC";
$result = mysqli_query($conn,$sql);
}else if ($ukuran == "Besar (35x22x55 CM)"){
$sql = "SELECT * FROM postRequest WHERE status != '0' AND berat = '1' AND ukuran = 'Kecil (20x20x20 CM)' OR ukuran = 'Sedang ( 30x25x20 CM)' OR ukuran = 'Besar (35x22x55 CM)' ORDER BY id DESC";
$result = mysqli_query($conn,$sql);
}
}else if ($berat == '2'){
if ($ukuran == "Kecil (20x20x20 CM)"){
$sql = "SELECT * FROM postRequest WHERE status != '0' AND berat = '1' OR berat = '2' AND ukuran = 'Kecil (20x20x20 CM)' ORDER BY id DESC";
$result = mysqli_query($conn,$sql);
}else if ($ukuran == "Sedang ( 30x25x20 CM)"){
$sql = "SELECT * FROM postRequest WHERE status != '0' AND berat = '1' OR berat = '2' AND ukuran = 'Kecil (20x20x20 CM)' OR ukuran = 'Sedang ( 30x25x20 CM)' ORDER BY id DESC";
$result = mysqli_query($conn,$sql);
}else if ($ukuran == "Besar (35x22x55 CM)"){
$sql = "SELECT * FROM postRequest WHERE status != '0' AND berat = '1' OR berat = '2' AND ukuran = 'Kecil (20x20x20 CM)' OR ukuran = 'Sedang ( 30x25x20 CM)' OR ukuran = 'Besar (35x22x55 CM)' ORDER BY id DESC";
$result = mysqli_query($conn,$sql);
}
}else if ($berat == '3'){
if ($ukuran == "Kecil (20x20x20 CM)"){
$sql = "SELECT * FROM postRequest WHERE status != '0' AND berat = '1' OR berat = '2' OR berat = '3' AND ukuran = 'Kecil (20x20x20 CM)' ORDER BY id DESC";
$result = mysqli_query($conn,$sql);
}else if ($ukuran == "Sedang ( 30x25x20 CM)"){
$sql = "SELECT * FROM postRequest WHERE status != '0' AND berat = '1' OR berat = '2' OR berat = '3'AND ukuran = 'Kecil (20x20x20 CM)' OR ukuran = 'Sedang ( 30x25x20 CM)' ORDER BY id DESC";
$result = mysqli_query($conn,$sql);
}else if ($ukuran == "Besar (35x22x55 CM)"){
$sql = "SELECT * FROM postRequest WHERE status != '0' AND berat = '1' OR berat = '2' OR berat = '3'AND ukuran = 'Kecil (20x20x20 CM)' OR ukuran = 'Sedang ( 30x25x20 CM)' OR ukuran = 'Besar (35x22x55 CM)' ORDER BY id DESC";
$result = mysqli_query($conn,$sql);
}
}else if ($berat == '4'){
if ($ukuran == "Kecil (20x20x20 CM)"){
$sql = "SELECT * FROM postRequest WHERE status != '0' AND berat = '1' OR berat = '2' OR berat = '3' OR berat = '4' AND ukuran = 'Kecil (20x20x20 CM)' ORDER BY id DESC";
$result = mysqli_query($conn,$sql);
}else if ($ukuran == "Sedang ( 30x25x20 CM)"){
$sql = "SELECT * FROM postRequest WHERE status != '0' AND berat = '1' OR berat = '2' OR berat = '3' OR berat = '4' AND ukuran = 'Kecil (20x20x20 CM)' OR ukuran = 'Sedang ( 30x25x20 CM)' ORDER BY id DESC";
$result = mysqli_query($conn,$sql);
}else if ($ukuran == "Besar (35x22x55 CM)"){
$sql = "SELECT * FROM postRequest WHERE status != '0' AND berat = '1' OR berat = '2' OR berat = '3' OR berat = '4' AND ukuran = 'Kecil (20x20x20 CM)' OR ukuran = 'Sedang ( 30x25x20 CM)' OR ukuran = 'Besar (35x22x55 CM)' ORDER BY id DESC";
$result = mysqli_query($conn,$sql);
}
}else if ($berat == '5'){
if ($ukuran == "Kecil (20x20x20 CM)"){
$sql = "SELECT * FROM postRequest WHERE status != '0' AND ukuran = 'Kecil (20x20x20 CM)' ORDER BY id DESC";
$result = mysqli_query($conn,$sql);
}else if ($ukuran == "Sedang ( 30x25x20 CM)"){
$sql = "SELECT * FROM postRequest WHERE status != '0' AND ukuran = 'Kecil (20x20x20 CM)' OR ukuran = 'Sedang ( 30x25x20 CM)' ORDER BY id DESC";
$result = mysqli_query($conn,$sql);
}else if ($ukuran == "Besar (35x22x55 CM)"){
$sql = "SELECT * FROM postRequest WHERE status != '0' ORDER BY id DESC";
$result = mysqli_query($conn,$sql);
}
}
$app=array();
if(mysqli_num_rows($result) > 0)
{
while($row = $result->fetch_assoc()) {
$newDate = date("d F Y", strtotime($row["tglPost"]));
$newPrice = number_format($row["price"],0,",",".");
$request=array("id"=>$row["id"],"email"=>$row["email"],"name"=>$row["name"],"description"=>$row["description"],"category"=>$row["category"],"country"=>$row["country"],"price"=>$newPrice,"ImageName"=>$row["imageName"],"url"=>$row["url"],"qty"=>$row["qty"],"ukuran"=>$row["ukuran"],"berat"=>$row["berat"],"kotaKirim"=>$row["kotaKirim"],"idKota"=>$row["idKota"],"provinsi"=>$row["provinsi"],"tglPost"=>$newDate,"nomorResi"=>$row["nomorResi"],"status"=>$row["status"]);
array_push($app,$request);
}
}
// headers to tell that result is JSON
header('Content-type: application/json');
echo json_encode($app);
?>
| true |
8f7b1abb9f94243ed17050e5404504d6cb46c90d | PHP | bcremer/LineReader | /src/LineReader.php | UTF-8 | 3,157 | 3.3125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace Bcremer\LineReader;
final class LineReader
{
/**
* Prevent instantiation
*/
private function __construct()
{
}
/**
* @return \Generator<int, string, void, void>
*
* @throws \InvalidArgumentException if $filePath is not readable
*/
public static function readLines(string $filePath): \Generator
{
if (!$fh = @fopen($filePath, 'r')) {
throw new \InvalidArgumentException('Cannot open file for reading: ' . $filePath);
}
return self::read($fh);
}
/**
* @return \Generator<int, string, void, void>
*
* @throws \InvalidArgumentException if $filePath is not readable
*/
public static function readLinesBackwards(string $filePath): \Generator
{
if (!$fh = @fopen($filePath, 'r')) {
throw new \InvalidArgumentException('Cannot open file for reading: ' . $filePath);
}
$size = filesize($filePath);
if (!\is_int($size)) {
throw new \RuntimeException('Could not get file size');
}
return self::readBackwards($fh, $size);
}
/**
* @param resource $fh
*/
private static function read($fh): \Generator
{
while (false !== $line = fgets($fh)) {
yield rtrim($line, "\n");
}
fclose($fh);
}
/**
* Read a file from the end using a buffer.
*
* This is way more efficient than using the naive method
* of reading the file backwards byte by byte looking for
* a newline character.
*
* @see http://stackoverflow.com/a/10494801/147634
*
* @param resource $fh
*
* @return \Generator<int, string, void, void>
*/
private static function readBackwards($fh, int $pos): \Generator
{
$buffer = null;
$bufferSize = 4096;
if ($pos === 0) {
return;
}
while (true) {
if (isset($buffer[1])) { // faster than count($buffer) > 1
yield array_pop($buffer);
continue;
}
if ($pos === 0 && \is_array($buffer)) {
yield array_pop($buffer);
break;
}
if ($bufferSize > $pos) {
$bufferSize = $pos;
$pos = 0;
} else {
$pos -= $bufferSize;
}
fseek($fh, $pos);
if ($bufferSize < 0) {
throw new \RuntimeException('Buffer size cannot be negative');
}
$chunk = fread($fh, $bufferSize);
if (!\is_string($chunk)) {
throw new \RuntimeException('Could not read file');
}
if ($buffer === null) {
// remove single trailing newline, rtrim cannot be used here
if (substr($chunk, -1) === "\n") {
$chunk = substr($chunk, 0, -1);
}
$buffer = explode("\n", $chunk);
} else {
$buffer = explode("\n", $chunk . $buffer[0]);
}
}
}
}
| true |
891b12b19c893f0b7e8c2dbb8aefc069d543d6f4 | PHP | cparello/CMS | /admin/billing/pastDueMonthly.php | UTF-8 | 9,900 | 2.515625 | 3 | [] | no_license | <?php
class pastDueMonthly {
private $contractKey = null;
private $prePayCount = null;
private $monthlyCount = null;
private $currentMonthDueDate = null;
private $nextMonthDueDate = null;
private $lateFee = null;
private $monthlyPayment = null;
private $nextPaymentDueDate = null;
private $todaysDate = null;
private $daysPastDue = null;
private $pastDueTotal = null;
private $cycleDay = null;
private $pastDay = null;
private $testSecs = null;
function setContractKey($contractKey) {
$this->contractKey = $contractKey;
}
//---------------------------------------------------------------------------------------------------------------------
//connect to database
function dbconnect() {
require"../dbConnect.php";
return $dbMain;
}
//----------------------------------------------------------------------------------------------------------------------------------------------
function loadFees() {
$dbMain = $this->dbconnect();
$stmt = $dbMain ->prepare("SELECT late_fee, nsf_fee, rejection_fee FROM fees WHERE fee_num = '1'");
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($late_fee, $nsf_fee, $rejection_fee);
$stmt->fetch();
$this->lateFee = $late_fee;
$stmt->close();
}
//--------------------------------------------------------------------------------------------------------------------
function loadMonthlyPayment() {
$dbMain = $this->dbconnect();
$stmt = $dbMain ->prepare("SELECT billing_amount FROM monthly_payments WHERE contract_key = '$this->contractKey'");
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($billing_amount);
$stmt->fetch();
$this->monthlyPayment = $billing_amount;
//$this->todaysDate = date("Y-m-d");
$this->todaysDate = date("Y-m-d H:i:s" ,mktime(23, 59, 59, date("m"), date("d"), date("Y")));
$datetime1 = new DateTime($this->nextPaymentDueDate);
$datetime2 = new DateTime($this->todaysDate);
$interval = $datetime1-> diff($datetime2);
$this->daysPastDue = $interval-> format('%d');
$this->monthsPastDue = $interval-> format('%m');
$this->yearsPastDue = $interval-> format('%y');
// $this->testSecs = "dgdfgf $this->monthsPastDue";
if($this->monthsPastDue >= 1) {
if($this->yearsPastDue >= 1) {
$months = $this->yearsPastDue * 12;
$this->monthsPastDue = $this->monthsPastDue + $months;
}
$this->monthlyPayment = ($this->monthlyPayment * $this->monthsPastDue) + $this->lateFee;
}else{
$this->monthlyPayment = 0;
}
$this->pastDueTotal = $this->monthlyPayment;
$this->pastDueTotal = sprintf("%01.2f", $this->pastDueTotal);
if(!$stmt->execute()) {
printf("Error: %s.\n monthly_payments function loadMonthlyPayment", $stmt->error);
}
$stmt->close();
}
//--------------------------------------------------------------------------------------------------------------------
function loadMonthly() {
$dbMain = $this->dbconnect();
$stmt = $dbMain ->prepare("SELECT count(*) AS count FROM monthly_payments WHERE contract_key='$this->contractKey' AND billing_amount != '0.00'");
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($count);
$stmt->fetch();
$this->monthlyCount = $count;
$stmt->close();
}
//----------------------------------------------------------------------------------------------------------------------------------------------
function loadSettledPayments() {
$dbMain = $this->dbconnect();
$stmt = $dbMain ->prepare("SELECT MAX(next_payment_due_date) FROM monthly_settled WHERE contract_key='$this->contractKey'");
$stmt->execute();
$stmt->store_result();
$numRows = $stmt->num_rows;
$stmt->bind_result($next_payment_due_date);
$stmt->fetch();
$stmt->close();
$stmt = $dbMain ->prepare("SELECT MAX(cycle_date) FROM monthly_payments WHERE contract_key ='$this->contractKey'");
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($cycle_date);
$stmt->fetch();
$stmt->close();
$todaysDateSecs = time();
if($next_payment_due_date != "") {
$monthlySettledDueDateSecs = strtotime($next_payment_due_date);
if($todaysDateSecs >= $monthlySettledDueDateSecs) {
$this->nextPaymentDueDate = $next_payment_due_date;
$this->loadFees();
$this->loadMonthlyPayment();
}
}elseif($next_payment_due_date == "") {
//create the past due day and monthly cycle date from monthly payment
$cycle_day = date("d", strtotime($cycle_date));
$pastDueDay = $this->pastDay + $cycle_day;
$cycleMonth = date("m", strtotime($cycle_date));
$cycleYear = date("Y", strtotime($cycle_date));
$monthlyPaymentsDueDate= date("Y-m-d H:i:s" ,mktime(0, 0, 0, $cycleMonth, $pastDueDay, $cycleYear));
$monthlyPaymentsDueDateSecs = strtotime($monthlyPaymentsDueDate);
// $this->testSecs = "$monthlyPaymentsDueDateSecs <br> $todaysDateSecs";
if($todaysDateSecs >= $monthlyPaymentsDueDateSecs) {
$this->nextPaymentDueDate = $monthlyPaymentsDueDate;
$this->loadFees();
$this->loadMonthlyPayment();
}
}
/*
$this->nextPaymentDueDate = $next_payment_due_date;
// if($this->nextPaymentDueDate != $this->nextMonthDueDate) {
// if($this->nextPaymentDueDate != "") {
// $this->loadFees();
// $this->loadMonthlyPayment();
// }
// }
if($this->nextPaymentDueDate != "" && $this->prePayCount == 0) {
if($this->nextPaymentDueDate != $this->nextMonthDueDate) {
$this->loadFees();
$this->loadMonthlyPayment();
}
}
if($this->nextPaymentDueDate != "" && $this->prePayCount > 0) {
$prepayEndDate = strtotime($next_payment_due_date);
$todaysDate = time();
if($todaysDate > $prepayEndDate) {
$this->loadFees();
$this->loadMonthlyPayment();
}
}
$stmt->close();
*/
}
//----------------------------------------------------------------------------------------------------------------------------------------------
function checkPrepay() {
$dbMain = $this->dbconnect();
$stmt = $dbMain ->prepare("SELECT count(*) AS count FROM pre_payments WHERE contract_key= '$this->contractKey'");
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($count);
$stmt->fetch();
$this->prePayCount = $count;
$stmt->close();
}
//----------------------------------------------------------------------------------------------------------------------------------------------
function loadRecordCount() {
$dbMain = $this->dbconnect();
$stmt = $dbMain ->prepare("SELECT count(*) FROM account_status WHERE account_status ='CU' AND contract_key='$this->contractKey'");
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($currentCount);
$stmt->fetch();
if($currentCount > 0) {
//check to see if account is monthly
$this->loadPastDay();
$this->loadMonthly();
if($this->monthlyCount == 1) {
//check to see if a prepayment has been made
$this->checkPrepay();
if($this->prePayCount == 0) {
$this->loadSettledPayments();
}
}
}
$stmt->close();
if($this->ajaxSwitch == 1) {
echo"$this->settledCount";
exit;
}
}
//---------------------------------------------------------------------------------------------------------------------------------------
function loadPastDay() {
$dbMain = $this->dbconnect();
$stmt = $dbMain ->prepare("SELECT past_day FROM billing_cycle WHERE cycle_key ='1'");
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($past_day);
$stmt->fetch();
$stmt->close();
$this->pastDay = $past_day;
//$stmt = $dbMain ->prepare("SELECT cycle_date FROM monthly_payments WHERE contract_key = '$this->contractKey'");
//$stmt->execute();
//$stmt->store_result();
//$stmt->bind_result($cycle_date);
//$stmt->fetch();
//$stmt->close();
//$this->cycleDay = date("d",strtotime($cycle_date));
//$nextDueDaysPast = $this->pastDay + $this->cycleDay;
//$this->currentMonthDueDate = date("Y-m-d" ,mktime(0, 0, 0, date("m") , $nextDueDaysPast, date("Y")));
//$this->nextMonthDueDate = date("Y-m-d" ,mktime(0, 0, 0, date("m")+1 , $nextDueDaysPast, date("Y")));
//$this->nextMonthDueDate = date("Y-m-d H:i:s" ,mktime(23, 59, 59, date("m")+1 , $nextDueDaysPast, date("Y")));
//$this->currentStatementDate = date("m/d/Y" ,mktime(0, 0, 0, date("m") , date("d"), date("Y")));
//$this->statementRangeEndDate = date("m/d/Y" ,mktime(0, 0, 0, date("m"), $nextDueDaysPast, date("Y")));
//$this->statementRangeStartDate = date("m/d/Y" ,mktime(0, 0, 0, date("m")-1 , $cycle_day, date("Y")));
}
//---------------------------------------------------------------------------------------------------------------------
function getPastDueTotal() {
return($this->pastDueTotal);
}
function getTestSecs() {
return($this->testSecs);
}
}
/*
if($ajax_switch == 1) {
$testPastDue = new pastDueCount();
$testPastDue-> loadCycleDate();
$testPastDue-> setAjaxSwitch($ajax_switch);
$testPastDue-> loadRecordCount();
}
*/
?> | true |
232612f778887d7d7d0fc7cea0e12f27cce74003 | PHP | shinjia/201807_HCU_WebApp | /db_install/install_table.php | UTF-8 | 1,035 | 2.84375 | 3 | [] | no_license | <?php
include 'config.php';
// 連接資料庫
$link = db_open();
// 新增資料表之SQL語法 (採用陣列方式,可以設定多個)
$a_table['person'] = '
CREATE TABLE person (
uid int(11) NOT NULL auto_increment,
usercode varchar(255) NULL,
username varchar(255) NULL,
address varchar(255) NULL,
birthday date default NULL,
height int(11) default NULL,
weight int(11) default NULL,
remark varchar(255) NULL,
PRIMARY KEY (uid)
)
';
// 執行SQL及處理結果
$msg = '';
foreach($a_table as $key=>$sqlstr)
{
$result = mysqli_query($link, $sqlstr);
$msg .= '資料表『' . $key . '』.........';
$msg .= ($result) ? '建立完成!' : '無法建立!'.mysqli_error($link);
$msg .= '<br>';
}
db_close($link);
$html = <<< HEREDOC
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>基本資料庫系統</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h2>資料表建立結果</h2>
{$msg}
</body>
</html>
HEREDOC;
echo $html;
?> | true |
42bba43e7265673d22ec7e47b6a38d2fb6749144 | PHP | gautamv16/verify_labs | /app/Http/Controllers/Admin/UsersController.php | UTF-8 | 4,908 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers\Admin;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class UsersController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$users = User::with('role')->where('status','=',1)->get();
$status = ["1"=>"Active","0"=>'Inactive'];
return view('admin.uaeusers.index',compact('users','status'));
}
protected function validator(array $data)
{
$message = [];
return Validator::make($data, [
'first_name' => 'required|regex:/^[a-zA-Z ]*$/|string|max:100',
'last_name' => 'required|regex:/^[a-zA-Z ]*$/|string|max:100',
'email' => 'required|unique:users|email:rfc,dns',
'password' => 'required',
'role_id' => 'required',
'contact_number' => 'required',
'status' => 'required',
],$message);
}
protected function updatevalidator(array $data,$id)
{
$message = [];
return Validator::make($data, [
'first_name' => 'required|regex:/^[a-zA-Z ]*$/|string|max:100',
'last_name' => 'required|regex:/^[a-zA-Z ]*$/|string|max:100',
'email' => 'required|email|unique:users,email,'.$id,
'password' => 'required',
'role_id' => 'required',
'contact_number' => 'required',
'status' => 'required',
],$message);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('admin.uaeusers.add');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
try{
$payload = $request->all();
$validator = $this->validator($payload);
if($validator->fails()){
return back()->withErrors($validator->errors())->withInput($request->all());
}
$payload['password'] = Hash::make($payload['password']);
$user = User::create($payload);
return redirect()->to('/admin/users')->with('success','UAE User created successfully!');
}catch(\Exception $e){
return redirect()->back()->with('error',$e->getMessage());
}
}
/**
* Display the specified resource.
*
* @param \App\AdminUser $adminUser
* @return \Illuminate\Http\Response
*/
public function show(User $adminUser)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\AdminUser $adminUser
* @return \Illuminate\Http\Response
*/
public function edit(Request $request,$id)
{
$user = User::where('id','=',$id)->first();
return view('admin.uaeusers.edit',compact('user'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\AdminUser $adminUser
* @return \Illuminate\Http\Response
*/
public function update(Request $request,$id )
{
try{
$payload = $request->all();
$validator = $this->updatevalidator($payload,$id);
if($validator->fails()){
return back()->withErrors($validator->errors())->withInput($request->all());
}
$user = User::find($id);
$user->first_name = $payload['first_name'];
$user->last_name = $payload['last_name'];
$user->email = $payload['email'];
$user->contact_number = $payload['contact_number'];
$user->role_id = $payload['role_id'];
$user->status = $payload['status'];
$user->save();
return redirect()->to('/admin/users')->with('success','UAE User Updated successfully!');
}catch(\Exception $e){
return redirect()->back()->with('error',$e->getMessage());
}
}
/**
* Remove the specified resource from storage.
*
* @param \App\AdminUser $adminUser
* @return \Illuminate\Http\Response
*/
public function destroy(AdminUser $adminUser)
{
try{
$admin = User::find($id);
$admin->delete();
return redirect()->to('/admin/users')->with('success','UAE User Deleted successfully!');
}catch(\Exception $e){
return redirect()->back()->with('error',$e->getMessage());
}
}
}
| true |
b742c778dd1aba14206d4e568a97c64c150b8cf5 | PHP | Harut61/emt_inspect | /app/Console/Commands/FillFlatVulnerabilityByDate.php | UTF-8 | 1,415 | 2.53125 | 3 | [] | no_license | <?php
namespace App\Console\Commands;
use App\FlatVulnerabilityByDate;
use App\Http\Controllers\VulnerabilityListController;
use App\Traits\Vulnerabilities;
use Illuminate\Console\Command;
class FillFlatVulnerabilityByDate extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'fill:flatVulnerabilityByDate';
/**
* The console command description.
*
* @var string
*/
protected $description = 'fill flat vulnerability by date';
protected $vulnerabilityListController;
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
$this->vulnerabilityListController = new VulnerabilityListController();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
echo 'run FillFlatVulnerabilityByDate Cron job'. PHP_EOL;
$vulnerabilitiesByDates = $this->vulnerabilityListController->groupVulnerabilitiesByDate();
FlatVulnerabilityByDate::create([
'vulnerabilities_by_date' => json_encode($vulnerabilitiesByDates),
]);
$flatTimeline = FlatVulnerabilityByDate::get();
if(count($flatTimeline) > 1){
FlatVulnerabilityByDate::first()->delete();
}
}
}
| true |
08e300558ebb710e5530f4dc0c3dcec8ef11e437 | PHP | rafaelbogaveev/vktest | /src/service/cacheService.php | UTF-8 | 3,836 | 2.828125 | 3 | [
"Apache-2.0"
] | permissive | <?php
/**
* Created by PhpStorm.
* User: root
* Date: 10/14/17
* Time: 5:49 AM
*/
require_once (__DIR__ . '/../data/memcached.php');
/**
* Returns data stored by key formed by parameters
*
* @param $key
* @return mixed
*/
function getValueByKey($key){
require (__DIR__.'/../data/memcached.php');
global $app;
$logger = $app->getContainer()->get('logger');
$data = $memcached->get($key);
$logger->info("Get data from cache by key=".$key.' value='.$data);
return $data;
}
/**
* @param $key
* @param $data
*/
function saveValueByKey($key, $data){
require (__DIR__.'/../data/memcached.php');
global $app;
$logger = $app->getContainer()->get('logger');
$logger->info("Save data into cache for key=".$key.' value: '.$data);
$memcached->set($key, $data);
}
/**
* @param $key
*/
function deleteByKey($key){
require (__DIR__.'/../data/memcached.php');
global $app;
$logger = $app->getContainer()->get('logger');
$logger->info("Deleting data from cache by key=".$key);
$memcached->delete($key);
}
/**
*
* @param $orderField
* @param $limit
* @param $offset
* @param $orderType
* @return string
*/
function getKeyForPage($orderField, $limit, $offset, $orderType){
global $app;
$logger = $app->getContainer()->get('logger');
$prefix = getKeyPrefix($orderField, $orderType);
$key = $prefix.'_'.$limit.'_'.$offset.'_'.$orderType;
$logger->info('Key requested for '.$orderField.'_'.$orderType.': '.$key);
return $key;
}
/**
* @param $orderField
* @param $orderType
*/
function getKeyPrefix($orderField, $orderType)
{
require(__DIR__ . '/../data/memcached.php');
global $app;
$logger = $app->getContainer()->get('logger');
$logger->info('Get prefix for '.$orderField.'_'.$orderType);
//
if (price_field == $orderField) {
$lastId = $memcached->get(price_prefix_key);
if (null == $lastId) {
$lastId = 1;
saveValueByKey(price_prefix_key, $lastId);
}
return $orderField . $lastId;
}
if (id_field == $orderField && desc == $orderType) {
$lastId = $memcached->get(id_prefix_desc_key);
if (null == $lastId) {
$lastId = 1;
saveValueByKey(id_prefix_desc_key, $lastId);
}
return $orderField . $lastId;
}
$lastId = $memcached->get(id_prefix_asc_key);
if (null == $lastId) {
$lastId = 1;
saveValueByKey(id_prefix_asc_key, $lastId);
}
return $orderField . $lastId;
}
/**
* Changes prefix for key that used to store pages in cache
*
* @param $orderField
* @param $orderType
*/
function changeKeyPrefix($orderField, $orderType)
{
require(__DIR__ . '/../data/memcached.php');
global $app;
$logger = $app->getContainer()->get('logger');
$logger->info('Changing prefix for '.$orderField.'_'.$orderType);
if (price_field == $orderField) {
$lastId = $memcached->get(price_prefix_key);
$lastId = null == $lastId ? 1 : $lastId + 1;
saveValueByKey(price_prefix_key, $lastId);
$logger->info('New prefix for '.price_prefix_key.': '.$lastId);
return;
}
if (id_field == $orderField && desc == $orderType) {
$lastId = $memcached->get(id_prefix_desc_key);
$lastId = null == $lastId ? 1 : $lastId + 1;
saveValueByKey(id_prefix_desc_key, $lastId);
$logger->info('New prefix for '.id_prefix_desc_key.': '.$lastId);
return;
}
if (id_field == $orderField && asc == $orderType) {
$lastId = $memcached->get(id_prefix_asc_key);
$lastId = null == $lastId ? 1 : $lastId + 1;
saveValueByKey(id_prefix_asc_key, $lastId);
$logger->info('New prefix for ' . id_prefix_asc_key . ': ' . $lastId);
return;
}
}
| true |
bc21c42ba2502638a03c702f8764cb7d6be26e0f | PHP | SheriefBadran/PHP_PhotoGallery | /data/db/DatabaseAccessModel.php | UTF-8 | 4,594 | 3.078125 | 3 | [] | no_license | <?php
require_once(HelperPath.DS.'db/DB_Factory.php');
class DatabaseAccessModel {
// private static $dbUsername = "129463_ew31819";
// private static $dbPassword = "Qy.q55fc";
// private static $connectionString = 'mysql:host=photogallery-129463.mysql.binero.se;dbname=129463-photogallery';
private static $dbUsername = "root";
private static $dbPassword = "root";
private static $connectionString = 'mysql:host=localhost;dbname=PhotoGallery';
protected $dbFactory;
private static $fields = "fields";
private static $paramPlaceHolder = "paramPlaceHolder";
private static $emptyRecordException = "There are zero results to fetch.";
private static $databaseFetchAllErrorException = "fetchAll failed to fetch results";
private static $databaseFetchErrorException = "fetch failed to fetch results";
public function __construct () {
$dbAbstactFactory = new DB_Factory();
$this->dbFactory = $dbAbstactFactory::getFactory(self::$dbUsername, self::$dbPassword, self::$connectionString);
}
// Helper methods.
protected function retrieveObjectGetters (Array $objectGetters, Array $objectMethods) {
$getterMethods = array();
foreach ($objectGetters as $objectGetter) {
foreach ($objectMethods as $objectMethod) {
if ($objectMethod === $objectGetter) {
$getterMethods[] = $objectMethod;
}
}
}
return $getterMethods;
}
protected function getObjectAttributeValues (Array $getterMethods, $object) {
$params = array();
foreach ($getterMethods as $getter) {
$params[] = call_user_func(array($object, $getter));
}
return $params;
}
protected function composePDOqueryComponents (Array $objectProperties) {
$tblFields = " (";
$paramString = "(";
$methods = get_class_methods(static::$repositoryType);
for ($i = 0; $i < count($objectProperties); $i++) {
$tblFields .= ($i === count($objectProperties) - 1) ? $objectProperties[$i]
: $objectProperties[$i] . ", ";
$paramString .= ($i === count($objectProperties) - 1) ? "?" : "?,";
}
$tblFields .= ") ";
$paramString .= ")";
return array(
self::$fields => $tblFields,
self::$paramPlaceHolder => $paramString
);
}
public function insert ($object) {
$objectMethods = get_class_methods($object);
$objectGetters = array_values(static::$tblFieldGetters);
$properties = array_keys(static::$tblFieldGetters);
$getters = $this->retrieveObjectGetters($objectGetters, $objectMethods);
$queryComponents = $this->composePDOqueryComponents($properties);
$params = $this->getObjectAttributeValues($getters, $object);
try {
$db = $this->dbFactory->createInstance();
$sql = "INSERT INTO " . static::$tblName;
$sql .= $queryComponents[self::$fields] . "VALUES " . $queryComponents[self::$paramPlaceHolder];
$query = $db->prepare($sql);
$result = $query->execute($params);
return $result;
}
catch (PDOException $e) {
// Check SQL STATE 23000 (Photo name already exist in database).
if ((int)$e->getCode() === 23000) {
// TODO: BAD CODE, CHANG THIS, ALSO IN PhotoUploadController!
throw new PhotoNameAlreadyExistException("A photo with the name " . $object->getName() . " is already uploaded.");
}
throw new \Exception($e->getMessage(), (int)$e->getCode());
}
}
public function fetchAllAssoc () {
try {
$db = $this->dbFactory->createInstance();
$sql = "SELECT * FROM " . static::$tblName;
$query = $db->prepare($sql);
$query->execute();
$result = $query->fetchAll();
if (empty($result)) {
throw new EmptyRecordException(self::$emptyRecordException);
}
if (!$result) {
throw new DatabaseErrorException(self::$databaseFetchAllErrorException);
}
return $result;
}
catch (PDOException $e) {
throw new \Exception($e->getMessage(), (int)$e->getCode());
}
}
public function countAll () {
try {
$db = $this->dbFactory->createInstance();
$sql = "SELECT COUNT(*) FROM " . static::$tblName;
$query = $db->prepare($sql);
$query->execute();
$result = $query->fetch();
if (empty($result)) {
throw new EmptyRecordException(self::$emptyRecordException);
}
if (!$result) {
throw new DatabaseErrorException(self::$databaseFetchErrorException);
}
$sum = (int)array_shift($result);
return $sum;
}
catch (PDOException $e) {
throw new \Exception($e->getMessage(), (int)$e->getCode());
}
}
} | true |
1d6817ef1a70ab6e524d85d3e8a0b76a85815eb0 | PHP | PierreLefeuvre/news | /rest/app/News.php | UTF-8 | 308 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class News extends Model
{
public function getTitleAttribute($value)
{
return ucfirst(mb_strtolower($value));
}
public function getContentAttribute($value)
{
return str_replace('<br>',"\n", $value);
}
}
| true |
583d751deef014f25936805dc9425d62a5c7c708 | PHP | OpencachingTeam/opencaching | /code/htdocs/lib2/translate_filescan.class.php | UTF-8 | 2,837 | 2.921875 | 3 | [] | no_license | <?php
/***************************************************************************
* You can find the license in the docs directory
*
* Unicode Reminder メモ
***************************************************************************/
class translate_filescan
{
private $msFilename;
private $msContent;
public $textlist;
function __construct($sFilename)
{
$this->filelist = array();
$this->msFilename = $sFilename;
$sContent = '';
$hFile = fopen($sFilename, 'rb');
while (!feof($hFile))
$sContent .= fread($hFile, 8192);
fclose($hFile);
$this->msContent = $sContent;
}
function parse()
{
$this->scanTranslationPlaceholders();
$this->scanTranslateFunctionCalls();
}
function scanTranslateFunctionCalls()
{
$nNextPos = strpos($this->msContent, "t"."('");
while ($nNextPos !== false)
{
// check for match
$bMatch = false;
if (substr($this->msContent, $nNextPos-12, 12) == '$translate->')
$bMatch = true;
else
{
if ($nNextPos == 0)
$sPrevChar = ' ';
else
$sPrevChar = substr($this->msContent, $nNextPos-1, 1);
if (preg_match('/^[a-zA-Z0-9_]$/', $sPrevChar) == 0)
$bMatch = true;
}
if ($bMatch == true)
{
$nEnd = $this->findEndOfPHPString($this->msContent, $nNextPos+3);
$nLine = $this->findLineOfPos($nNextPos);
$sText = substr($this->msContent, $nNextPos+3, $nEnd-$nNextPos-3);
$this->textlist[] = array('text' => $sText, 'line' => $nLine);
}
$nNextPos = strpos($this->msContent, "t"."('", $nNextPos+1);
}
}
function findEndOfPHPString($sCode, $nStartSearch)
{
$nEnd = 0;
while ($nEnd==0)
{
$nEnd = strpos($sCode, "'", $nStartSearch);
if (substr($sCode, $nEnd-1, 1) == '\\')
{
$nStartSearch = $nEnd+1;
$nEnd = 0;
}
}
return $nEnd;
}
function scanTranslationPlaceholders()
{
$nNextPos = strpos($this->msContent, '{'.'t');
while ($nNextPos !== false)
{
// check for match
if ((substr($this->msContent, $nNextPos, 3) == '{'.'t}') ||
(substr($this->msContent, $nNextPos, 3) == '{'.'t '))
{
$nStart = strpos($this->msContent, '}', $nNextPos);
$nEnd = strpos($this->msContent, '{/t}', $nNextPos);
$nLine = $this->findLineOfPos($nNextPos);
$sText = substr($this->msContent, $nStart+1, $nEnd-$nStart-1);
// TODO:plural
$this->textlist[] = array('text' => $sText, 'line' => $nLine);
}
$nNextPos = strpos($this->msContent, '{'.'t', $nNextPos+1);
}
}
// TODO: performance ... scan once at __construct and store line positions
function findLineOfPos($nPos)
{
$nLine = 1;
for ($n = 0; $n < $nPos; $n++)
if (substr($this->msContent, $n, 1) == "\n")
$nLine++;
return $nLine;
}
}
?> | true |
1d5ecfc347d3ef3ff044d0200180c9ef7787a4be | PHP | JML32/twitter-like | /php/functions/user.fn.php | UTF-8 | 848 | 3.015625 | 3 | [] | no_license | <?php
function register($db, $username, $password){
$check = $db->prepare("SELECT * FROM users WHERE username = :username");
$check->execute(array(
':username' => $username
));
if ($userExist = $check->fetch()){
// si la function renvoie true c'est que l'utilisateur existe
header('Location : index.php?msg=errorUserExist');
}
else{
//si la function ne renvoie rien c'est que l'utilisateur n'existe pas
// Comme l'utilisateur n'existe pas, on peut l'inserer dans la database
$insert = $db->prepare("INSERT INTO users (username,password, created_at, last_login");
$insert->execute(array(
':unsername' => $username,
':password' => sha1($password),
':created_at' => date('Y-m-d H:i:s'),
':last_login' => date('Y-m-d H:i:s')
));
header('Location:index.php?msg=success');
}
} | true |
81220b3389959ef3127cc11f34816676a1923f1f | PHP | thursdaybw/salsa-demo | /web/modules/salsa_api/src/ApiClient.php | UTF-8 | 4,218 | 2.609375 | 3 | [] | no_license | <?php
namespace Drupal\salsa_api;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Site\Settings;
use Drupal\Core\Url;
use GuzzleHttp\ClientInterface;
/**
* Dummy client. Can use this to simulate calling an API.
*
* This is a super dummy for this purpose, it does very little except
* return OK.
*/
class ApiClient {
/**
* HTTP client.
*
* @var \GuzzleHttp\ClientInterface
*/
protected $client;
/**
* Access to configuration info.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
private $configFactory;
/**
* Constructor.
*
* @param \GuzzleHttp\ClientInterface $client
* HTTP client.
* @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
* Config factory, give access to configuration data.
*/
public function __construct(ClientInterface $client, ConfigFactoryInterface $configFactory) {
$this->client = $client;
$this->configFactory = $configFactory;
}
/**
* Dummy method that would, but doesn't request a bearer token.
*
* For correct bearer token management we should authenticate with the API
* here and retrieve a bearer token and store that temporally.
* When the bearer token expires, then reauthenticate and retrieve a new
* token.
* Depending on the scope of the level of access token type in the API, we
* may also require a refresh token. Implementation here depends on the
* bearer token implementation in the API.
*
* It's also worth mentioning that all communicate that includes the bearer
* token between this application and the API must be sent over HTTPS to
* avoid the token being sniffed in transit.
*
* @return string
* String representation of bearer token.
*/
private function getToken(): string {
return "sometoken";
}
/**
* Get a movie by ID.
*
* @param array $data
* Some data to post. But we don't in this demo.
*
* @return string
* A simple string return for demo purposes, just "OK".
*/
public function postUserData(array $data = []) {
$token = $this->getToken();
$api_key = $this->getApiKey();
$config = $this->configFactory->get('salsa_api_form.settings');
// Get the URL for the API from configuration and append the API key to
// the query.
// Just a very sample get (not even a post).
//
// Ignoring this code as we don't use this $url variable and that generates
// an error.
// @codingStandardsIgnoreStart
$url = Url::fromUri(
$config->get('url'),
);
// @codingStandardsIgnoreEnd
$fields_string = json_encode($data);
/*
* Don't actually send the post, it will fail.
*
* We would do this:
* $response = $this->client->post($url, [
*/
return $this->post($url->getUri(), [
'api_key' => $api_key,
'body' => $fields_string,
'http_errors' => FALSE,
'headers' => [
'Content-Type' => 'application/json',
$headers = [
'Authorization' => 'Bearer ' . $token,
'Accept' => 'application/json',
],
],
]);
}
/**
* Get the API Key from settings.php.
*
* This is a simple way to store the api key.
* This only works if settings.php is not comitted to git
* and also relies on related technologies not exposing settings.php
* to access from outside. There are better/other solutions around depending
* on the context of the project, where it's hosted.
* For example, the key module: https://www.drupal.org/project/key connected
* to an external key management solution.
*
* @return mixed
* Return type depends on the value in the settings.
* It should be a string.
*/
protected function getApiKey() {
return Settings::get('salsa_api_key');
}
/**
* Dummy post, call this instead of the one on http_client.
*
* @param string $uri
* Url to submit to.
* @param array $options
* Options for the post request.
*
* @return \GuzzleHttp\Psr7\Response
* Would return a response, for this demo, i'm just returning a string.
*/
protected function post(string $uri, array $options = []) {
return "OK";
}
}
| true |
e365efe1a49c9c68ca9e46c9e92bdc9659cf9d73 | PHP | pferre/dojos | /src/TicTacToe/Board.php | UTF-8 | 1,502 | 3.265625 | 3 | [] | no_license | <?php
namespace App\TicTacToe;
use App\TicTacToe\Exception\IllegalPlayerMoveException;
class Board
{
/** @var PlayerMove[] */
private $state;
/**
* @param PlayerMove $move
* @throws IllegalPlayerMoveException
*/
public function add(PlayerMove $move): void
{
if (!$this->positionAlreadyTaken($move)) {
throw new IllegalPlayerMoveException("Position {$move->position()} already taken!");
}
$this->state = [$move];
}
public function firstPlayer(): ?Player
{
if ($this->stateIsInitialized()) {
return $this->state[0]->player();
}
return null;
}
public function nextPlayer(): Player
{
$currentPlayer = null;
if ($this->stateIsInitialized()) {
$latestMove = array_pop($this->state);
$currentPlayer = $latestMove->player();
}
if ($currentPlayer instanceof X) {
return new O();
}
return new X();
}
private function positionAlreadyTaken(PlayerMove $move): bool
{
if ($this->stateIsInitialized()) {
foreach ($this->state as $existingMove) {
if ($existingMove->position() === $move->position()) {
return false;
}
}
}
return true;
}
/**
* @return bool
*/
private function stateIsInitialized(): bool
{
return null !== $this->state;
}
}
| true |
5f562f2c68a1ba4c4c80c0f2a3330690b9ce6144 | PHP | AdelekeIO/PAS | /form_functions.php | UTF-8 | 886 | 2.90625 | 3 | [] | no_license | <?php
function check_required_fields($required_array)
{
$field_errors=array();
foreach ($required_array as $fieldname) {
if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && (!is_int($_POST[$fieldname])))){
if (empty($_POST[$fieldname]) && ($_POST[$fieldname]=='0')){
}else{$field_errors[]=$fieldname;}
}
}
return $field_errors;
}
function check_max_field_lenghts($field_legnth_array)
{
$field_errors=array();
foreach ($field_legnth_array as $fieldname => $maxlenght) {
if (strlen(trim(mysql_prep($_POST[$fieldname])))>$maxlenght) {
$field_errors[]=$fieldname;
}
}
return $field_errors;
}
function display_errors($error_array)
{
echo "<p class=\"errors\">";
echo "Please review the following fields:<br/>";
foreach ($error_array as $error) {
echo " - ".$error."<br/>";
}
echo "</p>";
}
?> | true |
b264056e2347e479d9f4bf72fc7549c93cf0b540 | PHP | yongho0720-nsmg/fanta_travel | /app/Console/Commands/CrawlerCheck.php | UTF-8 | 2,832 | 2.546875 | 3 | [] | no_license | <?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\CrawlerLog;
use App\Push;
use App\Board;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class CrawlerCheck extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'crawler:check';
/**
* The console command description.
*
* @var string
*/
protected $description = 'check crawler';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$logs = CrawlerLog::whereBetween('created_at',[Carbon::now()->addhour(-1),Carbon::now()])->get()->last();
$new_cnt = Board::select('type', DB::raw('count(*) as cnt'))->where('created_at','>',Carbon::now()->addhour(-1))->where('type','!=','news')->groupBy('type')->get();
$new_news_cnt = Board::select('type', DB::raw('count(*) as cnt'))->where('validation_at','>',Carbon::now()->addhour(-1))->where('type','=','news')->groupBy('type')->get();
//$cnt = $new_cnt[0]->cnt;
$send_str = "[크롤링 현황]\n";
$new_push_flag = false;
foreach($new_cnt as $cnt){
if(!$logs){
$send_str .= "[fanta_holic] [Error!!] 크롤링 수집이 정상적으로 수행되지 않았습니다.\n";
}else{
$send_str .= "[fanta_holic] - [".$cnt['type']."] 컨텐츠 ".$cnt['cnt']."개\n";
$new_push_flag = true;
}
}
if(isset($new_news_cnt[0]->cnt)){
$send_str .= "[fanta_holic] - [news] 컨텐츠 ".$new_news_cnt[0]->cnt."개\n";
$new_push_flag = true;
}
if($new_push_flag){
Push::create([
'app' => 'fantatravel',
'batch_type' => 'N',
'managed_type' => 'M',
'user_id' => 0,
'title' => '새로운 게시물이 등록되었습니다. ',
'content' => '새로운 게시물이 등록되었습니다.',
'tick' => 0,
'push_type' => 'T',
'action' => 'A',
'state' => 'R',
'start_date' => Carbon::now(),
]);
}
$query_array = array(
'chat_id' => '-1001321023161',
'text' => $send_str,
);
// URL
$request_url = "https://api.telegram.org/bot839567660:AAF2KAiL2QhAPmxRKf5OAlqOVI9vuhO1w70/sendmessage?" . http_build_query($query_array);
$curl_opt = array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $request_url,
);
// curl
$curl = curl_init();
curl_setopt_array($curl, $curl_opt);
var_dump(curl_exec($curl));
//dd($send_str);
}
}
| true |
6a39f719e6d9d2b0211e348d48e854eb42e60d85 | PHP | hyyan/gwp | /helpers/Gwp/Composer/Create.php | UTF-8 | 2,213 | 2.703125 | 3 | [] | no_license | <?php
/*
* This file is part of the hyyan/gwp package.
* (c) Hyyan Abo Fakher <tiribthea4hyyan@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Gwp\Composer;
use Composer\Script\Event;
use Gwp\Util;
/**
* Create Project Script
*
* @author Hyyan
*/
final class Create
{
/**
* Generate salt keys
*
* @param Event $event
* @return int
*/
public static function generateSalts(Event $event)
{
$root = dirname(dirname(dirname(__DIR__)));
$composer = $event->getComposer();
$io = $event->getIO();
$generate_salts = true;
if ($io->isInteractive()) {
$generate_salts = $io->askConfirmation(
'<info>Do you want to generat fresh salt keys ? (Note that this action will override your shared.php config file inside the config dir)'
. '</info> [<comment>Y,n</comment>]? '
, true
);
}
if (!$generate_salts) {
return 1;
}
$service = 'https://api.wordpress.org/secret-key/1.1/salt/';
$salts = @file_get_contents($service);
if (!$salts) {
$io->write("<error>"
. "An error occured while trying to generate the salts keys,"
. "Please try to generate the salt keys manually from the following url : \"" . $service
. "\" Then copy and paste the resault to your shared.php config file inside the config dir."
. "</error>");
return 1;
}
$content = Util::applyTemplate('Composer/shared.php.tpl', array(
'saltKeys' => $salts
));
if (!@file_put_contents($root . '/config/shared.php', $content)) {
$io->write("<error>"
. "An error occured while trying to write the salts keys,"
. "copy and paste the following line to your shared.php config file inside the config dir."
. "\n\n"
. "</error>"
. $salts
);
return 1;
}
}
}
| true |
7674b29ba76fc250ff697a858a5ef4283aeae621 | PHP | nsttam/phpObjet | /index.php | UTF-8 | 756 | 2.859375 | 3 | [] | no_license | <?php
include 'include.php';
$audiRS1 = new Audi('Audi', 'RS1', 100000, 5, 1, 1, 0);
$z900 = new Kawasaki('Z900', 9200, true);
var_dump($audiRS1);
$audiRS1->isQuatro = 10; //pour __set //j'essaie de donner valuer 10 a attribut isQuatro mais lui il est privée, donc j'ai message
//"l'attribute n'existe pas ou est prive" que j'ai mis dans function __set
$z900->topCase=1;//pour __set
$z900->isJaponaise=1;//pour __set
var_dump($z900);
echo ($z900->isJaponaise); //Impossible d'afficher la valeur car is japonaise is private. Message grace a function __get
echo ($z900->toto); //toto n'existe pas
$isJaponnaise = $z900->isJaponaise;//Impossible d'afficher la valeur car is japonaise is private. Message grace a function __get
?>
| true |
2572bfddc7997a15d7d5962f7db007657a0d518f | PHP | burgerballer44/tailgate | /app/Http/Requests/UpdateSeasonRequest.php | UTF-8 | 1,265 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Requests;
use App\Models\Common\DateOrString;
use App\Models\SeasonType;
use App\Models\Sport;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rules\Enum;
class UpdateSeasonRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Handle a passed validation attempt.
*/
protected function passedValidation(): void
{
$this->replace([
'season_start' => DateOrString::fromString($this->season_start),
'season_end' => DateOrString::fromString($this->season_end)
]);
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array|string>
*/
public function rules(): array
{
return [
'name' => 'required|max:255',
'sport' => ['required', new Enum(Sport::class)],
'season_type' => ['required', new Enum(SeasonType::class)],
'season_start' => ['required', 'string', 'max:255'],
'season_end' => ['required', 'string', 'max:255'],
];
}
}
| true |
1d2740d9842c19e52d2718f6b7861d3fb975ef3b | PHP | adrianacerdeira-zz/RecursosPHP | /Aula_47_Classes_e_Objetos_Heranca/metodos_magicos.php | UTF-8 | 3,479 | 4.15625 | 4 | [] | no_license | <?php
class Pessoa
{
private $idade;
private $nome;
public $profissao;
private $attrNaoDeclarados = [];
/**
* Método invocado quando o objeto é instanciado
* Pessoa constructor.
* @param $nome
* @param $idade
* @param $profissao
*/
public function __construct($nome, $idade, $profissao)
{
$this->nome = $nome;
$this->idade = $idade;
$this->profissao = $profissao;
echo "Sou $this->nome, tenho $this->idade e minha profissão é $this->profissao<br>";
}
/**
* Método chamado quando o objeto é destruído
*/
public function __destruct()
{
echo '<br>Ai, ai<br>';
}
/**
* Sempre que um objeto entrar em um contexto em que ele é convertido em um string este método é chamado
* @return string
*/
public function __toString()
{
// TODO: Implement __toString() method.
return "Sou $this->nome, tenho $this->idade e minha profissão é $this->profissao e fui convertido a um string<br>";
}
/**
* Sempre que vc chamar um método que não existe vai chamar o método call sendo que o nome vai ser um string e os argumentos um array
* @param $name
* @param $arguments
*/
public function __call($name, $arguments)
{
echo "<br>Oops o método $name não existe e não pode ser chamado com os ";
print_r($arguments);
}
/**
* Sempre que vc chamar um método static que não existe vai chamar o método call sendo que o nome vai ser um string e os argumentos um array
* @param $name
* @param $arguments
*/
public static function __callStatic($name, $arguments)
{
echo "<br>Oops o método static $name não existe e não pode ser chamado com os ";
print_r($arguments);
}
/**
* Método chamado sempre que eu tentar acessar um atributo que não existe, ele não pode declarar novos atributos
* @param $name
*/
public function __get($name)
{
array_push($this->attrNaoDeclarados, $name);
// $this->$name = $name;
// $this->tentei = "Tentei aqui";
echo "Lendo um atributo não declarado $name<br>";
return $name;
}
/**
* Método chamado quando tento dar um valor a um atributo não declarado
* @param $name
* @param $value
*/
public function __set($name, $value)
{
$this->attrNaoDeclarados[$name] = $value;
unset($this->$name);
}
/**
* Chamado ao tentar usar isset em uma propriedade privada ou protegida
* @param $name
*/
public function __isset($name)
{
echo "<br>A propriedade $name não é pública, você não pode acessá-la para ver se está declarada<br>";
return true;
}
/**
* Chamado ao tentar usar unset em uma propriedade privada ou protegida
* @param $name
*/
public function __unset($name)
{
echo "<br>A propriedade $name não é pública, você não pode acessá-la para destruí-la";
unset($this->$name);
}
/**
* Método que deve retornar um array e que será chamado em situações onde um debug é necessário
* @return string[]
*/
public function __debugInfo()
{
// return ['Porque vc quer saber de mim?<br>'];
return ["primeiro" => 'Porque vc quer saber de mim?<br>', "segundo" => "Este é o segundo elemento"];
}
}
?> | true |
73744846c7c4edfd3f2b53c9838ea500f2de4dcf | PHP | yhprogram/study | /samaple01.php | UTF-8 | 234 | 2.640625 | 3 | [] | no_license | <?php
$price = 12300;
$total = $price * 1.05;
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>sample page</title>
</head>
<body>
<?php echo "PHPによるテキストです。"; ?>
</body>
</html> | true |
aad697937f4feb1064bdd94d6db17c127f811964 | PHP | luongyen123/vitc | /HOANGDUCKIEN/demo.php | UTF-8 | 2,720 | 3.15625 | 3 | [] | no_license | <?php
// $mang_so_nguyen = [60, 62, 68, 71, 68, 73, 85, 66, 64, 76, 63, 81, 76, 73,
// 68, 72, 73, 75, 65, 74, 63, 67, 65, 64, 68, 73, 75, 79, 73];
// foreach ($mang_so_nguyen as $value) {
// $tong_gia_tri=0;
// $tong_gia_tri+=$value;
// $do_dai=count($mang_so_nguyen);
// }
// $tb= $tong_gia_tri/$do_dai;
// echo "Giá trị trung bình:$tb ";
// tìm giá trị lớn nhất nhỏ nhất của một tập hợp các mảng số nguyên
$mang1 = array(360,310,310,330,313,375,456,111,256,100);
$mang2 = array(350,340,356,330,321);
$mang3 = array(630,340,570,635,434,255,298);
$max = 0;
$min=0;
// Mảng 1
for ($i = 0; $i < count($mang1); $i++)
{
if ($max == 0){
$max = $mang1[$i];
}
else {
if ($mang1[$i] > $max){
$max = $mang1[$i];
}
}
}
// tìm giá trị min
for ($i = 0; $i < count($mang1); $i++)
{
if ($min == 0){
$min = $mang1[$i];
$positionmin = $i;
}
else {
if ($mang1[$i] < $min){
$min = $mang1[$i];
$positionmin = $i;
}
}
}
echo "các pt trong mảng 1: ";
foreach($mang1 as $value) {
echo "$value.", "";
}
echo "<br>Giá trị lớn nhất của mảng 1: $max";
echo "Giá trị nhỏ nhất của mảng 1: $min";
echo "<br><hr>";
// mảng 2
$max2 = 0;
for ($i = 0; $i < count($mang2); $i++)
{
if ($max2 == 0){
$max2 = $mang2[$i];
}
else {
if ($mang2[$i] > $max2){
$max2 = $mang2[$i];
}
}
}
// tìm giá trị min
$min2=0;
for ($i = 0; $i < count($mang2); $i++)
{
if ($min2 == 0){
$min2 = $mang2[$i];
}
else {
if ($mang2[$i] < $min2){
$min2 = $mang2[$i];
}
}
}
echo "các pt trong mảng 2: ";
foreach($mang2 as $value) {
echo " $value.", "";
}
echo "<br>Giá trị lớn nhất của mảng 2: $max2";
echo "Giá trị nhỏ nhất của mảng 2: $min2";
// mảng 3
$max3 = 0;
for ($i = 0; $i < count($mang3); $i++)
{
if ($max3 == 0){
$max3 = $mang3[$i];
}
else {
if ($mang3[$i] > $max3){
$max3 = $mang3[$i];
}
}
}
// tìm giá trị min
$min3=0;
for ($i = 0; $i < count($mang3); $i++)
{
if ($min3 == 0){
$min3 = $mang3[$i];
}
else {
if ($mang3[$i] < $min3){
$min3 = $mang3[$i];
}
}
}
echo "<br><hr>các pt trong mảng 3: ";
foreach($mang3 as $value) {
echo " $value.", "";
}
echo "<br>Giá trị lớn nhất của mảng 3: $max3";
echo "Giá trị nhỏ nhất của mảng 3: $min3";
?>
| true |
413d7d8b335125877cf257927f5201a874e5ce98 | PHP | czim/laravel-cms-models | /src/Support/Strategies/Traits/HasMorphRelationStrategyOptions.php | UTF-8 | 1,331 | 2.59375 | 3 | [
"MIT"
] | permissive | <?php
namespace Czim\CmsModels\Support\Strategies\Traits;
use Czim\CmsModels\Contracts\ModelInformation\Data\Form\ModelFormFieldDataInterface;
use Czim\CmsModels\ModelInformation\Data\Form\ModelFormFieldData;
/**
* Class HasMorphRelationStrategyOptions
*
* For form field strategy data that will have options according to this configuration pattern:
* https://github.com/czim/laravel-cms-models/blob/master/documentation/FormFieldStoreStrategies/RelationSingleMorph.md
*/
trait HasMorphRelationStrategyOptions
{
/**
* Returns the model class names that the model may be related to.
*
* @param ModelFormFieldDataInterface|ModelFormFieldData $data
* @return string[]
*/
protected function getMorphableModelsForFieldData(ModelFormFieldDataInterface $data)
{
$modelsOption = array_get($data->options(), 'models', []);
// Users may have set the string value with the model class, instead of a class => array value pair
$modelClasses = array_map(
function ($key, $value) {
if (is_string($value)) {
return $value;
}
return $key;
},
array_keys($modelsOption),
array_values($modelsOption)
);
return array_unique($modelClasses);
}
}
| true |
fa68c1fa9937c950ea560038fee3abc5ab5f33cb | PHP | PrashishPandey/Project1 | /laravel_8_api_crud/app/Http/Controllers/user_groups.php | UTF-8 | 3,653 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\model\user_group;
use App\model\user;
class user_groups extends Controller
{
//$ug=new user_group();
//$u=new user();
//-----insert function----
public function insert_group(Request $request){
//object create for user_group model
$ug=new user_group();
//get value
$ug-> group_id = $request-> group_id;
$ug-> group_name = $request-> group_name;
$ug-> group_type = $request-> group_type;
//insert
$ug-> save();
//check
if($ug-> save()){
return ['sucess'=>$ug];
}else{
return ['sucess'=>'operation failed'];
}
}
//------
public function insert_user(Request $request){
$u=new user();//object for use model
//data get
$u-> user_id = $request-> user_id;
$u-> group_id = $request-> group_id;
$u-> user_name = $request-> user_name;
$u-> user_pwd = $request-> user_pwd;
$u-> user_display_name = $request-> user_display_name;
$u-> user_mobile = $request-> user_mobile;
$u-> user_email = $request-> user_email;
$u-> registered_date = $request-> registered_date;
$u-> user_status = $request-> user_status;
//insert function call
$u-> save();
// check
if($u-> save()){
return ['sucess'=> $u];
}else{
return ['sucess'=>'operation failed'];
}
}
//----read func----
public function read_group(){
//to read value
return user_group::all();
}
public function read_user(){
return user::all();
}
//------ to update the table
public function update_group(Request $request,$group_id){
$groupup= user_group::where('group_id',$group_id);//find row
$groupup->update($request->all());//update row
return ['sucess'=>'updated group'];
}
//---update for user---
public function update_user(Request $request,$user_id){
//$userup=new user();
$userup= user::where('user_id',$user_id);//find row
//update value
/*
$userup-> user_id = $request-> input('user_id');
$userup-> group_id = $request-> input('group_id');
$userup-> user_name = $request-> input('user_name');
$userup-> user_pwd = $request-> input('user_pwd');
$userup-> user_display_name = $request-> input('user_display_name');
$userup-> user_mobile = $request-> input('user_mobile');
$userup-> user_email = $request-> input('user_email');
$userup-> registered_date = $request-> input('registered_date');
$userup-> user_status = $request-> input('user_status');
*/
//$userup->update();
$userup->update($request->all());// update the fields
return ['sucess'=> "updated"];
}
//--- to delete the column
//--delete for user_group
public function delete_usergroup(Request $request,$group_id){
$groupdel=user_group::where('group_id',$group_id);
$groupdel->delete();
return ['sucess'=>$groupdel];
}
//---delete for user
public function delete_user(Request $request, $user_id){
$userdel= user::where('user_id',$user_id);//it finds the specific row
//$userdel = user:: find($user_id);// it finds the user_id
$userdel-> delete();
return ['sucess'=>$userdel];
}
//---show by id
public function showbygroupid(Request $request,$group_id){
return user_group::where('group_id',$group_id)->get();
}
//---
public function showbyuserid(Request $request,$user_id){
//$showid= user::where('user_id',$user_id);
return user::where('user_id',$user_id)->get();
}
//----
}
| true |
2b4dc325e090972fad8fba1f91f37b43dc5eee20 | PHP | janainafortunato/Estudos_php | /classes/Composicao.php | UTF-8 | 415 | 2.515625 | 3 | [] | no_license | <?php
include_once '../Fornecedor.php';
include_once '../Contato.php';
//instancia novo fornecedor
$fornecedor = new Fornecedor;
$fornecedor->razaoSocial ='Produto Bom Gosto S.A.';
//atribuir informações de contato
$fornecedor->setContato('Mauro', '51 1234-5678', 'mauro@bomgosto.com.br');
//inprime informações
echo $fornecedor->razaoSocial . "<br>";
echo "Informações de contato <br>";
echo $fornecedor->getContato(); | true |
22a25e98b5720f38a89135102013e2a30cedec4e | PHP | Asera/TimeCounter | /timecount.php | UTF-8 | 358 | 3.046875 | 3 | [] | no_license | #! /usr/bin/php
<?php
require_once "TimeCounter.php";
$stdin = fopen('php://stdin', 'r');
$stdout = fopen('php://stdout', 'w');
$text = '';
while (!feof($stdin)) {
$text = $text.fgetc($stdin);
}
fputs($stdout, str_pad('', 20, '-').PHP_EOL);
$timeCounter = new TimeCounter($text);
$totalTime = $timeCounter->getTotalTime();
fputs($stdout, $totalTime); | true |
f4504c2fc0b6370ddf67e53754884ac2514dc2ef | PHP | st-universe/core | /src/Module/Colony/Lib/ColonyMenu.php | UTF-8 | 819 | 2.765625 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace Stu\Module\Colony\Lib;
use request;
use Stu\Component\Colony\ColonyEnum;
class ColonyMenu
{
private ?int $selectedColonyMenu;
public function __construct(?int $selectedColonyMenu)
{
$this->selectedColonyMenu = $selectedColonyMenu;
}
/**
* @param null|int $value
*
* @return false|string
*/
public function __get($value)
{
$menuType = request::getInt('menu');
if ($this->selectedColonyMenu === $value) {
return 'selected';
}
if ($menuType === $value) {
return 'selected';
}
if ($value === ColonyEnum::MENU_INFO && $menuType === 0 && $this->selectedColonyMenu === null) {
return 'selected';
}
return false;
}
}
| true |