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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
f5cd88df4c080752dc9c30f502dcc36f4819a780 | PHP | juliangut/spiral | /src/Exception/TransportException.php | UTF-8 | 836 | 2.796875 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/*
* A PSR7 aware cURL client (https://github.com/juliangut/spiral).
*
* @license BSD-3-Clause
* @link https://github.com/juliangut/spiral
* @author Julián Gutiérrez <juliangut@gmail.com>
*/
namespace Jgut\Spiral\Exception;
/**
* Transport exception.
*/
class TransportException extends \RuntimeException
{
/**
* @var string
*/
protected $category;
/**
* TransportException constructor.
*
* @param string $message
* @param int $code
* @param string $category
*/
public function __construct($message, $code = 0, $category = '')
{
parent::__construct($message, $code);
$this->category = trim($category);
}
/**
* Retrieve category.
*
* @return string
*/
public function getCategory()
{
return $this->category;
}
}
| true |
1b616d6496eb54eaf1c2d32ac7f736a0c1226550 | PHP | alertux/covid | /app/Http/Controllers/Controller.php | UTF-8 | 5,288 | 2.71875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Auth;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
private function basico($numero) {
$valor = array ('uno','dos','tres','cuatro','cinco','seis','siete','ocho','nueve','diez',
'once', 'doce', 'trece', 'catorce', 'quince', 'dieciséis', 'diecisiete', 'dieciocho', 'diecinueve',
'veinte', 'veintiuno', 'veintidos', 'veintitres', 'veinticuatro', 'veinticinco', 'veintiséis','veintisiete','veintiocho','veintinueve');
return $valor[$numero - 1];
}
private function decenas($n) {
$decenas = array (30=>'treinta',40=>'cuarenta',50=>'cincuenta',60=>'sesenta',70=>'setenta',80=>'ochenta',90=>'noventa');
if( $n <= 29) return $this->basico($n);
$x = $n % 10;
if ( $x == 0 ) {
return $decenas[$n];
} else
return $decenas[$n - $x].' y '.$this->basico($x);
}
private function centenas($n) {
$cientos = array (100 =>'cien',200 =>'doscientos',300=>'trecientos',
400=>'cuatrocientos', 500=>'quinientos',600=>'seiscientos',
700=>'setecientos',800=>'ochocientos', 900 =>'novecientos');
if( $n >= 100) {
if ( $n % 100 == 0 ) {
return $cientos[$n];
} else {
$u = (int) substr($n,0,1);
$d = (int) substr($n,1,2);
return (($u == 1)?'ciento':$cientos[$u*100]).' '.$this->decenas($d);
}
} else
return $this->decenas($n);
}
private function miles($n) {
if($n > 999) {
if( $n == 1000)
return 'mil';
else {
$l = strlen($n);
$c = (int)substr($n,0,$l-3);
$x = (int)substr($n,-3);
if($c == 1) {$cadena = 'mil '.$this->centenas($x);}
else if($x != 0) {$cadena = $this->centenas($c).' mil '.$this->centenas($x);}
else $cadena = $this->centenas($c). ' mil';
return $cadena;
}
} else
return $this->centenas($n);
}
private function millones($n) {
if($n == 1000000) {return 'un millón';}
else {
$l = strlen($n);
$c = (int)substr($n,0,$l-6);
$x = (int)substr($n,-6);
if($c == 1) {
$cadena = ' millón ';
} else {
$cadena = ' millones ';
}
return $this->miles($c).$cadena.(($x > 0)?$this->miles($x):'');
}
}
public function convertir($n) {
switch (true) {
case ( $n >= 1 && $n <= 29) : return $this->basico($n); break;
case ( $n >= 30 && $n < 100) : return $this->decenas($n); break;
case ( $n >= 100 && $n < 1000) : return $this->centenas($n); break;
case ($n >= 1000 && $n <= 999999): return $this->miles($n); break;
case ($n >= 1000000): return $this->millones($n);
}
}
public function getAccessToken(){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://accounts.zoho.com/oauth/v2/token?client_id=1000.9FGHBDOJ3Q930ODLM822GFHLWKQDEH&grant_type=refresh_token&client_secret=f2f909f0da7e6eecfd3ab1a9ea770f9e653c1b9dc9&refresh_token=1000.a6df690d348b2fdfe5362836776c5df0.d86740f8481b2498987919b140c2b5a8");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
$infoObj = json_decode($server_output);
curl_close ($ch);
if( isset($infoObj->access_token) ) {
Request()->session()->put('access_token', $infoObj->access_token);
return true;
}
return false;
}
public function getInvoiceList($oauth_token, $server_url, $page, $page_limit, $search_text){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$server_url."&page=".$page."&per_page=".$page_limit."&search_text=".$search_text);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Zoho-oauthtoken '.$oauth_token,
'Content-Type: application/x-www-form-urlencoded;charset=UTF-8"'
));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
return json_decode($server_output);
}
public function getInvoiceObj($oauth_token, $server_url, $creditnote_id){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$server_url.$creditnote_id."?organization_id=633541911");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Zoho-oauthtoken '.$oauth_token,
'Content-Type: application/x-www-form-urlencoded;charset=UTF-8"'
));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
return json_decode($server_output);
}
}
| true |
b486cfc22f685391f4b569fd7a72de16469a8517 | PHP | chuppistyle/ratchet | /src/Chat.php | UTF-8 | 1,108 | 3 | 3 | [] | no_license | <?php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
public $connect;
protected $clients;
public function __construct()
{
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
echo "New conntection! ({$conn->resourceId})";
print_r($conn);
}
public function onMessage(ConnectionInterface $from, $msg) {
$numRecv = count($this->clients) - 1;
echo $msg;
$msgObject = json_decode($msg);
foreach ($this->clients as $client) {
$client->send($msgObject->fname.'Hello from server');
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
| true |
f2c222088b6fab74e40f7266463c7bcc14f57686 | PHP | Gaetan-R/Paint-Shop | /src/DataFixtures/AppFixtures.php | UTF-8 | 3,050 | 2.671875 | 3 | [] | no_license | <?php
namespace App\DataFixtures;
use App\Entity\Blogpost;
use App\Entity\Categorie;
use App\Entity\Peinture;
use App\Entity\User;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
use Faker\Factory;
use Faker;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
class AppFixtures extends Fixture
{
private $encoder;
public function __construct(UserPasswordEncoderInterface $encoder){
$this->encoder = $encoder;
}
public function load(ObjectManager $manager)
{
$faker = Faker\Factory::create('fr_FR');
// Création d'un utilisateur
$user = new User();
$user->setEmail('banana@test.com')
->setPrenom($faker->firstName)
->setNom($faker->lastName)
->setRoles(['ROLE_PEINTRE'])
->setTelephone($faker->phoneNumber)
->setAPropos($faker->text);
$password = $this->encoder->encodePassword($user, 'password');
$user->setPassword($password);
$manager->persist($user);
// Création de 10 blogpost
for ($i=0; $i < 10; $i++) {
$blogpost = new Blogpost();
$blogpost->setTitre($faker->word(3, true))
->setCreatedAt($faker->dateTimeBetween('-6 month', 'now'))
->setContenu($faker->text(350))
->setSlug($faker->slug(3))
->setFile('Dk55.jpg')
->setPublication($faker->dateTimeBetween('-6 month', 'now'))
->setUser($user);
$manager->persist($blogpost);
}
// Création de 5 Catégories
for ($k=0; $k < 5; $k++) {
$categorie = new Categorie();
$categorie->setNom($faker->word)
->setDescription($faker->text)
->setCreatedAt($faker->dateTimeBetween('-6 month', 'now'))
->setFile('tableau_gaming_donkey_kong.jpg')
->setSlug($faker->slug);
$manager->persist($categorie);
//Création de 2 Peintures/catégorie
for ($j=0; $j < 2; $j++) {
$peinture = new Peinture();
$peinture->setNom($faker->word(3, true))
->setLargeur($faker->randomFloat(2,20,60))
->setHauteur($faker->randomFloat(2, 20,60))
->setEnVente($faker->randomElement([true, false]))
->setDateRealisation($faker->dateTimeBetween('-6 month', 'now'))
->setCreatedAt($faker->dateTimeBetween('-6 month', 'now'))
->setDescription($faker->text)
->setPrix($faker->randomFloat(2, 100, 9999))
->setPortfolio($faker->randomElement([true, false]))
->setUser($user)
->setFile('tableau_gaming_donkey_kong.jpg')
->setSlug($faker->slug)
->addCategorie($categorie);
$manager->persist($peinture);
}
}
$manager->flush();
}
}
| true |
cc6a49af4f4e7ebdee7075ee38c82a1bea3b2664 | PHP | PraktikumWebDasar41-02/modul5-ta-frznst | /s1.php | UTF-8 | 4,675 | 2.765625 | 3 | [] | no_license | <?php
include 'conn.php';
session_start();
if(isset($_POST['logout'])){
session_destroy();
}
if(isset($_SESSION['nim'])){
header("location:s2.php");
}
if (isset($_POST['submit'])) {
$nama=$_POST['nama'];
$nim=$_POST['nim'];
$email=$_POST['email'];
$tanggal=$_POST['tanggal'];
$fakultas=$_POST['fakultas'];
$prodi=$_POST['prodi'];
$cek=[];
if(empty($nama)){
$cek[0]="Nama harus diisi";
}
elseif(is_numeric($nama)==TRUE){
$cek[0]="Inputan Salah";
}
elseif(strlen(trim($nama," "))>20){
$cek[0]="Nama tidak boleh lebih dari 20 karakter";
}
//nama
if(empty($nim)){
$cek[1]="NIM harus diisi";
}
elseif(is_numeric($nim)==FALSE){
$cek[1]="Inputan Salah";
}
elseif(strlen(trim($nim," "))>10){
$cek[1]="NIM tidak boleh lebih dari 10 karakter";
}
//nim
if(empty($email)){
$cek[2]="Email harus diisi";
}
elseif(!preg_match("/@/",$email)&&!preg_match("/.com/",$email)){
$cek[2]="Inputan Salah";
}
//email
if(empty($tanggal)){
$cek[3]="Tanggal harus diisi";
}
//tanggal
if(empty($fakultas)){
$cek[4]="Fakultas harus dipilih";
}
//fakultas
if(empty($prodi)){
$cek[5]="Prodi harus dipilih";
}
//prodi
// print_r($cek);
else{
$_SESSION['nim']=$nim;
insert($nama,$nim,$email,$tanggal,$fakultas,$prodi);
header("location:s2.php");
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>soal1</title>
</head>
<body>
<form action="" method="POST">
<table>
<tr><td>Masukan nama </td><td><input type="text" name="nama"
value="<?php
if(isset($_POST['submit'])){
if(empty($cek[0])){echo $nama;}
}?>"
></td></tr>
<?php
if(!empty($cek[0])){
echo"<tr><td></td><td><mark>*".$cek[0]."</mark></td></tr>";
}
?>
<tr><td>Masukan nim </td><td><input type="text" name="nim"
value="<?php
if(isset($_POST['submit'])){
if(empty($cek[1])){echo $nim;}
}?>"
></td></tr>
<?php
if(!empty($cek[1])){
echo"<tr><td></td><td><mark>*".$cek[1]."</mark></td></tr>";
}
?>
<tr><td>Masukan email</td><td><input type="text" name="email"
value="<?php
if(isset($_POST['submit'])){
if(empty($cek[2])){echo $email;}
}?>"
></td>
<?php
if(!empty($cek[2])){
echo"<tr><td></td><td><mark>*".$cek[2]."</mark></td></tr>";
}
?>
<tr><td>Masukan tanggal</td><td><input type="date" name="tanggal"
value="<?php
if(isset($_POST['submit'])){
if(empty($cek[3])){echo $tanggal;}
}?>"
></td>
<?php
if(!empty($cek[3])){
echo"<tr><td></td><td><mark>*".$cek[3]."</mark></td></tr>";
}
?>
<tr><td>Pilih Fakultas</td><td><SELECT name="fakultas">
<option value="" selected>Pilih</option>
<option value="FIT" >FIT</option>
<option value="FIK" >FIK</option>
<option value="FKB" >FKB</option>
<option value="FEB" >FEB</option>
<option value="FTE" >FTE</option>
<option value="FRI" >FRI</option>
<option value="FIF" >FIF</option>
</td>
<?php
if(!empty($cek[4])){
echo"<tr><td></td><td><mark>*".$cek[4]."</mark></td></tr>";
}
?>
<tr><td>Pilih Prodi</td><td><SELECT name="prodi">
<option value="" selected>Pilih</option>
<option value="Manajemen Infromatika">MI</option>
<option value="Teknik Informatika" >IF</option>
<option value="Teknik Telekomunikasi" >TT</option>
<option value="Perhotelan" >Perhotelan</option>
<option value="Manajemen Pemasaran" >MP</option>
</td>
<?php
if(!empty($cek[5])){
echo"<tr><td></td><td><mark>*".$cek[5]."</mark></td></tr>";
}
?>
<tr><td><input type="submit" name="submit" value="submit"> </td></tr>
</table>
</form>
</body>
</html>
| true |
d478b5beccd58369ecfd476093ef9c05474392b1 | PHP | yell0ws/ddd-sales | /src/Infrastructure/Persistance/InMemory/Payment/InMemoryPaymentRepository.php | UTF-8 | 1,071 | 2.921875 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace App\Infrastructure\Persistance\InMemory\Payment;
use App\Domain\Payment\Model\Payment;
use App\Domain\Payment\Repository\PaymentRepository;
use App\Domain\Payment\ValueObject\PaymentId;
use Exception;
class InMemoryPaymentRepository implements PaymentRepository
{
/**
* @var Payment[]|array
*/
private $payments;
/**
* @param array|Payment[] $payments
*/
public function __construct(array $payments)
{
foreach ($payments as $payment) {
$this->payments[(string) $payment->getId()] = $payment;
}
}
/**
* @param PaymentId $paymentId
*
* @return Payment
*
* @throws Exception
*/
public function find(PaymentId $paymentId): Payment
{
if (false === \array_key_exists((string) $paymentId, $this->payments)) {
throw new Exception(
\sprintf('Not found payment with uuid %s', (string) $paymentId)
);
}
return $this->payments[(string) $paymentId];
}
}
| true |
52f06b86354905ad06796030dbd9e3ac0a5437ef | PHP | wombatastronaut/php-tdd | /tests/ReceipTest.php | UTF-8 | 1,375 | 2.84375 | 3 | [] | no_license | <?php
namespace Tests;
require dirname(dirname(__FILE__)) . '/vendor' . '/autoload.php';
use PHPUnit\Framework\TestCase;
use App\Receipt;
class ReceiptTest extends TestCase
{
public function setUp()
{
$this->receipt = new Receipt();
}
/**
* @test
*
* @dataProvider getTheTotalProvider
*/
public function it_can_get_the_total($items, $expected)
{
$coupon = null;
$actual = $this->receipt->getTotal($items, $coupon);
$this->assertEquals(
$expected,
$actual,
"It should return {$expected}"
);
}
/** @test */
public function it_can_get_the_total_and_coupon_with_exception()
{
$items = [1, 2, 3, 4, 5];
$coupon = 1.20;
$this->expectException('BadMethodCallException');
$this->receipt->getTotal($items, $coupon);
}
public function getTheTotalProvider()
{
return [
[[1, 2, 3, 4, 5], 15],
[[0, 5, 7, 2, 5], 19],
[[8, 2, 3, 1, 7], 21]
];
}
/** @test */
public function it_can_get_the_tax()
{
$amount = 10.00;
$tax = 0.10;
$actual = $this->receipt->getTax($amount, $tax);
$this->assertEquals(1.00, $actual);
}
public function tearDown()
{
unset($this->receipt);
}
} | true |
054073646da5cf1d1e006b991ddb3a822a3d0330 | PHP | Big-Shark/Farpost-app | /src/Service/ImageService.php | UTF-8 | 2,306 | 2.625 | 3 | [] | no_license | <?php
namespace App\Service;
use App\Component\Db;
class ImageService {
protected $db;
function __construct(Db $db)
{
$this->db = $db;
}
public function getImage($uid) {
$sql = "SELECT id, img, uid, date FROM image WHERE uid = :uid";
$result = $this->db->prepare($sql);
$result->bindParam('uid', $uid, PDO::PARAM_STR);
$result->execute();
return $result->fetchAll();
}
public function showImage($id) {
$sql = "SELECT img FROM image WHERE id = :id";
$result = $this->db->prepare($sql);
$result->bindParam('id', $id, PDO::PARAM_STR);
$result->execute();
$img = $result->fetch();
return $img['img'];
}
public function checkAuth() {
if (isset($_SESSION['user'])) {
return $_SESSION['user'];
}
header('Location: /user/registration');
die();
}
public function insertImage($uid) {
$file = $_FILES['file'];
$uploaddir = dirname($_SERVER['SCRIPT_FILENAME']) . "/UploadedFiles/";
$year = date("Y");
$month = date("m");
$day = date("d");
if (!file_exists("$uploaddir$year/")) {
mkdir("$uploaddir$year/", 0777);
}
if (!file_exists("$uploaddir/$year/$month/")) {
mkdir("$uploaddir$year/$month/", 0777);
}
if (!file_exists("$uploaddir$year/$month/$day/")) {
mkdir("$uploaddir$year/$month/$day/", 0777);
}
$info = pathinfo($file['name']);
$ext = empty($info['extension']) ? "" : "." . $info['extension'];
$uploadfile = "$year/$month/$day/" . $this->makeSeed() . $ext;
if (move_uploaded_file($file['tmp_name'], $uploaddir . $uploadfile)) {
$sql = "INSERT INTO image (img, uid) VALUES (:img, :uid) RETURNING id, img";
$result = $this->db->prepare($sql);
$result->bindParam('img', $uploadfile, PDO::PARAM_STR);
$result->bindParam('uid', $uid, PDO::PARAM_STR);
$result->execute();
$img = $result->fetch();
}
return $img;
}
private function makeSeed() {
list($usec, $sec) = explode(' ', microtime());
return $sec . (int)($usec * 100000);
}
}
| true |
726da18a8eba6490126e7cb2f95aa8ae72d330dd | PHP | milanvrba/freeman | /application/backend/modules/board/models/User.php | UTF-8 | 2,043 | 2.640625 | 3 | [] | no_license | <?php
class User extends SuperModel
{
protected $_data = array(
'id' => null,
'login' => null,
'password' => null,
'username' => null,
'date_login' => null,
'admin' => null,
);
protected $_formName = 'LoginForm';
public function authenticate()
{
$username = $this->login;
$password = $this->password;
$db = Zend_Registry::get('db');
$authAdapter = new Zend_Auth_Adapter_DbTable($db);
$authAdapter->setTableName('managers');
$authAdapter->setIdentityColumn('login');
$authAdapter->setCredentialColumn('password');
// Set the input credential values to authenticate against
$authAdapter->setIdentity($username);
$authAdapter->setCredential($password);
// do the authentication
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($authAdapter);
if ($result->isValid())
{
$data = $authAdapter->getResultRowObject(null, 'password');
$role = $this->getRole($data->id);
$data->role = $role;
$auth->getStorage()->write($data);
$lang = new Zend_Session_Namespace('Default');
if (!isset($lang->language)) {
$lang->language = 1;
Zend_Registry::set('lang', $lang->language);
}
return true;
}
else if (!$result->isValid()) {
$this->_error = Errors::getError(200);
return false;
}
else {
$this->_error = Errors::getError(201);
return false;
}
}
public function getRole($id)
{
$db = Zend_Registry::get('db');
return $db->fetchOne('SELECT g.group_type FROM managers AS m
LEFT JOIN groups AS g
on m.group_id = g.id
WHERE m.id = "' . $id . '"');
}
} | true |
9d25c14a7ea9ba6ed9963fcac839758263215c85 | PHP | gobb/Breadcrumbs | /tests/Breadcrumbs/Tests/TrailTest.php | UTF-8 | 2,182 | 2.578125 | 3 | [] | no_license | <?php
namespace Breadcrumb\Tests;
use Breadcrumbs\Trail;
use Breadcrumbs\Crumb;
class TrailTest extends \PHPUnit_Framework_TestCase
{
/**
* @covers Breadcrumb\Trail::count
*/
public function testCrumbs()
{
$trail = new Trail();
$crumb1 = new Crumb('homepage', '/');
$crumb2 = new Crumb('foo', '/foo');
$this->assertEquals(0, count($trail));
$trail->add($crumb1);
$this->assertEquals(1, count($trail));
$trail->add($crumb2);
$this->assertEquals(2, count($trail));
$expected = array($crumb1, $crumb2);
$this->assertEquals($expected, $trail->getCrumbs());
}
public function testAdd()
{
$trail = new Trail();
$crumb0 = new Crumb('homepage', '/');
$crumb1 = new Crumb('foo', '/foo');
$trail->add($crumb0);
$this->assertEquals($trail, $crumb0->getTrail());
$trail[] = $crumb1;
$this->assertEquals($trail, $crumb1->getTrail());
}
public function testGet()
{
$trail = new Trail();
$crumb0 = new Crumb('homepage', '/');
$crumb1 = new Crumb('foo', '/v');
$trail->add($crumb0);
$this->assertEquals($crumb0, $trail->get(0));
$trail[] = $crumb1;
$this->assertEquals($crumb1, $trail[1]);
}
public function testHas()
{
$trail = new Trail();
$crumb0 = new Crumb('homepage', '/');
$trail->add($crumb0);
$this->assertTrue($trail->has(0));
$crumb1 = new Crumb('foo', '/foo');
$trail[] = $crumb1;
$this->assertTrue(isset($trail[1]));
}
public function testRemove()
{
$trail = new Trail();
$crumb0 = new Crumb('homepage', '/');
$crumb1 = new Crumb('foo', '/foo');
$crumb2 = new Crumb('bar', '/bar');
$trail[] = $crumb0;
$trail[] = $crumb1;
$trail[] = $crumb2;
$this->assertEquals(3, count($trail));
$trail->remove(2);
$this->assertEquals(2, count($trail));
unset($trail[1]);
$this->assertEquals(1, count($trail));
$this->assertEquals($crumb0, $trail[0]);
}
}
| true |
e545a6b1ba874569e0879872a3478d7259dbea0f | PHP | buchunzai7/ETShop-for-PHP-Yii2 | /common/models/CartItemAttr.php | UTF-8 | 2,689 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
/**
* ETShop-for-PHP-Yii2
*
* @author Tony Wong
* @date 2015-05-18
* @email 908601756@qq.com
* @copyright Copyright © 2015年 EleTeam
* @license The MIT License (MIT)
*/
namespace common\models;
use Yii;
use common\components\ETActiveRecord;
/**
* This is the model class for table "cart_item_attr".
*
* @property integer $id
* @property integer $item_id 来自CartItem::$id
* @property integer $attr_item_id 来自ProductAttrItem::$id
* @property integer $attr_item_value_id 来自ProductAttrItemValue::$id
* @property integer $status
* @property integer $created_at
* @property integer $updated_at
*
* @property ProductAttrItem $attrItem
* @property ProductAttrItemValue $attrItemValue
* @property CartItem $item
*/
class CartItemAttr extends ETActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'cart_item_attr';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['item_id', 'attr_item_id', 'attr_item_value_id', 'status', 'created_at', 'updated_at'], 'integer'],
[['attr_item_id'], 'exist', 'skipOnError' => true, 'targetClass' => ProductAttrItem::className(), 'targetAttribute' => ['attr_item_id' => 'id']],
[['attr_item_value_id'], 'exist', 'skipOnError' => true, 'targetClass' => ProductAttrItemValue::className(), 'targetAttribute' => ['attr_item_value_id' => 'id']],
[['item_id'], 'exist', 'skipOnError' => true, 'targetClass' => CartItem::className(), 'targetAttribute' => ['item_id' => 'id']],
['status', 'default', 'value' => self::STATUS_ACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'item_id' => Yii::t('app', 'Item ID'),
'attr_item_id' => Yii::t('app', 'Attr Item ID'),
'attr_item_value_id' => Yii::t('app', 'Attr Item Value ID'),
'status' => Yii::t('app', 'Status'),
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getAttrItem()
{
return $this->hasOne(ProductAttrItem::className(), ['id' => 'attr_item_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getAttrItemValue()
{
return $this->hasOne(ProductAttrItemValue::className(), ['id' => 'attr_item_value_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getItem()
{
return $this->hasOne(CartItem::className(), ['id' => 'item_id']);
}
}
| true |
713463fc0c4b27a7c59c070212a538c62381be41 | PHP | duarteduu/PAP | /createProvider.php | UTF-8 | 1,630 | 2.84375 | 3 | [] | no_license | <?php
session_start();
require_once 'backend/conn.php';
require_once 'backend/requireLogin.php';
require_once 'backend/requireAdmin.php';
// error variables initialization
$error = '';
// form submit
if (isset($_POST['nome'])){
$name = trim($_POST['nome']);
if (strlen($name) < 4 || strlen($name) > 20) {
$error = "O nome de utilizador deve ter entre 4 e 20 caracters. <br/>";
} else{
$sql = "SELECT id, nome FROM fornecedores WHERE nome='".$name."';";
$result = $conn->query($sql);
if ($result->num_rows > 0){
$error = "O nome de utilizador já está a ser utilizado. <br/>";
} else{
$sql = "INSERT INTO fornecedores(nome) VALUES ('".$name."');";
$conn->query($sql);
header('Location: providers.php');
}
}
}
?>
<!doctype html>
<html lang="pt">
<head>
<?php require_once 'header.php'; ?>
<title>Adicionar Fornecedor</title>
</head>
<body>
<div id="interface-form">
<div id="header-text">
Adicionar fornecedor
<hr/>
</div>
<div id="interface-form">
<form method="post">
<div id="input-container">
<div id="input-name">
<label for="nome">Nome</label>
</div>
<input type="text" name="nome" id="nome" placeholder="e.g. PC DIGA">
</div>
<input type="submit" value="Criar">
<a href="providers.php"><button type="button" class="red">Voltar</button></a>
</form>
</div>
<p class="red-color"><?php echo $error; ?></p>
</div>
</body>
</html>
| true |
3afca7e514c2bfee5f70af9e92330eb5166aed2a | PHP | Jorge-CR/Eintrag | /model/extended/class.usuarioDAOExt.php | UTF-8 | 452 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
class usuarioDAOExt extends usuarioDAO {
public function search($user, $password) {
$sql = 'SELECT usu_id, usu_cedula, usu_nombre, usu_direccion, usu_telfijo, usu_celular, usu_correo, rol_id FROM r_usuario WHERE usu_nombre = :user AND usu_contraseña = :pass';
$params = array(
':user' => (string) $user,
':pass' => (string) $password
);
return $this->query($sql, $params);
}
}
| true |
4150168430fb3298a5fbf1a80591ba4f4c0bc87b | PHP | Trianlos/dropbox-acuenta | /val.php | UTF-8 | 1,086 | 2.6875 | 3 | [] | no_license | <?php
error_reporting(0);
session_start();
$con = new mysqli("localhost", "root", "", "testeando");
if ($con->connect_errno)
{
echo "Fallo al conectar a MySQL: (" . $con->connect_errno . ") " . $con->connect_error;
exit();
}
//Valida que los campos de usuario y contraseña tengan datos para su validacion
@mysqli_query($con, "SET NAMES 'utf8'");
$user = strtolower(mysqli_real_escape_string($con, $_POST['user']));
$pass = mysqli_real_escape_string($con, $_POST['pass']);
if ($user == null || $pass == null)
{
echo '<span>Por favor complete todos los campos.</span>';
}
else
{
$consulta = mysqli_query($con, "SELECT name, pass FROM users WHERE name = '$user' AND pass = '$pass'");
if (mysqli_num_rows($consulta) > 0)
{
$_SESSION["user"] = $user;
echo '<script>location.href = "panel.php"</script>';
}
else
{
echo '<span>El usuario y/o clave son incorrectas, vuelva a intentarlo.</span>';
}
}
?> | true |
cb19ad212d70a1066ef11fcfc0c3326351c8d163 | PHP | BennyJake/movie | /php/class/theater.php | UTF-8 | 1,416 | 3.328125 | 3 | [
"MIT"
] | permissive | <?php
/**
* Created by PhpStorm.
* User: Ben
* Date: 1/13/14
* Time: 9:30 PM
*/
namespace movietheater;
class theater {
private $tid;
private $movie_array;
private $var_array;
public function __init($tid=NULL){
if($tid){
$this->setTid($tid);
}
$this->movie_array = array();
$this->var_array = array();
}
public function addMovie($mid,movie $movie){
$this->movie_array[$mid] = $movie;
}
public function getMovie($mid=NULL){
if($mid){
return $this->movie_array[$mid];
}
else{
return $this->movie_array;
}
}
/**
* @param mixed $tid
*/
public function setVarVal($var,$val)
{
$this->var_array[$var] = $val;
}
public function setVarValList(array $array)
{
foreach($array as $var=>$val){
setVarVal($var,$val);
}
}
/**
* @param mixed $tid
*/
public function getVarVal($var)
{
if(isset($this->var_array[$var])){
return $this->var_array[$var];
}
else{
return NULL;
}
}
/**
* @param mixed $tid
*/
public function setTid($tid)
{
$this->tid = $tid;
}
/**
* @return mixed
*/
public function getTid()
{
return $this->tid;
}
} | true |
1288d3bd033d5adbdb8027fe8932fce4d5db9d45 | PHP | piotrooo/php-hosts | /src/PhpHosts/Hosts.php | UTF-8 | 5,056 | 2.78125 | 3 | [
"MIT"
] | permissive | <?php
/**
* Copyright (C) 2020
* Piotr Olaszewski <piotroo89@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
declare(strict_types=1);
namespace PhpHosts;
use Ouzo\Utilities\Arrays;
use Ouzo\Utilities\FluentFunctions;
use PhpHosts\File\FileParser;
use PhpHosts\File\FileWriter;
use PhpHosts\Path\FixedPathProvider;
use PhpHosts\Path\OsBasedPathProvider;
use PhpHosts\Path\PathProvider;
class Hosts
{
private PathProvider $pathProvider;
private FileParser $fileParser;
private FileWriter $fileWriter;
/** @var HostEntry[] */
private array $hostEntries;
public static function initialize(): Hosts
{
return new Hosts(new OsBasedPathProvider(), new FileParser(), new FileWriter());
}
public static function import(string $path): Hosts
{
if (!file_exists($path)) {
throw new HostsFileNotExistsException("Hosts file '{$path}' not exists.");
}
return new Hosts(new FixedPathProvider($path), new FileParser(), new FileWriter());
}
public function __construct(PathProvider $pathProvider, FileParser $fileParser, FileWriter $fileWriter)
{
$this->pathProvider = $pathProvider;
$this->fileParser = $fileParser;
$this->fileWriter = $fileWriter;
$this->populate();
}
public function count(): int
{
return count($this->hostEntries);
}
/**
* @return HostEntry[]
*/
public function entries(): array
{
return $this->hostEntries;
}
public function existsByName(string $name): bool
{
return Arrays::any($this->hostEntries, function (HostEntry $hostEntry) use ($name) {
return in_array($name, $hostEntry->getNames());
});
}
public function existsByIp(string $ip): bool
{
return Arrays::any($this->hostEntries, function (HostEntry $hostEntry) use ($ip) {
return $ip === $hostEntry->getIp();
});
// return Arrays::any($this->hostEntries, FluentFunctions::extractExpression('getIp()')->equals($ip));
}
public function findByName(string $name): ?HostEntry
{
return Arrays::find($this->hostEntries, function (HostEntry $hostEntry) use ($name) {
return in_array($name, $hostEntry->getNames());
});
}
public function findByIp(string $ip): ?HostEntry
{
return Arrays::find($this->hostEntries, FluentFunctions::extractExpression('getIp()')->equals($ip));
}
public function add(HostEntry $hostEntry): void
{
$existingHostEntry = $this->findByIp($hostEntry->getIp());
if (is_null($existingHostEntry)) {
$this->hostEntries[] = $hostEntry;
} else {
$existingHostEntry->concat($hostEntry);
}
}
/**
* @param HostEntry[] $hostEntries
*/
public function addAll(array $hostEntries): void
{
foreach ($hostEntries as $hostEntry) {
$this->add($hostEntry);
}
}
public function removeByIp(string $ip): void
{
$existingHostEntry = $this->findByIp($ip);
$this->removeEntry($existingHostEntry);
}
public function removeByName(string $name): void
{
$existingHostEntry = $this->findByName($name);
$this->removeEntry($existingHostEntry);
}
public function write(): void
{
$this->fileWriter->write($this->pathProvider->get(), $this->hostEntries);
}
public function populate(): void
{
$this->hostEntries = $this->fileParser->parse($this->pathProvider->get());
}
private function removeEntry(?HostEntry $existingHostEntry): void
{
if (!is_null($existingHostEntry)) {
$this->hostEntries = Arrays::filter($this->hostEntries, function (HostEntry $hostEntry) use ($existingHostEntry) {
return $hostEntry->isReal() &&
$existingHostEntry->isReal() &&
$hostEntry->getIp() != $existingHostEntry->getIp();
});
}
}
}
| true |
743fbbfdc400f0cc4612100f7c03fe406cf51e8a | PHP | bkatk/wordpresstinysnippets | /categories/class-names-for-category-links.php | UTF-8 | 783 | 2.53125 | 3 | [] | no_license | <?php
/*
Plugin Name: [ + ] Class Names for Category Links
Plugin URI: https://github.com/ex-mi/wordpresstinysnippets
Description: Functional plugin that adds unique class names for category links.
Author: Ex.Mi
Version: 1.0
Author URI: https://ex-mi.ru/
License: GPL3
*/
if ( ! defined( 'ABSPATH' ) ) exit( 'Nope :)' );
function wpts_class_names_for_category_links($thelist) {
$categories = get_the_category();
if ( !$categories || is_wp_error($categories) ) {return $thelist;}
foreach ( $categories as $category ) {
$output .= '<a class="category-' . $category->slug . '" href="' . esc_url(get_category_link($category->term_id)) . '">' . $category->name . '</a>';
}
return $output;
}
add_filter( 'the_category', 'wpts_class_names_for_category_links'); | true |
fdaee4d6dc30d43b7b12e378fbb782bbc6dad31b | PHP | infostars/headless-chromium-php | /src/Clip.php | UTF-8 | 1,670 | 3.125 | 3 | [
"Fair"
] | permissive | <?php
/**
* @license see LICENSE
*/
namespace HeadlessChromium;
class Clip
{
protected $x;
protected $y;
protected $height;
protected $width;
protected $scale;
/**
* Clip constructor.
* @param $x
* @param $y
* @param $height
* @param $width
* @param $scale
*/
public function __construct($x, $y, $width, $height, $scale = 1)
{
$this->x = $x;
$this->y = $y;
$this->height = $height;
$this->width = $width;
$this->scale = $scale;
}
/**
* @return mixed
*/
public function getX()
{
return $this->x;
}
/**
* @return mixed
*/
public function getY()
{
return $this->y;
}
/**
* @return mixed
*/
public function getHeight()
{
return $this->height;
}
/**
* @return mixed
*/
public function getWidth()
{
return $this->width;
}
/**
* @return mixed
*/
public function getScale()
{
return $this->scale;
}
/**
* @param mixed $x
*/
public function setX($x)
{
$this->x = $x;
}
/**
* @param mixed $y
*/
public function setY($y)
{
$this->y = $y;
}
/**
* @param mixed $height
*/
public function setHeight($height)
{
$this->height = $height;
}
/**
* @param mixed $width
*/
public function setWidth($width)
{
$this->width = $width;
}
/**
* @param mixed $scale
*/
public function setScale($scale)
{
$this->scale = $scale;
}
}
| true |
0165f1bd7296674cb3aacbfab65d2c4a5c7535c8 | PHP | dimitrije-krstic/yoga | /src/Model/CommentDataWrapper.php | UTF-8 | 1,416 | 2.953125 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace App\Model;
use App\Services\UploadHelper;
class CommentDataWrapper
{
/**
* @var string
*/
private $content;
/**
* @var \DateTime
*/
private $createdAt;
/**
* @var string
*/
private $authorName;
/**
* @var string|null
*/
private $authorProfileImage;
private string $authorSlug;
public function __construct(
string $comment,
\DateTime $createdAt,
string $authorName,
?string $authorProfileImage,
string $authorSlug
) {
$this->content = $comment;
$this->createdAt = $createdAt;
$this->authorName = $authorName;
$this->authorProfileImage = $authorProfileImage;
$this->authorSlug = $authorSlug;
}
public function getContent(): string
{
return $this->content;
}
public function getCreatedAt(): \DateTime
{
return $this->createdAt;
}
public function getAuthorName(): string
{
return $this->authorName;
}
public function getAuthorProfileImage(): string
{
return empty($this->authorProfileImage) ? UploadHelper::USER_DEFAULT_IMAGE_SMALL_PATH :
UploadHelper::USER_IMAGE_DIRECTORY_SMALL.'/'.$this->authorProfileImage ;
}
public function getAuthorSlug(): string
{
return $this->authorSlug;
}
}
| true |
d053a4ca69fae4be8514d8c816abe1c9c09c60ad | PHP | PenMessier/online_shop | /models/cart.class.php | UTF-8 | 1,652 | 2.734375 | 3 | [] | no_license | <?
class Cart {
public static function getCart($user_id) {
$goods = db::getInstance()->Select(
"SELECT*FROM temp_orders
LEFT JOIN goods
ON temp_orders.good_id = goods.id
WHERE temp_orders.user_id = '$user_id'"
);
return $goods;
}
public static function getCartitem($id, $user_id) {
$result = db::getInstance()->selectOne("SELECT*FROM temp_orders WHERE good_id= :id AND user_id = :user_id", ['id' => $id, 'user_id' => $user_id]);
if(!$result)
return false;
return $result;
}
public static function editOrder($quantity, $id, $user_id) {
$result = db::getInstance()->Query("UPDATE temp_orders SET quantity = $quantity WHERE good_id = :id AND user_id=:user_id", ['id'=> $id, 'user_id' => $user_id])->rowCount();
if(!$result)
return false;
return true;
}
public static function deleteItem($table, $cart_id) {
$result = db::getInstance()->Query("DELETE FROM $table WHERE cart_id=:cart_id", ['cart_id'=>$cart_id])->rowCount();
if(!$result)
return false;
return true;
}
// addItem($user_id, $good_id, $quantity, $price)
public static function addItem($args) {
$values = [];
foreach ($args as $arg) {
if($arg == 'null') {
$values[] = 'null';
} else {
$values[] = "'$arg'";
}
}
$values_s = implode(',',$values);
$result = db::getInstance()->Query("INSERT INTO temp_orders (user_id, good_id, quantity, price) VALUES ($values_s)")->rowCount();
if(!$result)
return false;
return true;
}
public static function getUserid () {
if (isset($_SESSION['login'])) {
$user_id = $_SESSION['uid'];
} else {
$user_id = session_id();
}
return $user_id;
}
}
| true |
e76e3d690b7af0971e8fce82bc3fcbcd974b7bc0 | PHP | CreepingPanda/FennecPlusUltra | /models/CategoryManager.class.php | UTF-8 | 2,596 | 3.21875 | 3 | [] | no_license | <?php
class CategoryManager
{
// ________ PROPRIETES ________
private $database;
// ________________
// ________ CONSTRUCT ________
public function __construct($database)
{
$this->database = $database;
}
// ________________
// ________ METHODES ________
public function findById($id)
{
$id = intval($id);
$query = "SELECT * FROM category WHERE id = ".$id;
$result = $this->database->query($query);
if ( $result )
{
$category = $result->fetchObject("Category", array($this->database));
if ( $category )
{
return $category;
}
else
{
throw new Exception("Catégorie introuvable.");
}
}
else
{
throw new Exception("Erreur - Base de données.");
}
}
public function create(User $currentUser, $name, $description)
{
$category = new Category($this->database);
if ( $currentUser )
{
if ( $currentUser->getRights() == 2 )
{
$set = $category->setName($name);
if ( $set === true )
{
$set = $category->setDescription($description);
if ( $set === true )
{
$name = $this->database->quote($category->getName());
$description = $this->database->quote($category->getDescription());
$query = "INSERT INTO category (name, description)
VALUES (".$name.", ".$description.")";
$result = $this->database->exec($query);
if ( $result )
{
$id = $this->database->lastInsertId();
if ( $id )
{
try
{
return $this->findById($id);
}
catch(Exception $e)
{
$errors[] = $e->getMessage();
}
}
else
{
throw new Exception("Catastrophe serveur.");
}
}
else
{
throw new Exception("Catastrophe base de données.");
}
}
else
{
throw new Exception($set);
}
}
else
{
throw new Exception($set);
}
}
else
{
throw new Exception("Erreur : Droits d'administration requis.");
}
}
else
{
throw new Exception("Erreur : Connexion requise.");
}
}
public function edit(User $currentUser, Category $category)
{
$id = intval($category->getId());
$name = $this->database->quote($category->getName());
$description = $this->database->quote($category->getDescription());
$query = "UPDATE category SET name = '".$name."', description = '".$description."' WHERE id = ".$id;
$result = $this->database->exec($query);
if ( $result )
{
return true;
}
else
{
throw new Exception("Catastrophe base de données.");
}
}
// ________________
}
?> | true |
a62eeb9c4d2980426cf2a6b33b2742a1737276bb | PHP | danibram/danux | /application/migrations/2013_03_20_114806_create_wardrobe_table.php | UTF-8 | 765 | 2.546875 | 3 | [
"MIT",
"LicenseRef-scancode-dco-1.1"
] | permissive | <?php
class Create_Wardrobe_Table {
/**
* Make changes to the database.
*
* @return void
*/
public function up()
{
Schema::create('l_wardrobe_table', function($table){
$table->increments('id');
$table->integer('budget_id');
$table->string('name');
$table->string('width');
$table->string('height');
$table->string('prof');
$table->string('nmods');
$table->string('doors');
$table->string('typedoor');
$table->string('paritypos');
$table->string('handle');
$table->string('tperfil');
$table->string('perfil');
$table->string('marco');
$table->timestamps();
});
}
/**
* Revert the changes to the database.
*
* @return void
*/
public function down()
{
Schema::drop('l_wardrobe_table');
}
} | true |
78b0663b50ecf5c7c0babf1085c0837e2201b456 | PHP | maks-nurgazy/CV-maker | /src/Service/UploaderHelper.php | UTF-8 | 719 | 2.703125 | 3 | [] | no_license | <?php
namespace App\Service;
use Gedmo\Sluggable\Util\Urlizer;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class UploaderHelper
{
private $uploadPath;
public function __construct(string $uploadPath)
{
$this->uploadPath = $uploadPath;
}
public function uploadAvatarImage(UploadedFile $uploadedFile):string
{
$destination = $this->uploadPath.'/avatar_image';
$originalFilename = pathinfo($uploadedFile->getClientOriginalName(), PATHINFO_FILENAME);
$newFilename = Urlizer::urlize($originalFilename).'-'.uniqid().'.'.$uploadedFile->guessExtension();
$uploadedFile->move($destination,$newFilename);
return $newFilename;
}
} | true |
32e67a7c945c83e796bf64cd01ae723375fc95a9 | PHP | yerzhant/clinics | /app/app/WorkTime.php | UTF-8 | 894 | 2.90625 | 3 | [
"MIT"
] | permissive | <?php
namespace App;
class WorkTime extends Model
{
public function getDayStringAttribute()
{
switch ($this->day) {
case 1:
$day = "Пн";
break;
case 2:
$day = "Вт";
break;
case 3:
$day = "Ср";
break;
case 4:
$day = "Чт";
break;
case 5:
$day = "Пт";
break;
case 6:
$day = "Сб";
break;
case 7:
$day = "Вс";
break;
}
return $day;
}
public function getFromTimeAttribute($value)
{
return substr($value, 0, 5);
}
public function getToTimeAttribute($value)
{
return substr($value, 0, 5);
}
}
| true |
9ea28fd37c8a820a9c7fd4e828bbda8a8c1d9430 | PHP | winni4eva/ratings-pro | /app/User.php | UTF-8 | 2,198 | 2.578125 | 3 | [] | no_license | <?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Branch;
use App\Category;
use App\BranchUser;
use Tymon\JWTAuth\Contracts\JWTSubject as AuthenticatableUserContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
class User extends Authenticatable implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract, AuthenticatableUserContract
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'first_name', 'last_name', 'email', 'company', 'password', 'role', 'role_branch_zone_id'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function branches(){
return $this->belongsToMany(Branch::class,'branch_user')
->withTimestamps()
->withPivot('admin');
}
public function branch(){
return $this->belongsToMany(Branch::class,'branch_user');
}
public function branchUser(){
return $this->hasMany(BranchUser::class);
}
public function setFirstNameAttribute($value){
$this->attributes['first_name'] = ucfirst( strtolower( $value ) );
}
public function setLastNameAttribute($value){
$this->attributes['last_name'] = ucfirst( strtolower( $value ) );
}
public function setCompanyAttribute($value){
$this->attributes['company'] = strtoupper( strtolower( $value ) );
}
/**
* @return mixed
*/
public function getJWTIdentifier()
{
return $this->getKey(); // Eloquent model method
}
/**
* @return array
*/
public function getJWTCustomClaims()
{
return [
'user' => [
'id' => $this->id,
'email' => $this->email
]
];
}
}
| true |
7f9ceca2d132a1d38ce2aa6bea7a9c2ef1ad2313 | PHP | jakub-klapka/secret-file-manager | /secret-file-manager.php | UTF-8 | 3,217 | 2.53125 | 3 | [] | no_license | <?php
/**
* Plugin Name: Lumiart's Secret Files Manager
* Description: Upload big files via FTP and create secret link to send them to clients.
* Version: 1.1
* Author: Jakub Klapka
* Author URI: http://www.lumiart.cz
*/
namespace Lumiart\SecretFileManager;
define( 'LUMI_SFM_CORE_PATH', plugin_dir_path( __FILE__ ) . 'core' . DIRECTORY_SEPARATOR );
define( 'LUMI_SFM_TEMPLATES_PATH', plugin_dir_path( __FILE__ ) . 'templates' . DIRECTORY_SEPARATOR );
define( 'LUMI_SFM_CSS_JS_VER', 3 );
/**
* @var array $lumi_sfm Array containing references to all SFM classes
*/
$lumi_sfm = array();
global $lumi_sfm;
$lumi_sfm = array(
'static_version' => 3,
'plugin_base_file_path' => __FILE__,
'capability' => 'manage_secret_files',
'files_url' => get_bloginfo( 'url' ) . '/wp-secret-files',
'files_path' => ABSPATH . 'wp-secret-files',
'import_path' => ABSPATH . 'wp-secret-files/import',
'storage_limit' => defined( 'LUMI_SFM_STORAGE_LIMIT' ) ? LUMI_SFM_STORAGE_LIMIT : 2 * 1024 * 1024 * 1024
);
/**
* Classes autoloading
* Classes are loaded based on their need to be loaded on admin, frontend or both. (to save some mem)
*/
$classes_to_load['glob'] = glob( LUMI_SFM_CORE_PATH . '*.glob.php' );
if ( is_admin() ) {
$classes_to_load['admin'] = glob( LUMI_SFM_CORE_PATH . '*.admin.php' );
} else {
$classes_to_load['frontend'] = glob( LUMI_SFM_CORE_PATH . '*.frontend.php' );
}
foreach ( $classes_to_load as $scope => $files ) {
if ( $files != false ) {
foreach ( $files as $file ) {
include_once $file;
$class_name = basename( $file, '.' . $scope . '.php' );
$class_name_with_namespace = '\\Lumiart\\SecretFileManager\\' . ucwords( $scope ) . '\\' . $class_name;
$lumi_sfm[ $scope ][ $class_name ] = new $class_name_with_namespace;
}
}
}
/**
* Template classes loading
* Those contain functions used in templates - which are loaded on demand to save mem
* Will return reference to class, which can contain your functions. It will load the class, if it's not loaded yet.
* @var string $name
* @return \Lumiart\SecretFileManager\Template\AdminPage
*/
function lumi_sfm_template( $name ) {
if ( empty( $name ) ) {
return false;
}
if ( isset( $lumi_sfm['Template'][ $name ] ) ) {
return $lumi_sfm['Template'][ $name ]; //If template functions are already loaded
}
include_once LUMI_SFM_CORE_PATH . $name . '.template.php';
$class_name = '\\Lumiart\\SecretFileManager\\Template\\' . $name;
$lumi_sfm['Template'][ $name ] = new $class_name;
return $lumi_sfm['Template'][ $name ];
}
/**
* Install and uninstall hooks
*/
register_activation_hook( __FILE__, function () {
include_once LUMI_SFM_CORE_PATH . 'InstallUninstall.php';
$inst = new InstallUninstall();
$inst->add_capabilities_to_admin();
$inst->create_dirs();
$inst->flush_rewrite_activate();
} );
/**
* PSR Autoloader
*/
spl_autoload_register( function( $class_name ) {
$namespace = "Lumiart\\SecretFileManager\\";
if( substr( $class_name, 0, strlen( $namespace ) ) === $namespace ) {
require_once( str_replace( "\\", '/', substr( $class_name, strlen( $namespace ) ) ) . '.php' );
}
} );
| true |
e698fcc234dac053b4d01df5cfa64007d53c339d | PHP | xd5508/ganbaobei | /include/php/login.php | UTF-8 | 921 | 2.515625 | 3 | [] | no_license | <?php
header("Content-type: text/html; charset=utf-8");
date_default_timezone_set("PRC");
session_start();
$get_start_time = time();
include_once("../../lib/mysql.class.php");
include_once("../../lib/user.class.php");
$own = new mysql();
if($_POST['username'] == '') die('请填写您的账号!');
if($_POST['password'] == '') die('请填写您的密码!');
$a = array(
'phone'=>$_POST['username'],
'password'=>$_POST['password']
);
//print_r($a);
$user = new user($a);
$result = $user->login($own);
//print_r('error:' . $result . '. ');
switch($result) {
case 1000:
$_SESSION['user'] = $user->person;
die('登陆成功!');
break;
case 1001:
die('账号不存在!');
break;
case 1002:
die('密码错误!');
break;
case 1012:
$_SESSION['user'] = $user->person;
die('登陆成功!');
break;
default:
die('未知错误,错误代码:#'.$result);
break;
}
?>
| true |
44a8754501ac24d997906708881b68eaca52a596 | PHP | qschen2/Hello | /qschen2/src/Hello.php | UTF-8 | 104 | 2.53125 | 3 | [] | no_license | <?php
namespace Qschen2;
class Hello {
public static function say()
{
return "hello qschn2!";
}
} | true |
5e2a614da961f421b89d7bf3cd6e45c16095bba6 | PHP | AbdellahAilali/SymfonyMessenger | /appli/src/EventDispatcher/Event.php | UTF-8 | 362 | 3.0625 | 3 | [] | no_license | <?php
namespace App\EventDispatcher;
class Event
{
protected $nom;
//Action qui déclenche l'instruction
public function setNom($nom)
{
echo ' EventEntry ';
$this->nom = $nom;
echo ' EventExit ';
}
//getNom pour obtenir le nom depuis le
public function getNom()
{
return $this->nom;
}
}
| true |
f5edb832abe2a6784439066a5dc50d4c31f38457 | PHP | nyeholt/relapse | /november/services/UserService.php | UTF-8 | 14,641 | 2.765625 | 3 | [] | no_license | <?php
include_once dirname(__FILE__).'/exceptions/ExistingUserException.php';
include_once dirname(__FILE__).'/exceptions/RecursiveGroupException.php';
include_once dirname(__FILE__).'/exceptions/NonEmptyGroupException.php';
include_once 'november/model/GroupMember.php';
include_once 'model/LeaveApplication.php';
/**
* Stuff for managing users.
*
*/
class UserService implements Configurable
{
/**
* The db service for retrieving objects
*
* @var DbService
*/
public $dbService;
/**
* The auth service
*
* @var AuthService
*/
public $authService;
/**
* The tracker service
*
* @var TrackerService
*/
public $trackerService;
/**
* NotificationService
*
* @var NotificationService
*/
public $notificationService;
/**
* @var ProjectService
*/
public $projectService;
/**
* @var AuthComponent
*/
public $authComponent;
/**
* What's our user class?
*
* @var string
*/
private $userClass = 'User';
/**
* Configure the service
*
* @param array $config
*/
public function configure($config)
{
$this->userClass = ifset($config, 'user_class', 'User');
}
public function getUserClass()
{
return $this->userClass;
}
/**
* Get a user by the given ID
*
* @param unknown_type $id
* @return unknown
*/
public function getUser($id)
{
return $this->dbService->getById($id, $this->userClass);
}
public function getByName($username)
{
return $this->getUserByField('username', $username);
}
/**
* Get a user by a particular field
*
* @param string $field
* @param mixed $value
* @return User
*/
public function getUserByField($field, $value)
{
if (!$value) {
return null;
}
return $this->dbService->getByField(array($field => $value), $this->userClass);
}
/**
* get a list of users matching a criteria
*
*/
public function getUserList($fields = array(), $excludeExternal = true)
{
// if $excludeExternal is true, then we don't include them in the listing
if ($excludeExternal) {
$fields['role<>'] = User::ROLE_EXTERNAL;
}
$users = $this->dbService->getObjects($this->userClass, $fields, 'username asc');
return $users;
}
/**
* Get a list of users for a particular client
*
* This must bind against the 'user' table to make sure there's both a
* user record AND a contact record under the given client name
*
* @param String $clientName
*/
public function getUsersForClient($id)
{
$select = $this->dbService->select();
/* @var $select Zend_Db_Select */
$select->from(mb_strtolower($this->userClass))
->joinInner('contact', mb_strtolower($this->userClass).'.contactid = contact.id')
->joinInner('client', 'contact.clientid = client.id')
->where('client.id=?', $id);
$items = $this->dbService->fetchObjects($this->userClass, $select);
return $items;
}
/**
* Creates a new user
*
* @param Array $params
* @return The created user
* @throws InvalidModelException
* @throws ExistingUserException
*/
public function createUser($params, $setAsAuthenticated = true, $role = User::ROLE_USER, $userType = null)
{
if ($userType == null) {
$userType = $this->userClass;
}
// Check if there's a user with this email first.
$select = $this->dbService->select();
$select->from(strtolower($userType), '*')->
where('username=?', $params['username'])->
orWhere('email=?', $params['email']);
$existing = $this->dbService->getObject($select, $userType);
if ($existing) {
throw new ExistingUserException($params['username'].' already exists');
}
$newPass = null;
if (isset($params['password'])) {
$newPass = $params['password'];
}
$params['role'] = $role;
// Create a user with initial information
$user = $userType;
$user = new $user();
$user->generateSaltedPassword($params['password']);
unset($params['password']);
$user->bind($params);
$validator = new ModelValidator();
if (!$validator->isValid($user)) {
throw new InvalidModelException($validator->getMessages());
}
// so now we save the user, then reset their password which emails,
// then we set them as the authenticated user.
if ($this->dbService->createObject($user)) {
$this->trackerService->track('create-user', $user->id);
if ($setAsAuthenticated) {
$this->authService->setAuthenticatedUser($user);
}
return $user;
}
return null;
}
/**
* Update a given user.
* @param NovemberUser $userToEdit
* @param array $params
*/
public function updateUser($userToEdit, $params, $synch=true)
{
if (isset($params['email'])) {
// Check if there's a user with this email first.
$existing = $this->dbService->getByField(array('email'=>$params['email']), $this->userClass);
if ($existing && $existing->id != $userToEdit->getId()) {
throw new ExistingUserException($params['email'].' already exists');
}
}
// Make sure no role is being changed! we do that in another method.
unset($params['role']);
$newPass = null;
if (isset($params['password'])) {
$newPass = $params['password'];
$userToEdit->generateSaltedPassword($params['password']);
unset($params['password']);
}
$userToEdit->bind($params);
$validator = new ModelValidator();
if (!$validator->isValid($userToEdit)) {
throw new InvalidModelException($validator->getMessages());
}
$ret = $this->dbService->updateObject($userToEdit);
$this->authComponent->updateUser($userToEdit, $newPass);
return $ret;
}
public function saveUser($user)
{
$this->dbService->saveObject($user);
}
/**
* Retrieves the amount of leave a given user has.
*/
public function getLeaveForUser(User $user, $leaveType="Annual")
{
$leave = $this->dbService->getByField(array('username'=>$user->getUsername(), 'leavetype'=>$leaveType), 'Leave');
if (!$leave && $user) {
// Need to create new
$params = array('username'=>$user->getUsername(), 'days'=>0, 'leavetype'=>$leaveType);
$leave = $this->dbService->saveObject($params, 'Leave');
}
if (!$leave) {
throw new Exception("Could not retrieve Leave details for ".$user->getUsername());
}
return $leave;
}
/**
* Get all leave applications
*/
public function getLeaveApplications($where=array(), $order='id desc', $page=null, $number=null)
{
return $this->dbService->getObjects('LeaveApplication', $where, $order, $page, $number);
}
public function getLeaveApplicationsCount($where=array())
{
return $this->dbService->getObjectCount($where, 'LeaveApplication');
}
/**
* Get leave application for a single user
*/
public function getLeaveApplicationsForUser(User $user)
{
return $this->getLeaveApplications(array('username=' => $user->getUsername()));
}
/**
* Updates the amount of bonus leave a user has available
*/
public function updateLeave(Leave $leave, $days)
{
$old = $leave->days;
$leave->days = $days;
$this->dbService->beginTransaction();
$ret = $this->dbService->saveObject($leave);
$this->trackerService->track('leave-updated', "$old changed to $days");
$this->dbService->commit();
return $ret;
}
/**
* Figure out how many days of leave someone has based on
* when they started.
*/
public function calculateLeave(CrmUser $user)
{
$leavePerYear = za()->getConfig('days_leave', 20);
$yearLength = 365.25;
$timeInDays = strtotime($user->startdate);
if (!$timeInDays) {
return 0;
}
$timeInDays = time() - $timeInDays;
return $timeInDays / 86400 / $yearLength * $leavePerYear;
}
/**
* Make an application for leave
*/
public function applyForLeave(User $user, $params)
{
$leave = $this->getLeaveForUser($user);
if (!$leave) {
throw new Exception("Could not create leave application");
}
$app = $this->saveLeaveApplication($params);
if ($app) {
// get all the usernames who are either admins or power users
$approvers = $this->getApprovers();
if (count($approvers)) {
// Notify of the application
$msg = new TemplatedMessage('new-leave-application.php', array('model'=>$app));
$this->notificationService->notifyUser('New Leave Application', $approvers, $msg);
}
}
return $app;
}
/**
* Gets all the users that could be approvers
*/
public function getApprovers()
{
$admins = $this->getUserList(array('role='=>'Admin'));
$powers = $this->getUserList(array('role='=>'Power'));
$approvers = array();
foreach ($admins as $admin) {
$approvers[] = $admin->username;
}
foreach ($powers as $power) {
$approvers[] = $power->username;
}
return $approvers;
}
public function saveLeaveApplication($params)
{
return $this->dbService->saveObject($params, 'LeaveApplication');
}
/**
* Set the leave status
*/
public function setLeaveStatus(LeaveApplication $leaveApplication, $status, $daysAffected = 0)
{
$leaveApplication->status = $status;
$leaveApplication->approver = za()->getUser()->getUsername();
if ($daysAffected) {
$leaveApplication->days = $daysAffected;
}
$this->dbService->beginTransaction();
if ($status == LeaveApplication::LEAVE_DENIED) {
$leaveApplication->days = 0;
}
$this->dbService->saveObject($leaveApplication);
if ($status == LeaveApplication::LEAVE_APPROVED) {
// if it's leave approved, need to create a task in the relevant project milestone
// and make sure the user has time added for it
}
$this->applyTimeForLeave($leaveApplication);
$this->trackerService->track('leave-updated', "Leave application for $leaveApplication->username set to $status");
$this->dbService->commit();
// send a message to the user
$msg = new TemplatedMessage('leave-updated.php', array('model'=>$leaveApplication));
$this->notificationService->notifyUser('Leave Application Updated', $leaveApplication->username, $msg);
}
/**
* Get the task that represents the leave for a given leave application
* and add some time to it for the given application
*/
public function applyTimeForLeave(LeaveApplication $leaveApplication)
{
$project = $this->projectService->getProject(za()->getConfig('leave_project'));
if (!$project) {
throw new Exception("Leave project not set correctly in configuration");
}
$monthYear = date('F Y', strtotime($leaveApplication->to));
$params = array('parentid='=>$project->id, 'title='=>$monthYear);
// get the appropriate milestone
$projs = $this->projectService->getProjects($params);
$milestone = null;
if (count($projs)) {
$milestone = $projs[0];
} else {
// create a new milestone
// $milestone
$date = date('Y-m-t', strtotime($leaveApplication->to)).' 23:59:59';
$milestone = $this->projectService->createMilestone($project, $monthYear, $date);
}
// now get the task for the given leave app
$taskTitle = $leaveApplication->leavetype.' Leave #'.$leaveApplication->id.': '.$leaveApplication->username.' '.date('Y-m-d', strtotime($leaveApplication->from)).' - '.date('Y-m-d', strtotime($leaveApplication->to));
$params = array('projectid='=>$milestone->id, 'title='=>$taskTitle);
$tasks = $this->projectService->getTasks($params);
$user = $this->getUserByField('username', $leaveApplication->username);
$task = null;
if (count($tasks)) {
$task = $tasks[0];
// delete all timesheet entries for this user on this task
$records = $this->projectService->getDetailedTimesheet($user, $task->id);
foreach ($records as $record) {
$this->projectService->removeTimesheetRecord($record);
}
} else {
// create the new task
$task = new Task();
za()->inject($task);
$task->title = $taskTitle;
$task->projectid = $milestone->id;
$task->category = 'Leave';
$task->due = $leaveApplication->to;
$task->description = $leaveApplication->reason;
$task->estimated = za()->getConfig('day_length') * $leaveApplication->days;
$task->complete = 1;
$task = $this->projectService->saveTask($task);
}
if ($task != null) {
// now add all the timesheet entries for each given day
$startTime = strtotime(date('Y-m-d', strtotime($leaveApplication->from)).' 09:00:00');
// now go through and add time for the given day
for ($i = 0; $i < $leaveApplication->days; $i++) {
// see if today's a weekend, if so we want to skip til the next monday
$curDay = date('D', $startTime);
if ($curDay == 'Sat') {
$startTime += (2 * 86400);
} else if ($curDay == 'Sun') {
$startTime += 86400;
}
$endTime = $startTime + (za()->getConfig('day_length') * 3600);
$this->projectService->addTimesheetRecord($task, $user, $startTime, $endTime);
$startTime += 86400;
}
}
}
/**
* Make a user an admin
*
* @param NovemberUser $user
*/
public function setUserRole(CrmUser $user, $role=null)
{
if (!$role) $role = User::ROLE_USER;
$user->role = $role;
$this->trackerService->track('set-role', $role.'_user-'.$user->id.'_by-'.za()->getUser()->getId());
$this->dbService->updateObject($user);
}
}
?> | true |
3577e44825e1f3fac328a28923e9198b2740086e | PHP | ludo6577/web | /Acceuil/forum/php/MySql/MySqlCommand.php | UTF-8 | 1,593 | 3.3125 | 3 | [] | no_license | <?php
class ParamType
{
const Integer = "i";
const Double = "d";
const String = "s";
const Bytes = "b";
}
class MySqlCommand
{
private $parametersValues;
private $parametersTypes;
private $nbParameters;
public function __construct(MySqlConnection $connection, $queryText)
{
$this->stmt = $connection->prepare($queryText);
$this->parametersTypes = "";
$this->parametersValues = array();
$this->nbParameters = 0;
}
public function AddParameter($type, $value)
{
$this->parametersValues[$this->nbParameters] = $value;
$this->parametersTypes .= $type;
$this->nbParameters++;
}
public function ExecuteQuery()
{
$this->bindParam();
$this->stmt->execute();
if($result = $this->stmt->get_result())
{
$index=0;
$Rows = array();
while ($row = $result->fetch_assoc())
{
$Rows[$index] = $row;
$index++;
}
$this->stmt->close();
$result->free();
return $Rows;
}
}
/*
* Please don't look down!
* Most akward method to allow multiple parameters
*/
private function bindParam()
{
if($this->nbParameters == 0)
return;
$stmt = $this->stmt;
call_user_func_array(array($stmt, "bind_param"), $this->refValues(array_merge(array($this->parametersTypes), $this->parametersValues)));
}
private function refValues($arr)
{
if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+ ( thx PHP ;) )
{
$refs = array();
foreach($arr as $key => $value)
$refs[$key] = &$arr[$key];
return $refs;
}
return $arr;
}
} | true |
024f7513e94785537b3b71526e0444de8a0d9cc4 | PHP | madman/tree | /src/App/Controller/ApiVersionController.php | UTF-8 | 307 | 2.5625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
class ApiVersionController {
protected $version;
public function __construct($version)
{
$this->version = $version;
}
public function __invoke()
{
return new JsonResponse(['version' => $this->version]);
}
}
| true |
534e130ac124b72deb093abb622e43a3a4515b7b | PHP | beardedandnotmuch/yii2-jwt-user | /src/models/DestroyedToken.php | UTF-8 | 2,253 | 2.75 | 3 | [
"MIT"
] | permissive | <?php
namespace beardedandnotmuch\user\models;
use Yii;
use Lcobucci\JWT\Parser as JWTParser;
/**
* This is the model class for table "{{%user_destroyed_tokens}}".
*
* @property integer $id
* @property integer $user_id
* @property string $token_hash
* @property string $expired_at
* @property string $created_at
*
* @property User $user
*/
class DestroyedToken extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%user_destroyed_tokens}}';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['user_id'], 'integer'],
[['token_hash'], 'string', 'max' => 255],
[['expired_at', 'created_at'], 'datetime', 'format' => 'php:Y-m-d H:i:s'],
[['token_hash'], 'unique'],
[['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::class, 'targetAttribute' => ['user_id' => 'id']],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'user_id' => 'User ID',
'token_hash' => 'Token Hash',
'expired_at' => 'Expired At',
'created_at' => 'Created At',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getUser()
{
return $this->hasOne(User::class, ['id' => 'user_id']);
}
/**
* Factory method.
*
* @return DestroyedToken
*/
public static function fromString($token)
{
$jwt = (new JWTParser())->parse((string) $token);
$expiredAt = null;
if ($jwt->hasClaim('exp')) {
$expiredAt = date('Y-m-d H:i:s', $jwt->getClaim('exp'));
}
$model = new self();
$model->setAttributes([
'token_hash' => md5($token),
'expired_at' => $expiredAt,
'created_at' => date('Y-m-d H:i:s'),
]);
return $model;
}
/**
* Returns true if token was destroyed by user.
*
* @return boolean
*/
public static function isExist($token)
{
return self::find()->andWhere(['token_hash' => md5($token)])->exists();
}
}
| true |
336ee8ab89bedb26498aae5304dc916da5d37dc4 | PHP | cwmiller/broadworks-connector | /src/Ocip/Models/CallToNumber.php | UTF-8 | 2,752 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace CWM\BroadWorksConnector\Ocip\Models;
/**
* CallToNumber
*
* Call to Number.
*
* @Groups [{"id":"c0d21ef9ba207c335d8347e5172fce1d:1091","type":"sequence"}]
*/
class CallToNumber
{
/**
* @ElementName type
* @Type \CWM\BroadWorksConnector\Ocip\Models\CallToNumberType
* @Group c0d21ef9ba207c335d8347e5172fce1d:1091
* @var \CWM\BroadWorksConnector\Ocip\Models\CallToNumberType|null
*/
protected $type = null;
/**
* @ElementName number
* @Type string
* @Optional
* @Group c0d21ef9ba207c335d8347e5172fce1d:1091
* @MinLength 1
* @MaxLength 23
* @var string|null
*/
protected $number = null;
/**
* @ElementName extension
* @Type string
* @Optional
* @Group c0d21ef9ba207c335d8347e5172fce1d:1091
* @MinLength 2
* @MaxLength 20
* @var string|null
*/
protected $extension = null;
/**
* Getter for type
*
* @return \CWM\BroadWorksConnector\Ocip\Models\CallToNumberType
*/
public function getType()
{
return $this->type instanceof \CWM\BroadWorksConnector\Ocip\Nil ? null : $this->type;
}
/**
* Setter for type
*
* @param \CWM\BroadWorksConnector\Ocip\Models\CallToNumberType $type
* @return $this
*/
public function setType(\CWM\BroadWorksConnector\Ocip\Models\CallToNumberType $type)
{
$this->type = $type;
return $this;
}
/**
* @return $this
*/
public function unsetType()
{
$this->type = null;
return $this;
}
/**
* Getter for number
*
* @return string
*/
public function getNumber()
{
return $this->number instanceof \CWM\BroadWorksConnector\Ocip\Nil ? null : $this->number;
}
/**
* Setter for number
*
* @param string $number
* @return $this
*/
public function setNumber($number)
{
$this->number = $number;
return $this;
}
/**
* @return $this
*/
public function unsetNumber()
{
$this->number = null;
return $this;
}
/**
* Getter for extension
*
* @return string
*/
public function getExtension()
{
return $this->extension instanceof \CWM\BroadWorksConnector\Ocip\Nil ? null : $this->extension;
}
/**
* Setter for extension
*
* @param string $extension
* @return $this
*/
public function setExtension($extension)
{
$this->extension = $extension;
return $this;
}
/**
* @return $this
*/
public function unsetExtension()
{
$this->extension = null;
return $this;
}
}
| true |
39673aa189c88909f1d8f85565a4101dfb120c19 | PHP | PetrosMAMALIOGKAS/PHPexercises | /formulaire/traitement.php | UTF-8 | 1,043 | 2.75 | 3 | [] | no_license | <!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>Home Page</title>
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link href="style1.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<?php
$surname = $_POST["nom"];
echo "le nom vous avez declaré est " . $surname;
$name = $_POST["prenom"];
echo "<br/>le prenom vous avez declaré est " . $name;
$gender = $_POST["sexe"];
echo "<br/>la sexe vous avez declaré est " . $gender;
$xp = $_POST["experience"];
echo "<br/>vous avez " . $xp . "années d experience";
$lang = $_POST["languages"];
echo "<br/> vous avez declaré les languages ";
foreach ($lang as $l) {
echo $l . " ";
}
$langu = $_POST["langues"];
echo "<br/> vous parlez ";
foreach ($langu as $l) {
echo $l . " ";
}
$com = $_POST["coman"];
echo "<br/> et Aussi : " . $com;
?>
</body>
</html> | true |
8883006089d54c2c0c9a7abb991cd14d2c575cea | PHP | mykrov/geocompra | /app/GEOEMPRESA.php | UTF-8 | 3,148 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
/**
* @property int $IDEMPRESA
* @property string $RAZONSOCIAL
* @property string $RUC
* @property string $CORREO
* @property string $RUTACERTIFICADO
* @property string $LOGOEMPRESA
* @property int $IDPROVINCIA
* @property int $IDCANTON
* @property int $IDPARROQUIA
* @property string $AGENTERETENCION
* @property string $CONTRIBUYENTEESPECIAL
* @property string $ACTIVIDADECONOMICA
* @property int $IDTIPONEGOCIO
* @property string $CLAVEERTIFICADO
* @property string $ESTADO
* @property GEOPARROQUIUM $gEOPARROQUIum
* @property GEOPROVINCIUM $gEOPROVINCIum
* @property GEOTIPONEGOCIO $gEOTIPONEGOCIO
* @property GEOCANTON $gEOCANTON
* @property GEOBODEGA[] $gEOBODEGAs
* @property GEODETFORMAPAGO[] $gEODETFORMAPAGOs
* @property GEOPROVEEDOR[] $gEOPROVEEDORs
* @property GEOUSUARIO[] $gEOUSUARIOs
*/
class GEOEMPRESA extends Model
{
public $timestamps = false;
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'GEOEMPRESA';
/**
* The primary key for the model.
*
* @var string
*/
protected $primaryKey = 'IDEMPRESA';
/**
* @var array
*/
protected $fillable = ['RAZONSOCIAL', 'RUC', 'CORREO', 'RUTACERTIFICADO', 'LOGOEMPRESA', 'IDPROVINCIA', 'IDCANTON', 'IDPARROQUIA', 'AGENTERETENCION', 'CONTRIBUYENTEESPECIAL', 'ACTIVIDADECONOMICA', 'IDTIPONEGOCIO', 'CLAVEERTIFICADO', 'ESTADO'];
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function gEOPARROQUIum()
{
return $this->belongsTo('App\GEOPARROQUIUM', 'IDPARROQUIA', 'IDPARROQUIA');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function gEOPROVINCIum()
{
return $this->belongsTo('App\GEOPROVINCIUM', 'IDPROVINCIA', 'IDPROVINCIA');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function gEOTIPONEGOCIO()
{
return $this->belongsTo('App\GEOTIPONEGOCIO', 'IDTIPONEGOCIO', 'IDTIPONEGO');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function gEOCANTON()
{
return $this->belongsTo('App\GEOCANTON', 'IDCANTON', 'IDCANTON');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function gEOBODEGAs()
{
return $this->hasMany('App\GEOBODEGA', 'IDEMPRESA', 'IDEMPRESA');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function gEODETFORMAPAGOs()
{
return $this->hasMany('App\GEODETFORMAPAGO', 'IDEMPRESA', 'IDEMPRESA');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function gEOPROVEEDORs()
{
return $this->hasMany('App\GEOPROVEEDOR', 'IDEMPRESA', 'IDEMPRESA');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function gEOUSUARIOs()
{
return $this->hasMany('App\GEOUSUARIO', 'IDEMPRESA', 'IDEMPRESA');
}
}
| true |
e348b1c9ac9041c63cc689e637a0a927595fc1fc | PHP | evaldobarbosa/sanitizer | /example/example1.php | UTF-8 | 415 | 2.921875 | 3 | [] | no_license | <?php
require "autoloader.php";
use Sanitize\Sanitizer;
$intFilter = Sanitize\Sanitizer::add('int','n1');
$numFilter = Sanitize\Sanitizer::add('float','f1');
$thousand = $numFilter->thousand();
echo $intFilter->sanitize("12X0") . "\n";
echo $numFilter->sanitize("12.0") . "\n";
echo $numFilter->sanitize("12,0") . "\n";
echo $thousand->sanitize("12.000,00") . "\n";
echo $thousand->sanitize("12,000,00") . "\n"; | true |
7c8d64e299c46bbad7a526a550938081b382ac2f | PHP | It-Soul/test | /www/protected/components/MainHelper.php | UTF-8 | 5,148 | 2.65625 | 3 | [] | no_license | <?php
class MainHelper
{
public static function initCalendar($canAssign = false)
{
$calendarItems = [];
$calendarStart = strtotime('01/01/' . (date('Y') - 5));
$calendarFinish = strtotime('12/31/' . (date('Y') + 5));
for ($i = $calendarStart; $i < $calendarFinish; $i += 86400) {
list($year, $month, $day) = explode("|", date("Y|m|d", $i));
$calendar[] = $year . '-' . $month . '-' . $day;
}
foreach (array_reverse($calendar) as $date) {
$calendarModel = Calendar::model()->findAllByAttributes(array('data' => $date));
if ($canAssign) {
if ($calendarModel) {
$calendarItems[$date] = array(
'id' => 'activedate',
'data-date' => $date,
'title' => 'Призначити',
'style' => 'font-weight: bold; width: 25px;',
'class' => 'btn btn-warning',
'href' => '#',
'data-toggle' => 'modal',
'data-target' => '#myModal',
);
} else {
$calendarItems[$date] = array(
'id' => 'activedate',
'data-date' => $date,
'title' => 'Призначити',
'style' => 'font-weight: bold; color: #fffff;',
'href' => '#',
'data-toggle' => 'modal',
'data-target' => '#myModal',
);
}
} else {
$calendarItems[$date] = array(
'id' => 'activedate',
'data-date' => $date,
'title' => 'Призначити',
'style' => !empty($calendarModel) ? 'font-weight: bold; width: 25px;' : 'font-weight: bold; color: #fffff;',
'class' => !empty($calendarModel) ? 'btn btn-warning' : '',
);
}
}
return $calendarItems;
}
public static function generateConfirmCode($number)
{
$arr = array('1', '2', '3', '4', '5', '6', '7', '8', '9', '0');
$code = "";
for ($i = 0; $i < $number; $i++) {
$index = rand(0, count($arr) - 1);
$code .= $arr[$index];
}
return $code;
}
public static function generatePassword($number)
{
$arr = array('a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'r', 's',
't', 'u', 'v', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F',
'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'R', 'S',
'T', 'U', 'V', 'X', 'Y', 'Z',
'1', '2', '3', '4', '5', '6',
'7', '8', '9', '0', '.', ',',
'(', ')', '[', ']', '!', '?',
'&', '^', '%', '@', '*', '$',
'<', '>', '/', '|', '+', '-',
'{', '}', '`', '~');
$pass = "";
for ($i = 0; $i < $number; $i++) {
$index = rand(0, count($arr) - 1);
$pass .= $arr[$index];
}
return $pass;
}
public static function translit($str)
{
$translit = array(
'А' => 'a', 'Б' => 'b', 'В' => 'v', 'Г' => 'g', 'Д' => 'd', 'Е' => 'e', 'Ё' => 'yo', 'Ж' => 'zh', 'З' => 'z',
'И' => 'i', 'Й' => 'i', 'К' => 'k', 'Л' => 'l', 'М' => 'm', 'Н' => 'n', 'О' => 'o', 'П' => 'p', 'Р' => 'r',
'С' => 's', 'Т' => 't', 'У' => 'u', 'Ф' => 'f', 'Х' => 'h', 'Ц' => 'ts', 'Ч' => 'ch', 'Ш' => 'sh', 'Щ' => 'sch',
'Ъ' => '', 'Ы' => 'y', 'Ь' => '', 'Э' => 'e', 'Ю' => 'yu', 'Я' => 'ya',
'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ё' => 'yo', 'ж' => 'zh', 'з' => 'z',
'и' => 'i', 'й' => 'i', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o', 'п' => 'p', 'р' => 'r',
'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'ts', 'ч' => 'ch', 'ш' => 'sh', 'щ' => 'sch',
'ъ' => '', 'ы' => 'y', 'ь' => '', 'э' => 'e', 'ю' => 'yu', 'я' => 'ya',
' ' => '-', '!' => '', '?' => '', '(' => '', ')' => '', '#' => '', ',' => '', '№' => '', ' - ' => '-', '/' => '-', ' ' => '-',
'A' => 'a', 'B' => 'b', 'C' => 'c', 'D' => 'd', 'E' => 'e', 'F' => 'f', 'G' => 'g', 'H' => 'h', 'I' => 'i', 'J' => 'j', 'K' => 'k', 'L' => 'l', 'M' => 'm', 'N' => 'n',
'O' => 'o', 'P' => 'p', 'Q' => 'q', 'R' => 'r', 'S' => 's', 'T' => 't', 'U' => 'u', 'V' => 'v', 'W' => 'w', 'X' => 'x', 'Y' => 'y', 'Z' => 'z',
'"' => '', '\'' => ''
);
return strtr($str, $translit);
}
public static function setNumberFormat($number)
{
return str_replace(',', '.', $number);
}
} | true |
5770d44e2bfe5370a066477eec8a596b953b29ee | PHP | mattrubin/Glitch | /common/init.php | UTF-8 | 765 | 2.75 | 3 | [] | no_license | <?php
define('CAT_SORT', 'categories');
define('ALPHA_SORT', 'alphabetical');
define('SORT_DEFAULT', CAT_SORT);
session_start();
// If no sort mode exists, set the default
if(!isset($_SESSION['sort_mode'])) $_SESSION['sort_mode'] = SORT_DEFAULT;
// If a new sort mode is specified, set it now
if(isset($_GET['sort'])) {
$_SESSION['sort_mode'] = $_GET['sort'];
}
// Set the convenience booleans for the sort mode
if($_SESSION['sort_mode'] == CAT_SORT){
$cat_sort = TRUE;
$alpha_sort = FALSE;
} else if($_SESSION['sort_mode'] == ALPHA_SORT){
$alpha_sort = TRUE;
$cat_sort = FALSE;
} else {
// If for some reason we have a bad value, reset it
$_SESSION['sort_mode'] = SORT_DEFAULT;
$cat_sort = TRUE;
$alpha_sort = FALSE;
}
?> | true |
344dd2bacf9e31e32d7882d0994340fbc19e1f95 | PHP | piernik/imap | /src/MailboxesParser/MailboxesParserInterface.php | UTF-8 | 994 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
/**
* Created by PhpStorm.
* User: Lukasz
* Date: 2017-12-01
* Time: 10:22.
*/
namespace Ddeboer\Imap\MailboxesParser;
/**
* Class MailboxesParser.
*/
interface MailboxesParserInterface
{
/**
* Set language for parser.
*
* @param string $lang
*/
public function setLanguage(string $lang);
/**
* @return ParsedMailbox[]
*/
public function getFolders(): array;
/**
* @return array
*/
public function getTreeStructure(): array;
/**
* @param array $specialFoldersNames
*/
public function setSpecialFoldersNames(array $specialFoldersNames);
/**
* @param $special
*
* @return null|string
*/
public function getMailboxNameForSpecial($special);
/**
* @param string $specialFolder Name of special folder
* @param string $id Id for that special folder
*/
public function addSpecialFolderId($specialFolder, $id);
}
| true |
63b93d1e5abcf46ac7f0e3adc02386d03d2825c6 | PHP | AsisBhatt/EMO | /apps/console/components/console/ConsoleCommand.php | UTF-8 | 1,172 | 2.84375 | 3 | [] | no_license | <?php defined('MW_PATH') || exit('No direct script access allowed');
/**
* ConsoleCommand
*
* @package Unika DMS
* @author Serban George Cristian <business@unikainfocom.in>
* @link http://www.unikainfocom.in/
* @copyright 2013-2017 Unika DMS (http://www.unikainfocom.in/)
* @license http://www.unikainfocom.in/support
* @since 1.3.6.6
*
*/
class ConsoleCommand extends CConsoleCommand
{
// whether this should be verbose and output to console
public $verbose = 0;
/**
* @param $message
* @param bool $timer
* @param string $separator
* @return int
*/
protected function stdout($message, $timer = true, $separator = "\n")
{
if (!$this->verbose) {
return 0;
}
if (!is_array($message)) {
$message = array($message);
}
$out = '';
foreach ($message as $msg) {
if ($timer) {
$out .= '[' . date('Y-m-d H:i:s') . '] - ';
}
$out .= $msg;
if ($separator) {
$out .= $separator;
}
}
echo $out;
return 0;
}
}
| true |
13d31d69091744a653f1fb37b7c1469c8abe271a | PHP | muhammadtalha007/ssgs | /app/Http/Controllers/StaffController.php | UTF-8 | 2,161 | 2.546875 | 3 | [] | no_license | <?php
namespace App\Http\Controllers;
use App\Staff;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
class StaffController extends Controller
{
public function login(Request $request)
{
if (Staff::where(['email' => $request->email, 'password' => $request->password])->exists()) {
$id = Staff::where(['email' => $request->email, 'password' => $request->password])->first()['id'];
Session::put('id', $id);
Session::remove('isAdmin');
return redirect('home');
} else {
return redirect()->back()->withErrors(['Invalid username or password']);
}
}
public function getStaffListView()
{
$staff = Staff::all();
return view('staff')->with(['staff' => $staff]);
}
public function getAddStaffView()
{
return view('add-staff');
}
public function saveStaff(Request $request)
{
$staff = new Staff();
$staff->name = $request->name;
$staff->email = $request->email;
$staff->password = $request->password;
$result = $staff->save();
if ($result == true) {
return redirect('staff')->with('message', "Staff Saved Successfully");
} else {
return redirect()->back()->with('message', $result);
}
}
public function deleteStaff($staffId)
{
Staff::where('id', $staffId)->delete();
return redirect()->back();
}
public function editStaff($staffId)
{
$staff = Staff::where('id', $staffId)->first();
return view('edit-staff')->with(['staff' => $staff]);
}
public function saveEditedStaff(Request $request)
{
$staff = Staff::where('id', $request->staffId)->first();
$staff->name = $request->name;
$staff->email = $request->email;
$staff->password = $request->password;
$result = $staff->update();
if ($result == true) {
return redirect('staff')->with('message', "Staff updated Successfully");
} else {
return redirect()->back()->with('message', $result);
}
}
}
| true |
2c95fc6500ee2437656b35fe614d22e59bba35bb | PHP | HNavanjani/ProjectsDoneAtSLIIT | /Projects_Completed_For_Bsc/1stYear/eHut/ITA FINAL-20191105T024409Z-001/ITA FINAL/AssignmentPhp/Checkout.php | UTF-8 | 4,361 | 2.515625 | 3 | [] | no_license | <?php
session_start();
include_once 'dbconnect.php';
$error = false;
if(!$_SESSION['login']){
header("location:Sign_In.php");
die;
}
if (isset($_POST['signup'])) {
$name = mysqli_real_escape_string($con, $_POST['name']);
$address = mysqli_real_escape_string($con, $_POST['address']);
$zip = mysqli_real_escape_string($con, $_POST['zip']);
$email = mysqli_real_escape_string($con, $_POST['email']);
if (!preg_match("/^[a-zA-Z ]+$/",$name)) {
$error = true;
$name_error = "<span style='color:red'>Name must contain only alphabets and space"."<br/>";
}
if (!preg_match("/^[0-9a-zA-Z]+$/",$address)) {
$error = true;
$address_error = "<span style='color:red'>Address must contain only alphabets and numbers"."<br/>";
}
if (!preg_match("/^[0-9]+$/",$zip)) {
$error = true;
$zip_error = "<span style='color:red'>Zip Code must contain only numbers"."<br/>";
}
if(!filter_var($email,FILTER_VALIDATE_EMAIL)) {
$error = true;
$email_error = "<span style='color:red'>Please Enter Valid Email ID"."<br/>";
}
if (!$error) {
if(mysqli_query($con, "INSERT INTO users(name,Address,ZipCode,email) VALUES('" . $name . "', '" . $address . "','" . $zip . "','" . $email . "' )")) {
$successmsg = "Successfully Completed! <a href='checkoutpayment.php'>Click here to Enter Your Payment Details</a>";
} else {
$errormsg = "Error in completing...Please try again later!";
}
}
}
?>
<?php
$connect = mysqli_connect("localhost", "root", "", "newehutdb1");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Online Computer & Mobile Accessories Shop</title>
<link rel="stylesheet"type="text/css"href="div3clmns.css"/>
<script src="CForm_Validation.js"></script>
<style>
input[type=text], input[type=password] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
.imgcontainer {
text-align: center;
margin: 24px 0 12px 0;
}
img.avatar {
width: 40%;
border-radius: 50%;
}
button {
background-color:#ff3399;
color: white;
font-weight:bold;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
}
button:hover {
opacity: 0.8;
}
.container {
padding: 16px;
}
.clearfix::after {
content: "";
display: table;
}
</style>
</head>
<body>
<?php
include("LogHeader.php");
?>
<?php
include "content.php"
?>
<?php
include("Primarybar.php");
?>
<div id="content">
<h2>Checkout</h2>
<h3>Where would you like the order shipped to ?</h3>
<form role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="signupform">
<div class="imgcontainer">
<img src="add_user.png" alt="Avatar" class="avatar">
</div>
<div class="container">
<fieldset>
<legend>Step:1</legend>
<label for="name"> Name</label>
<input type="text" name="name" placeholder="Enter Name" required value="<?php if($error) echo $name; ?>" class="form-control" />
<span ><?php if (isset($name_error)) echo $name_error; ?></span>
<label for="name">Address</label>
<input type="text" name="address" placeholder="Enter Address" required value="<?php if($error) echo $address; ?>" class="form-control" />
<span ><?php if (isset($address_error)) echo $address_error; ?></span>
<label for="name">Zip Code</label>
<input type="text" name="zip" placeholder="Enter Zip Code" required value="<?php if($error) echo $zip; ?>" class="form-control" />
<span ><?php if (isset($zip_error)) echo $zip_error; ?></span>
<label for="name">Email</label>
<input type="text" name="email" placeholder="Email" required value="<?php if($error) echo $email; ?>" class="form-control" />
<span ><?php if (isset($email_error)) echo $email_error; ?></span>
<input type="submit" name="signup" value="Submit" />
</fieldset>
</form>
</div>
</form>
<span style='color:green'><?php if (isset($successmsg)) { echo $successmsg; } ?></span>
<span style='color:red'><?php if (isset($errormsg)) { echo $errormsg; } ?></span>
</div>
<?php
include("Secondarybar.php");
?>
<?php
include("Footer.php");
?>
</body>
</html> | true |
5ddcb42364101d328ed940bde85f1e9eb5b43897 | PHP | thalassa-web/BarcodeHelper | /src/code128/Calculator.php | UTF-8 | 1,062 | 2.953125 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/**
* Created by PhpStorm.
* User: bruno
* Date: 12/02/2019
* Time: 14:34
*/
namespace ThalassaWeb\BarcodeHelper\code128;
use ThalassaWeb\BarcodeHelper\ancetre\ICalculateur;
/**
* Class Calculator
* Calcule clé de contrôle Code 128
* @package ThalassaWeb\BarcodeHelper\calculateur
*/
class Calculator implements ICalculateur
{
use CheckDigitConverter;
/**
* Obtenir la clé de contrôle
* @param Enchainement $donnees
* @return string
*/
public function getCleControle($donnees): string
{
$arrData = $donnees->getValeurs();
// Initialisation de la valeur du checkDigit avec la valeur de démarrage
$checkDigit = $arrData[0];
// Ajout de la valeur multipliée par la position du caractère
for ($index = 1; $index < count($arrData); $index++) {
$checkDigit += $index * $arrData[$index];
}
// Conversion du Checkdigit numérique en caractère ASCII
return $this->valueToAscii($checkDigit % 103, $donnees->getLastSubset());
}
}
| true |
c34e6bde3380371ee91e09765048f0a5b138e8ec | PHP | argordmel/Daily-Content-Manager | /default/app/controllers/dc-admin/usuario_controller.php | UTF-8 | 3,388 | 2.578125 | 3 | [] | no_license | <?php
/**
* Dailyscript - app | web | media
*
*
*
* @category Administracion
* @package Controllers
* @author Iván D. Meléndez
* @copyright Copyright (c) 2010 Dailyscript Team (http://www.dailyscript.com.co)
* @version 1.0
*/
Load::models('usuario');
Load::models('post');
class UsuarioController extends ApplicationController {
public function before_filter() {
if(Input::isAjax()) {
View::template(null);
}
}
public function index() {
}
public function entrar() {
$usuario = new Usuario();
$usuario->entrar();
}
public function salir() {
$usuario = new Usuario();
$usuario->salir();
}
/**
* Método para agregar un nuevo usuario
*/
public function agregar() {
//Titulo de la página
$this->title = 'Nueva usuario';
//Ckeck de los radios para habilitar comentarios
// $this->check_si = (HABILITAR_USUARIO) ? false : true;
// $this->check_no = (disabled) ? true : false;
$this->check_si = true;
$this->check_no = false;
//Array para determinar la visibilidad de los post
$this->tipo = array(
Grupo::ADMINISTRADOR => 'Administrador',
Grupo::AUTOR => 'Autor',
Grupo::COLABORADOR => 'Colaborador',
Grupo::EDITOR => 'Editor'
);
//Verifico si ha enviado los datos a través del formulario
if(Input::hasPost('usuario')) {
//Verifico que el formulario coincida con la llave almacenada en sesion
if(SecurityKey::isValid()) {
Load::models('usuario');
$usuario = new Usuario(Input::post('usuario'));
$resultado = $usuario->registrarUsuario();
if($resultado) {
View::select('usuario');
}/* else {
//Hago persitente los datos
$this->categoria = Input::post('categorias');
$this->etiquetas = Input::post('etiquetas');
}
$this->post = $post;*/
} else {
Flash::info('La llave de acceso ha caducado. Por favor intente nuevamente.');
}
}
}
public function checkEmail(){
$salida['status'] = "ERROR";
if ( Input::hasPost('email') ) {
$email = Input::post('email');
Load::model('usuario');
$usuario = new Usuario();
if ( !$usuario->buscarEmail($email) ) {
$salida['status'] = "OK";
}
}
View::template(null);
View::response('json');
print json_encode($salida);
}
public function checkLogin(){
$salida['status'] = "ERROR";
if ( Input::hasPost('login') ) {
$login = Input::post('login');
Load::model('usuario');
$usuario = new Usuario();
if ( !$usuario->buscarLogin($login) ) {
$salida['status'] = "OK";
}
}
View::template(null);
View::response('json');
print json_encode($salida);
}
}
?>
| true |
9928d05c8b750ccbb18bf47123b57ceedd7eac87 | PHP | kr056/SoftUni | /Software Technologies July 2017/02_PHP Basic Syntax Lab/07_Celsius-Farenhait.php | UTF-8 | 893 | 3.53125 | 4 | [
"MIT"
] | permissive | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<?php
$msgAfterCel="";
if(isset($_GET['cel'])) {
$cel = floatval($_GET['cel']);
$fah = celsiusToFahrenheit($cel);
$msgAfterCel = "$cel °C = $fah °F";
}
$msgAfterFah="";
if(isset($_GET['fah'])) {
$fah = floatval($_GET['fah']);
$cel = fahrenheitToCelsius($fah);
$msgAfterFah = "$fah °F = $cel °C";
}
function celsiusToFahrenheit(float $celsius) : float
{
return $celsius*1.8 +32;
}
function fahrenheitToCelsius(float $fahrenheit) : float
{
return ($fahrenheit-32)/1.8;
}
?>
<form>
Celsius:
<input type="number" name="cel" />
<input type="submit" value="Convert" />
<?= $msgAfterCel ?>
</form>
<form>
Fahrenheit:
<input type="number" name="fah" />
<input type="submit" value="Convert" />
<?= $msgAfterFah ?>
</form>
</body>
</html> | true |
5f9ec0b80af3a098d528ca01a4102e3522439ffb | PHP | AhmedSalahBasha/ahmedsalah-blog | /admin/includes/view_all_posts.php | UTF-8 | 5,360 | 2.65625 | 3 | [] | no_license | <?php
if(isset($_POST['checkBoxArray'])){
foreach($_POST['checkBoxArray'] as $postValueId){
$bulk_options = $_POST['bulkOptions'];
switch($bulk_options){
case 'published':
$query = "UPDATE posts SET post_status = '{$bulk_options}' ";
$query .= "WHERE post_id = {$postValueId} ";
$update_published_status = mysqli_query($connection, $query);
if(!$update_published_status){
die("Update Query Failed! " . mysqli_error($connection));
}
break;
case 'draft':
$query = "UPDATE posts SET post_status = '{$bulk_options}' ";
$query .= "WHERE post_id = {$postValueId} ";
$update_draft_status = mysqli_query($connection, $query);
if(!$update_draft_status){
die("Update Query Failed! " . mysqli_error($connection));
}
break;
case 'delete':
$query = "DELETE FROM posts WHERE post_id = {$postValueId} ";
$delete_post = mysqli_query($connection, $query);
if(!$delete_post){
die("Update Query Failed! " . mysqli_error($connection));
}
break;
}
}
}
?>
<form action="" method="post">
<table class="table table-bordered table-hover">
<div id="bulkOptionContainer" class="col-xs-4" style="padding:0px;">
<select class="form-control" name="bulkOptions" id="">
<option value="">Select Options</option>
<option value="published">Publish</option>
<option value="draft">Draft</option>
<?php if($_SESSION['user_role']=="admin"){ ?> <option value="delete">Delete</option> <?php } ?>
</select>
</div>
<div class="col-xs-4">
<input type="submit" name="submit" value="Apply" class="btn btn-success">
<a href="posts.php?source=add_post" class="btn btn-primary">Add New</a>
</div>
<thead>
<tr>
<th><input id="selectAllBoxes" type="checkbox"></th>
<th>Id</th>
<th>Title</th>
<th>Author</th>
<th>Date</th>
<th>Image</th>
<th>Status</th>
<th>Tags</th>
<th>Comments</th>
<th>Category</th>
</tr>
</thead>
<tbody>
<?php //////////////// Select All Posts ////////////////
$query = "SELECT * FROM posts";
$select_posts = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($select_posts)){
$post_id = $row['post_id'];
$post_title = $row['post_title'];
$post_author = $row['post_author'];
$post_date = $row['post_date'];
$post_image = $row['post_image'];
$post_status = $row['post_status'];
$post_tags = $row['post_tags'];
$post_comments = $row['post_comment_count'];
$post_category = $row['post_cat_id'];
echo "<tr>";
?>
<td><input class="checkBoxes" type="checkbox" name="checkBoxArray[]" value="<?php echo $post_id; ?>"></td>
<?php
echo "<td>{$post_id}</td>";
echo "<td><a href='../post.php?p_id={$post_id}'>{$post_title}</a></td>";
echo "<td>{$post_author}</td>";
echo "<td>{$post_date}</td>";
echo "<td><img class='img-responsive' width='100' src='../images/{$post_image}'></td>";
echo "<td>{$post_status}</td>";
echo "<td>{$post_tags}</td>";
// Increasing Comments Counter for each post
$count_query = "SELECT * FROM comments WHERE comment_post_id = $post_id ";
$send_comment_query = mysqli_query($connection, $count_query);
$comments_counter = mysqli_num_rows($send_comment_query);
echo "<td>{$comments_counter}</td>";
// Print the Category Name in the Table //
$query = "SELECT * FROM categories WHERE cat_id = {$post_category} ";
$select_cat_id = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($select_cat_id)){
$cat_id = $row['cat_id'];
$cat_title = $row['cat_title'];
echo "<td>{$cat_title}</td>";
}
if(!$select_cat_id){
die("Query Failed ! " . mysqli_error($connection));
}
if($_SESSION['user_role']=="admin" || $_SESSION['firstname'].' '.$_SESSION['lastname']==$post_author){
echo "<td><a href='posts.php?source=edit_post&p_id={$post_id}'>Edit</a></td>";}
if($_SESSION['user_role']=="admin"){
echo "<td><a href='posts.php?delete={$post_id}'>Delete</a></td>";
}
echo "</tr>";
}
?>
</tbody>
</table>
</form>
<?php
if(isset($_GET['delete'])){
if(isset($_SESSION['user_role'])){
if($_SESSION['user_role']=='admin'){
$the_post_id = $_GET['delete'];
$query = "DELETE FROM posts WHERE post_id = {$the_post_id} ";
$delete_query = mysqli_query($connection, $query);
if(!$delete_query){
die("Query Failed !! " . mysqli_error($connection));
}
header("Location: posts.php");
}
}
}
?> | true |
5efe32eb572d8249c295f928fac8c7d93f98c4dc | PHP | Salamek/nette-files | /src/Salamek/Files/TImagePipe.php | UTF-8 | 935 | 2.546875 | 3 | [] | no_license | <?php declare(strict_types = 1);
/**
* Copyright (C) 2016 Adam Schubert <adam.schubert@sg1-game.net>.
*/
namespace Salamek\Files;
use Nette;
/**
* Class TImagePipe
* @package Salamek\Files
* @deprecated
*/
trait TImagePipe
{
/** @var ImagePipe */
public $imgPipe;
/**
* @param ImagePipe $imgPipe
* @deprecated
*/
public function injectImgPipe(ImagePipe $imgPipe)
{
user_error('Dont use TImagePipe, it is deprecated, jus use latte filters/macros or autowire requested pipe service', E_USER_DEPRECATED);
$this->imgPipe = $imgPipe;
}
/**
* @param null $class
* @return Nette\Templating\FileTemplate|\stdClass
*/
protected function createTemplate($class = null)
{
$template = parent::createTemplate($class);
/** @var \Nette\Templating\FileTemplate|\stdClass $template */
$template->_imagePipe = $this->imgPipe;
return $template;
}
} | true |
95139b5a7779ed529c0bfa4a172eb952cce821c6 | PHP | b-dvulhatka/hackerrank-php | /Interview Preparation Kit/Sorting/Mark and Toys.php | UTF-8 | 710 | 3.359375 | 3 | [
"MIT"
] | permissive | <?php
// Complete the maximumToys function below.
function maximumToys($prices, $k)
{
sort($prices);
$quantity = 0;
foreach ($prices as $price) {
$k -= $price;
if ($k <= 0) {
break;
}
$quantity++;
}
return $quantity;
}
$fptr = fopen(getenv("OUTPUT_PATH"), "w");
$stdin = fopen("php://stdin", "r");
fscanf($stdin, "%[^\n]", $nk_temp);
$nk = explode(' ', $nk_temp);
$n = intval($nk[0]);
$k = intval($nk[1]);
fscanf($stdin, "%[^\n]", $prices_temp);
$prices = array_map('intval', preg_split('/ /', $prices_temp, -1, PREG_SPLIT_NO_EMPTY));
$result = maximumToys($prices, $k);
fwrite($fptr, $result . "\n");
fclose($stdin);
fclose($fptr);
| true |
67c4a45672f2b64c7f29706836718e37b67d7dc6 | PHP | darkrazor99/simpleLoginSystem | /home.php | UTF-8 | 598 | 2.828125 | 3 | [] | no_license | <?php
include 'classes/usersview.class.php';
session_start();
$userviewr = new UsersView();
if (isset($_SESSION["name"])){
$message= $userviewr->welcomeUserByName($_SESSION["name"]);
echo $message;
}
else {
header("location: login.php");
}
if(isset($_POST["logout"])) {
session_destroy();
header("location: login.php");
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form method="post">
<button type="submit" name="logout">Logout</button>
</form>
</body>
</html>
| true |
6d21cf2e49d08a3adab63de50c878e959f0dd72a | PHP | zeeshanbashir/codeception | /tests/unit/UserTest.php | UTF-8 | 807 | 2.65625 | 3 | [] | no_license | <?php
namespace Tajawal\Test;
use Tajawal\Codecept\User;
class UserTest extends \Codeception\Test\Unit
{
/**
* @var User
*/
protected $user;
protected function _before()
{
$this->user = new User();
}
/**
* This test to check invalid password
*
* @return void
*/
public function testInvalidLengthPassword()
{
$password = "23d3";
$response = $this->user->isValidPassword($password);
$this->assertFalse($response);
}
/**
* This test to verify password is valid
*
* @return void
*/
public function testValidLengthPassword()
{
$password = "accepted";
$response = $this->user->isValidPassword($password);
$this->assertTrue($response);
}
} | true |
4e193bc583708f9d946451c94a96392cef1358fd | PHP | omarfurrer/footbit | /app/Http/Controllers/PagesController.php | UTF-8 | 2,522 | 2.546875 | 3 | [] | no_license | <?php
namespace App\Http\Controllers;
use App\Repositories\Eloquent\MatchesRepositoryEloquent;
use App\Repositories\Eloquent\PlayersRepositoryEloquent;
use App\Repositories\Eloquent\RefereesRepositoryEloquent;
use App\Repositories\Eloquent\TeamsRepositoryEloquent;
use App\Repositories\Eloquent\TournamentsRepositoryEloquent;
class PagesController extends Controller {
/**
* Tournaments Repository.
*
* @var TournamentsRepositoryEloquent
*/
public $tournamentsRepository;
/**
* Matches Repository.
*
* @var MatchesRepositoryEloquent
*/
public $matchesRepository;
/**
* Players Repository.
*
* @var PlayersRepositoryEloquent
*/
public $playersRepository;
/**
* Teams Repository.
*
* @var TeamsRepositoryEloquent
*/
public $teamsRepository;
/**
*
* @param TournamentsRepositoryEloquent $tournamentsRepository
* @param MatchesRepositoryEloquent $matchesRepository
* @param PlayersRepositoryEloquent $playersRepository
* @param TeamsRepositoryEloquent $teamsRepository
* @param RefereesRepositoryEloquent $refereesRepository
*/
public function __construct(TournamentsRepositoryEloquent $tournamentsRepository, MatchesRepositoryEloquent $matchesRepository, PlayersRepositoryEloquent $playersRepository,
TeamsRepositoryEloquent $teamsRepository)
{
parent::__construct();
$this->tournamentsRepository = $tournamentsRepository;
$this->matchesRepository = $matchesRepository;
$this->playersRepository = $playersRepository;
$this->teamsRepository = $teamsRepository;
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function getDashboard()
{
$user = $this->authUser;
$player = $user->player;
$team = $player->teams()->first();
$stats = [];
$tournaments = $this->tournamentsRepository->getTournamentsByPlayerID($player->id);
$matches = $this->matchesRepository->getFutureMatchesByPlayerID($player->id)->sortBy('starting_at');
$upcomingMatch = $matches->first();
return view('dashboard', compact('user', 'player', 'team', 'stats', 'tournaments', 'matches', 'upcomingMatch'));
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function getLanding()
{
return view('landing');
}
}
| true |
4a59360e81166d56ea7ecdea37ec5684fed297ac | PHP | wastedgod/sampleMessageBoard | /application/repository/BaseRepository.abstract.php | UTF-8 | 576 | 2.65625 | 3 | [] | no_license | <?php
namespace sampleMessageBoard\application\repository;
use Doctrine\ORM\EntityRepository;
abstract class BaseRepository extends EntityRepository implements iRepository{
public function create(iModel $model){
$this->getEntityManager()->persist($model);
$this->getEntityManager()->flush();
}
public function remove(iModel $model){
$this->getEntityManager()->remove($model);
$this->getEntityManager()->flush();
}
public function update(iModel $model){
$this->getEntityManager()->persist($model);
$this->getEntityManager()->flush();
}
}
?>
| true |
b8b79c88fb36e5accf7d201b696f881e14b89995 | PHP | Zamachi/WebIS | /WBISFramework/models/tagsModel.php | UTF-8 | 393 | 2.59375 | 3 | [] | no_license | <?php
namespace app\models;
use app\core\DBModel;
class TagsModel extends DBModel{
public $tag_id;
public $tag_name;
public function tableName()
{
return "tags";
}
public function attributes(): array
{
return [
"tag_id",
"tag_name"
];
}
public function rules(): array
{
return [];
}
} | true |
dcf194dba0cc82a8d3a3f2f41e35ac4d0c0c8283 | PHP | gabemarquesi/Repub | /Repub/php/repub.controlador/notificacaoControlador.php | UTF-8 | 2,281 | 2.8125 | 3 | [] | no_license | <?php
include_once '../repub.persistencia/bd_repub.php';
include_once '../repub.modelos/notificacao.php';
class NotificacaoControlador {
public $bd;
function __construct() {
$this->bd = new BDRepub();
}
public function get($id) {
$sql = "SELECT * FROM a14017.notificacao WHERE id=:param1";
$params[] = $id;
$obj = $this->bd->executeQuery($sql, $params);
if (count($obj) > 0) {
$notificacao = new Notificacao($obj[0]->id, $obj[0]->texto, $obj[0]->usuarioID);
}
return $notificacao;
}
public function create($notificacao) {
if ($notificacao == null) {
throw new Exception('Uma notificação não-nula precisa ser fornecida.');
}
$ex = Notificacao::validate($notificacao);
if ($ex != null) {
throw $ex;
}
$sql = "INSERT INTO a14017.notificacao (usuarioID, texto) VALUES (:param1, :param2)";
$params = array($notificacao->usuarioID, $notificacao->texto);
if (!$this->bd->executeNonQuery($sql, $params)) {
throw new Exception('Um erro ocorreu durante a criação da notificação.');
}
$novaNotificacao = $this->get($this->bd->lastID);
return $novaNotificacao;
}
public function delete($id) {
$sql = "DELETE FROM a14017.notificacao WHERE id = :param1";
$params = array($id);
if (!$this->bd->executeNonQuery($sql, $params)) {
throw new Exception('Um erro ocorreu ao deletar a notificação.');
}
}
public function update($notificacao) {
if ($notificacao == null) {
throw new Exception('Uma notificação não-nula precisa ser fornecida.');
}
$ex = Notificacao::validate($notificacao);
if ($ex != null) {
throw $ex;
}
$sql = "UPDATE a14017.notificacao SET usuarioID = :param1, texto = :param2";
$params = array($notificacao->usuarioID, $notificacao->texto);
if (!$this->bd->executeNonQuery($sql, $params)) {
throw new Exception('Um erro ocorreu ao atualizar a notificação.');
}
$novaNotificacao = $this->get($notificacao->id);
return $novaNotificacao;
}
}
| true |
206b4c64313dcf5d540256aaa51b551016f967af | PHP | exelentshakil/easycoupons | /includes/Admin/Coupon.php | UTF-8 | 13,235 | 2.5625 | 3 | [] | no_license | <?php
namespace Easy\Coupons\Admin;
class Coupon {
private $database_table;
/**
* @var array
*/
private $screens = ['easy-video'];
/**
* @var array
*/
private $fields = [
[
'label' => 'Video Url',
'id' => 'video',
'type' => 'url',
'default' => 'https://www.youtube.com/embed/<video-id>',
],
];
public function __construct()
{
global $wpdb;
$this->database_table = $wpdb->prefix . 'easycoupons';
// add custom Easy Video post type
add_action('init', [$this, 'create_easyvideo_cpt']);
// add custom meta box
add_action( 'add_meta_boxes', [$this, 'add_meta_boxes'] );
add_action( 'save_post', [$this, 'save_fields'] );
// generate shortcode box after post submit
add_action( 'submitpost_box', [$this, 'callback__submitpost_box'] );
}
public function coupons() {
include __DIR__ . '/views/coupons.php';
}
public function coupons_log() {
include __DIR__ . '/views/coupons_log.php';
}
public function generate_coupons() {
global $wpdb;
$table_name = $this->database_table; // do not forget about tables prefix
$message = '';
$notice = '';
// this is default $item which will be used for new records
$default = array(
// 'id' => 0,
'coupon' => '',
'expiry_date' => '',
'is_used' => 0,
'created_by' => get_current_user_id(),
'created_at' => date('Y-m-d H:i:s'),
);
// here we are verifying does this request is post back and have correct nonce
if ( isset($_REQUEST['nonce']) && wp_verify_nonce($_REQUEST['nonce'], basename(__FILE__))) {
$generated = 0;
$target = $_REQUEST['code_count'];
$expire = $_REQUEST['expire_date'];
while ($generated < $target) {
$item = $default;
$item['coupon'] = $this->generate_code();
$date = new \DateTime($expire);
$item['expiry_date'] = date('Y-m-d H:i:s', $date->getTimestamp());
$result = $wpdb->insert($table_name, $item);
if ($result) {
$generated++;
}
if ($generated == $target) {
$message = $target.' coupon code generated!';
}
}
} else {
// if this is not post back we load item to edit or give new one to create
$item = $default;
if (isset($_REQUEST['id'])) {
$item = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $_REQUEST['id']), ARRAY_A);
if (!$item) {
$item = $default;
$notice = __('Item not found', 'easycoupons');
}
}
}
// here we adding our custom meta box
add_meta_box('coupons_form_meta_box', 'Bulk Coupon Code Generator', [$this, 'easy_coupons_form_meta_box_handler'], 'new-coupon', 'normal', 'default');
?>
<div class="wrap">
<div class="icon32 icon32-posts-post" id="icon-edit"><br></div>
<h2><?php _e('Easy Coupons', 'easycoupons')?>
<a class="add-new-h2" href="<?php echo get_admin_url(get_current_blog_id(), 'admin.php?page=coupons');?>"><?php _e('Back to list', 'easycoupons')?></a>
</h2>
<?php if (!empty($notice)): ?>
<div id="notice" class="error"><p><?php echo $notice ?></p></div>
<?php endif;?>
<?php if (!empty($message)): ?>
<div id="message" class="updated"><p><?php echo $message ?></p></div>
<?php endif;?>
<form id="form" method="POST">
<input type="hidden" name="nonce" value="<?php echo wp_create_nonce(basename(__FILE__))?>"/>
<?php /* NOTICE: here we storing id to determine will be item added or updated */ ?>
<input type="hidden" name="id" value="<?php echo $item['id'] ?>"/>
<div class="metabox-holder" id="poststuff">
<div id="post-body">
<div id="post-body-content">
<?php /* And here we call our custom meta box */ ?>
<?php do_meta_boxes('new-coupon', 'normal', $item); ?>
<input type="submit" value="<?php _e('Save', 'easycoupons')?>" id="submit" class="button-primary" name="submit">
</div>
</div>
</div>
</form>
</div>
<?php
}
/**
* This function renders our custom meta box
* $item is row
*
* @param $item
*/
function easy_coupons_form_meta_box_handler($item)
{
?>
<table cellspacing="2" cellpadding="5" style="width: 100%;" class="form-table">
<tbody>
<tr class="form-">
<th valign="top" scope="row">
<label for="code_count"><?php _e('Number of Coupon', 'easycoupons')?></label>
</th>
<td>
<input id="code_count" name="code_count" type="number" min="1" max="100" value="1"
class="small-text" required>
</td>
</tr>
<tr class="form-">
<th valign="top" scope="row">
<label for="expire_date"><?php _e('Expiry Date', 'easycoupons')?></label>
</th>
<td>
<input id="expire_date" name="expire_date" type="date" class="regular-text" min="<?php echo date('Y-m-d'); ?>" required>
</td>
</tr>
</tbody>
</table>
<?php
}
/**
* This function generates coupon codes.
*
*/
private function generate_code(){
$bytes = random_bytes(2);
// var_dump(bin2hex($bytes));
return bin2hex($bytes);
}
public function init( $page ) {
$page = isset( $_GET['action'] ) ? $_GET['action'] : '';
switch ( $page ) {
case 'settings':
$template = __DIR__ . '/views/generate-coupons.php';
break;
default:
$template = __DIR__ . '/views/dashboard.php';
break;
}
if ( file_exists( $template ) ) {
include $template;
}
}
public function menu_page() {
wp_enqueue_script( 'main' );
include __DIR__ . '/views/dashboard.php';
}
// Register Custom Post Type Easy Video
function create_easyvideo_cpt() {
$labels = array(
'name' => _x( 'Easy Videos', 'Post Type General Name', 'easycoupons' ),
'singular_name' => _x( 'Easy Video', 'Post Type Singular Name', 'easycoupons' ),
'menu_name' => _x( 'Easy Videos', 'AdminLoader Menu text', 'easycoupons' ),
'name_admin_bar' => _x( 'Easy Video', 'Add New on Toolbar', 'easycoupons' ),
'archives' => __( 'Easy Video Archives', 'easycoupons' ),
'attributes' => __( 'Easy Video Attributes', 'easycoupons' ),
'parent_item_colon' => __( 'Parent Easy Video:', 'easycoupons' ),
'all_items' => __( 'All Easy Videos', 'easycoupons' ),
'add_new_item' => __( 'Add New Easy Video', 'easycoupons' ),
'add_new' => __( 'Add New', 'easycoupons' ),
'new_item' => __( 'New Easy Video', 'easycoupons' ),
'edit_item' => __( 'Edit Easy Video', 'easycoupons' ),
'update_item' => __( 'Update Easy Video', 'easycoupons' ),
'view_item' => __( 'View Easy Video', 'easycoupons' ),
'view_items' => __( 'View Easy Videos', 'easycoupons' ),
'search_items' => __( 'Search Easy Video', 'easycoupons' ),
'not_found' => __( 'Not found', 'easycoupons' ),
'not_found_in_trash' => __( 'Not found in Trash', 'easycoupons' ),
'featured_image' => __( 'Featured Image', 'easycoupons' ),
'set_featured_image' => __( 'Set featured image', 'easycoupons' ),
'remove_featured_image' => __( 'Remove featured image', 'easycoupons' ),
'use_featured_image' => __( 'Use as featured image', 'easycoupons' ),
'insert_into_item' => __( 'Insert into Easy Video', 'easycoupons' ),
'uploaded_to_this_item' => __( 'Uploaded to this Easy Video', 'easycoupons' ),
'items_list' => __( 'Easy Videos list', 'easycoupons' ),
'items_list_navigation' => __( 'Easy Videos list navigation', 'easycoupons' ),
'filter_items_list' => __( 'Filter Easy Videos list', 'easycoupons' ),
);
$args = array(
'label' => __( 'Easy Video', 'easycoupons' ),
'description' => __( '', 'easycoupons' ),
'labels' => $labels,
'menu_icon' => 'dashicons-video-alt3',
'supports' => array('title','thumbnail'),
'taxonomies' => array(),
'public' => false,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 100,
'show_in_admin_bar' => false,
'show_in_nav_menus' => false,
'can_export' => true,
'has_archive' => false,
'hierarchical' => false,
'exclude_from_search' => true,
'show_in_rest' => false,
'publicly_queryable' => false,
'capability_type' => 'post',
);
register_post_type( 'easy-video', $args );
}
public function add_meta_boxes() {
add_meta_box(
'LockedVideo',
__( 'Locked Video', 'easycoupons' ),
[$this, 'meta_box_callback'],
'easy-video',
'normal',
'default'
);
}
/**
* @param $post
*/
public function meta_box_callback( $post ) {
wp_nonce_field( 'easy_coupons_nonce', 'easy_coupons_nonce' );
$this->field_generator( $post );
}
/**
* @param $post
*/
public function field_generator( $post ) {
$output = '';
foreach ( $this->fields as $field ) {
$label = '<label for="' . $field['id'] . '">' . $field['label'] . '</label>';
$meta_value = get_post_meta( $post->ID, $field['id'], true );
if ( empty( $meta_value ) ) {
if ( isset( $field['default'] ) ) {
$meta_value = $field['default'];
}
}
switch ( $field['type'] ) {
default:
$input = sprintf(
'<input %s id="%s" name="%s" type="%s" value="%s">', 'color' !== $field['type'] ? 'style="width: 100%"' : '',
$field['id'],
$field['id'],
$field['type'],
$meta_value
);
}
$output .= $this->format_rows( $label, $input );
}
echo '<table class="form-table"><tbody>' . $output . '</tbody></table>';
}
/**
* @param $label
* @param $input
*/
public function format_rows( $label, $input ) {
return '<div style="margin-top: 10px;"><strong>' . $label . '</strong></div><div>' . $input . '</div>';
}
/**
* @param $post_id
* @return mixed
*/
public function save_fields( $post_id ) {
if ( ! isset( $_POST['easy_coupons_nonce'] ) ) {
return $post_id;
}
$nonce = $_POST['easy_coupons_nonce'];
if ( ! wp_verify_nonce( $nonce, 'easy_coupons_nonce' ) ) {
return $post_id;
}
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return $post_id;
}
foreach ( $this->fields as $field ) {
if ( isset( $_POST[$field['id']] ) ) {
switch ( $field['type'] ) {
case 'url':
$_POST[$field['id']] = esc_url_raw( $_POST[$field['id']] );
break;
case 'text':
$_POST[$field['id']] = sanitize_text_field( $_POST[$field['id']] );
break;
}
update_post_meta( $post_id, $field['id'], $_POST[$field['id']] );
} else if ( 'checkbox' === $field['type'] ) {
update_post_meta( $post_id, $field['id'], '0' );
}
}
}
/**
* @param $post
*/
public function callback__submitpost_box( $post ) {
if ( 'easy-video' === $post->post_type && 'publish' === $post->post_status ) {
echo '<div class="sc-box">
<div class="postbox-header"><h2 class="hndle ui-sortable-handle">Video Shortcode</h2></div>
<div class="inside">
<input type="text" value="[easy-coupon id=', esc_attr( $post->ID ), ']" readonly>
<p>Use this shortcode to render a locked video</p>
</div>
</div>';
}
}
} | true |
72dd30fb9a0d3c29e7f61bea340c6c81527f6f00 | PHP | sebastian-misiewicz/widget-o-php | /Widgeto/Rest/LogoutRest.php | UTF-8 | 483 | 2.59375 | 3 | [] | no_license | <?php
namespace Widgeto\Rest;
use Widgeto\Repository\AuthRepository;
class LogoutRest {
/* @var $app \Slim\Slim */
public function __construct($app) {
$app->post('/rest/logout/', function () use ($app) {
$token = $app->request->headers("auth-token");
if (!isset($token) || empty($token)) {
$app->error();
}
AuthRepository::removeToken($token);
});
}
}
| true |
726fa0366a3ef8e1dde0335b35d5e6eb163f1708 | PHP | Aarthi-Saba/PHP-CMS-Blog-Application | /admin/includes/ViewAllUsers.php | UTF-8 | 3,044 | 2.5625 | 3 | [] | no_license | <table class="table table-bordered table-hover">
<thead>
<tr>
<th>User Id</th>
<th>Username</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Profile Image</th>
<th>Role</th>
<th style="text-align:center" colspan=2>Roles</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
global $sqlconnection;
$alluserquery = mysqli_prepare($sqlconnection,"SELECT User_Id,User_Name,User_FirstName,User_LastName,User_Email,
User_Image,User_Role FROM USER");
mysqli_stmt_execute($alluserquery);
mysqli_stmt_bind_result($alluserquery,$userid,$username,$userfirstname,$userlastname,$useremail,
$userimage,$userrole);
mysqli_stmt_store_result($alluserquery);
if(mysqli_stmt_num_rows($alluserquery)>=1)
{
while(mysqli_stmt_fetch($alluserquery))
{
?>
<?php
echo "<tr>";
echo "<td>$userid</td>";
echo "<td>$username</td>";
echo "<td>$userfirstname</td>";
echo "<td>$userlastname</td>";
echo "<td>$useremail</td>";
echo "<td><img width=100 src = '/cms/images/$userimage' alt='image'></td>";
echo "<td>$userrole</td>";
echo "<td> <a href='Users.php?change_to_admin={$userid}'>Admin</a></td>";
echo "<td> <a href='Users.php?change_to_subscriber={$userid}'>Subscribe</a></td>";
echo "<td> <a href='Users.php?source=edit_user&u_id={$userid}'>EDIT</a></td>";
echo "<td> <a href='Users.php?delete={$userid}'>DELETE</a></td>";
echo "</tr>";
}
}
else{
echo "No users to display";
}
?>
</tbody>
</table>
<?php
if(isset($_GET['change_to_admin']))
{
$userid = Escape($_GET['change_to_admin']);
$adminquery = "UPDATE USER SET User_Role='Admin' WHERE User_id=$userid ";
$approvedadmin= mysqli_query($sqlconnection,$adminquery);
header("Location: Users.php");
exit;
}
if(isset($_GET['change_to_subscriber']))
{
$userid = Escape($_GET['change_to_subscriber']);
$subscriberquery = "UPDATE USER SET User_Role='Subscriber' WHERE User_id=$userid ";
$approvedsubscriber = mysqli_query($sqlconnection,$subscriberquery);
header("Location: Users.php");
exit;
}
if(isset($_GET['delete']))
{
if(is_admin())
{
$deleteuserid = mysqli_real_escape_string($sqlconnection,$_GET['delete']);
$deleteuserquery = "DELETE FROM USER WHERE User_Id=$deleteuserid";
$deleteduser = mysqli_query($sqlconnection,$deleteuserquery);
header("Location: Users.php");
exit;
}
}
?> | true |
6047d431a45d8be6fd8be7c9818f87883527ced7 | PHP | instantjay/emailphp | /src/Providers/Mandrill.php | UTF-8 | 2,381 | 2.796875 | 3 | [
"MIT"
] | permissive | <?php
namespace instantjay\emailphp\Providers;
class Mandrill extends Provider {
private $apiKey;
public function __construct($apiKey, $defaultSenderEmailAddress, $defaultSenderName)
{
parent::__construct($defaultSenderEmailAddress, $defaultSenderName);
$this->apiKey = $apiKey;
}
private function prepareRecipientArray($emailAddress, $name, $type = 'to') {
$a = [
'email' => $emailAddress,
'name' => $name,
'type' => $type
];
return $a;
}
public function send($email) {
$recipients = [];
foreach($email->getRecipients() as $r) {
$recipients[] = $this->prepareRecipientArray($r->getEmailAddress(), $r->getName(), 'to');
}
foreach($email->getCCRecipients() as $r) {
$recipients[] = $this->prepareRecipientArray($r->getEmailAddress(), $r->getName(), 'cc');
}
foreach($email->getBCCRecipients() as $r) {
$recipients[] = $this->prepareRecipientArray($r->getEmailAddress(), $r->getName(), 'bcc');
}
$senderEmailAddress = ($email->getSenderEmailAddress() ? $email->getSenderEmailAddress() : $this->defaultSenderEmailAddress);
$senderName = ($email->getSenderEmailAddress() ? $email->getSenderEmailAddress() : $this->defaultSenderName);
$message = array(
"subject" => $email->getSubject(),
"from_email" => $senderEmailAddress,
"from_name" => $senderName,
"to" => $recipients
);
if($email->isHTML()) {
$message['text'] = 'Your e-mail client does not support HTML.';
$message['html'] = $email->getBody();
}
else {
$message['text'] = $email->getBody();
}
if($email->getReplyToEmailAddress()) {
$message['headers']['Reply-To'] = $email->getReplyToEmailAddress();
}
$mandrill = new \Mandrill($this->apiKey);
try {
$result = $mandrill->messages->send($message);
}
catch(\Mandrill_Error $e) {
return false;
}
foreach($result as $r) {
if($r["status"] != "sent") {
// Do something here if an email to one recipient fails.
return false;
}
}
return $result;
}
} | true |
2636782e8153c0e636f41ae08fca2e6fd3d5f092 | PHP | tschalch/labdb | /html/getGene.php | UTF-8 | 637 | 2.71875 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
include("connect.php");
#print $_GET['geneIDs'];
$geneIDs = explode(":",$_GET['geneIDs']);
$type = $_GET['type'];
$sequence = '';
#print_r($geneIDs);
foreach ($geneIDs as $geneID){
if ($geneID){
$query = "SELECT * FROM genes WHERE id=$geneID";
#print $query;
$result=mysql_query($query);
#print mysql_error($link);
$row = mysql_fetch_assoc($result);
if($type=='DNA')$part = $row['DNASequence'];
if($type=='protein')$part = $row['proteinSequence'];
if($part){
$sequence .= $part;
} else {
$sequence = "sequence info missing!";
break;
}
}
}
mysql_close();
print $sequence;
?> | true |
208824371c8e7065ab79c4bfa77b8beba49e54e1 | PHP | KeylaRocha/Trabalho_BD1_UFV_2019-2 | /application/models/pessoafisica_model.php | UTF-8 | 9,113 | 2.796875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
*---------------------------------------------------------------
* MODEL PESSOAFISICA
*---------------------------------------------------------------
*
* Model que trata as funções relacionadas ao objeto PessoaFisica.
* Todas as funções que necessitam de acessos ao banco de dados,
* estão descritas neste arquivo.
*
*/
class PessoaFisica_model extends CI_Model {
/**
* Construtor
*/
public function __construct() {
parent::__construct();
}
/**
* Retorna a quantidade de linhas na tabela
*/
public function record_count() {
return $this->db->count_all("pessoafisica");
}
/**
* Insere um pessoa fisica no banco de dados
*/
public function inserirPessoaFisica($pessoafisica){
// O parâmetro da função deve ser um objeto do tipo 'PessoaFisica'
if($pessoafisica instanceof PessoaFisica){
$this->db->trans_start();
$dados = array ('id' => $pessoafisica->getIdCliente(),
'nome' => $pessoafisica->getNome(),
'telefone' => $pessoafisica->getTelefone(),
'email' => $pessoafisica->getEmail());
$this->db->insert('cliente', $dados);
if($pessoafisica->getIdCliente()==NULL)
$id = $this->db->insert_id();
else
$id =$pessoafisica->getIdCliente();
// Insere o administrador
$dados = array ('idCliente' => $id,
'CPF' => $pessoafisica->getCPF(),
'dataNascimento' => $pessoafisica->getDataNascimento());
$this->db->insert('pessoafisica', $dados);
// Finaliza a transação e fecha a conexão
$this->db->trans_complete();
//$this->db->close();
if($this->db->trans_status())
return $id;
return FALSE;
}
}
/**
* Edita um administrador no banco de dados
*/
public function editarPessoaFisica($pessoafisica){
// O parâmetro da função deve ser um objeto do tipo 'PessoaFisica'
if($pessoafisica instanceof PessoaFisica){
$this->db->trans_start();
$dados = array ('id' => $pessoafisica->getIdCliente(),
'nome' => $pessoafisica->getNome(),
'telefone' => $pessoafisica->getTelefone(),
'email' => $pessoafisica->getEmail());
$this->db->where('id', $pessoafisica->getIdCliente());
$this->db->update('cliente', $dados);
// Insere a pessoa fisica
$dados = array ('idCliente' => $pessoafisica->getIdCliente(),
'CPF' => $pessoafisica->getCPF(),
'dataNascimento' => $pessoafisica->getDataNascimento());
// Pesquisa se existe pessoa fisica no banco de dados
$this->db->where('idCliente', $pessoafisica->getIdCliente());
// Atualiza a alteração no banco de dados
$this->db->update('pessoafisica', $dados);
// Finaliza a transação e fecha a conexão
$this->db->trans_complete();
$this->db->close();
if($this->db->trans_status())
return TRUE;
return FALSE;
}
}
/**
* Lista todos os administradores retornando um array com todos os itens cadastrados no banco de dados.
* Se a função for chamada sem parâmetros, considera que o usuário quer listar todos os itens.
*/
public function listarPessoasFisicas($limit = 0, $start = 0) {
// Caso não seja passado nenhum valor limite como parâmetro, inicia a variável com o número total de administradores cadastrados no banco de dados
if ($limit == 0) {
$limit = $this->record_count();
}
// Inicia a transação
$this->db->trans_start();
//$this->db->order_by('status ASC, nome ASC');
$this->db->limit($limit, $start);
// Realiza a pesquisa no banco de dados e joga os dados na query
$query = $this->db->query('SELECT p.idCliente, p.CPF, p.dataNascimento, c.nome, c.telefone, c.email from pessoafisica p
JOIN cliente c ON p.idCliente = c.id;');
// Finaliza a transação e fecha a conexão
$this->db->trans_complete();
$this->db->close();
$pessoasfisicas = array();
// Verifica se encontrou alguma pessoa fisica na query
if ($query->num_rows() > 0 ) {
// Joga os resultados dentro da variável $pessoasfisicas
foreach ($query->result() as $row) {
// Se a pessoa fisica não tiver com status 'excluído'
$pessoasfisicas[] = new PessoaFisica( $row->idCliente,
$row->CPF,
$row->dataNascimento,
$row->nome,
$row->telefone,
$row->email);
}
// Retorna o array com todos os administradores encontrados
return $pessoasfisicas;
}
return NULL;
}
public function listarPessoasFisicasByFaturamento($limit = 0, $start = 0) {
// Caso não seja passado nenhum valor limite como parâmetro, inicia a variável com o número total de administradores cadastrados no banco de dados
if ($limit == 0) {
$limit = $this->record_count();
}
// Inicia a transação
$this->db->trans_start();
//$this->db->order_by('status ASC, nome ASC');
$this->db->limit($limit, $start);
// Realiza a pesquisa no banco de dados e joga os dados na query
$query = $this->db->query('SELECT p.idCliente, p.CPF, p.dataNascimento, c.nome, c.telefone, c.email, sum(a.valorTotal) as faturamento from aluguel as a JOIN reserva as r ON
r.idReserva = a.idReserva RIGHT JOIN cliente c ON r.idCliente = c.id JOIN pessoafisica p ON p.idCliente = c.id GROUP BY
p.idCliente ORDER BY faturamento DESC');
// Finaliza a transação e fecha a conexão
$this->db->trans_complete();
$this->db->close();
$pessoasfisicas = array();
// Verifica se encontrou alguma pessoa fisica na query
if ($query->num_rows() > 0 ) {
// Joga os resultados dentro da variável $pessoasfisicas
foreach ($query->result() as $row) {
// Se a pessoa fisica não tiver com status 'excluído'
$pessoasfisicas[] = array(new PessoaFisica( $row->idCliente,
$row->CPF,
$row->dataNascimento,
$row->nome,
$row->telefone,
$row->email),
$row->faturamento);
}
// Retorna o array com todos os administradores encontrados
return $pessoasfisicas;
}
return NULL;
}
/**
* Obtém todos os dados do administrador baseado no código recebido como parâmetro.
*/
public function getPessoaFisica($idCliente) {
$this->db->trans_start();
// Realiza a pesquisa no banco de dados e joga os dados na query
$query = $this->db->query('SELECT p.idCliente, p.CPF, p.dataNascimento, c.nome, c.telefone, c.email from pessoafisica p
JOIN cliente c ON p.idCliente = c.id WHERE id="'.$idCliente.'";');
// Finaliza a transação e fecha a conexão
$this->db->trans_complete();
//$this->db->close();
// Caso não tenha encontrado nenhum administrador, retorna um valor nulo
if ($query->num_rows() == 0)
return null;
// Caso encontre o dado, pega a linha que contém este administrador
$row = $query->row();
// Retorna o administrador requisitado
return new PessoaFisica( $row->idCliente,
$row->CPF,
$row->dataNascimento,
$row->nome,
$row->telefone,
$row->email);
}
public function getPessoaFisicaByCPF($cpf) {
$this->db->trans_start();
// Realiza a pesquisa no banco de dados e joga os dados na query
$query = $this->db->query('SELECT p.idCliente, p.CPF, p.dataNascimento, c.nome, c.telefone, c.email from pessoafisica p
JOIN cliente c ON p.idCliente = c.id WHERE p.CPF="'.$cpf.'";');
// Finaliza a transação e fecha a conexão
$this->db->trans_complete();
//$this->db->close();
// Caso não tenha encontrado nenhum administrador, retorna um valor nulo
if ($query->num_rows() == 0)
return null;
// Caso encontre o dado, pega a linha que contém este administrador
$row = $query->row();
// Retorna o administrador requisitado
return new PessoaFisica( $row->idCliente,
$row->CPF,
$row->dataNascimento,
$row->nome,
$row->telefone,
$row->email);
}
public function podeRemover($campo,$id) {
// Inicia a transação
$this->db->trans_start();
$this->db->where($campo,$id);
$query = $this->db->get('pessoafisica');
$this->db->trans_complete();
//$this->db->close();
if ($query->num_rows() == 0)
return True;
return False;
}
public function removerPessoaFisica($id) {
// Inicia a transação
$this->db->trans_start();
$this->db->where('idCliente',$id);
$query = $this->db->delete('pessoafisica');
$this->db->trans_complete();
//$this->db->close();
if($this->db->trans_status())
return TRUE;
return FALSE;
}
}
/* End of file pessoafisica_model.php */
/* Location: ./application/models/pessoafisica_model.php */ | true |
2e831ae6c9904787b7fe791c13184ca915c71774 | PHP | lifenglsf/JunaShare-Service | /profiles/juna_v1/modules/junaapp/users/includes/sms.inc | UTF-8 | 1,495 | 2.515625 | 3 | [] | no_license | <?php
require_once 'alisms/TopSdk.php';
function sendsms($data) {
//print_r($data);exit;
$smssettings = unserialize(variable_get('smssettings'));
$c = new TopClient;
$c->format = 'json';
$c->appkey = $smssettings['appkey'];//$appkey;
$c->secretKey = $smssettings['secret'];//$secret;
$req = new AlibabaAliqinFcSmsNumSendRequest;
$req->setExtend("");
$req->setSmsType("normal");
$req->setSmsFreeSignName($smssettings['sign']);
$param = json_encode(array('code' => $data['code'], 'product' => $smssettings['product']));
$req->setSmsParam($param);
$req->setRecNum($data['mobile']);
$req->setSmsTemplateCode($smssettings['templateid']);//"SMS_585014"
$resp = $c->execute($req);
return $resp;
}
/**
* Common SMS sending function.
* @param $mobile
* @param $sign
* @param array $args
* @param string $templateId
* @return mixed|\ResultSet|\SimpleXMLElement
*/
function smsSending($mobile, $sign, $args = array(), $templateId = 'SMS_585014') {
$smssettings = unserialize(variable_get('smssettings'));
$c = new TopClient;
$c->format = 'json';
$c->appkey = $smssettings['appkey'];//$appkey;
$c->secretKey = $smssettings['secret'];//$secret;
$req = new AlibabaAliqinFcSmsNumSendRequest;
$req->setExtend("");
$req->setSmsType("normal");
$req->setSmsFreeSignName($sign);
$param = json_encode($args);
$req->setSmsParam($param);
$req->setRecNum($mobile);
$req->setSmsTemplateCode($templateId);//
$resp = $c->execute($req);
return $resp;
}
| true |
3e240c30e3cfbe8867fb322d6238a9c6575bc9fd | PHP | Vashthestupid/WEST_BURGER | /WEST_BURGER/src/views/admin/plats/index_plat.php | UTF-8 | 2,087 | 2.59375 | 3 | [] | no_license | <?php
// On récupère l'id et le nom du plat
$select = "SELECT plat.id, nomPlat FROM plat ORDER BY plat.id DESC";
$req = $db->prepare($select);
$req->execute();
$plats = array();
while($data = $req->fetchObject()){
array_push($plats,$data);
}
?>
<div class="container">
<div class="row">
<div class="col-sm-12 offset-md-3 col-md-5">
<div class="table-responsive mt-3">
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Nom du plat</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
foreach ($plats as $plat) {
?>
<tr>
<td><?= $plat->id ?></td>
<td><?= $plat->nomPlat ?></td>
<td>
<a href="<?= $router->generate('Voir_plat')?>?id=<?=$plat->id?>">
<button class="btn btn-outline-dark">
Voir
</button>
</a>
<a href="<?= $router->generate('Editer_plat')?>?id=<?=$plat->id?>">
<button class="btn btn-outline-dark">
Editer
</button>
</a>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
<div class="navigation">
<a class="nav-link" href="/admin/plats/Nouveau_plat">Créer un nouveau plat</a>
</div>
</div>
</div>
</div>
</div> | true |
4ae3cc560f507bd9bcea6eefe7f3da4f274d1436 | PHP | fsilberg/bnote | /BNote-Releases/BNote/Patches/patch210/update_db.php | UTF-8 | 2,177 | 2.65625 | 3 | [] | no_license | <?php
/*************************
* UPGRADES THE DATABASE *
* @author Matti Maier *
* Patch 2.1 *
*************************/
// path to src/ folder
$PATH_TO_SRC = "src/";
?>
<html>
<head>
<title>Database Update</title>
</head>
<body>
<?php
// include necessary libs
require_once $PATH_TO_SRC . "data/database.php";
require_once $PATH_TO_SRC . "presentation/widgets/error.php";
// build DB connection
$db = new Database();
?>
<p><b>This script updates the bluenote system's database structure. Please make sure it is only executed once!</b></p>
<h3>Log</h3>
<p>
<?php
/*
* TASK 1: Add columns "mobile" and "business" to table "contact"
*/
// get a list of fields
$fields = $db->getFieldsOfTable("contact");
// add fields only when they do not exist
if(!in_array("mobile", $fields)) {
$query = "ALTER TABLE contact ADD COLUMN mobile varchar(30) AFTER fax";
$db->execute($query);
echo "<i>column contact.mobile added</i><br>";
}
else {
echo "<i>column contact.mobile already exists.</i><br>";
}
if(!in_array("business", $fields)) {
$query = "ALTER TABLE contact ADD COLUMN business varchar(30) AFTER mobile";
$db->execute($query);
echo "<i>column contact.business added</i><br>";
}
else {
echo "<i>column contact.business already exists.</i><br>";
}
/*
* TASK 2: Add row to "module" table with new contact module for users
*/
$mod_exists = $db->getCell("module", "count(*)", "name = 'Mitspieler'");
$mod_id = -1;
if($mod_exists > 0) {
echo "<i>Module 'Mitspieler' already exists in database.</i><br>";
}
else {
$query = "INSERT INTO module (name) VALUES ('Mitspieler')";
$mod_id = $db->execute($query);
echo "<i>Module 'Mitspieler' added.</i><br>";
}
/*
* TASK 3: Add privileges for all users for the new contact module
*/
if($mod_id > 0) {
$query = "SELECT id FROM " . $db->getUserTable();
$users = $db->getSelection($query);
for($i = 1; $i < count($users); $i++) {
$query = "INSERT INTO privilege (user, module) VALUES (" . $users[$i]["id"] . ", $mod_id)";
$db->execute($query);
}
echo "<i>Privileges to the new module 'Mitspieler' added to <u>all</u> users.</i><br>";
}
?>
<br/>
<b><i>COMPLETE.</i></b>
</p>
</body>
</html> | true |
1204ac3ca3a459ce1cc2d421d93f249a65ca2719 | PHP | fecaps/working_out | /src/Generator/Exercises.php | UTF-8 | 1,774 | 3 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace App\Generator;
use App\Enum\Participant as ParticipantEnum;
use App\Generator\Context\ExercisingLevelContext;
use App\Generator\Level\BeginnerExercising;
use App\Generator\Level\ProfessionalExercising;
final class Exercises
{
private $participants;
private $exercisingLevelContext;
private $beginnerExercising;
private $professionalExercising;
public function __construct()
{
$this->participants = ParticipantEnum::PARTICIPANTS;
$this->exercisingLevelContext = new ExercisingLevelContext();
$this->beginnerExercising = new BeginnerExercising();
$this->professionalExercising = new ProfessionalExercising();
}
public function defineSequences(): array
{
foreach ($this->participants as $participantKey => $participant) {
$this->participants[$participantKey] = $this->defineParticipantWithExercises(
$this->participants,
$participantKey
);
}
return $this->participants;
}
private function defineParticipantWithExercises(array $allParticipants, int $participantKey): array
{
$allParticipants[$participantKey][ParticipantEnum::EXERCISES_KEY] = [];
$level = $allParticipants[$participantKey][ParticipantEnum::LEVEL_KEY];
if ($level === ParticipantEnum::BEGINNER_LEVEL) {
$this->exercisingLevelContext->defineLevel($this->beginnerExercising);
}
if ($level === ParticipantEnum::PROFESSIONAL_LEVEL) {
$this->exercisingLevelContext->defineLevel($this->professionalExercising);
}
return $this->exercisingLevelContext->defineParticipantWithExercises($allParticipants, $participantKey);
}
}
| true |
786905fc99edc010d23f33e7c2f6b2fe87607174 | PHP | mukesh2122/samlink | /protected/viewc/forum/common/onlineUsers.php | UTF-8 | 705 | 2.5625 | 3 | [] | no_license | <div class="forumUserOnline">
<p><?php echo $OnlineUsers, $this->__(" users are online"); ?></p>
<p> <?php echo $onlineMembers,$this->__(" members"), ", ", $onlineGuests,$this->__(" guests"); ?> </p>
<?php
$members = 0;
foreach ($allOnlineUsers as $user) {
if($model->isMember($user->ID_PLAYER) === TRUE){
$members ++;
if($members != $onlineMembers){ ?>
<a href="<?php echo MainHelper::site_url('player/'.$user->URL); ?>" > <?php echo $user->DisplayName; ?> </a>,
<?php
}else{?>
<a href="<?php echo MainHelper::site_url('player/'.$user->URL); ?>" > <?php echo $user->DisplayName; ?> </a>
<?php
}
}
} ?>
</div> | true |
b6a87acecc338c5bd7c8bfe127bdfcd2e19cfae9 | PHP | asaokamei/tuum-skeleton | /app/Config/Factory/LoggerFactory.php | UTF-8 | 1,146 | 2.53125 | 3 | [] | no_license | <?php
namespace App\Config\Factory;
use Interop\Container\ContainerInterface;
use Monolog\Handler\FingersCrossedHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Monolog\Processor\UidProcessor;
use Tuum\Builder\AppBuilder;
class LoggerFactory
{
/**
* @var bool
*/
private $isDebug;
/**
* @param AppBuilder $builder
* @return LoggerFactory
*/
public static function forge(AppBuilder $builder)
{
$self = new self();
$self->isDebug = $builder->debug;
return $self;
}
/**
* @param ContainerInterface $c
* @return Logger
*/
public function __invoke(ContainerInterface $c)
{
$settings = $c->get('settings')['logger'];
$logger = new Logger($settings['name']);
$logger->pushProcessor(new UidProcessor());
$logger->pushHandler(new FingersCrossedHandler(
new StreamHandler($settings['path'], Logger::DEBUG)
));
if ($this->isDebug) {
$logger->pushHandler(new StreamHandler($settings['path'], Logger::DEBUG));
}
return $logger;
}
} | true |
e3ec99fe6238885ffc380670cd67c87b1ce9e2f4 | PHP | tongzebin/php | /wenjianfuzhi/bb/php18/3/3-1.php | UTF-8 | 355 | 2.546875 | 3 | [] | no_license | <?php
$a="./1.txt";
var_dump(is_dir($a));
var_dump(is_readable($a));
var_dump(is_writable($a));
var_dump(is_executable($a));
var_dump($qe=touch('3.txt'));
var_dump($ee=file_exists($a));
if(file_exists('3.txt')){
unlink("./3.txt");
}else{
echo '文件不存在';
}
var_dump(is_file('1.txt'));
| true |
6635d91e5401094bc71639a226d6f716d8a8b3a4 | PHP | ducbl98/PHP_L5_Inheritance | /Errands/MyClass.php | UTF-8 | 314 | 3.28125 | 3 | [] | no_license | <?php
class MyClass
{
/**
* MyClass constructor.
*/
public function __construct()
{
echo 'Calling constructor<br/>';
}
function some_method()
{
echo 'Calling a method<br/>';
}
function __destruct()
{
echo 'Calling destructor<br/>';
}
} | true |
fc3f5ef44c73367b308cf077834dfb3def059f25 | PHP | Dampkring1/OperationScreens | /func/fetchuser.php | UTF-8 | 2,750 | 2.625 | 3 | [] | no_license | <?php
$connect = mysqli_connect("localhost", "passbook", "Jhjkbr3kv7e7(aD04BsKh8DsqFgfja", "passbook");
$output = '';
$sql = "SELECT * FROM historical WHERE user LIKE '%".$_POST["search"]."%'";
$result = mysqli_query($connect, $sql);
if(mysqli_num_rows($result) > 0)
{
$output .= '<div class="table-responsive">
<table class="table table bordered">
<tr>
<th>SD Reference:</th>
<th>Company:</th>
<th>Engineer Name:</th>
<th>Pass Allocated:</th>
<th>Time In:</th>
<th>Date</th>
</tr>';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["sdref"].'</td>
<td>'.$row["company"].'</td>
<td>'.$row["name"].'</td>
<td>'.$row["passnum"].'</td>
<td>'.$row["time"].'</td>
<td>'.$row["date"].'</td>
</tr>
';
}
echo $output;
}
else
{
echo 'Data Not Found';
}
?>
<center><div class="alert alert-info">User has signed in the following engineers:</div></center>
<?php
$connect = mysqli_connect("localhost", "passbook", "Jhjkbr3kv7e7(aD04BsKh8DsqFgfja", "passbook");
$output = '';
$sql = "SELECT * FROM historical WHERE returnby LIKE '%".$_POST["search"]."%'";
$result = mysqli_query($connect, $sql);
if(mysqli_num_rows($result) > 0)
{
$output .= '<div class="table-responsive">
<table class="table table bordered">
<tr>
<th>SD Reference:</th>
<th>Company:</th>
<th>Engineer Name:</th>
<th>Pass Allocated:</th>
<th>Time Out:</th>
<th>Date</th>
</tr>';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["sdref"].'</td>
<td>'.$row["company"].'</td>
<td>'.$row["name"].'</td>
<td>'.$row["passnum"].'</td>
<td>'.$row["timeret"].'</td>
<td>'.$row["date"].'</td>
</tr>
';
}
echo $output;
}
else
{
echo 'Data Not Found';
}
?>
<center><div class="alert alert-info">User has signed out the following engineers:</div></center>
| true |
1e8d0b45c29a21fe520fe10b0d9fdd020546a03d | PHP | knxroot/FONDEF-D08I1205 | /lib/DatabaseUtils.class.php | UTF-8 | 751 | 3.109375 | 3 | [] | no_license | <?php
class DatabaseUtils
{
public static function getQueryKeys($array)
{
$keys = array_keys($array);
array_walk($keys, create_function('&$key', '$key = $key;'));
return implode(', ', $keys);
}
public static function getQueryPlaceholders($array)
{
$keys = array_keys($array);
array_walk($keys, create_function('&$key', '$key = ":".$key;'));
return implode(', ', $keys);
}
public static function prepareInsertQuery($table, $object)
{
$sql = sprintf('INSERT INTO %s (%s) VALUES (%s)',
$table,
self::getQueryKeys($object),
self::getQueryPlaceholders($object));
return $sql;
}
}
| true |
56f390ac61587a36af964f4ae1f8f360fd09187e | PHP | grimskin/cardmaster | /src/Helper/ManaVariator.php | UTF-8 | 1,723 | 2.859375 | 3 | [] | no_license | <?php
namespace App\Helper;
use App\Model\CardDefinition;
/**
* @deprecated
*/
class ManaVariator
{
public static function getManaOptions(CardDefinition ...$cardDefinitions): array
{
$lands = array_filter($cardDefinitions, function (CardDefinition $item) {
return $item->isLand();
});
return self::manaOptionsGenerator(...$lands);
}
private static function manaOptionsGenerator(CardDefinition ...$cardDefinitions): array
{
if (!count($cardDefinitions)) { return []; }
$result = [];
$card = array_pop($cardDefinitions);
$cardManaOptions = self::getLandManaOptions($card);
if (!count($cardDefinitions)) {
return array_map(function($item) {
return [$item];
}, $cardManaOptions);
}
foreach ($cardManaOptions as $manaOption) {
foreach (self::manaOptionsGenerator(...$cardDefinitions) as $option) {
$result[] = [$manaOption, ...$option];
}
}
return $result;
}
public static function getLandManaOptions(CardDefinition $card): array
{
return array_values(array_filter([
'1',
$card->canProduce(CardDefinition::COLOR_WHITE) ? CardDefinition::COLOR_WHITE : null,
$card->canProduce(CardDefinition::COLOR_BLUE) ? CardDefinition::COLOR_BLUE : null,
$card->canProduce(CardDefinition::COLOR_BLACK) ? CardDefinition::COLOR_BLACK : null,
$card->canProduce(CardDefinition::COLOR_RED) ? CardDefinition::COLOR_RED : null,
$card->canProduce(CardDefinition::COLOR_GREEN) ? CardDefinition::COLOR_GREEN : null,
]));
}
}
| true |
44968e9add0784fce23e821c5818138789a6dd4c | PHP | parix1999/php-snacks-b1 | /Snack-1/index.php | UTF-8 | 1,709 | 2.84375 | 3 | [] | no_license | <!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snack-1</title>
</head>
<body>
<!-- Traccia:
Creiamo una struttura dati che rappresenta le partite di basket, di un'ipotetica tappa di calendario
ogni array interno conterrà le seguenti informazioni:
- squadra di casa
- squadra ospite
- punti fatti dalla squadra di casa
- punti fatti dalla squadra ospite
stampiamo a schermo tutte le partite con questo schema:
Olimpia Milano - Cantù | 55-60
-->
<?php
#Creazione delle array:
$partite = [
[
"casa" => "Olimpia Milano",
"ospiti" => "Cantù",
"puntiCasa" => "55",
"puntiOspiti" => "60"
],
[
"casa" => "Virtus Lanciano",
"ospiti" => "Roma",
"puntiCasa" => "40",
"puntiOspiti" => "50"
],
[
"casa" => "Bologna",
"ospiti" => "Venezia",
"puntiCasa" => "50",
"puntiOspiti" => "70"
],
];
#Per stamparlo a video devo ragruppare i data:
#Entro dentro alle array con un for:
for ($i = 0; $i < count($partite); $i++) {
#Assegno ad una varibile i dati da prendere:
$string = $partite[$i]['casa'] . " - " . $partite[$i]['ospiti'] . " | " . $partite[$i]['puntiCasa'] . " - " . $partite[$i]['puntiOspiti'] . "<br>";
echo $string;
}
?>
</body>
</html> | true |
f10a44e60bfa5ca56a6f0cd0fc3253f07299ffc6 | PHP | scozdev/web-servis-basit | /register.php | UTF-8 | 1,703 | 2.625 | 3 | [] | no_license | <?php
require 'db.php';
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$user_name = $_POST['user_name'] ? $_POST['user_name'] : '';
$user_mail = $_POST['user_mail'] ? $_POST['user_mail'] : '';
$user_pass = $_POST['user_pass'] ? $_POST['user_pass'] : '';
$user_confirmation = rand(0, 1000) . rand(0, 1000);
$user_condition = 0;
$userControl = $db->query("select * from users where user_name='$user_name' or user_mail='$user_mail'")->rowCount();
class User
{
public $text;
public $isRegister;
}
$user = new User();
if (empty($user_name) || empty($user_mail) || empty($user_pass)) {
$user->text = 'Bos alan birakilamaz.';
$user->isRegister = false;
echo json_encode($user);
} else if ($userControl) {
$user->text = 'Kullanici zaten var.';
$user->isRegister = false;
echo json_encode($user);
} else {
$kaydet = $db->prepare("INSERT INTO users SET
user_name=:user_name,
user_mail=:user_mail,
user_pass=:user_pass,
user_confirmation=:user_confirmation,
user_condition=:user_condition
");
$insert = $kaydet->execute(array(
'user_name' => $user_name,
'user_mail' => $user_mail,
'user_pass' => $user_pass,
'user_confirmation' => $user_confirmation,
'user_condition' => $user_condition
));
if ($insert) {
$user->text = 'Kayit basarili.';
$user->isRegister = true;
echo json_encode($user);
} else {
$user->text = 'Kayit basarisiz .';
$user->isRegister = false;
echo json_encode($user);
}
}
}
| true |
3b9feded08b4a8537575795f62bc69a6c9d0d13a | PHP | thinwalk/techneter | /app/Modules/Forum/Repositories/Eloquents/ForumCategoryRepository.php | UTF-8 | 1,378 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Modules\Forum\Repositories\Eloquents;
use App\Modules\Forum\Repositories\Contracts\ForumCategoryRepositoryInterface;
use App\Repositories\EloquentRepository;
use App\Repositories\OperateIdTrait;
use App\Modules\Forum\Models\ForumCategory;
use App\Exceptions\RepositoryException;
class ForumCategoryRepository extends EloquentRepository implements ForumCategoryRepositoryInterface
{
use OperateIdTrait;
public function __construct()
{
$forumCategoryModel = ForumCategory::getInstance();
parent::__construct($forumCategoryModel);
}
protected function initFilterField()
{
$this->filterFields = ['id','ids'];
}
protected function initOrderField()
{
$this->orderFields = ['id_asc', 'id_desc','weight_asc', 'weight_desc'];
}
protected function initValidatorRules()
{
$this->rules = [
'STORE' => [
'name' => 'required|string|max:100',
'weight' => 'required|integer',
],
'UPDATE' => [
'name' => 'string|max:100',
'weight' => 'integer',
],
'FILTERFIELD' => [
'id' => 'integer',
'ids' => 'array',
'ids.*' => 'integer',
]
];
}
}
| true |
23df6d56cf805aa5ff22b68f598eb813cbbac2fe | PHP | MthulisiNdzombane/camagru | /components/Router.php | UTF-8 | 482 | 3 | 3 | [] | no_license | <?php
class Router
{
private $routes;
public function _construct()
{
$routesPath = ROOT.'config/routes.php';
$this->routes = include($routesPath);
}
public function run()
{
print_r(($this->routes));
//Get required string
//Check his required in routes.php
//If true -> define controller and action
//Connect class-controller file
//Create object, call method (action)
}
} | true |
1ddd0f2572c1c73537acaa6bfbb6d3c346cc5397 | PHP | 1999davidramos/Gues-My-Nomber | /turnoMaquina.php | UTF-8 | 1,754 | 3.03125 | 3 | [] | no_license | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Adivina maquina</title>
</head>
<body>
<a href="index.php">Volver a la pagina principal</a>
<br>
<form method="post">
<input type="submit" name="correcto" value="Es CORRECTO!!!" />
<input type="submit" name="NumeroPeque" value="EL numero es mas PEQUEÑO" />
<input type="submit" name="NumeroGrande" value="EL numero es mas GRANDE" />
</form>
<?php
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
if(array_key_exists('correcto', $_POST)) {
correcto();
}
else if(array_key_exists('NumeroPeque', $_POST)) {
NumeroPeque();
}
else if(array_key_exists('NumeroGrande', $_POST)) {
NumeroGrande();
}
if (!isset($_SESSION['IntentosRealizados'])){
$_SESSION['IntentosRealizados'] = 0;
}
if (!isset($_SESSION['pequeNum'])){
$_SESSION['pequeNum'] = 1;
}
if (!isset($_SESSION['grandeNun'])){
$_SESSION['grandeNun'] = $_SESSION['numerolimite'];
}
if (!isset($_SESSION['CONTADOR'])){
$_SESSION['CONTADOR'] = 0;
adivinaNumero();
}
function adivinaNumero() {
$_SESSION['CONTADOR']++;
$_SESSION['IntentosRealizados'] = rand ($_SESSION['pequeNum'], $_SESSION['grandeNun']);
echo "El numero es ".$_SESSION['IntentosRealizados']."?";
}
function NumeroPeque() {
$_SESSION['grandeNun'] = ($_SESSION['IntentosRealizados']-1);
adivinaNumero();
}
function NumeroGrande() {
$_SESSION['pequeNum'] = ($_SESSION['IntentosRealizados']+1);
adivinaNumero();
}
function correcto() {
header("Location: mostrarResultado.php");
exit;
}
?>
</body>
</html> | true |
ddbe9c1dd4100c9775a95ec5724916ca7b80cfa4 | PHP | filipekp/queue | /src/db/adaptors/Mysqli.php | UTF-8 | 8,619 | 2.859375 | 3 | [] | no_license | <?php
namespace filipekp\queue\db\adaptors;
use filipekp\queue\db\DatabaseException;
use PF\helpers\MyArray;
/**
* Třída MySQLi.
*
* @author Pavel Filípek <pavel@filipek-czech.cz>
* @copyright © 2019, Proclient s.r.o.
* @created 03.04.2019
*/
final class Mysqli implements IAdaptor
{
private $hostname = NULL;
private $username = NULL;
private $password = NULL;
private $database = NULL;
private $port = '3306';
private $connection;
private $isMultiQuery = FALSE;
private $countAffected = 0;
private $inTransaction = FALSE;
private static $transactions = [];
public $tryQuery = 10;
private static $errors = [1213, 1205];
/**
* Mysqli constructor.
*
* @param $hostname
* @param $username
* @param $password
* @param $database
* @param string $port
*
* @throws \Exception
*/
public function __construct($hostname, $username, $password, $database, $port = '3306') {
$this->hostname = $hostname;
$this->username = $username;
$this->password = $password;
$this->database = $database;
$this->port = $port;
$this->connection = new \mysqli();
$this->connect();
}
/**
* @param $sql
*
* @return array|bool|\mysqli_result|\stdClass
* @throws DatabaseException|\ErrorException
*/
private function queryExec($sql) {
$this->connection->multi_query($sql);
if (!$this->connection->errno) {
$this->isMultiQuery = $this->connection->more_results();
$data = [];
if ($this->isMultiQuery) {
do {
if (($result = $this->connection->store_result()) instanceof \mysqli_result) {
while ($rowArray = $result->fetch_assoc()) {
$dataResult[] = $rowArray;
}
$resultClass = new \stdClass();
$resultClass->num_rows = $result->num_rows;
$resultClass->row = isset($dataResult[0]) ? $dataResult[0] : [];
$resultClass->rows = $dataResult;
$data[] = $resultClass;
$result->close();
} else {
$this->countAffected += $this->connection->affected_rows;
$data[] = TRUE;
}
} while ($this->connection->more_results() && $this->connection->next_result());
return $data;
} else {
$query = $this->connection->store_result();
if ($query instanceof \mysqli_result) {
$data = [];
while ($row = $query->fetch_assoc()) {
$data[] = $row;
}
$result = new \stdClass();
$result->num_rows = $query->num_rows;
$result->row = isset($data[0]) ? $data[0] : [];
$result->rows = $data;
$query->close();
return $result;
} else {
$this->countAffected = $this->connection->affected_rows;
return TRUE;
}
}
} else {
throw new DatabaseException($this->connection->error, $this->connection->errno);
}
}
/**
* @param $sql
* @param null $currentTry
*
* @return array|bool|mixed|\mysqli_result|\stdClass
* @throws \Exception
*/
public function query($sql, &$currentTry = NULL) {
$this->countAffected = 0;
$currentTry = $this->tryQuery;
$this->currentTry = 1;
$result = FALSE;
try {
$result = $this->queryExec($sql);
} catch (\ErrorException $e) {
if (in_array($e->getCode(), self::$errors) && $currentTry > 0) {
while ($currentTry && !($result = $this->queryExec($sql))) {
$currentTry--;
$this->currentTry++;
sleep(1);
}
if (!$currentTry) {
throw $e;
}
} else {
throw new DatabaseException('⚠ Error: ' . $this->connection->error . ' => ' . $sql, (int)$this->connection->errno);
}
}
return $result;
}
/**
* @param null $name
*
* @return bool
*/
public function beginTransaction($name = NULL) {
$name = $this->getNameOfTransaction($name);
if ($this->inTransaction($name)) {
throw new \LogicException(
'⚠ Couldn\'t call `' . __FUNCTION__ . '()`. Instance of `' . __CLASS__ . '` in transaction `' . $name . '`.',
10100
);
}
if (count(self::$transactions) == 0) {
$return = $this->connection->begin_transaction(0, $name);
} else {
$return = $this->connection->savepoint($name);
}
$this->setInTransaction($name, TRUE);
return $return;
}
/**
* @param null $name
*
* @return bool
*/
public function commit($name = NULL) {
$name = $this->getNameOfTransaction($name);
if (!$this->inTransaction($name)) {
throw new \LogicException(
'⚠ Couldn\'t call `' . __FUNCTION__ . '()`. Instance of `' . __CLASS__ . '` isn\'t in transaction `' . $name . '`.',
10110
);
}
$this->setInTransaction($name, FALSE);
if (count(self::$transactions) == 0) {
$return = $this->connection->commit();
} else {
$return = TRUE;
}
return $return;
}
/**
* @param null $name
*
* @return bool
*/
public function rollback($name = NULL) {
$name = $this->getNameOfTransaction($name);
if (!$this->inTransaction($name)) {
throw new \LogicException(
'⚠ Couldn\'t call `' . __FUNCTION__ . '()`. Instance of `' . __CLASS__ . '` isn\'t in transaction `' . $name . '`.',
10101
);
}
$return = $this->connection->rollback(0, $name);
$this->setInTransaction($name, FALSE);
return $return;
}
/**
* @param string $value
*
* @return string
*/
public function escape($value) {
return $this->connection->real_escape_string($value);
}
/**
* @return int
*/
public function countAffected() {
return $this->countAffected;
}
/**
* @return mixed
*/
public function getLastId() {
return $this->connection->insert_id;
}
/**
* @return bool
*/
public function isConnected() {
return @$this->connection->ping();
}
/**
* @return mixed|void
* @throws DatabaseException
*/
public function reconnect() {
$this->closeConnection();
return $this->connect();
}
private function getNameOfTransaction($name = NULL) {
return ((is_null($name)) ? 'NA___NULL' : $name);
}
/**
* @param null $name
* @param bool $state
*
* @return string|null
*/
private function setInTransaction($name = NULL, $state = TRUE) {
$name = $this->getNameOfTransaction($name);
if ($state) {
self::$transactions[$name] = TRUE;
} else {
$transactionsArr = MyArray::init(self::$transactions);
$transactionsArr->unsetItem([$name]);
}
$this->connection->autocommit(count(self::$transactions) < 1);
return $name;
}
/**
* @param null $name
*
* @return bool
*/
public function inTransaction($name = NULL) {
$name = $this->getNameOfTransaction($name);
return (bool)MyArray::init(self::$transactions)->item([$name], FALSE);
}
/**
* @return mixed|void
* @throws DatabaseException
*/
public function connect() {
$this->connection->connect($this->hostname, $this->username, $this->password, $this->database, $this->port);
if ($this->connection->connect_error) {
throw new DatabaseException($this->connection->connect_error, $this->connection->connect_errno);
}
$this->connection->set_charset("utf8");
$this->connection->query("SET SQL_MODE = ''");
return TRUE;
}
/**
* Close current connection.
*
* @return bool
*/
public function closeConnection() {
$thread = $this->connection->thread_id;
@$this->connection->close();
return @$this->connection->kill($thread);
}
} | true |
5dd11ac38d7a775766f53f91b5188c96f0d2d7a6 | PHP | hilalahmad32/iNotebook-website-php-ajax | /php/login.php | UTF-8 | 799 | 2.59375 | 3 | [] | no_license | <?php
include "config.php";
session_start();
if (isset($_POST["email"]) || isset($_POST["password"])) {
$email = mysqli_real_escape_string($conn, $_POST["email"]);
$password = mysqli_real_escape_string($conn, md5($_POST["password"]));
$sql = "SELECT * FROM users WHERE email='{$email}' AND passwrd='{$password}'";
$run_sql = mysqli_query($conn, $sql);
if (mysqli_num_rows($run_sql) > 0) {
while($row=mysqli_fetch_assoc($run_sql)){
$_SESSION["username"]=$row["username"];
$_SESSION["user_id"]=$row["id"];
}
if(isset($_POST["rememberme"])){
setcookie("email",$_POST["email"],time()+86400);
setcookie("password",$_POST["password"],time()+86400);
}
echo 1;
} else {
echo 0;
}
}
| true |
3824baf9505eb4f370aeabe67f7246f738811655 | PHP | duyanh1992/PHP_ZendVN | /PHP_ARRAY/second/array_chang_key_case.php | UTF-8 | 395 | 3.140625 | 3 | [] | no_license | <?php
echo "Old array: ";
$arr = array('one'=>'HTML','tWo'=>'CSS','THree'=>'PHP');
print_r($arr); //('one'=>'HTML','tWo'=>'CSS','THree'=>'PHP')
echo "<br />";
echo "New array: ";
$newArr = array_change_key_case($arr, CASE_UPPER);
print_r($arr); //('ONE'=>'HTML','TWO'=>'CSS','THREE'=>'PHP')
// Nếu muốn chuyển các key về dạng lowercase thì bỏ đi giá trị CASE_UPPER
?> | true |
e0f170f902cf6252be4439d612bc746b6880650a | PHP | judgedim/mutagenesis | /library/Mutagenesis/Adapter/AdapterAbstract.php | UTF-8 | 2,267 | 2.65625 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/**
* Mutagenesis
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://github.com/padraic/mutateme/blob/rewrite/LICENSE
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to padraic@php.net so we can send you a copy immediately.
*
* @category Mutagenesis
* @package Mutagenesis
* @subpackage UnitTests
* @copyright Copyright (c) 2010 Pádraic Brady (http://blog.astrumfutura.com)
* @license http://github.com/padraic/mutateme/blob/rewrite/LICENSE New BSD License
*/
namespace Mutagenesis\Adapter;
use Mutagenesis\Runner\Base as BaseRunner;
use Mutagenesis\Mutant\MutantInterface;
abstract class AdapterAbstract
{
const TIMED_OUT = 'timed out';
const PROCESS_FAILURE = 'process failure';
/**
* Output from the test library in use
*
* @var string
*/
protected $_output = '';
/**
* Runs the tests suite according to Runner set options and the execution
* order of test case (if any). It then returns an array of two elements.
* First element is a boolean result value indicating if tests passed or not.
* Second element is an array containing the key "stdout" which stores the
* output from the last test run.
*
* @abstract
*
* @param \Mutagenesis\Runner\Base $runner
* @param bool $useStdout
* @param bool $firstRun
* @param MutantInterface|bool $mutant
* @param array $testCases
*
* @return array
*/
abstract public function runTests(BaseRunner $runner, $useStdout = false,
$firstRun = false, $mutant = false, array $testCases = array());
/**
* Set the test library output so it can be used later
*
* @param string $output
*/
public function setOutput($output)
{
$this->_output = $output;
}
/**
* Get the test library output
*
* @return string
*/
public function getOutput()
{
return $this->_output;
}
}
| true |
cea167c7fda81746258e57a607ef933eac7dfeb8 | PHP | vansang1201200/advanced-Object-oriented-design.php | /thuc-hanh/class-chicken.php | UTF-8 | 259 | 2.859375 | 3 | [] | no_license | <?php
include_once './classAnimal.php';
include_once './class-edible.php';
class chicken extends Aminal {
public function makeSound()
{
return "chicken : dau xa";
}
public function howtoEat(){
return "aaaaa";
}
} | true |
5ac06e9329f72fff02b394e1b9a0657426957bc8 | PHP | eklundchristopher/viewpress | /src/Filters/TemplateHandler.php | UTF-8 | 3,059 | 2.96875 | 3 | [
"MIT"
] | permissive | <?php
namespace EklundChristopher\ViewPress\Filters;
use EklundChristopher\ViewPress\Application;
abstract class TemplateHandler
{
/**
* Holds the Application implementation.
*
* @var \EklundChristopher\ViewPress\Application
*/
protected $app;
/**
* Instantiate a new filter object.
*
* @param \EklundChristopher\ViewPress\Application $application
* @return void
*/
public function __construct(Application $application)
{
$this->app = $application;
}
/**
* Return an array of templates in order of precedence.
*
* @param array $templates
* @return array
*/
abstract public function templates(array $templates);
/**
* Trigger the event.
*
* @param string $template
* @return void
*/
public function handle($template)
{
$templates = $this->templates([]);
return $this->iterate(
is_array($templates) ? $templates : [$templates]
);
}
/**
* Iterate over the templates.
*
* @param array $templates
* @return string|null
*/
protected function iterate(array $templates)
{
$response = null;
foreach ($templates as $template) {
if (! $template or ! is_null($response)) {
continue;
}
$response = $this->load($template);
}
return $response;
}
/**
* Attempt to find a matching filepath.
*
* @param string $template
* @return string
*/
protected function load($template)
{
if ($this->isTemplate($template)) {
return $this->loadTemplate($template);
}
if ($this->app->view->exists($this->stripExtension($template))) {
return $template;
}
if (locate_template($template)) {
return $template;
}
}
/**
* Determine whether the template is an actual template file or just a regular file.
*
* @param string $template
* @return boolean
*/
protected function isTemplate($template)
{
return (boolean) preg_match('/^template\:/i', $template);
}
/**
* Load a template file.
*
* @param string $template
* @return string|null
*/
protected function loadTemplate($template)
{
$template = preg_replace('/^template\:/i', null, $template);
if (file_exists(get_stylesheet_directory().'/'.$template)) {
return get_stylesheet_directory().'/'.$template;
}
if (file_exists(get_template_directory().'/'.$template)) {
return get_template_directory().'/'.$template;
}
return null;
}
/**
* Get the relative path starting from the active theme directory.
*
* @param string $template
* @return string
*/
protected function stripExtension($template)
{
return str_ireplace(['.blade.php', '.php'], null, $template);
}
}
| true |
35fbd32aaf22b688d60730debd4e28bab787567b | PHP | CouponIsTalking/PriceWatch | /trackit/app/Model/OcResponse.php | UTF-8 | 7,311 | 2.578125 | 3 | [] | no_license | <?php
App::uses('AppModel', 'Model');
/**
* OcResponse Model
*
*/
class OcResponse extends AppModel {
public function getType($ocr)
{
return $ocr['OcResponse']['response_type'];
}
public function mark_accepted($ocr_id)
{
$ocr = $this->getRawResponseByOcrId($ocr_id);
if (empty($ocr))
{
return false;
}
$ocr['OcResponse']['processed'] = 1;
$ocr['OcResponse']['processing_result'] = 1;
$this->id = $ocr['OcResponse']['id'];
if ($this->save($ocr))
{
return true;
}
else
{
return false;
}
}
public function mark_unaccepted($ocr_id)
{
$ocr = $this->getRawResponseByOcrId($ocr_id);
if (empty($ocr))
{
return false;
}
$ocr['OcResponse']['processed'] = 1;
$ocr['OcResponse']['processing_result'] = 0;
$this->id = $ocr['OcResponse']['id'];
if ($this->save($ocr))
{
return true;
}
else
{
return false;
}
}
public function getRawResponsesByOCId($oc_id)
{
$ocrs = $this->find('all', array(
'conditions'=>array('oc_id' => $oc_id),
'recursive' => -1
));
return $ocrs;
}
public function getRawResponseByOcrId($ocr_id)
{
$ocr = $this->find('first', array(
'conditions'=>array('id' => $ocr_id),
'recursive' => -1
));
return $ocr;
}
public function getRawResponsesByOcrIds($ocr_ids)
{
$ocrs = $this->find('all', array(
'conditions'=>array('id' => $ocr_ids),
'recursive' => -1
));
return $ocrs;
}
public function getRawOcResponsesByBloggerId($blogger_id)
{
if (empty($blogger_id)) return null;
$oc_responses = $this->find('all', array('recursive' => -1, 'conditions' => array ('blogger_id' => $blogger_id)));
return $oc_responses;
}
public function findResponseByBloggerAndOcId($blogger_id, $oc_id)
{
if (empty($blogger_id) || empty($oc_id)) return null;
$oc_response = $this->find('first',
array(
'recursive' => -1,
'conditions' =>
array (
'blogger_id' => $blogger_id,
'oc_id' => $oc_id
)
)
);
return $oc_response;
}
public function doesBloggerOwnOcr($blogger_id, $ocr_id)
{
if (empty($blogger_id) || empty($ocr_id)) return null;
$oc_response = $this->find('first',
array(
'recursive' => -1,
'conditions' =>
array (
'blogger_id' => $blogger_id,
'id' => $ocr_id
)
)
);
if (!empty($oc_response['OcResponse']))
{
return true;
}
else
{
return false;
}
}
private function addRawResponseData($cpr)
{
$result = array ('success' => false, 'data' => array());
$cpr_entry = array ('OcResponse' => $cpr);
$this->create();
$save_response = $this->save($cpr_entry);
if (!empty($save_response))
{
$result['success'] = true;
$result['data'] = $save_response;
$result['saveid'] = $this->id;
}
else
{
$result['success'] = false;
$result['data'] = $save_response;
}
return $result;
}
public function verify_verifier($verifier = null, $oc_id = null)
{
if (empty($verifier) || empty($oc_id)) { return false; }
$temp = explode ('UMN', $verifier);
if (2 != count($temp)) { return false; }
$key = $temp[0];
$user_id = $temp[1];
if (empty($key) || empty($user_id)) { return false; }
$found = $this->find('first', array(
'recursive' => -1,
'conditions' => array(
'id' => $key,
'oc_id' => $oc_id,
'user_id' => $user_id
)
));
if (!empty($found['OcResponse']))
{
return $found['OcResponse'];
}
return false;
}
public function addRawGenResponseData($params)
{
$result = array ('success' => false, 'data' => array());
$cpr = array();
if (empty($params['user_id'])
|| empty($params['company_id'])
|| empty($params['promo_method'])
)
{
return $result;
}
$cpr['user_id'] = $params['user_id'];
$cpr['oc_id'] = $params['resp_for_obj_id'];
$cpr['response_type'] = $params['promo_method'];
$cpr['response_blog_link'] = $params['live_link'];
$cpr['response_data'] = $params['json_promo_response'];
$cpr['response_live_id'] = $params['postid'];
// coupon code, company info
$cpr['company_id'] = $params['company_id'];
$cpr['coupon_code'] = $params['coupon_code'];
$cpr['uid_cid_coupon_code'] = $params['uid_cid_coupon_code'];
//share info
$cpr['share_title'] = $params['share_title'];
$cpr['share_desc'] = $params['share_desc'];
$cpr['share_image_link'] = $params['share_image_link'];
$cpr['share_news_title'] = $params['share_news_title'];
$cpr['share_news_link'] = $params['share_news_link'];
// key share metrics
if (!empty($params['update_like_count'])
&& 1==$params['update_like_count'])
{
$cpr['like_count'] = $params['like_count'];
}
if (!empty($params['update_comment_count'])
&& 1==$params['update_comment_count'])
{
$cpr['comment_count'] = $params['comment_count'];
}
if (!empty($params['update_share_count'])
&& 1==$params['update_share_count'])
{
$cpr['share_count'] = $params['share_count'];
}
if (!empty($params['update_retweet_count'])
&& 1==$params['update_retweet_count'])
{
$cpr['retweet_count'] = $params['retweet_count'];
}
$cpr['processed'] = 0;
$cpr['created'] = date("Y-m-d H:i:s");
$result = $this->addRawResponseData($cpr);
return $result;
}
public function addRawTweetResponseData($user_id, $oc_id, $tweet_response_data)
{
$cpr = array();
$cpr['user_id'] = $user_id;
$cpr['oc_id'] = $oc_id;
$cpr['response_type'] = 'tweet';
$cpr['response_data'] = json_encode($tweet_response_data);
$cpr['processed'] = 0;
$cpr['created'] = date("Y-m-d H:i:s");
$result = $this->addRawResponseData($cpr);
return $result;
}
public function addRawFBResponseData($user_id, $oc_id, $fb_response_data)
{
$cpr = array();
$cpr['user_id'] = $user_id;
$cpr['oc_id'] = $oc_id;
$cpr['response_type'] = 'fb_post';
$cpr['response_data'] = json_encode($fb_response_data);
$cpr['processed'] = 0;
$cpr['created'] = date("Y-m-d H:i:s");
$result = $this->addRawResponseData($cpr);
return $result;
}
public function set_used_val($oc_id, $used_val)
{
if (empty($oc_id)){return false;}
$ocr = array('OcResponse'=>array('id'=>$oc_id,'used'=>$used_val));
$this->id = $oc_id;
$saved = $this->save($ocr, true, array('used'));
if (!empty($saved)){return true;}
return false;
}
public function getEmails($oc_id)
{
if (empty($oc_id)){return false;}
$emails = $this->find('all', array(
'recursive' => -1, 'conditions' => array (
'response_type IN' => array('single_email_ns_signup', 'dual_email_ns_signup'),
'oc_id' => $oc_id
),
'fields'=>array('response_data'))
);
return $emails;
}
public function update_coupon_code($ocr_id, $coupon_code, $user_id_n_company_id_coupon){
if (empty($ocr_id)){return false;}
$to_update = array('OcResponse'=>array('id'=>$ocr_id, 'coupon_code' => $coupon_code,
'uid_cid_coupon_code' => $user_id_n_company_id_coupon));
$this->id = $ocr_id;
$saved = $this->save($to_update, true, array('coupon_code', 'uid_cid_coupon_code'));
if (!empty($saved)){return true;}
else{ return false;}
}
} | true |
d4b53aea69e9648ce214c6bba4c9744c34aeccd1 | PHP | Neppord/phocate | /src/File/PhpFile.php | UTF-8 | 513 | 2.953125 | 3 | [] | no_license | <?php
declare(strict_types = 1);
namespace Phocate\File;
use Phocate\Parsing\Token\Tokens;
class PhpFile
{
/** @var string */
private $path;
public function __construct(string $path)
{
$this->path = $path;
}
public function getTokens(): Tokens
{
$content = file_get_contents($this->path);
$tokens = token_get_all($content);
return new Tokens($tokens, count($tokens));
}
public function getPath()
{
return $this->path;
}
} | true |
07e308ad04ad203acc086cb64d0e0a13d15c4eca | PHP | 9TF/contact | /user/signup.php | UTF-8 | 7,830 | 2.59375 | 3 | [] | no_license | <?php
$status = 0;
$template = 1;
$user_name = '';
$password = '';
$confirm_password = '';
$name = '';
$email = '';
$number = '';
$question = '';
$image = '';
$answer = '';
$verified = '';
$verification_code='';
$error = array();
if (isset($_POST['signup'])) {
$user_name = $_REQUEST['user_name'];
$password = trim($_REQUEST['password']);
$confirm_password = $_REQUEST['confirm_password'];
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$number = $_REQUEST['number'];
$question = $_REQUEST['question'];
$answer = $_REQUEST['answer'];
/* step 1 all field are completely filled */
if (empty($user_name)) {
$error['user_name'] = 'enter user name';
}
if (!empty($user_name)) {
$query = "select * from users where user_name='$user_name'";
require_once '../includes/db.inc.php';
$result = @mysql_query($query);
if (mysql_num_rows($result) === 1) {
$error['user_name'] = 'user name already exist ';
}
}
if (empty($password)) {
$error['password'] = 'enter password';
}
if (empty($confirm_password)) {
$error['confirm_password'] = 'enter confirm password';
}
if (empty($name)) {
$error['name'] = 'enter name';
}
if (empty($email)) {
$error['email'] = 'enter email';
}
if (empty($number)) {
$error['number'] = 'enter number';
}
if (empty($question)) {
$error['question'] = 'enter question';
}
if (empty($answer)) {
$error['answer'] = 'enter answer';
}
/* step 2 validation */if (count($error) == 0) {
if (!preg_match('/^[A-Za-z][A-Za-z0-9]*$/', $user_name)) {
$error['user_name'] = 'User Name is not Valid';
}
if (strlen($password) < 6) {
$error['password'] = 'Password must be at least 6 characters';
}
if ($password != $confirm_password) {
$error['confirm_password'] = 'Passwords do not match';
}
if (!preg_match('/^[A-Za-z0-9]+@[A-Za-z0-9]+\.[A-Za-z]+$/', $email)) {
$error['email'] = 'Email is not Valid';
}
}
if (count($error) == 0) {
$str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$str = str_shuffle($str);
$verification_code = substr($str, 0, 20);
$password = sha1($password);
$answer = sha1($answer);
$query = "INSERT INTO `cb`.`users` (`user_name`, `password`, `name`, `image`, `email`, `number`, `question`, `answer`, `verified`, `verification_code`) VALUES ('$user_name', '$password', '$name', '', '$email', '$number', '$question', '$answer', 'N', '$verification_code')";
require_once '../includes/db.inc.php';
echo $user_name;
echo $password;
echo $name;
echo $number;
echo $email;
echo $answer;
echo $verification_code;
//@mysql_query($query) or die('quries not run');
if (mysql_query($query)) {
$template = 2;
}
}
}
?><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Contact Book</title>
<link href="../style/w3.css" rel="stylesheet" type="text/css"/>
<link href="../style/style.css" rel="stylesheet" type="text/css"/>
</head>
<body >
<div class="w3-top">
<ul class="w3-navbar w3-red w3-large w3-center">
<li style="width:100%"><a href="../index.php">CONTACT BOOK</a></li>
</ul>
</div>
<br><br><br>
<div class="w3-card-12 w3-center w3-white" style="margin:auto; max-width: 500px ;width:auto;">
<button class="w3-btn-block w3-red" style="">Register</button>
<?php if ($template == 1) { ?>
<form action="signup.php" method="POST">
<div class="w3-section w3-center" >
<table>
<tbody>
<tr>
<td>User Name</td>
<td>
<input class="w3-input w3-animate-input" type="text" name="user_name" " value="<?php if(isset($error['user_name'])){ echo $error['user_name'];} else {echo $user_name; }?>" />
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input class="w3-input w3-animate-input" type="password" name="password" placeholder="<?php echo $error['password']; ?>"/>
</td>
</tr>
<tr>
<td>Confirm Password</td>
<td>
<input class="w3-input w3-animate-input" type="password" name="confirm_password" placeholder="<?php echo $error['password']; ?>"/>
</td>
</tr>
<tr>
<td>Name</td>
<td>
<input class="w3-input w3-animate-input" type="text" name="name" value="<?php echo $name; ?>" placeholder="<?php echo $error['name']; ?>" />
</td>
</tr>
<tr>
<td>Email</td>
<td>
<input class="w3-input w3-animate-input" type="text" name="email" placeholder="<?php echo $error['email']; ?>" value="<?php echo $email; ?>" />
</td>
</tr>
<tr>
<td>Number</td>
<td>
<input class="w3-input w3-animate-input" type="text" name="number" value="<?php echo $number; ?>" placeholder="<?php echo $error['number']; ?>" />
</td>
</tr>
<tr>
<td>Security Question</td>
<td>
<input class="w3-input w3-animate-input" type="text" name="question" value="<?php echo $question; ?>" placeholder="<?php echo $error['question']; ?> " />
</td>
</tr>
<tr>
<td>Answer</td>
<td>
<input class="w3-input w3-animate-input" type="text" name="answer" value="" placeholder="<?php echo $error['answer']; ?>" />
</td>
</tr>
</tbody>
</table>
</div>
<input type="submit" name="signup" class="w3-btn-block w3-red" value="Submit"/>
</form>
<?php } ?>
<?php if ($template == 2) { ?>
<h3>Congratulation Registered successfully. <br>
GO TO YOUR EMAIL <?php echo $email; ?> AND <br>
PLEASE CLICK THE VERIFICATION LINK GIVEN IN YOUR EMAIL ID.</h3>
<?php } ?>
</div>
</body>
</html>
| true |
98ce4daf58e2aa8271e9919e88fc674af510ffeb | PHP | cchura94/curso_php | /Proyecto/models/Producto.php | UTF-8 | 1,569 | 2.6875 | 3 | [] | no_license | <?php
$dir_root = $_SERVER['DOCUMENT_ROOT'];
require_once($dir_root."/php/Proyecto/models/Conexion.php");
class Producto extends Conexion
{
public function lista()
{
$sql = "SELECT * from productos";
return Conexion::consultaRetorno($sql);
}
public function guardar($nom, $cant, $precio, $imagen, $des, $cat_id)
{
$sql = "INSERT into productos (nombre, cantidad, precio, imagen, descripcion, categoria_id, proveedor_id) values('$nom', $cant,$precio, '$imagen', '$des', $cat_id, 1)";
Conexion::consultaSimple($sql);
}
public function mostrar($id)
{
$sql = "SELECT * from productos where id = $id";
$categoria = Conexion::consultaRetorno($sql);
return $categoria->fetchAll()[0];
}
public function modificar($nom, $cant, $precio, $imagen, $des, $cat_id, $id)
{
$sql = "UPDATE productos set nombre = '$nom', cantidad=$cant, precio=$precio, imagen='$imagen', descripcion = '$des', categoria_id = $cat_id where id = $id";
Conexion::consultaSimple($sql);
}
public function eliminar($id)
{
$sql = "DELETE from productos where id = $id";
Conexion::consultaSimple($sql);
}
public function buscar($buscar)
{
$sql = "SELECT * from productos where nombre like '%$buscar%'";
return Conexion::consultaRetorno($sql);
}
public function imprimir($id)
{
$sql = "SELECT * from productos where id =$id";
return Conexion::consultaRetorno($sql);
}
}
| true |
078666f5558c4d189f8a120f966d896cec973108 | PHP | espci-alumni/annuaire | /interface/class/agent/atlas/marks.php | UTF-8 | 2,128 | 2.53125 | 3 | [] | no_license | <?php
class agent_atlas_marks extends agent
{
public $get = array(
'zoom:i:1:5' => 1,
'mnLt:f:-90:90' => -90,
'mxLt:f:-90:90' => 90,
'mnLg:f:-180:180' => -180,
'mxLg:f:-180:180' => 180,
);
function compose($o)
{
$sql = 'IF((VARIANCE(longitude)!=0 OR VARIANCE(latitude)!=0) AND ""!=div';
switch ($this->get->zoom)
{
case 5: $sql = $this->buildGeoQuery(5, 'city', 'country,div1,div2,city,c.city_id'); break;
case 4: $sql = $this->buildGeoQuery(4, 'city', 'country,div1,div2,city'); break;
case 3: $sql = $this->buildGeoQuery('IF(div2!="",3,4)', $sql.'2,CONCAT_WS(", ",div2,div1,country),city)', 'country,div1,div2,IF(div2!="",0,city)'); break;
case 2: $sql = $this->buildGeoQuery('IF(div1!="",2,4)', $sql.'1,CONCAT_WS(", ", div1,country),city)', 'country,div1, IF(div1!="",0,city)'); break;
case 1:
default: $sql = $this->buildGeoQuery(1, 'country', 'country');
}
$o->marks = new loop_sql($sql);
return $o;
}
protected function buildGeoQuery($zoom, $label, $groupBy)
{
$sql = SESSION::get('atlasResults');
$sql = !$sql || true === $sql ? 'f.city_id!=0' : "f.fiche_id IN ({$sql})";
$sql = "SELECT
{$label} AS label,
ROUND(AVG(longitude)*1000 + 180000) AS lng,
ROUND(AVG(latitude)*1000 + 90000) AS lat,
COUNT(*) AS nb,
c.city_id AS id,
{$zoom} AS zoom
FROM " . annuaire::$city_table . ' JOIN ' . annuaire::$fiche_table . " ON f.city_id=c.city_id
WHERE ({$sql})
AND latitude BETWEEN {$this->get->mnLt} AND {$this->get->mxLt}
AND " . ($this->get->mnLg < $this->get->mxLg
? "longitude BETWEEN {$this->get->mnLg} AND {$this->get->mxLg}"
: "NOT (longitude BETWEEN {$this->get->mxLg} AND {$this->get->mnLg})"
) . "
GROUP BY {$groupBy}";
return $sql;
}
}
| true |
1c819a0da3a992a1e013fc2661a919a128f499f6 | PHP | Gabr13dev/pagina-pessoal | /dash/lib/Chart.class.php | UTF-8 | 2,288 | 2.78125 | 3 | [] | no_license | <?php
/*
*
*
*/
class Chart {
public $chartType,$data;
function __construct($type,$values = [],$names = [],$nameId)
{
$this->chartType = $type;
$this->data = $values;
$this->names = $names;
$this->nameId = $nameId;
}
private function initChartDependences(){
echo "<style>";
echo file_get_contents(BASE_URL.'/css/Chart.min.css');
echo "</style>";
echo "<script>";
echo file_get_contents(BASE_URL.'/js/Chart.min.js');
echo "</script>";
}
private function transformArray($data,$index,$separate = ""){
$limiter = count($data) - 1;
$out = "[";
foreach($data as $key => $array){
$out .= $separate. $array[$index] .= ($key != $limiter ? $separate.",":"");
}
$out .= $separate."]";
return $out;
}
public function createChartFollowers(){
$this->initChartDependences();
$chart = [];
echo "<canvas id='".$this->nameId."' width='600px' height='200px'></canvas>
<script>
var ctx = document.getElementById('".$this->nameId."').getContext('2d');
var myChart = new Chart(ctx, {
type: '".$this->chartType."',
data: {
labels: ".$this->names.",
datasets: [{
label: 'Evolução de seguidores',
data: ".$this->data.",
backgroundColor: [
'rgba(153, 102, 255, 0.2)',
'rgba(232, 32, 32, 0.7)',
'rgba(17, 214, 47, 0.7)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>";
}
} | true |
847e3c19c4c6adad87496252e4d87b666130f46e | PHP | ifeanyi-ajimah/student-management | /app/Http/Controllers/MyClassController.php | UTF-8 | 1,984 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\MyClass;
class MyClassController 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)
{
//using mass assignment to store data
MyClass::create($request->all());
session()->flash('notif','You Have Successfully created a new Course');
return back();
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($myclass_id)
{
$classes = MyClass::where('active',1)->find($myclass_id);
return view('layout.update',compact('classes'));
}
/**
* 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($myclass_id)
{
MyClass::find($myclass_id)->delete();
return back();
}
public function register(){
return view('students.studentRegister');
}
}
| true |
0928c3e2af2bed3888c61971979cd687dfdf9dab | PHP | xapu3ma/ulitayka | /app/Repositories/PolicyRepository.php | UTF-8 | 548 | 2.921875 | 3 | [] | no_license | <?php
namespace App\Repositories;
use App\User;
class PolicyRepository
{
/**
* Получить все задачи заданного пользователя.
*
* @param User $user
* @return Collection
*/
public function forUser(User $user)
{
$policies = $user->policies()->orderBy('created_at', 'asc')->get();
foreach ($policies as $police) {
$police->risks;
$police->travelers;
$police->countries;
}
return $policies;
}
} | true |
036972cb8b068b4cd33927567090489318ccf33c | PHP | uzproger/yii2-migrator | /src/MigrateController.php | UTF-8 | 4,029 | 2.609375 | 3 | [] | no_license | <?php
namespace uzproger\migrator;
use Yii;
use yii\console\controllers\MigrateController as BaseMigrateController;
use yii\db\Query;
use yii\helpers\ArrayHelper;
/**
* Yii2 migrator class
*/
class MigrateController extends BaseMigrateController
{
/**
* @var string Main migration name
*/
public $baseMigrationName = 'Base';
/**
* @var boolean Show base migration
*/
public $showBaseMigration = false;
/**
* @var array Migration pathes.
*/
public $additionalPaths = [];
/**
* @inheritdoc
*/
public function beforeAction($action)
{
echo "\n";
if ($this->showBaseMigration) {
$this->additionalPaths = ArrayHelper::merge([
[
'name' => $this->baseMigrationName,
'path' => $this->migrationPath,
]
], $this->additionalPaths);
}
$this->selectModule();
return parent::beforeAction($action);
}
/**
* Console select module
*
* @return void
*/
protected function selectModule()
{
$selectedModule = Console::select("please select module", $this->getMigrationPaths());
$this->setMigrationPath($selectedModule);
}
/**
* Set migration path of selected module
*
* @throws Exception
* @return void
*/
protected function setMigrationPath($module)
{
if (!isset($this->migrationPaths[$module]) || !isset($this->migrationPaths[$module]['path'])) {
throw new \Exception("Undefinied module or wrong path format.");
}
$this->migrationPath = $this->migrationPaths[$module]['path'];
}
/**
* @inheritdoc
*/
protected function getMigrationHistory($limit)
{
if ($this->db->schema->getTableSchema($this->migrationTable, true) === null) {
$this->createMigrationHistoryTable();
}
$query = new Query;
$rows = $query->select(['version', 'apply_time'])
->from($this->migrationTable)
->where('path_hash=:path_hash', [':path_hash' => $this->hashPath()])
->orderBy('version DESC')
->limit($limit)
->createCommand($this->db)
->queryAll();
$history = ArrayHelper::map($rows, 'version', 'apply_time');
unset($history[self::BASE_MIGRATION]);
return $history;
}
/**
* @inheritdoc
*/
protected function createMigrationHistoryTable()
{
$tableName = $this->db->schema->getRawTableName($this->migrationTable);
echo "Creating migration history table \"$tableName\"...";
$this->db->createCommand()->createTable($this->migrationTable, [
'version' => 'varchar(180) NOT NULL PRIMARY KEY',
'path_hash' => 'varchar(32) NOT NULL',
'apply_time' => 'integer',
])->execute();
$this->db->createCommand()->insert($this->migrationTable, [
'version' => self::BASE_MIGRATION,
'path_hash' => $this->hashPath(),
'apply_time' => time(),
])->execute();
echo "done.\n";
}
/**
* @inheritdoc
*/
protected function addMigrationHistory($version)
{
$command = $this->db->createCommand();
$command->insert($this->migrationTable, [
'version' => $version,
'path_hash' => $this->hashPath(),
'apply_time' => time(),
])->execute();
}
/**
* Generate hash for current migration path
* @return string
*/
protected function hashPath()
{
return md5($this->migrationPath);
}
/**
* Returns migration paths
* @return array
*/
protected function getMigrationPaths()
{
return $this->additionalPaths;
}
} | true |
bfe74f0e0b02c689554f429127e03ce76f2884a2 | PHP | tonyyuanzaizai/tower-open-api-php | /common.php | UTF-8 | 3,566 | 2.65625 | 3 | [] | no_license | <?php
function getIp(){
return $_SERVER['REMOTE_ADDR'];
}
function getIp2(){
$ip = "Unknow";
if (getenv("HTTP_CLIENT_IP")){
$ip = getenv("HTTP_CLIENT_IP");
}
else if(getenv("HTTP_X_FORWARDED_FOR")){
$ip = getenv("HTTP_X_FORWARDED_FOR");
}
else if(getenv("REMOTE_ADDR")){
$ip = getenv("REMOTE_ADDR");
}
return $ip;
}
function formatData(){
return $_SERVER['REMOTE_ADDR'];
}
function getObjectType($value){
if(is_string($value)){
return 'string';
}
if(is_bool($value)){
return 'bool';
}
if(is_int($value)){
return 'int';
}
if(is_float($value)){
return 'floor';
}
if(is_integer($value)){
return 'integer';
}
if(is_real($value)){
return 'real';
}
if(is_array($value)){
return 'array';
}
if(is_object($value)){
return 'object';
}
}
function http_get_contents($pay_server){
// create a new curl resource
$timeout = 30;
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $pay_server);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
return $file_contents;
}
function http_post_contents($pay_server, $post_data){
// create a new curl resource
$timeout = 30;
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $pay_server);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
return $file_contents;
}
//要抓https请先确定php.ini内有
//extension=php_openssl.dll
//allow_url_include=on
function https_get_contents($token_url)
{
// Get an App Access Token
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $token_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$params = curl_exec($ch);
curl_close($ch);
return $params;
}
function http_post_json_data($pay_server, $post_data) {
$data_string = json_encode($post_data);
$ch = curl_init($pay_server);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
return $result;
}
function https_get_header_json($token_url) {
// create a new curl resource
$timeout = 30;
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $token_url);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
return $file_contents;
}
?>
| true |
0f83c6b32858b87785d91937ccdf56f5a6c09253 | PHP | Devil29/Thesis_Uploader | /Notice Board/core/classes/core.php | UTF-8 | 1,212 | 2.703125 | 3 | [] | no_license | <?php
//echo "core";
// include_once '../../../config/config.php';
define("HOST11", "http://localhost/ProjectUploader");
define("HOSTNAME", "localhost");
define("USERNAME", "root");
define("PASS", "kunal");
define("DBNAME", "project");
?>
<?php
class core {
public $count;
protected $db, $result;
private $rows;
public function __construct() {
$this->db = new mysqli("HOSTNAME","USERNAME","PASS","DBNAME");
$count = 10;
}
public function query($sql)
{
?>
<div class="message">
<p><?php echo $sql; ?></p>
</div>
<?php
$this->result = $this->db->query(" SELECT * FROM `chat` ");
?>
<div class="message">
<p><?php echo (int)$this->db->affected_rows; ?></p>
</div>
<?php
}
public function rows()
{
?>
<div class="message">
<p><?php echo (int)$this->db->affected_rows; ?></p>
</div>
<?php
for ($x=1; $x <= (int)$this->db->affected_rows; $x++) {
# code...
$count = $count + 1;
?>
<div class="message">
<p><?php echo "rsdgV"; ?></p>
</div>
<?php
$this->rows[] = $this->result->fetch_assoc();
}
return $this->rows;
}
// public function tell()
// {
// return $count;
// }
}
?> | true |
d7792377b7c73fc62214aaaf3727ee86556c7511 | PHP | Innmind/RabbitMQManagement | /src/Control.php | UTF-8 | 867 | 2.5625 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types = 1);
namespace Innmind\RabbitMQ\Management;
use Innmind\RabbitMQ\Management\Control\{
Users,
VHosts,
Permissions,
};
use Innmind\Server\Control\Server;
final class Control
{
private Users $users;
private VHosts $vhosts;
private Permissions $permissions;
private function __construct(Server $server)
{
$this->users = Users::of($server);
$this->vhosts = VHosts::of($server);
$this->permissions = Permissions::of($server);
}
public static function of(Server $server): self
{
return new self($server);
}
public function users(): Users
{
return $this->users;
}
public function vhosts(): VHosts
{
return $this->vhosts;
}
public function permissions(): Permissions
{
return $this->permissions;
}
}
| true |
cce53e6706d9ab6c8f4ba179f6e17410cc604161 | PHP | kuso-megane/blog | /www/Models/infra/database/tests/CategoryTableTest.php | UTF-8 | 1,151 | 2.53125 | 3 | [] | no_license | <?php
use PHPUnit\Framework\TestCase;
use infra\database\src\CategoryTable;
use myapp\myFrameWork\DB\Connection;
use myapp\myFrameWork\DB\MyDbh;
class CategoryTableTest extends TestCase
{
const TABLENAME = 'Category';
private $dbh;
private $table;
protected function setUp():void
{
$this->dbh = (new Connection(TRUE))->connect();
$this->table = new CategoryTable(TRUE);
$this->dbh->truncate($this::TABLENAME);
$sth = $this->dbh->insert($this::TABLENAME, ':id, :name, :num', [':id' => 0, ':num' => 0], MyDbh::ONLY_PREPARE);
for ($i = 1; $i < 3; ++$i) {
$sth->bindValue(':name', "category{$i}");
$sth->execute();
}
}
public function testFindAll()
{
$this->assertSame([
['id' => 1, 'name' => 'category1', 'num' => 0],
['id' => 2, 'name' => 'category2', 'num' => 0]
], $this->table->findAll());
}
public function testFindById()
{
$c_id = 1;
$this->assertSame([
'id' => 1, 'name' => 'category1', 'num' => 0
], $this->table->findById($c_id));
}
} | true |
0fb9a839af7df1e201d7d5ed3020516044323515 | PHP | slavkoss/fwphp | /fwphp/glomodul/z_examples/php_patterns/singleton_B12phpfw.php | UTF-8 | 4,320 | 2.5625 | 3 | [
"MIT"
] | permissive | <?php
// J:\awww\www\fwphp\glomodul\z_examples\php_patterns\singleton_B12phpfw.php
//SINGLETON PATTERN with a class that establishes a database connection,
//and restricts the number of instances to only one.
//https://phpenthusiast.com/blog/the-singleton-design-pattern-in-php
namespace B12phpfw\module\php_patterns ;
use B12phpfw\core\zinc\Autoload ;
use B12phpfw\core\zinc\Config_allsites ;
//use B12phpfw\core\zinc\Db_allsites;
//use B12phpfw\core\zinc\Dbconn_allsites;
//1. settings - properties - assign global variables to use them in any code part
$module_towsroot = '../../../../' ; //to web server doc root or our doc root by ISP
//$dirup_to_app = str_replace('\\','/', dirname(__DIR__) ) ; //to app eg glomodul
$pp1 = (object) //=properties global array (like Oracle Forms property palette)
[ 'dbg'=>'1', 'stack_trace'=>[[str_replace('\\','/', __FILE__ ).', lin='.__LINE__]]
//1.1
, 'module_towsroot'=>$module_towsroot
//1.2
, 'module_version'=>'6.0.4.0 php_patterns', 'vendor_namesp_prefix'=>'B12phpfw'
//1.3 F o r A u t o l o a d
, 'module_path_arr'=>[ //MUST BE NUM INDEXED for auto loader loop (not 'string'=>...)
str_replace('\\','/', __DIR__ ).'/' //thismodule_cls_dir_path
//dir of global clses for all sites :
, str_replace('\\','/', realpath($module_towsroot.'zinc')) .'/'
]
] ;
//2. global cls loads classes scripts automatically
require($pp1->module_towsroot.'zinc/Autoload.php'); //or Composer's autoload cls-es
$autoloader = new Autoload($pp1);
if ('1') {Config_allsites::jsmsg( [ basename(__FILE__) //. __METHOD__
.', line '. __LINE__ .' SAYS'=>' '
,'where am I'=>'AFTER A u t o l o a d'
] ) ; }
// ****************************************************************************
echo '<h1>Better : URL contains Home_ ctr method read_post (?i/read_post/)</h1>' ;
// ****************************************************************************
echo
'URL MUST BE : http://dev1:8083/fwphp/glomodul/z_examples/php_patterns/singleton_B12phpfw.php?i/read_post/';
//ee ...'read_post' => QS.'i/read_post/' ,
echo '<p>Page call is only $db = new Home_ctr($pp1) ; (or new App, or simmilar).</p>';
$db = new Home_ctr($pp1) ; //Home_ ctr (or App) class "inherits" index.php ee "inherits" $ p p 1
// ****************************************************************************
echo '<h1>'. 'Worse : not used Home_ ctr method read_post' .'</h1>' ;
// ****************************************************************************
echo
'URL is without ?i/read_post/ : http://dev1:8083/fwphp/glomodul/z_examples/php_patterns/singleton_B12phpfw.php';
echo '<p>Page call must contain code in method read_post.</p>';
//3. process request from ibrowser & send response to ibrowser :
//1=autol STEP_2=conf 3=view/rout/disp 4=preCRUD 5=onCRUD
//STEP_3=rout/disp is in parent::__construct : fw core calls method in Home_ctr cls
echo '<h3>'.basename(__FILE__) //. __METHOD__
. ', line '. __LINE__ .' SAYS: Before $db = new Home_ctr($pp1) ; '.'</h3>' ;
echo '$db = new Home_ctr($pp1) ; //Home_ ctr "inherits" index.php ee inherits $p p1';
// $cursor is: object(PDOStatement)#9 (1) {
// ["queryString"]=>
// string(37) "SELECT COUNT(*) COUNT_ROWS FROM posts"
//}
//The result is the same connection for both instances.
//ee is_null(self::$instance) is printed ONLY ONCE DURING PAGE LIFE - SINGLETON !!! :
//B12phpfw\core\zinc\Dbconn_allsites::get_or_new_dball ln=32 SAYS:
//is_null(self::$instance)
$db = new Home_ctr($pp1) ; //Home_ ctr "inherits" index.php ee inherits $p p1
$cursor = $db->rr("SELECT COUNT(*) COUNT_ROWS FROM posts", [], __FILE__ .', ln '. __LINE__ ) ;
$db = new Home_ctr($pp1) ; //Home_ ctr "inherits" index.php ee inherits $p p1
//SELECT * FROM admins ORDER BY username
$cursor = $db->rr("SELECT COUNT(*) COUNT_ROWS FROM posts", [], __FILE__ .', ln '. __LINE__ ) ;
//$db::disconnect(); //NOT problem ON LINUX
//return $cursor ;
while ($row = $db->rrnext($cursor)): {$r = $row ;} endwhile; //c_, R_, U_, D_
echo '<pre>$cursor = $db->rr("SELECT COUNT(*) COUNT_ROWS FROM posts"...) is: '; var_dump($cursor); echo '</pre>';
echo '$db->rrnext($cursor))='; print_r($r);
exit(0);
| true |
7d6e3c174353e06f5f0164bd6265489a80b141ef | PHP | sjelfull/api-traffic-inspector | /proxy.php | UTF-8 | 2,717 | 2.78125 | 3 | [] | no_license | <?php
/*
* Warning! Read and use at your own risk!
*
* This tiny proxy script is completely transparent and it passes
* all requests and headers without any checking of any kind.
* The same happens with JSON data. They are simply forwarded.
*
* This is just an easy and convenient solution for the AJAX
* cross-domain request issue, during development.
* No sanitization of input is made either, so use this only
* if you are sure your requests are made correctly and
* your urls are valid.
*
*/
$method = $_SERVER['REQUEST_METHOD'];
if ( $_GET && $_GET['url'] ) {
$headers = getallheaders();
$headers_str = [];
$url = $_GET['url'];
foreach ($headers as $key => $value) {
if ( $key == 'Host' )
continue;
$headers_str[] = $key . ":" . $value;
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL, $url);
if ( $method !== 'GET' ) {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
}
if ( $method == "PUT" || $method == "PATCH" || ($method == "POST" && empty($_FILES)) ) {
$data_str = file_get_contents('php://input');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_str);
//error_log($method.': '.$data_str.serialize($_POST).'\n',3, 'err.log');
}
elseif ( $method == "POST" ) {
$data_str = array();
if ( !empty($_FILES) ) {
foreach ($_FILES as $key => $value) {
$full_path = realpath($_FILES[ $key ]['tmp_name']);
$data_str[ $key ] = '@' . $full_path;
}
}
//error_log($method.': '.serialize($data_str+$_POST).'\n',3, 'err.log');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_str + $_POST);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers_str);
curl_setopt($ch, CURLOPT_ENCODING, '');
$output = curl_exec($ch);
$data = explode("\n", $output);
$responseHeaders = [];
$responseHeaders['status'] = $data[0];
array_shift($data);
foreach ($data as $part) {
$middle = explode(":", $part);
$responseHeaders[ trim($middle[0]) ] = trim($middle[1]);
}
curl_close($ch);
echo "<pre>";
print_r($responseHeaders);
echo "</pre>";
if ( isset($headers['Content-Type']) ) {
header('Content-Type: ' . $headers['Content-Type']);
}
else {
header('Content-Type: application/json');
}
echo $output;
}
else {
echo $method;
var_dump($_POST);
var_dump($_GET);
$data_str = file_get_contents('php://input');
echo $data_str;
} | true |
e4e4751b4f1048764a8f5c1e4286d9b43b3ac6dc | PHP | fullstack82/Master-php-7 | /php7/ejercicios-bloques1/ejercicio5.php | UTF-8 | 530 | 3.765625 | 4 | [] | no_license | <?php
/*
- Ejercicio nº 5:
Hacer un programa que muestre todos los números entre dos numeros que nos llegan por la url($_GET)
*/
if (isset($_GET['numero1']) && isset($_GET['numero2'])) {
$numero1 = $_GET['numero1'];
$numero2 = $_GET['numero2'];
if ($numero < $numero2) {
for ($i = $numero1; $i <= $numero2; $i++) {
echo "<h4>$i</h4>";
}
}else{
echo "<h1> El numero 1 debe ser menor al numero 2</h1>";
}
} else {
echo "<h1>Los parametros get no existen</h1>";
}
| true |
ca36e5966b841d5872a42616d147de6afb42d48d | PHP | shafqatali/code-signal | /isMAC48Address/is_mac_48_address.php | UTF-8 | 309 | 2.875 | 3 | [] | no_license | <?php
function isMAC48Address($inputString) {
$ia = explode('-', $inputString);
if(sizeof($ia) != 6){ return false;}
foreach($ia as $v){
if(strlen($v) != 2 || !preg_match("/^[a-f0-9]{2,}$/i", $v)){
return false;
}
}
return true;
}
| true |