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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
cbc463c3487f2f1ab96af693487799e68477dcd3 | PHP | infosportlery/Sportlery_mvp | /plugins/sportlery/library/models/LocationTime.php | UTF-8 | 1,325 | 2.625 | 3 | [] | no_license | <?php
namespace Sportlery\Library\Models;
use Model;
class LocationTime extends Model
{
use \October\Rain\Database\Traits\Validation;
/*
* Validation
*/
public $rules = [
'monday_start' => 'before:monday_end',
'tuesday_start' => 'before:tuesday_end',
'wednesday_start' => 'before:wednesday_end',
'thursday_start' => 'before:thursday_end',
'friday_start' => 'before:friday_end',
'saturday_start' => 'before:saturday_end',
'sunday_start' => 'before:sunday_end',
];
/**
* @var string The database table used by the model.
*/
public $table = 'spr_location_times';
public function filterFields($fields, $context = null)
{
if ($context === 'relation') {
$days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
foreach ($days as $day) {
$start = "{$day}_start";
$end = "{$day}_end";
if (!$fields->$start->value || !$fields->$end->value) {
$fields->$start->label = ucfirst($day);
$fields->$start->type = 'text';
$fields->$start->value = 'Closed';
$fields->$end->hidden = true;
}
}
}
}
}
| true |
5d5fd65bd163a13f79d58034c81e263c565b7d48 | PHP | veewee/xpath-reader | /src/Reader/Handler/XmlImportingReader.php | UTF-8 | 833 | 2.75 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace XpathReader\Reader\Handler;
use XpathReader\Reader\Matcher\MatcherInterface;
use XpathReader\Reader\Node\NodeSequence;
use XpathReader\Reader\XpathReader;
class XmlImportingReader
{
/**
* @var MatcherInterface[]
*/
private array $matchers;
/**
* @var callable(string): string
*/
private $importedXmlResolver;
public function __construct(callable $importedXmlResolver, MatcherInterface ... $matchers)
{
$this->matchers = $matchers;
$this->importedXmlResolver = $importedXmlResolver;
}
public function __invoke(NodeSequence $sequence, string $xml): iterable
{
$reader = new XpathReader(...$this->matchers);
yield from $reader->readXml(($this->importedXmlResolver)($xml), $sequence->pop());
}
}
| true |
ef0d6ed8efd52c7209301134bdf6212d053d6a56 | PHP | gvsurenderreddy/aastra-phone-php | /src/Clearvox/Aastra/Phone/Contracts/SupportsHardKeyInterface.php | UTF-8 | 272 | 2.59375 | 3 | [] | no_license | <?php
namespace Clearvox\Aastra\Phone\Contracts;
interface SupportsHardKeyInterface
{
/**
* Returns the number of HardKeys on the phone or 0
* if the model doesn't support HardKeys.
*
* @return int
*/
public function numberOfHardKeys();
} | true |
d942c46b620cc06a57da5eaebe79493ecd2cd4d6 | PHP | MatokUK/shunting-yard-php | /src/Tokenizer.php | UTF-8 | 1,299 | 3.328125 | 3 | [] | no_license | <?php
namespace Matok\ShuntingYard;
use Matok\ShuntingYard\Token\ValueToken;
class Tokenizer
{
/** @var string */
private $expression;
/** @var int */
private $length;
public function __construct($expression)
{
$this->expression = $expression;
$this->length = strlen($this->expression);
}
public function getTokens()
{
$digit = '';
for ($i = 0; $i < $this->length; $i++) {
if ($this->isSpaceOnPosition($i)) {
continue;
}
if (!$this->isDigitOnPosition($i)) {
yield new ValueToken($this->expression[$i]);
} else {
$digit .= $this->expression[$i];
if ($this->isDigitFinished($i)) {
yield new ValueToken($digit);
$digit = '';
}
}
}
}
private function isSpaceOnPosition(int $pos): bool
{
return ctype_space($this->expression[$pos]);
}
private function isDigitOnPosition(int $pos): bool
{
return ctype_digit($this->expression[$pos]);
}
private function isDigitFinished(int $pos): bool
{
return !isset($this->expression[$pos+1]) || !ctype_digit($this->expression[$pos+1]);
}
} | true |
8324ead492f6aa97de1e230647bfcf9ed74e0457 | PHP | ningnayang/YNNshop | /backend/filters/RbacFilter.php | UTF-8 | 930 | 2.59375 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
//命名空间
namespace backend\filters;
use yii\base\ActionFilter;
use yii\web\HttpException;
class RbacFilter extends ActionFilter{
//在操作执行之前
public function beforeAction($action)
{
if(!\Yii::$app->user->can($action->uniqueId)){//如果用户没有权限
//如果没有登录,引导用户登录
if(\Yii::$app->user->isGuest){
//跳转至登录页面
//注意,一定要加send,因为即使这个用户有权限,但是没有登录,如果不加登录也相当于return true
return $action->controller->redirect(\Yii::$app->user->loginUrl)->send();//模型没有跳转方法,只有控制器才有,所有要先找到这个控制器
}
//没有权限 抛出异常
throw new HttpException(403,'对不起,您没有该操作权限');
}
return true;
}
}
| true |
871bd35d39ec5f068713d86ddd13fdc3fc19c09c | PHP | Beaves83/cfgweb | /database/seeds/UserTableSeeder.php | UTF-8 | 1,579 | 2.5625 | 3 | [] | no_license | <?php
use Illuminate\Database\Seeder;
use App\User;
use App\Role;
class UserTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//Creamos usuario con el perfil de Administrador
$user = new User();
$user->name = 'Administrador';
$user->password = Hash::make('admin@email.es');
$user->email = 'admin@email.es';
$user->email_verified_at = new \DateTime();
$user->created_at = new \DateTime();
$user->updated_at = new \DateTime();
$user->save();
$user->roles()->attach(Role::where('name', 'admin')->first());
//Creamos usuario con el perfil de User
$user = new User();
$user->name = 'Usuario de pruebas';
$user->password = Hash::make('usuario@email.es');
$user->email = 'usuario@email.es';
$user->email_verified_at = new \DateTime();
$user->created_at = new \DateTime();
$user->updated_at = new \DateTime();
$user->save();
$user->roles()->attach(Role::where('name', 'user')->first());
//Creamos usuario con el perfil de Gestor
$user = new User();
$user->name = 'Gestor de pruebas';
$user->password = Hash::make('gestor@email.es');
$user->email = 'gestor@email.es';
$user->email_verified_at = new \DateTime();
$user->created_at = new \DateTime();
$user->updated_at = new \DateTime();
$user->save();
$user->roles()->attach(Role::where('name', 'gestor')->first());
}
}
| true |
45e4408b907666d9aadfa8c689a1d3a2d34520b1 | PHP | kennCK/ilinya | /api/app/Ilinya/Message/Facebook/Ai.php | UTF-8 | 4,351 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Ilinya\Message\Facebook;
use App\Ilinya\Bot;
use App\Ilinya\Tracker;
use App\Ilinya\Http\Curl;
use App\Ilinya\Message\Facebook\Codes;
use App\Ilinya\Message\Facebook\Form;
use App\Ilinya\Message\Facebook\Postback;
use App\Ilinya\Message\Facebook\QuickReply;
use App\Ilinya\Response\Facebook\AiResponse;
use App\Ilinya\Webhook\Facebook\Messaging;
use App\Ilinya\Helper\Validation;
use App\Ilinya\API\QueueCardFields;
use App\Ilinya\API\Ai as AiResponseManager;
use App\Ilinya\User;
class Ai{
protected $bot;
protected $form;
protected $tracker;
protected $code;
protected $validation;
protected $aiResponse;
protected $postback;
protected $quickReply;
protected $curl;
protected $user;
protected $messaging;
function __construct(Messaging $messaging){
$this->bot = new Bot($messaging);
$this->form = new Form($messaging);
$this->tracker= new Tracker($messaging);
$this->code = new Codes();
$this->validation = new Validation($messaging);
$this->aiResponse = new AiResponse($messaging);
$this->postback = new Postback($messaging);
$this->quickReply = new QuickReply($messaging);
$this->curl = new Curl();
$this->messaging = $messaging;
}
public function user(){
$user = $this->curl->getUser($this->messaging->getSenderId());
$this->user = new User($this->messaging->getSenderId(), $user['first_name'], $user['last_name']);
}
public function manage($reply){
/*
1. get result
2. if result, check action
2.1 action is null, reply text
2.2 action is not null, manage action
3. else result, reply error
*/
$reply = strtolower($reply);
$data = [
"column" => "question",
"clause" => "like",
"value" => $reply
];
$result = AiResponseManager::retrieve($data);
if($result){
/*
1. Get Code
2. Manage code
*/
if($result[0]['answer'] != NULL){
$this->answerHandler($result[0]['answer']);
}
if($result[0]['action'] != NULL){
$this->actionTypeHandler($result[0]);
}
}else{
$dataError = [
"column" => "question",
"clause" => "=",
"value" => "not_found"
];
$errorResult = AiResponseManager::retrieve($dataError);
$this->saveNewQuestion($reply);
if($errorResult){
$this->bot->reply($errorResult[0]['answer'], true);
}else{
$this->bot->reply("We're working to be able to respond your concern :)", true);
}
}
}
public function actionTypeHandler($object){
switch (strtolower($object['action_type'])) {
case 'postback':
$custom = [
"type" => "postback",
"payload" => $object['action'],
"parameter" => NULL
];
$this->postback->manage($custom);
break;
case 'quick_reply':
$custom = [
"type" => "messaging",
"quick_reply" => array(
"payload" => $object['action'],
"parameter" => NULL
),
"text" => NULL,
"attachment" => NULL
];
$this->quickReply->manage($custom);
break;
}
}
public function answerHandler($text){
if(strpos($text, '%') != false){
$answer = explode('%', $text, -1);
if(sizeof($answer) > 1){
$responseText = '';
for($row = 0; $row < sizeof($answer); $row++){
$responseText .=$this->codeHandler($answer[$row]);
}
$this->bot->reply($responseText, true);
}else{
$this->bot->reply($text, true);
}
}else{
$this->bot->reply($text, true);
}
}
public function codeHandler($text){
$response = '';
switch (strtolower($text)) {
case '@fname':
$this->user();
return $this->user->getFirstName();
case '@lname':
$this->user();
return $this->user->getLastName();
case '@cname':
$this->user();
return $this->user->getFirstName()." ".$this->user->getLastName();
default:
return $text;
}
}
public function saveNewQuestion($text){
// save to ai here
$data = [
"question" => $text
];
return AiResponseManager::create($data);
}
}
| true |
6f2017b434dade29bef242ac2ecc0ee049a1ead1 | PHP | iopiopi1/roadaccident | /module/Application/src/src/models/Application/Entity/User.php | UTF-8 | 5,832 | 3.09375 | 3 | [] | no_license | <?php
namespace Application\Entity;
/**
* User
*/
class User
{
/**
* @var integer
*/
private $id;
/**
* @var string
*/
private $username;
/**
* @var integer
*/
private $status;
/**
* @var \DateTime
*/
private $dateCreated;
/**
* @var \DateTime
*/
private $dateEdited;
/**
* @var string
*/
private $email;
/**
* @var string
*/
private $password;
/**
* @var string
*/
private $phone;
/**
* @var string
*/
private $firstname;
/**
* @var string
*/
private $lastname;
/**
* @var \DateTime
*/
private $birthdate;
/**
* @var integer
*/
private $vkId;
/**
* @var integer
*/
private $okId;
/**
* @var \DateTime
*/
private $passwordChangeddate;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set username
*
* @param string $username
*
* @return User
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* @return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set status
*
* @param integer $status
*
* @return User
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* @return integer
*/
public function getStatus()
{
return $this->status;
}
/**
* Set dateCreated
*
* @param \DateTime $dateCreated
*
* @return User
*/
public function setDateCreated($dateCreated)
{
$this->dateCreated = $dateCreated;
return $this;
}
/**
* Get dateCreated
*
* @return \DateTime
*/
public function getDateCreated()
{
return $this->dateCreated;
}
/**
* Set dateEdited
*
* @param \DateTime $dateEdited
*
* @return User
*/
public function setDateEdited($dateEdited)
{
$this->dateEdited = $dateEdited;
return $this;
}
/**
* Get dateEdited
*
* @return \DateTime
*/
public function getDateEdited()
{
return $this->dateEdited;
}
/**
* Set email
*
* @param string $email
*
* @return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set password
*
* @param string $password
*
* @return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* @return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set phone
*
* @param string $phone
*
* @return User
*/
public function setPhone($phone)
{
$this->phone = $phone;
return $this;
}
/**
* Get phone
*
* @return string
*/
public function getPhone()
{
return $this->phone;
}
/**
* Set firstname
*
* @param string $firstname
*
* @return User
*/
public function setFirstname($firstname)
{
$this->firstname = $firstname;
return $this;
}
/**
* Get firstname
*
* @return string
*/
public function getFirstname()
{
return $this->firstname;
}
/**
* Set lastname
*
* @param string $lastname
*
* @return User
*/
public function setLastname($lastname)
{
$this->lastname = $lastname;
return $this;
}
/**
* Get lastname
*
* @return string
*/
public function getLastname()
{
return $this->lastname;
}
/**
* Set birthdate
*
* @param \DateTime $birthdate
*
* @return User
*/
public function setBirthdate($birthdate)
{
$this->birthdate = $birthdate;
return $this;
}
/**
* Get birthdate
*
* @return \DateTime
*/
public function getBirthdate()
{
return $this->birthdate;
}
/**
* Set vkId
*
* @param integer $vkId
*
* @return User
*/
public function setVkId($vkId)
{
$this->vkId = $vkId;
return $this;
}
/**
* Get vkId
*
* @return integer
*/
public function getVkId()
{
return $this->vkId;
}
/**
* Set okId
*
* @param integer $okId
*
* @return User
*/
public function setOkId($okId)
{
$this->okId = $okId;
return $this;
}
/**
* Get okId
*
* @return integer
*/
public function getOkId()
{
return $this->okId;
}
/**
* Set passwordChangeddate
*
* @param \DateTime $passwordChangeddate
*
* @return User
*/
public function setPasswordChangeddate($passwordChangeddate)
{
$this->passwordChangeddate = $passwordChangeddate;
return $this;
}
/**
* Get passwordChangeddate
*
* @return \DateTime
*/
public function getPasswordChangeddate()
{
return $this->passwordChangeddate;
}
}
| true |
747605b75658a1bac45b5443b8662119506a2b3c | PHP | dathalongbay/1901ephp | /day2/7.array/index3.php | UTF-8 | 882 | 3.90625 | 4 | [] | no_license | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Foreach mảng chỉ số ( mảng có key là số ) </h1>
<h1>toán tử ! là toán tử phủ định</h1>
<?php
// Mảng chỉ số
$students = array("nguyen van a1","nguyen van a2","nguyen van a3","nguyen van a4","nguyen van a5",);
echo "<pre>";
print_r($students);
echo "</pre>";
echo "<br> Dạng foreach đầy đủ";
// Dạng foreach đầy đủ
if (is_array($students) && !empty($students)) {
foreach($students as $key => $value) {
echo "<br> Key : " . $key . " Value : " . $value;
}
}
echo "<br> Dạng foreach rút gọn";
// Dạng foreach rút gọn chỉ lặp và xuất ra cái value
if (is_array($students) && !empty($students)) {
foreach($students as $value) {
echo "<br> Value : " . $value;
}
}
?>
</body>
</html> | true |
f71c02b8a29642bd1e420b334d9f5af919753987 | PHP | Funck-Felipe97/APS | /Model/Dao/funcionarioDao.php | UTF-8 | 3,252 | 2.71875 | 3 | [] | no_license | <?php
include "banco.php";
/**
* @Funck
*/
class FuncionarioDao{
private $connection;
function __construct(){
$this->connection = getConnection();
}
public function insere_funcionario($funcionario){
$sql = "CALL insere_funcionario(? , ? , ? , ? , ? , ? , ? , ? , ? , ?);";
$stmt = $this->connection->prepare($sql);
return $stmt->execute(
array($funcionario->getNome() ,
$funcionario->getCpf() ,
$funcionario->getSenha() ,
$funcionario->getUser() ,
$funcionario->getData_nascimento() ,
$funcionario->getCargo()->getId() ,
$funcionario->getEndereco()->getRua() ,
$funcionario->getEndereco()->getBairro() ,
$funcionario->getEndereco()->getCidade() ,
$funcionario->getEndereco()->getNumero()
));
}
public function listar_funcionarios_todos(){
$sql = "CALL listar_funcionarios_todos();";
$stmt = $this->connection->prepare($sql);
$stmt->execute();
$funcionarios = array();
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $linha) {
$funcionario = $this->preenche_funcionario($linha);
$funcionarios[] = $funcionario;
}
return $funcionarios;
}
public function buscar_funcionario_id($id){
$sql = "CALL buscar_funcionario_id(?);";
$stmt = $this->connection->prepare($sql);
$stmt->execute(array($id));
$funcionario = $this->preenche_funcionario($stmt->fetch(PDO::FETCH_ASSOC));
return $funcionario;
}
public function atualizar_funcionario($funcionario){
$sql = "CALL atualizar_funcionario(? , ? , ? , ? , ? , ? , ?);";
$stmt = $this->connection->prepare($sql);
$stmt->execute(
array($funcionario->getId(),
$funcionario->getNome() ,
$funcionario->getCpf() ,
$funcionario->getSenha() ,
$funcionario->getUser() ,
$funcionario->getData_nascimento(),
$funcionario->getCargo()->getId()
));
}
public function buscar_funcionario_user($user){
$sql = "CALL buscar_funcionario_user(?);";
$stmt = $this->connection->prepare($sql);
$stmt->execute(array($user));
$funcionario = $this->preenche_funcionario($stmt->fetch(PDO::FETCH_ASSOC));
return $funcionario;
}
public function buscar_funcionario_cpf($cpf){
$sql = "CALL buscar_funcionario_cpf(?);";
$stmt = $this->connection->prepare($sql);
$stmt->execute(array($cpf));
$funcionario = $this->preenche_funcionario($stmt->fetch(PDO::FETCH_ASSOC));
return $funcionario;
}
private function preenche_funcionario($linha){
$funcionario = new Funcionario();
$funcionario->setId($linha["fun_id"]);
$funcionario->setNome($linha["fun_nome"]);
$funcionario->setCpf($linha["fun_cpf"]);
$funcionario->setUser($linha["fun_user_name"]);
$funcionario->setSenha($linha["fun_senha"]);
$funcionario->setData_nascimento($linha["fun_data_nasc"]);
$end = new Endereco();
$end->setRua($linha["end_rua"]);
$end->setBairro($linha["end_bairro"]);
$end->setCidade($linha["end_cidade"]);
$end->setId($linha["end_id"]);
$car = new Cargo();
$car->setDescricao($linha["car_descricao"]);
$car->setId($linha["car_id"]);
$funcionario->setEndereco($end);
$funcionario->setCargo($car);
return $funcionario;
}
}
?> | true |
33aa7dade89b8acf7cc97926119e04c81f300fbb | PHP | rwivan/news | /models/User.php | UTF-8 | 1,551 | 2.546875 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace app\models;
use app\mailer\Mailer;
use dektrium\user\helpers\Password;
use dektrium\user\models\Token;
use dektrium\user\models\User AS BaseUser;
/**
* Class User.
* Модель пользователя.
*
* @property-read Mailer $mailer
*
* @package app\models
*/
class User extends BaseUser
{
/**
* Создание пользователя администратором.
*
* @return bool
*
* @throws \Exception
*/
public function createByAdmin()
{
if ($this->getIsNewRecord() == false) {
throw new \RuntimeException('Calling "' . __CLASS__ . '::' . __METHOD__ . '" on existing user');
}
$transaction = $this->getDb()->beginTransaction();
try {
$this->password = $this->password == null ? Password::generate(8) : $this->password;
$this->trigger(self::BEFORE_CREATE);
if (!$this->save()) {
$transaction->rollBack();
return false;
}
/** @var Token $token */
$token = \Yii::createObject(['class' => Token::class, 'type' => Token::TYPE_CONFIRMATION]);
$token->link('user', $this);
$this->mailer->sendCreateByAdminMessage($this, $token);
$this->trigger(self::AFTER_CREATE);
$transaction->commit();
return true;
} catch (\Exception $e) {
$transaction->rollBack();
\Yii::warning($e->getMessage());
throw $e;
}
}
}
| true |
9d8e343fd2153fa7c3fa02ffea0d4e60c8bd863a | PHP | gabrielsalazar8486/laravel-ddd-skeleton | /src/ERP/Provider/Application/Find/ProviderFinder.php | UTF-8 | 696 | 2.546875 | 3 | [] | no_license | <?php
namespace Medine\ERP\Provider\Application\Find;
use Medine\ERP\Provider\Application\ProviderResponse;
use Medine\ERP\Provider\Domain\ValueObjects\ProviderId;
use Medine\ERP\Provider\Infrastructure\Persistence\MySqlProviderRepository;
class ProviderFinder
{
private $repository;
public function __construct(MySqlProviderRepository $repository)
{
$this->repository = $repository;
}
public function __invoke(ProviderFinderRequest $request)
{
$provider = $this->repository->find(new ProviderId($request->id()));
return new ProviderResponse(
$provider->id()->value(),
$provider->name()->value()
);
}
}
| true |
2e127177be21d11b0d71acb6b7f45e0c326cecd3 | PHP | vishnuprasadmuraleedharan/purephp-examples | /insertinto.php | UTF-8 | 737 | 2.890625 | 3 | [] | no_license | <?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "pureDb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('denny', 'Doe', 'john@example.com');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('elf', 'Moe', 'mary@example.com');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('freddy', 'Dooley', 'julie@example.com')";
if($conn->multi_query($sql)===TRUE){
echo"data inserted into myguests";
} else{
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
| true |
632efccfbbc7a1e32640b041fcc3c36b9b553082 | PHP | chpdesign/depcap | /System/ORM/Types/File.php | UTF-8 | 13,858 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
namespace ComposerPack\System\ORM\Types;
class File extends Type {
protected $valid = [];
public function valid($valid = null)
{
if(is_null($valid))
{
return $this->valid;
}
$this->valid = $valid;
}
public function blockField($model, $formid, $url)
{
$key = $this->key();
$value = $model[$key];
$valid = $this->valid();
ob_start();
?>
<div class="row">
<?php
$filescount = 0;
if(!empty($value))
{
$file = new \SplFileInfo($value);
// filter out directories
try
{
if($file->isFile()) {
// Use pathinfo to get the file extension
$info = pathinfo($file->getPathname());
// Check there is an extension and it is in the whitelist
if (isset($info['extension']) && (empty($valid) || isset($valid[$info['extension']]))) {
$file = array(
'filename' => $file->getFilename(),
'path' => str_replace(get('base_dir'), "", $info['dirname']) . '/',
'size' => $file->getSize(),
'type' => $info['extension'], // 'PDF' or 'Word'
'created' => date('Y-m-d H:i:s', $file->getCTime())
);
$filescount++;
?>
<div class="col-md-12 <?php echo $this->formFieldId(); ?>item">
<input class=" <?php echo 'can-disable '.($this->disabled() ? 'field-disabled disabled' : ''); ?>" type="hidden" name="<?php echo $key; ?>"
value="<?php echo $file['path'] . $file['filename']; ?>" <?php echo $this->disabled() ? 'disabled="disabled"' : ''; ?>/>
<?php if (!($this->disabled())) { ?>
<span class="action">
<span class="btn btn-danger pull-left remove"><i class="glyphicon glyphicon-remove"></i></span>
</span>
<?php } ?>
<a href="<?php echo $url.'/download?'; ?><?php echo http_build_query(['file' => $file['path'].$file['filename']]); ?>" download="<?php echo $file['filename']; ?>" class="btn btn-link"
<?php
if($this->iconType(strtolower($file['type'])) == 'image')
{
?>rel="popover" data-template='<div class="popover" role="tooltip"><h3 class="popover-title"></h3><div class="popover-content"></div></div>' data-placement="bottom" data-title="" data-content='<img style="max-width: 200px; max-height: 200px;" src="<?php echo $url.'/download?'; ?><?php echo http_build_query(['file' => $file['path'].$file['filename']]); ?>"/>'<?php
}
?>
>
<i class="fa <?php echo $this->icon(strtolower($file['type'])); ?>"></i>
<span data-filename="<?php echo $file['path'].$file['filename']; ?>" class="filename"><?php echo $file['filename']; ?></span>
</a>
</div><?php
}
}
}
catch (\Exception $e)
{
}
}
?>
<script id="<?php echo $this->formFieldId(); ?>clone" type="text/template">
<div class="col-md-12 <?php echo $this->formFieldId(); ?>item">
<input type="hidden" name="<?php echo $key; ?>" />
<div class="progress">
<div class="progress-bar progress-bar-success progress-bar-striped active" role="progressbar" aria-valuenow="45" aria-valuemin="0" aria-valuemax="100" style="min-width: 4em;">
</div>
</div>
<div class="finished hidden">
<span class="action">
<span class="btn btn-danger pull-left remove"><i class="glyphicon glyphicon-remove"></i></span>
</span>
<a href="" download class="btn btn-link"><i class="fa fa-file-o"></i> <span class="filename"></span></a>
</div>
</div>
</script>
<?php if(!($this->disabled())){ ?>
<div class="col-md-2 col-lg-3 <?php echo $filescount > 0 ? 'hidden' : ''; ?> upload-btn">
<button type="button" class="btn btn-site btn-file btn-block">
<input type="file" title="Hozzáadás"/>
<i class="fa fa-file-o"></i> Hozzáadás
</button>
</div>
<?php } else if($filescount == 0) { ?>
<div class="col-md-2">
<div class="help-block">Nincsen fájl feltöltve!</div>
</div>
<?php } ?>
<?php
?>
<div class="clearfix"></div>
</div>
<script type="text/javascript">
(function(){
var icons = <?php echo json_encode(self::$icons); ?>;
var extensions = <?php echo json_encode(self::$extensions); ?>;
$(document).on('change', '.<?php echo $this->formFieldId(); ?> .btn-file :input[type="file"]', function(evt){
var _this = this;
var tgt = evt.target || window.event.srcElement,
files = tgt.files;
$(_this).parents('.upload-btn').addClass('hidden');
for (var index = 0; index < files.length; index++)
{
var $fileTemplate = $($('#<?php echo $this->formFieldId(); ?>clone').text().trim());
$('#<?php echo $this->formFieldId(); ?>clone').before($fileTemplate);
var form = new FormData();
var file = this.files[index];
form.append('file', file);
this.value = '';
var $this = $(this);
var url = '<?php echo $url.'/tempfolder'; ?>';
$.ajax({
xhr: function()
{
var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
$('.progress-bar',$fileTemplate).text((Math.round(percentComplete * 10000) / 100)+'%');
$('.progress-bar',$fileTemplate).css({width: (Math.round(percentComplete * 10000) / 100)+'%'});
}
}, false);
//Download progress
xhr.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
$('.progress-bar',$fileTemplate).text(percentComplete+'%');
$('.progress-bar',$fileTemplate).css({width: percentComplete+'%'});
}
}, false);
return xhr;
},
dataType: 'json', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
url: url,
processData: false,
data: form,
type: 'post',
success: function(response){
if(response.result)
{
$('.progress', $fileTemplate).addClass('hidden');
$('.finished', $fileTemplate).removeClass('hidden');
var filename = response.result.split(/(\\|\/)/g).pop();
var extension = filename.split('.').pop().toLowerCase();
if(extensions[extension] && icons[extensions[extension]]) {
$('.fa', $fileTemplate).attr('class', '').addClass('fa').addClass(icons[extensions[extension]]);
if(extensions[extension] == 'image')
$('a', $fileTemplate).attr('rel','popover').data('template', '<div class="popover" role="tooltip"><h3 class="popover-title"></h3><div class="popover-content"></div></div>').data('placement','bottom').data('title','').data('content', '<img style="max-width: 200px; max-height: 200px;" src="'+'<?php echo $url.'/download'; ?>?file='+response.result+'"/>').popover({trigger: "hover", html: true});
}
else
$('.fa', $fileTemplate).attr('class', '').addClass('fa fa-file-o');
$('.filename', $fileTemplate).text(filename);
$('.filename', $fileTemplate).data('filename', response.result);
$('[download]', $fileTemplate).attr('href', '<?php echo $url.'/download'; ?>?file=' + response.result);
$('[download]', $fileTemplate).attr('download', response.result.split(/(\\|\/)/g).pop());
$(':input', $fileTemplate).val(response.result);
}
}
})
}
});
$(document).on('click', '.<?php echo $this->formFieldId(); ?> .remove', function(){
if($(this).hasClass('field-disabled') || $(this).hasClass('disabled'))
return false;
var $this = $(this);
var $parent = $this.parents('.<?php echo $this->formFieldId(); ?>item');
var filename = $('.filename', $parent).data('filename');
var data = {remove: filename};
var url = '<?php echo $url.'/tempfolder'; ?>';
$.ajax({
url: url,
data: data,
type: 'POST',
dataType: 'JSON',
success: function(response){
if(response.result === filename) {
$('.<?php echo $this->formFieldId(); ?> .btn-file :input[type="file"]').parents('.upload-btn').removeClass('hidden');
$parent.remove();
}
}
});
return false;
});
$('.<?php echo $this->formFieldId(); ?> [data-toggle="popover"][data-trigger="hover"]').popover({trigger: "hover", html: true});
})();
</script>
<?php
return ob_get_clean();
}
public function __construct(array $field = [])
{
parent::__construct($field);
}
public function icon($type)
{
if(empty($type))
return self::$icons['file'];
$type = strtolower($type);
if(isset(self::$extensions[$type]) && isset(self::$icons[self::$extensions[$type]]))
return self::$icons[self::$extensions[$type]];
return self::$icons['file'];
}
public function iconType($type)
{
if(empty($type))
return self::$extensions['file'];
$type = strtolower($type);
if(isset(self::$extensions[$type]))
return self::$extensions[$type];
return self::$extensions['file'];
}
// https://github.com/spatie/font-awesome-filetypes
// nyomán... php-sítva...
protected static $icons = [
'image' => 'fa-file-image-o',
'pdf' => 'fa-file-pdf-o',
'word' => 'fa-file-word-o',
'powerpoint' => 'fa-file-powerpoint-o',
'excel' => 'fa-file-excel-o',
'audio' => 'fa-file-audio-o',
'video' => 'fa-file-video-o',
'zip' => 'fa-file-zip-o',
'code' => 'fa-file-code-o',
'text' => 'fa-file-text-o',
'file' => 'fa-file-o'
];
protected static $extensions = [
'gif' => 'image',
'jpeg' => 'image',
'jpg' => 'image',
'png' => 'image',
'pdf' => 'pdf',
'doc' => 'word',
'docx' => 'word',
'ppt' => 'powerpoint',
'pptx' => 'powerpoint',
'xls' => 'excel',
'xlsx' => 'excel',
'aac' => 'audio',
'mp3' => 'audio',
'ogg' => 'audio',
'avi' => 'video',
'flv' => 'video',
'mkv' => 'video',
'mp4' => 'video',
'gz' => 'zip',
'zip' => 'zip',
'css' => 'code',
'html' => 'code',
'js' => 'code',
'txt' => 'text',
'file' => 'file'
];
} | true |
a90f0b842783394829574e1f86b4f2dde82000cf | PHP | Mateos81/ProjetAutoEcole | /EclipsePHP/Projet/application/BLL/Salarie.php | ISO-8859-1 | 7,723 | 3.046875 | 3 | [] | no_license | <?php
/**
* Projet 2me Anne 3iL
* @author CIULLI - MATEOS - ROUX
* @version 1.0
* @package BLL
*/
include "Personne.php";
include "Vehicule.php";
include "Ville.php";
include __DIR__ . "/../DAL/DAL_Salarie.php";
/**
* Classe reprsentant un salari.
*/
class Salarie extends Personne {
/** Poste du salari courant. */
private $salarie_poste;
/** Surnom du salari courant. */
private $salarie_surnom;
/** Vhicule dont est responsable le salari courant. */
private $salarie_vehicule;
/**
* Constructeur vide servant crer un salari via les modifieurs.
* A utiliser quand toutes les informations ne sont pas disponibles.
* Peut aussi tre utilis pour typer les champs.
*/
public function __construct() {
$this->personne_id = -1;
$this->personne_nom = "";
$this->personne_prenom = "";
$this->personne_adr = "";
$this->personne_ville = new Ville();
$this->personne_tel = "";
$this->salarie_poste = 0;
$this->salarie_surnom = "";
$this->salarie_vehicule = new Vehicule();
}
/**
* "Constructeur" complet.
* @param $id Identifiant du salari.
* @param $nom Nom du salari.
* @param $prenom Prnom du salari.
* @param $adr Adresse du salari.
* @param Ville $ville Ville du salari.
* @param $tel Tlphone du salari.
* @param $poste Poste du salari.
* @param $surnom Surnom du salari.
* @param Vehicule $vehicule
* @return Une nouvelle instance de Salarie.
*/
public function Salarie(
$id,
$nom,
$prenom,
$adr,
Ville $ville,
$tel,
$poste,
$surnom,
Vehicule $vehicule) {
$this->personne_id = $id;
$this->personne_nom = $nom;
$this->personne_prenom = $prenom;
$this->personne_adr = $adr;
$this->personne_ville = $ville;
$this->personne_tel = $tel;
$this->salarie_poste = $poste;
$this->salarie_surnom = $surnom;
$this->salarie_vehicule = $vehicule;
}
/**
* Constructeur bas sur le surnom d'un salari,
* car c'est l'information que l'on connait.
* @param Le surnom du salari.
* @return Une nouvelle instance de Salarie.
*/
public function SalarieSurnom($surnom) {
$instance = new self();
// Recherche du salari dans la base
$salarie = array();
$salarie = DAL_Salarie::getSalarieBySurnom($surnom);
// Renseignement des champs
$instance->personne_id = $salarie[0]['salarie_id'];
$instance->personne_nom = $salarie[0]['salarie_nom'];
$instance->personne_prenom = $salarie[0]['salarie_prenom'];
$instance->salarie_surnom = $salarie[0]['salarie_surnom'];
$instance->personne_adr = $salarie[0]['salarie_adr'];
$instance->personne_ville =
new Ville(
$salarie[0]['salarie_ville'],
$salarie[0]['salarie_cp']);
$instance->salarie_poste = $salarie[0]['salarie_poste'];
$instance->salarie_vehicule =
new Vehicule($salarie[0]['salarie_vehicule']);
return $instance;
}
/**
* Accesseur sur le poste du salari.
* @return Le numro du poste du salari.
*/
public function getSalarie_poste() {
return $this->salarie_poste;
}
/**
* Accesseur sur le surnom du salari.
* @return Le surnom du salari.
*/
public function getSalarie_surnom() {
return $this->salarie_surnom;
}
/**
* Accesseur sur le vhicule du salari.
* @return Vehicule Le vhicule du salari.
*/
public function getSalarie_vehicule() {
return $this->salarie_vehicule;
}
/**
* Modifieur sur le poste du salari courant.
* @param $valeur Le nouveau poste du salari.
*/
public function setSalarie_poste($valeur) {
$this->salarie_poste = $valeur;
}
/**
* Modifieur sur le surnom du salari courant.
* @param $valeur Le nouveau surnom du salari.
*/
public function setSalarie_surnom($valeur) {
$this->salarie_surnom = $valeur;
}
/**
* Modifieur sur le vhicule du salari courant.
* @param Vehicule $valeur Le nouveau vhicule du salari.
*/
public function setSalarie_vehicule(Vehicule $valeur) {
$this->salarie_vehicule = $valeur;
}
/**
* Cration d'un nouveau salari en base de donnes.
*/
public function creerSalarie() {
// Cration en base
DAL_Salarie::creerSalarie(
$this->personne_nom,
$this->personne_prenom,
$this->salarie_surnom,
$this->personne_adr,
$this->personne_ville->getVille_nom(),
$this->personne_ville->getVille_cp(),
$this->personne_tel,
$this->salarie_vehicule->getVehicule_num(),
$this->salarie_poste);
// Rcupration de l'identifiant unique
// N'est pas retourn par creerSalarie
// car on ne peut faire de RETURN avec un UPDATE
// dans la mme fonction...
$this->personne_id = DAL_Salarie::getCurSalarie();
}
/**
* Mise en jour en base d'un salari
* suivant les informations de l'objet courant.
*/
public function modifierSalarie() {
DAL_Salarie::modifierSalarie(
$this->personne_id,
$this->personne_nom,
$this->personne_prenom,
$this->salarie_surnom,
$this->personne_adr,
$this->personne_ville->getVille_nom(),
$this->personne_ville->getVille_cp(),
$this->personne_tel,
$this->salarie_vehicule->getVehicule_num(),
$this->salarie_poste);
}
/**
* Suppression en base du salari courant.
*/
public function supprimerSalarie() {
DAL_Salarie::supprimerSalarie($this->personne_id);
}
/**
* Rcupre et renvoie la liste de tous les lves
* associs au salari courant.
* @return La liste des lves.
*/
public function listeEleves() {
return DAL_Salarie::listeEleves($this->personne_id);
}
/**
* Rcupre et renvoie la liste de toutes les leons
* dispenses par salari courant.
* @return La liste des leons.
*/
public function listeLecons() {
return DAL_Salarie::listeLecons($this->personne_id);
}
/**
* Rcupre et renvoie la liste des salaris.
* @param $nom Filtre optionnel sur le nom du salari recherch.
* @param $prenom Filtre optionnel sur le prnom du salari recherch.
* @param $surnom Filtre optionnel sur le surnom du salari recherch.
* @param $poste Filtre optionnel sur le poste du salari recherch.
* @return array(Salarie) La liste des salaris.
*/
public static function listeSalaries(
$nom,
$prenom,
$surnom,
$poste) {
$tabData =
DAL_Salarie::listeSalaries(
$nom,
$prenom,
$surnom,
$poste);
$tabSalaries = array();
while ($row = oci_fetch_array($tabData, OCI_ASSOC+OCI_RETURN_NULLS)) {
$salarie = new Salarie();
$ville = new Ville();
$vehicule = new Vehicule();
$vehicule->VehiculeNum(intval($row['SALARIE_VEHICULE']));
$salarie->Salarie(
intval($row['SALARIE_ID']),
$row['SALARIE_NOM'],
$row['SALARIE_PRENOM'],
$row['SALARIE_ADR'],
$ville->Ville($row['SALARIE_VILLE'], $row['SALARIE_CP']),
$row['SALARIE_TEL'],
$row['SALARIE_POSTE'],
$row['SALARIE_SURNOM'],
$vehicule);
$tabSalaries[] = $salarie;
}
return $tabSalaries;
}
}
?>
| true |
aaad0361d8615c17a63f004df7f8d5f0c61a9e0d | PHP | yfix/yf_utf8_funcs | /utf8_str_split.php | UTF-8 | 2,094 | 3.078125 | 3 | [] | no_license | <?php
/**
* Implementation str_split() function for UTF-8 encoding string.
*
* @created 2008-12-15
* @license http://creativecommons.org/licenses/by-sa/3.0/
* @author Nasibullin Rinat <nasibullin at starlink ru>
* @charset ANSI
* @version 1.0.1
*/
function utf8_str_split(/*string*/ $string, /*int*/ $length = null)
{
if (! is_string($string)) trigger_error('A string type expected in first parameter, ' . gettype($string) . ' given!', E_USER_ERROR);
$length = ($length === null) ? 1 : intval($length);
if ($length < 1) return false;
#there are limits in regexp for {min,max}!
if ($length < 100)
{
preg_match_all('/(?>[\x09\x0A\x0D\x20-\x7E] # ASCII
| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
#| (.) # catch bad bytes
){1,' . $length . '}
/xsS', $string, $m);
$a =& $m[0];
}
else
{
preg_match_all('/(?>[\x09\x0A\x0D\x20-\x7E] # ASCII
| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
#| (.) # catch bad bytes
)
/xsS', $string, $m);
$a = array();
for ($i = 0, $c = count($m[0]); $i < $c; $i += $length) $a[] = implode('', array_slice($m[0], $i, $length));
}
#check UTF-8 data
$distance = strlen($string) - strlen(implode('', $a));
if ($distance > 0)
{
trigger_error('Charset is not UTF-8, total ' . $distance . ' unknown bytes found!', E_USER_WARNING);
return false;
}
return $a;
}
?> | true |
b45485cf16ead13607cac63e0beca8756a3c7790 | PHP | binthec/meister | /app/Http/Controllers/Auth/AuthController.php | UTF-8 | 2,680 | 2.578125 | 3 | [] | no_license | <?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\PaidVacation;
use Session;
use Carbon\Carbon;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use App\Http\Requests;
use Illuminate\Http\Request;
use Auth;
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers;
//ユーザ認証後のリダイレクト先
protected $redirectPath = '/dashboard';
protected $redirectTo = '/dashboard';
//認証されていないユーザのリダイレクト先
protected $loginPath = '/login';
/**
* @param Request $request
* @return type
*/
public function authenticate(Request $request)
{
if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
//ログインの度にDBレコードを更新する
$user = User::find(Auth::user()->id);
$user->setOriginalPaidVacations();
return redirect()->intended('dashboard');
} else {
//認証に失敗した場合
return redirect($this->loginPath())
->withInput($request->only($this->loginUsername(), 'remember'))
->withErrors([
$this->loginUsername() => $this->getFailedLoginMessage(),
]);
}
}
/**
* 登録
*
* @param Request $request
* @return ユーザ登録画面
*/
public function getRegister()
{
return view('auth.register');
}
/**
* 登録実行
*
* @param Request $request
* @return ユーザ一覧に戻る
*/
public function postRegister(Request $request)
{
$validator = Validator::make($request->all(), [
'last_name' => 'required|max:255',
'first_name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:8',
'date_of_entering' => 'required',
]);
if ($validator->fails()) {
return redirect()
->back()
->withErrors($validator)
->withInput();
}
$user = new User;
$user->last_name = $request->last_name;
$user->first_name = $request->first_name;
$user->email = $request->email;
$user->status = User::ACTIVE;
$user->type_of_employment = $request->type_of_employment;
$user->department = $request->department;
$user->password = bcrypt($request->password);
$user->date_of_entering = User::getStdDate($request->date_of_entering); //入社日
$user->base_date = User::getStdDate($request->base_date); //起算日
$user->role = $request->role;
$user->memo = $request->memo;
$user->save();
//有給の再計算
$user->setOriginalPaidVacations();
\Session::flash('flashMsg', 'ユーザ情報を保存しました');
return redirect('/user'); //一覧ページに戻る
}
}
| true |
0a97b90f29a529624efa2edae552fe5fe8ab2dab | PHP | GadgetPodda/blog-script | /admin/addpost.php | UTF-8 | 1,647 | 2.984375 | 3 | [
"MIT"
] | permissive | <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Simple Blog Script</title>
<style>
.add{
padding: 25px;
width: 150px;
background-color: dodgerblue;
border: 0px;
color: white;
}
input[type=text], textarea {
border: 1px solid grey;
border-radius: 5px;
padding: 8px;
width: 80%;
}
</style>
</head>
<body>
<?php
include "config.php";
date_default_timezone_set($timezone);
// Check user login or not
if(!isset($_SESSION['uname'])){
header('Location: login.php');
}
$conn = new mysqli($host, $user, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['submit'])) {
$title = $_POST['title'];
$content = $_POST['content'];
$t=time();
$date = (date("Y-m-d",$t));
$time = (date("H:i",$t));
$sql = "INSERT INTO posts (id, title, content, date, time)
VALUES (NULL, '$title', '$content', '$date', '$time')";
if ($conn->query($sql) === TRUE) {
echo "New post created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
<a href="index.php">Return Home</a><br><br>
<form method="post" action="">
<input type="text" name="title" placeholder="Title of the Post"><br><br>
<textarea name="content" placeholder="Post Content (HTML Allowed)" style="height:700px;"></textarea><br><br>
<input type="submit" value="Add Post" name="submit" class="add">
</form> | true |
c7a3d243426214b166fec98ac8441662ca9d088c | PHP | oach/tbd | /ci_test/application/helpers/admin_helper.php | UTF-8 | 4,801 | 2.71875 | 3 | [] | no_license | <?php
/*function createDropDown($config) {
$class = key_exists('class', $config) ? ' class="' . $config['class'] . '"' : '';
$onchange = key_exists('onchange', $config) ? ' ' . $config['onchange'] : '';
$str = '
<select id="' . $config['id'] . '" name="' . $config['name'] . '"' . $class . $onchange . '>
';
foreach ($config['data'] as $data)
{
$select = $config['selected'] == $data['id'] ? ' selected' : '';
$name = (key_exists('upperCase', $config) && $config['upperCase'] === true) ? ucwords($data['name']) : $data['name'];
$str .= '
<option value="' . $data['id'] . '"' . $select . '>' . $name . '</option>
';
}
$str .= '
</select>
';
return $str;
}*/
function createDropDownNoKeys($config) {
$class = key_exists('class', $config) ? ' class="' . $config['class'] . '"' : '';
$str = '
<select id="' . $config['id'] . '" name="' . $config['name'] . '"' . $class . '>
';
foreach($config['data'] as $data) {
$select = $config['selected'] == $data ? ' selected="selected"' : '';
$str .= '
<option value="' . $data . '"' . $select . '>' . $data . '</option>
';
}
$str .= '
</select>
';
return $str;
}
function createDropDownStyles($config) {
$class = key_exists('class', $config) ? ' class="' . $config['class'] . '"' : '';
$onchange = key_exists('onchange', $config) ? ' ' . $config['onchange'] : '';
$str = '
<select id="' . $config['id'] . '" name="' . $config['name'] . '"' . $class . $onchange . '>
';
///echo '<pre>'; print_r($config['data']); echo '</pre>'; exit;
//$arr_major = array();
$arr_styles = array();
//$i = 0;
$j = 0;
foreach($config['data'] as $data) {
if(!in_array($data['origin'] . '_' . $data['styleType'], $arr_styles)) {
$str .= $j > 0 ? '</optgroup>' : '';
}
/*if(!in_array($data['styleType'], $arr_major)) {
$str .= $i > 0 ? '</optgroup>' : '';
$arr_major[] = $data['styleType'];
$str .= '
<optgroup label="' . $data['styleType'] . '">
';
}*/
if(!in_array($data['origin'] . '_' . $data['styleType'], $arr_styles)) {
//$str .= $j > 0 ? '</optgroup>' : '';
$arr_styles[] = $data['origin'] . '_' . $data['styleType'];
$str .= '
<optgroup label="' . $data['origin'] . ' ' . $data['styleType'] . '">
';
}
$select = $config['selected'] == $data['id'] ? ' selected="selected"' : '';
$name = (key_exists('upperCase', $config) && $config['upperCase'] === true) ? ucwords($data['name']) : $data['name'];
$str .= '
<option value="' . $data['id'] . '"' . $select . '>' . $name . '</option>
';
//$i++;
$j++;
}
$str .= '
</select>
';
return $str;
}
function checkForImage($config, $edit = true, $wrap = true) {
$img = '';
$nub = '';
// see if width is set as a config value
$width = key_exists('width', $config) ? ' width="' . $config['width'] . '"' : '';
// see if height is set as a config value
$height = key_exists('height', $config) ? ' height="' . $config['height'] . '"' : '';
if(!empty($config['picture'])) {
// see if alternate text is set as a config value
$alt = key_exists('alt', $config) ? ' title="' . $config['alt'] . '" alt="' . $config['alt'] . '"' : '';
// see if standard wrap text is to be used
if($wrap === true) {
$img = '<div class="admin_beerPic"><img src="' . base_url() . 'images/beers/' . $config['picture'] . '"' . $alt . $width . $height . ' /></div>';
} else {
$img = '<img src="' . base_url() . 'images/beers/' . $config['picture'] . '"' . $alt . $width . $height . ' />';
}
$nub = '<li class="delete"><a href="#" onclick="if(confirm(\'Are you sure you want to delete this image?\')) {new Ajax.Request(\'' . base_url() . 'ajax/deleteImage/beer/' . $config['id'] . '\', {asynchronous: true, evalScripts: true, method: \'get\', onComplete: function(response) {$(\'item_list_container_' . $config['id'] . '\').update(response.responseText);}});}; return false;"><img src="' . base_url() . 'images/nubbin_trash.gif" title="delete image" alt="delete image" /></a></li>';
} else {
if($wrap === true) {
$img = '<div class="admin_beerPic"><img src="' . base_url() . 'images/beers/bottle.gif"' . $width . $height . ' /></div>';
} else {
$img = '<img src="' . base_url() . 'images/beers/bottle.gif"' . $width . $height . ' />';
}
}
if($edit === true) {
$nub = '
<div id="nubbin_' . $config['id'] . '" class="nubbin">
<ul>
' . $nub . '
<li class="edit"><a href="' . base_url() . 'admin/uploadImage/' . $config['id'] . '"><img src="' . base_url() . 'images/nubbin_editPhoto.jpg" title="edit image" alt="edit image" /></a></li>
</ul>
</div>
';
} else {
$nub = '';
}
return $nub . $img;
}
function imageExists($config) {
$boolean = false;
if(file_exists($config['path'] . $config['fileName'])) {
$boolean = true;
}
return $boolean;
}
?> | true |
9f4e26f9927a4c54823649ce83e1c391d44d1f70 | PHP | ueccssrnd/training2014 | /day2/examples/4.php | UTF-8 | 690 | 2.84375 | 3 | [] | no_license | <!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Handling User Input</title>
</head>
<body>
<h1>Login</h1>
<p>
<?php
$submitted = filter_input(INPUT_POST, 'submit');
if(isset($submitted)) {
$user = filter_input(INPUT_POST, 'username');
$pwd = filter_input(INPUT_POST, 'password');
echo "result >> username : $user && password : $pwd";
}
?>
</p>
<form action="" method="post">
<input type="text" name="username" placeholder="username">
<input type="password" name="password" placeholder="password">
<button type="submit" name="submit" value="submit">Login</button>
</form>
</body>
</html> | true |
8b0be06f4d04c565e5a370d55b4ae65d2fe20c48 | PHP | shimoikura/basic_php | /Class/task.php | UTF-8 | 657 | 3.734375 | 4 | [] | no_license | <?php
class Calculater
{
public $a = 10;
public $b = 20;
public $c = 30;
public $d = 50;
public $result;
public function add()
{
$this->result = $this->a + $this->b;
return $this->result;
}
public function sub()
{
$this->result = $this->d - $this->b;
return $this->result;
}
public function mul()
{
$this->result = $this->b * $this->b;
return $this->result;
}
public function div()
{
$this->result = $this->c / $this->a;
return $this->result;
}
}
$answer = new Calculater();
echo $answer->add()."<br>";
echo $answer->sub()."<br>";
echo $answer->mul()."<br>";
echo $answer->div()."<br>";
?>
| true |
9fd48369e8a0ffe4f4fbf7c11a7303de3d6de3e6 | PHP | myadminpanel/chipinnow | /PHPScript/sports/api/edit_trainer_profile.php | UTF-8 | 3,419 | 2.53125 | 3 | [] | no_license | <?php
include "../config.inc.php";
require_once '../class.database.php';
include "error_response.php"
require_once 'function.php';
$arrRecord = array();
$arrError = array();
foreach ($_POST as $key => $value) {
if ($key == 'trainer_id') {
if (empty($value)) {
$arrError[$key] = $key . " is empty";
}
} else if ($key == "email") {
if (filter_var($value, FILTER_VALIDATE_EMAIL) === false) {
$arrError[$key] = $key . " is incorrect format";
}
}
}
if (count($arrError) > 0) {
$arrRecord['data']['success'] = 0;
$arrRecord['data']['profile'] = $arrError;
echo json_encode($arrRecord);
exit();
}
//Sanitize post array
$_POST = sanitize($_POST);
//Check User already exist
$sqlUserExist = "SELECT * FROM tbl_trainer_profile WHERE user_id='" . $db->escape($_POST['trainer_id']) . "'";
//$resultUserExist = mysqli_query($con, $sqlUserExist);
$resultUserExist = $db->query($sqlUserExist)->fetch();
if ($db->affected_rows > 0) {
$sqlUpdate = "UPDATE tbl_trainer_profile SET city='".$db->escape($_POST['city'])."',
about_coach='".$db->escape($_POST['about_coach'])."',experience='" . $db->escape($_POST['experience']) . "',
college='" . $db->escape($_POST['college']) . "',qualification='" . $db->escape($_POST['qualification']) . "',
achievement='" . $db->escape($_POST['achievement']) . "',license='" . $db->escape($_POST['license']) . "' WHERE user_id='" . $db->escape($_POST['trainer_id']) . "'";
$result = $db->query($sqlUpdate)->execute();
if ($result->affected_rows) {
$sql = "SELECT * FROM tbl_trainer_profile WHERE user_id = '" . $db->escape($_POST['trainer_id']) . "'";
$rows = $db->query($sql)->fetch();
$sqlOrder = "SELECT( SELECT count(*) FROM tbl_orders WHERE trainer_id= '" . $db->escape($_POST['trainer_id']) . "' and status='Accepted') as accepted,"
. " ( SELECT count(*) FROM tbl_orders WHERE trainer_id=" . $db->escape($_POST['trainer_id']) . " and status='Cancelled') as canceled,"
. " ( SELECT count(*) FROM tbl_orders WHERE trainer_id=" . $db->escape($_POST['trainer_id']) . " and status='Pending') as pending,"
. " ( SELECT count(*) FROM tbl_orders WHERE trainer_id=" . $db->escape($_POST['trainer_id']) . " and status='Rejected') as disapprove,"
. " ( SELECT count(*) FROM tbl_orders WHERE trainer_id=" . $db->escape($_POST['trainer_id']) . " and status='Completed') as complete";
$rowsOrder = $db->query($sqlOrder)->fetch();
if ($db->affected_rows > 0) {
if (!empty($rowsOrder)) {
$rows[0]['accepted'] = $rowsOrder[0]['accepted'];
$rows[0]['canceled'] = $rowsOrder[0]['canceled'];
$rows[0]['pending'] = $rowsOrder[0]['pending'];
$rows[0]['disapprove'] = $rowsOrder[0]['disapprove'];
$rows[0]['complete'] = $rowsOrder[0]['complete'];
}
$arrRecord['data']['success'] = 1;
$arrRecord['data']['general'] = $rows;
} else {
$arrRecord['data']['success'] = 0;
$arrRecord['data']['general'] = $error;
}
} else {
$arrRecord['data']['success'] = 0;
$arrRecord['data']['profile'] = $error;
}
}
echo json_encode($arrRecord);
?> | true |
2920e99317a824dee5fc12b98a984ceb3f9f112a | PHP | famstutz/Workspace | /zwischenpruefung/view_products.php | UTF-8 | 1,796 | 3.140625 | 3 | [] | no_license | <?php
require_once("class.product.php");
require_once("class.cart.php");
require_once("class.parameterHelper.php");
session_start();
if (!parameterHelper::isSessionParameterSet("cart")) {
$cart = new cart();
parameterHelper::setSessionParameter("cart", $cart);
}
else {
$cart = parameterHelper::getSessionParameter("cart");
}
if(parameterHelper::isGetParameterSet("operation")) {
$operation = parameterHelper::getGetParameter("operation");
switch($operation) {
case "add_to_cart":
$id = parameterHelper::getGetParameter("id");
addProductToCart($cart, $id);
break;
}
}
function addProductToCart($cart, $id) {
$product = product::getProduct($id);
$cart->addProduct($product);
echo "<h2>Successfully added product to cart</h2>";
}
?>
<h1>View products</h1>
<table border="1">
<tr>
<th>Name</th>
<th>Description</th>
<th>Prize</th>
<th>Operation</th>
</tr>
<?php
$products = product::getAllProducts();
foreach ($products as $product) {
echo "<tr>";
echo "<td>" . $product->getName() ."</td>";
echo "<td>" . $product->getDescription() ."</td>";
echo "<td>" . $product->getPrize() ."</td>";
echo "<td>[<a href='index.php?action=view_products&operation=add_to_cart&id=" . $product->getId() . "'>add-to-cart</a>]</td>";
echo "</tr>";
}
?>
</table>
<ul>
<li>[<a href="index.php">to-main-page</a>]</li>
<li>[<a href="index.php?action=add_remove_product">new/remove-product</a>]</li>
<li>[<a href="index.php?action=my_cart">my-cart</a>]</li>
</ul> | true |
fecbd3e782252c42b847b27e300018cd95f96124 | PHP | ccs-open-source/support-artists-project | /app/Models/Stream.php | UTF-8 | 2,005 | 2.78125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Models;
use DateTime;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
class Stream extends Model
{
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'tags' => 'array'
];
/**
* @return mixed|string
*/
public function getRouteKeyName()
{
return 'slug';
}
/**
* @return string
* @throws \Exception
*/
public function getPostTimeAgoAttribute()
{
return $this->timeElapsedString($this->created_at);
}
/**
* Get Slug from Title
*/
public function setTitleAttribute($value)
{
$this->attributes['slug'] = \Str::slug($value, '-');
$this->attributes['title'] = $value;
}
public function artist()
{
return $this->belongsTo(Artist::class, 'artist_id', 'id');
}
/**
* @param $datetime
* @param bool $full
* @return string
* @throws \Exception
*/
protected function timeElapsedString($datetime, $full = false)
{
$now = Carbon::now();
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$string = array(
'y' => trans('date.year'),
'm' => trans('date.month'),
'w' => trans('date.week'),
'd' => trans('date.day'), //'day',
'h' => trans('date.hour'), // 'hour',
'i' => trans('date.minute'),
's' => trans('date.second'),
);
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
} else {
unset($string[$k]);
}
}
if (!$full) {
$string = array_slice($string, 0, 1);
}
return $string ? implode(', ', $string) . ' '.trans('date.ago') : trans('date.just-now');
}
}
| true |
351dc1919f2908da1ce8dad4ab8e6b5e0d01dcbf | PHP | shasha007/PUphp | /apps/pufinance/Lib/Model/PufinanceCreditModel.class.php | UTF-8 | 2,897 | 2.65625 | 3 | [] | no_license | <?php
/**
* 用户PU金模型
*/
class PufinanceCreditModel extends Model
{
public function getPufinanceCreditInfo($condtion)
{
return $this->where($condtion)->find();
}
/**
* 通过UID获取用户PU金额度信息
*
* @param integer $uid 用户UID
*
* @return mixed
*/
public function getPufinanceCreditInfoByUid($uid)
{
return $this->getPufinanceCreditInfo(array('uid' => $uid));
}
/**
* 初始化用户PU金
*
* @param $uid
*
* @return array
*/
public function initPufinanceCredit($uid)
{
$amount = '1000.00';
$freeAmount = '200.00';
$pucredit = array(
'uid' => $uid,
'all_amount' => $amount,
'usable_amount' => $amount,
'free_amount' => $freeAmount,
'free_usable_amount' => $freeAmount,
'free_risk' => 200
);
$this->add($pucredit);
return $pucredit;
}
/**
* 更新用户PU金数据
*
* @param integer $uid
* @param array $data
*
* @return mixed
*/
public function updatePufinanceCredit($uid, $data)
{
return $this->where(array('uid' => $uid))->save($data);
}
/*
* 列表
*/
public function getPufinanceCreditLists($map){
$lists = array();
$lists = $this->table(C('DB_PREFIX').'pufinance_credit pc')
->field('pc.uid,pc.all_amount,pc.usable_amount,pc.free_amount,pc.free_usable_amount,pu.realname,pu.ctfid,pc.free_risk,pc.status,m.money umoney,pm.money pmoney,u.email')
->join(C('DB_PREFIX').'pufinance_user pu on pc.uid = pu.uid')/*关联pu金用户表*/
->join(C('DB_PREFIX').'pufinance_money pm on pm.uid=pc.uid')/*关联用户PU币表(来源PU金)*/
->join(C('DB_PREFIX').'money m on m.uid=pc.uid')/*关联ts_money表*/
->join(C('DB_PREFIX').'user u on u.uid=pc.uid')/*关联ts_user*/
->where($map)
->findPage(15);
return $lists;
}
/**
* 使用户加入白名单/黑名单
* @param $uid,$status: 0:初始状态 1:白名单 2:黑名单
*/
public function addWhiteList($uid,$status)
{
$data['status'] = $status;
$res = $this->where("uid=$uid")->save($data);
return $res;
}
//导出数据
public function getCreditDatas($map=array(), $order='c.uid desc', $limit='0,100'){
return $this->table(C('DB_PREFIX').'pufinance_credit c')
->field('u.uid,u.realname,u.ctfid,c.all_amount,c.usable_amount,c.free_amount,c.free_usable_amount,c.free_risk,c.status')
->join(C('DB_PREFIX').'pufinance_user u on u.uid=c.uid')
->where($map)
->order($order)
->limit($limit)
->select();
}
} | true |
d000de1cf5388b1db55488640e5096f827e9319c | PHP | oojacoboo/graphqlite | /tests/Fixtures/Integration/Controllers/ContactController.php | UTF-8 | 1,997 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
namespace TheCodingMachine\GraphQLite\Fixtures\Integration\Controllers;
use Porpaginas\Arrays\ArrayResult;
use Porpaginas\Result;
use TheCodingMachine\GraphQLite\Annotations\Mutation;
use TheCodingMachine\GraphQLite\Annotations\Query;
use TheCodingMachine\GraphQLite\Annotations\Security;
use TheCodingMachine\GraphQLite\Fixtures\Integration\Models\Contact;
use TheCodingMachine\GraphQLite\Fixtures\Integration\Models\User;
class ContactController
{
/**
* @Query()
* @return Contact[]
*/
public function getContacts(): array
{
return [
new Contact('Joe'),
new User('Bill', 'bill@example.com'),
];
}
/**
* @Mutation()
* @param Contact $contact
* @return Contact
*/
public function saveContact(Contact $contact): Contact
{
return $contact;
}
/**
* @Mutation()
* @param \DateTimeInterface $birthDate
* @return Contact
*/
public function saveBirthDate(\DateTimeInterface $birthDate): Contact {
$contact = new Contact('Bill');
$contact->setBirthDate($birthDate);
return $contact;
}
/**
* @Query()
* @return Contact[]
*/
public function getContactsIterator(): ArrayResult
{
return new ArrayResult([
new Contact('Joe'),
new User('Bill', 'bill@example.com'),
]);
}
/**
* @Query()
* @return string[]|ArrayResult
*/
public function getContactsNamesIterator(): ArrayResult
{
return new ArrayResult([
'Joe',
'Bill',
]);
}
/**
* @Query(outputType="ContactOther")
*/
public function getOtherContact(): Contact
{
return new Contact('Joe');
}
/**
* Test that we can have nullable results from Porpaginas.
*
* @Query()
* @return Result|Contact[]|null
*/
public function getNullableResult(): ?Result
{
return null;
}
}
| true |
62d4f9866ea154300b51f0fe1922d2e9a1bf195b | PHP | Geldymuradov/WiRunner | /Aplikacja/tests/TestyKalkulatoraTempa.php | UTF-8 | 3,321 | 2.5625 | 3 | [] | no_license | <?php
class TestyKalkulatoraTempa extends PHPUnit_Framework_TestCase
{
/**
* @backupGlobals disabled
* @backupStaticAttributes disabled
*/
public function test_kalkulatorTempa_11_0()
{
$my_activities = new my_activities();
$this->assertNotEquals("Wprowadź prawidłowe wartości!", $my_activities->kalkulatorTempa(10, 0, 0, 1));
$this->assertNotEquals("Wprowadź prawidłowe wartości!", $my_activities->kalkulatorTempa(500, 20, 10, 22));
$this->assertNotEquals("Wprowadź prawidłowe wartości!", $my_activities->kalkulatorTempa(42.195, 3, 23, 30));
$this->assertNotEquals("Wprowadź prawidłowe wartości!", $my_activities->kalkulatorTempa(21.195, 1, 32, 04));
}
/**
* @backupGlobals disabled
* @backupStaticAttributes disabled
*/
public function test_kalkulatorTempa_11_1()
{
$my_activities = new my_activities();
$this->assertEquals("Wprowadź prawidłowe wartości!", $my_activities->kalkulatorTempa("abvc", 10, 20, 20));
$this->assertEquals("Wprowadź prawidłowe wartości!", $my_activities->kalkulatorTempa("1a", 10, 20, 20));
$this->assertEquals("Wprowadź prawidłowe wartości!", $my_activities->kalkulatorTempa("a1", 10, 20, 20));
$this->assertEquals("Wprowadź prawidłowe wartości!", $my_activities->kalkulatorTempa("Ala ma kota", 10, 20, 20));
}
/**
* @backupGlobals disabled
* @backupStaticAttributes disabled
*/
public function test_kalkulatorTempa_11_2()
{
$my_activities = new my_activities();
$this->assertEquals("Wprowadź prawidłowe wartości!", $my_activities->kalkulatorTempa(42.195, "abvc", 23, 23));
$this->assertEquals("Wprowadź prawidłowe wartości!", $my_activities->kalkulatorTempa(21.195, "1a", 23, 23));
$this->assertEquals("Wprowadź prawidłowe wartości!", $my_activities->kalkulatorTempa(10, "a1", 23, 23));
$this->assertEquals("Wprowadź prawidłowe wartości!", $my_activities->kalkulatorTempa(22.45, "Ala ma kota", 23, 23));
}
/**
* @backupGlobals disabled
* @backupStaticAttributes disabled
*/
public function test_kalkulatorTempa_11_3()
{
$my_activities = new my_activities();
$this->assertEquals("Wprowadź prawidłowe wartości!", $my_activities->kalkulatorTempa(42.195, 23,"abvc", 23));
$this->assertEquals("Wprowadź prawidłowe wartości!", $my_activities->kalkulatorTempa(21.195, 23 ,"1a", 23));
$this->assertEquals("Wprowadź prawidłowe wartości!", $my_activities->kalkulatorTempa(10, 23 ,"a1", 23));
$this->assertEquals("Wprowadź prawidłowe wartości!", $my_activities->kalkulatorTempa(22.45, 23,"Ala ma kota", 23));
}
/**
* @backupGlobals disabled
* @backupStaticAttributes disabled
*/
public function test_kalkulatorTempa_11_4()
{
$my_activities = new my_activities();
$this->assertEquals("Wprowadź prawidłowe wartości!", $my_activities->kalkulatorTempa(42.195, 23, 23,"abvc"));
$this->assertEquals("Wprowadź prawidłowe wartości!", $my_activities->kalkulatorTempa(21.195, 23, 23 ,"1a"));
$this->assertEquals("Wprowadź prawidłowe wartości!", $my_activities->kalkulatorTempa(10, 23 , 23 ,"a1"));
$this->assertEquals("Wprowadź prawidłowe wartości!", $my_activities->kalkulatorTempa(22.45, 23, 2,"Ala ma kota"));
}
}
?>
| true |
878b8181c31324e093c57c4d3e259f3ef2a61b0b | PHP | Tyke1986/spheres | /profile.php | UTF-8 | 6,324 | 2.640625 | 3 | [] | no_license | <?php
/*
Julien Roger
http://www.julienroger.com
julienroger@gmail.com
November 21, 2011
Last updated: November 21, 2011
*/
include("includes/db.php");
include("includes/session.php");
include("includes/components.php");
$profile_situaiton = $_GET['p'];
if(empty($profile_situaiton)) {
$profile_situaiton = 0;
}
session_start();
//if the user has not logged in
if(!isLoggedIn())
{
$logged_in = 0;
header('Location: index.php?redirect='. basename($_SERVER['PHP_SELF']));
die();
}
else
$logged_in = 1;
// Need a way to detect whether a first name is set or not. If not, ask them!
// Gender default selector
if($_SESSION['user_gender'] == 1) { // user is male
$opt_pns = "";
$opt_m = "selected='selected'";
$opt_f = "";
} elseif($_SESSION['user_gender'] == 2) { // user is female
$opt_pns = "";
$opt_m = "";
$opt_f = "selected='selected'";
} else {
$opt_pns = "selected='selected'";
$opt_m = "";
$opt_f = "";
}
//page content follows
include("top-header.php");
?>
<script type="text/javascript" src="includes/passstr.js"></script>
<title>Spheres</title>
<?php
include("top-nav.php");
include("sub-nav.php");
?>
<!-- <div class="rightfloater">
<a href="#profile">Change your Profile</a>
<a href="#email">Change your Email Address</a>
<a href="#password">Change your Password</a>
</div> -->
<div id="main">
<h3>Profile</h3>
<div id="Profile pic">
<?php
if(is_file("assets/" . urlencode(base64_encode($_SESSION['user_email'])) . "/" . $_SESSION['user_profilepic']))
{
$profile_pic = "/slir/w150-h150-c1:1/assets/" . urlencode(base64_encode($_SESSION['user_email'])) . "/" . $_SESSION['user_profilepic'];
echo "<img src=\"$profile_pic\" />";
}
else
echo "No profile pic.";
?>
</div>
<?php if($profile_situaiton == 55) {echo "<h3>Please enter a name to use Spheres.</h3>";}
?>
<div class="formarea">
<a name="profile"><h3>Change your profile</h3></a>
<form id="userProfile" name="changeprofile" enctype="multipart/form-data" action="includes/change_profile.php" method="post">
<div class="formLine"><div class="field"><label>Profile Picture: </label></div>
<div class="formField"><input id="file" type="file" name="profile_picture" class="formStyle" />
</div></div>
<div class="formLine">
<?php if($profile_situaiton == 55) {echo "<span class=\"bubbletipspan\" title=\"You must enter a first and last name before using Spheres.\">" ;} ?>
<div class="field">
<label>Name: </label></div>
<div class="formField"><input value=<?php echo "\"" . $_SESSION['user_firstname'] . "\"" ?> type="text" name="new_firstname" class="formStyle <?php if($profile_situaiton == 55) {echo "importantField";} ?>"/>
<input value=<?php echo "\"" . $_SESSION['user_lastname'] . "\"" ?> type="text" name="new_lastname" class="formStyle <?php if($profile_situaiton == 55) {echo "importantField";} ?>"/>
</div>
<?php if($profile_situaiton == 55) {echo "</span>" ;} ?>
</div>
<div class="formLine"><div class="field"><label>Gender: </label></div>
<div class="formField">
<select name="new_gender">
<option value=0 <?php echo $opt_pns; ?>> Prefer not to say</option>
<option value=1 <?php echo $opt_m; ?>> Male</option>
<option value=2 <?php echo $opt_f; ?>> Female</option>
</select>
</div></div>
<div class="formLine"><div class="field"><label>About Me: </label></div>
<div class="formField">
<textarea class="formStyle" cols="42" rows="12" id="bio" name="new_bio" /><?php if(empty($_SESSION['user_bio'])) {
echo "Write a bit about yourself...";
} else { echo $_SESSION['user_bio'];
} ?></textarea>
</div></div>
<input type="hidden" name="old_email" value=<?php echo "\"" . $_SESSION['user_email'] . "\"" ?> />
<input type="hidden" name="profiletype" value="profile" />
<input class="reddButton rightButton" type="submit" value="Update Profile" />
</form>
</div>
<div class="formarea">
<a name="email"><h3>Change your Email Address</h3></a>
<form id="userProfile" name="changeemail" enctype="multipart/form-data" action="includes/change_profile.php" method="post">
<div class="formLine"><div class="field"><label>Email address: </label><span class="tooltipspan" title="This is your login credential as well.">?</span></div>
<div class="formField"><input value=<?php echo "\"" . $_SESSION['user_email'] . "\"" ?> type="text" name="new_email" class="formStyle"/>
</div></div>
<div class="formLine"><div class="field"><label>Password: </label></div>
<div class="formField"><input type="password" name="password" class="formStyle"/>
</div></div>
<input type="hidden" name="old_email" value=<?php echo "\"" . $_SESSION['user_email'] . "\"" ?> />
<input type="hidden" name="profiletype" value="email" />
<input class="reddButton rightButton" type="submit" value="Change Email Address" />
</form>
</div>
<div class="formarea">
<a name="password"><h3>Change your Password</h3></a>
<form id="userProfile" name="changepass" enctype="multipart/form-data" action="includes/change_profile.php" method="post">
<div class="formLine"><div class="field"><label>New Password: </label></div>
<div class="formField"><input type="password" value="" name="pass1" class="formStyle" />
<div id="iSM">
<ul class="weak">
<li id="iWeak"></li>
<li id="iMedium"></li>
<li id="iStrong""></li>
</ul>
Password Strength: <div id="StrengthIndicator">
</div></div>
</div></div>
<div class="formLine"><div class="field"><label>New Password again: </label></div>
<div class="formField"><input type="password" name="pass2" class="formStyle"/>
</div></div>
<div class="formLine"><div class="field"><label>Old Password: </label></div>
<div class="formField"><input type="password" name="password" class="formStyle"/>
</div></div>
<input type="hidden" name="old_email" value=<?php echo "\"" . $_SESSION['user_email'] . "\"" ?> />
<input type="hidden" id="passstrength" name="passstrength" value='' />
<input type="hidden" name="profiletype" value="password" />
<input class="reddButton rightButton" type="submit" value="Change Password" />
</form>
</div>
</div>
<div id="endmain">
<br /><br />
</div>
<?php
include("sub-footer.php");
include("footer.php");
?> | true |
524cbccaab2126068a48d8cb0c227b7d5960917a | PHP | edwardyi/ProblemSet | /App/NumericFloatFunction.php | UTF-8 | 966 | 3.3125 | 3 | [] | no_license | <?php
namespace ProblemSets;
class NumericFloatFunction
{
public function format($num)
{
if(!is_numeric($num)) {
throw new \InvalidArgumentException();
}
$formatted = (string)$num;
$isPointExist = strpos(abs($formatted), '.');
$strLength = strlen(abs($formatted));
if ($strLength <= 3 || ($isPointExist && $isPointExist <=3 ))
{
return $formatted;
}
list($a, $back) = strpos($formatted, '.') ? explode('.', abs($formatted)) : array((string)abs($formatted), '');
$front = "";
for ($i=0; $i<strlen($a); $i++)
{
$front .= $a[$i];
if ($i % 3 == 0 && $i<strlen($a)-1)
{
$front .= ",";
}
}
$formatted = strpos($formatted, '.')===false ? $front.$back : $front.'.'.$back;
return $num < 0 ? '-'.$formatted : $formatted;
}
} | true |
6aeafcbce81016efd0d91282b1858a895c0f5024 | PHP | rmasters/DoctrineSchemaBuilder | /src/Doctrine/DBAL/Schema/Builder.php | UTF-8 | 5,240 | 2.828125 | 3 | [
"MIT"
] | permissive | <?php
/**
* Copyright (c) 2013 Josiah Truasheim
*
* 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.
*/
namespace Doctrine\DBAL\Schema;
use Closure;
/**
* Schema Builder
*
* Expresses the definition of a database schema in terms of the desired state
* rather than a reflection of change to existing state.
*
* @author Josiah <josiah@jjs.id.au>
*/
class Builder
{
/**
* DBAL Schema
*
* @var Schema
*/
protected $schema;
/**
* Instantiates a new schema builder instance for the specified schema
*
* @param Schema $schema DBAL Schema
*/
public function __construct(Schema $schema)
{
$this->schema = $schema;
}
/**
* Create Table
*
* Creates a database table unless it already exists in the database.
*
* @example
* ```php
* use Doctrine\DBAL\Schema\Table;
* $builder->createTable('foo', function (Table $table) {
* // ... definition code
* });
* ```
* @param string $name Table name
* @param callable $definition Table definition callback
* @return Builder
*/
public function createTable($name, $definition)
{
if (!$this->schema->hasTable($name)) {
call_user_func($definition, $this->schema->createTable($name));
}
return $this;
}
/**
* Define Table
*
* Ensures that the table matches the specified definition by replacing any
* existing definition with the specified definition.
*
* @example
* ```php
* use Doctrine\DBAL\Schema\Table;
* $builder->createTable('foo', function (Table $table) {
* // ... definition code
* });
* ```
* @param string $name Table name
* @param callable $definition Table definition callback
* @return Builder
*/
public function defineTable($name, $definition)
{
$this->dropTable($name);
call_user_func($definition, $this->schema->createTable($name));
return $this;
}
/**
* Drop Table
*
* Drops a database table from the schema, when the table is not in the
* schema nothing happens.
*
* @example
* ```php
* $builder->dropTable('foo');
* ```
* @param string $name Table name
* @return Builder
*/
public function dropTable($name)
{
if ($this->schema->hasTable($name)) {
$this->schema->dropTable($name);
}
return $this;
}
/**
* Defines a named foreign key relationship
*
* When a foreign key relationship exists with the same name on the database
* it will be replaced with this definition.
*
* @param string|Table $localTable Local table
* @param array $localColumns Local columns
* @param string|Table $foreignTable Foreign table
* @param array $foreignColumns Foreign columns (default to primary key)
* @return Builder
*/
public function defineNamedForeignKey($name, $localTable, array $localColumns, $foreignTable, array $foreignColumns = null, array $options = array())
{
// Load the local table
if (!$localTable instanceof Table) {
$localTable = $this->schema->getTable($localTable);
}
// Load the foreign table
if (!$foreignTable instanceof Table) {
$foreignTable = $this->schema->getTable($foreignTable);
}
// Where the foreign columns are not specified they are retrieved from
// the foreign tables primary key definition.
if (is_null($foreignColumns)) {
$foreignColumns = $foreignTable->getPrimaryKeyColumns();
}
// Where the foreign key exists, it should be removed for recreation
if ($localTable->hasForeignKey($name)) {
$localTable->removeForeignKey($name);
}
// Actual foreign key is added using the local Doctrine DBAL Table and
// referencing the other specified options
$localTable->addNamedForeignKeyConstraint($name, $foreignTable, $localColumns, $foreignColumns, $options);
// Method chaining is supported
return $this;
}
} | true |
b62a13d182c1d6ed8030ef00288eb90d73fb8482 | PHP | sysvyz/hurl | /src/Node/Strings/StringLeftTrim.php | UTF-8 | 217 | 2.609375 | 3 | [] | no_license | <?php
namespace Hurl\Node\Strings;
use Hurl\Node\Abstracts\AbstractStringNode;
class StringLeftTrim extends AbstractStringNode
{
public function __invoke(...$data)
{
return ltrim($data[0]);
}
} | true |
2a2ec3f4148bb27b1c434c07dff2ad7b4abd2b29 | PHP | alanly/languageleap | /app/LangLeap/Rank/Answer.php | UTF-8 | 664 | 2.9375 | 3 | [] | no_license | <?php namespace LangLeap\Rank;
use App;
use LangLeap\Quizzes\Answer as VideoAnswer;
/**
* A ranking quiz-question answer reprsentation structure.
* @author Alan Ly <hello@alan.ly>
*/
class Answer {
public $id;
public $text;
/**
* Creates a new Answer instance from a given `LangLeap\Quizzes\Answer`.
* @param LangLeap\Quizzes\Answer $videoAnswer
* @return Answer
*/
public static function createFromVideoAnswer(VideoAnswer $videoAnswer)
{
// Create a new instance of self.
$answer = App::make('LangLeap\Rank\Answer');
// Map the attributes.
$answer->id = $videoAnswer->id;
$answer->text = $videoAnswer->answer;
return $answer;
}
}
| true |
5372a8bd23e61bafa8afae4b1e1fb5960e58f3f6 | PHP | FabienLY/tests | /22-activite/correction/2/blog/view/frontend/modify_view.php | UTF-8 | 1,696 | 2.5625 | 3 | [] | no_license | <?php $template_title = 'Mon super blog - modifier le commentaire' ;
ob_start();
if (!empty ($data_req_get_post['title']))
{ ?>
<br />
<br />
<div class="news">
<h3>
<?php echo '<strong>' . htmlspecialchars(strip_tags($data_req_get_post['title'])) . '</strong> <em>le ' . htmlspecialchars(strip_tags($data_req_get_post['date_format_post'])) . '</em>' ; ?>
</h3>
<p> <?php echo nl2br(htmlspecialchars(strip_tags($data_req_get_post['content']))) ; ?><br />
</p>
</div>
<?php
if (!empty ($data_req_get_post_comment['comment']))
{ ?>
<form class="modify_comment" action="index.php?action=modify&id_post=<?= $_GET['id_post'] ?>&id_comment=<?= $_GET['id_comment'] ?>" method="post">
<p>
<?php echo '<strong>' . htmlspecialchars(strip_tags($data_req_get_post_comment['author'])) . '</strong><br /> le ' . htmlspecialchars(strip_tags($data_req_get_post_comment['date_format_comment'])) . ' :<br /><br />"' ; ?>
<?php echo nl2br(htmlspecialchars(strip_tags($data_req_get_post_comment['comment']))) ; ?> "<br />
</p>
</div>
<div>
<p>Modification de ce post : </p>
</div>
<div>
<input type="text" name="modification" id="modification" required size="100"/>
</div>
<div>
<br />
<input type="submit" value="Poster" />
</form>
<?php
}
else
{
echo ('La requête n\'a pas retrouvé le commentaire') ; // throw new Exception('La requête n\'a pas retrouvé le commentaire');
}
}
else
{
echo ('La requête n\'a pas retrouvé le post') ; // throw new Exception('La requête n\'a pas retrouvé le post');
}
$template_content = ob_get_clean();
require('template.php'); | true |
85072957fe68ad46cd39d636b1f04775813f6966 | PHP | minsuRob/devJunior | /승민스/workspace/phpProject/array/19.php | UTF-8 | 328 | 3.109375 | 3 | [] | no_license | <?php
$grades = array('egoing'=>10, 'k8805'=>6, 'sorialgi'=>80);
echo $grades['sorialgi'].'<br/>';
$grades = array('egoing'=>10, 'k8805'=>6, 'sorialgi'=>80);
foreach($grades as $key => $value){
echo "key: {$key} value:{$value}<br />";
}
//foreach grades 배열에 담긴 요소의 숫자만큼 반복문을 실행
?> | true |
f8aa60cb0cadb2c91503c297ff10d529d9fd4824 | PHP | lost1987/test_workspace | /core/db.class.php | UTF-8 | 2,537 | 3.09375 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: lost
* Date: 14-8-5
* Time: 下午2:57
* 基于PDO:MYSQL的数据库操作类
*/
namespace core;
class DB {
private $_resouce = null;
private $_host = null;
private $_user = null;
private $_passwd = null;
private $_port = null;
private $_stmt = null;
function __construct($dbname){
$this->init_db($dbname);
}
private function init_db($dbname){
$config = Configure::instance();
$config->load('db');
$this->_host = $config->db[$dbname]['host'];
$this->_user = $config->db[$dbname]['user'];
$this->_passwd = $config->db[$dbname]['passwd'];
$this->_port = $config->db[$dbname]['port'];
$this->_resouce = new \PDO("mysql:host=$this->_host;dbname=$dbname",$this->_user,$this->_passwd);
if(!$this->_resouce)
throw new \Exception('can not connect host '.$this->_host);
}
/**
* 设置PDO选项
* @param int $pdo_attr PDO属性 PDO::
* @param bool $val
* @return $this
*/
function setOptions($pdo_attr,$val){
$this->_resouce->setAttribute($pdo_attr,$val);
return $this;
}
/**
* @param $sql
* @param array $params
* @return $this
*/
function execute($sql,$params=null){
$this->_stmt = $this->_resouce->prepare($sql);
return $this->_stmt->execute($params);
}
/**
* 简单的执行sql
* @param $sql
* @return $this
*/
function simple_exec($sql){
$this->_resouce->exec($sql);
return $this;
}
/**
* @param int $style
* @return mixed
*/
function fetch($style = \PDO::FETCH_ASSOC){
return $this->_stmt->fetch($style);
}
/**
* @param int $style
* @return mixed
*/
function fetch_all($style = \PDO::FETCH_ASSOC){
return $this->_stmt->fetchAll($style);
}
function insert_id(){
return $this->_resouce->lastInsertId();
}
function begin(){
$this->_resouce->beginTransaction();
return $this;
}
function commit(){
$this->_resouce->commit();
return $this;
}
function rollback(){
$this->_resouce->rollBack();
return $this;
}
function close(){
$this->_resouce = null;
}
function change($dbname){
$this->close();
$this->init_db($dbname);
}
} | true |
e985e2f95e1c357bab1048e6584b7795e41ffd44 | PHP | SACMVK/LudothequeBTS | /job/dao/Config_Dao.php | UTF-8 | 3,276 | 3.140625 | 3 | [] | no_license | <?php
Function loadConfig() {
// stefan : Chargement du fichier
$xml_config = simplexml_load_file ( 'data/config/config.xml' );
// stefan : cr�ation d'un array
$config = [];
// stefan : pour chaque élément ...
foreach ( $xml_config as $xml_option ) {
// stefan : on ajoute l'option ainsi que son texte
$xml_nom_option = utf8_decode(strval($xml_option->nom));
$xml_texte_affichage_option = utf8_decode(strval($xml_option->texte_affichage));
$xml_valeur_option = utf8_decode(strval($xml_option->valeur));
/* stefan : concernant les valeurs bool�ennes
* elles sont stockées en tant que string.
* is_bool ne permet pas de faire la conversion
* en boolean.
* On passe donc par un test de valeur de la string :
* si c'est 'true', alors on stocke une valeur booléenne true,
* si c'est 'false', alors on stocke une valeur booléenne false.
*/
if ($xml_valeur_option=='true'){
$xml_valeur_option = true;
}
else if ($xml_valeur_option=='false'){
$xml_valeur_option = false;
}
/* stefan : le seul test automatisable concerne les nombre.
* is_numeric permet de parser (parcourir) la string.
* Si tous les caract�res sont des nombres, alors il s'agit
* bien d'un numeric (integer, float, ...).
*/
else if (is_numeric ($xml_valeur_option)){
$xml_valeur_option = (int)$xml_valeur_option;
}
/* stefan : sinon, il s'agit d'une valeur string.
*/
$config [$xml_nom_option] = [$xml_texte_affichage_option,$xml_valeur_option];
}
return $config;
}
Function saveConfig($config) {
$xml_config_output = new DOMImplementation ();
// Création d'une instance DOMDocumentType (dtd)
$dtd = $xml_config_output->createDocumentType ( 'config', '', 'data/config/config.dtd' );
// Création d'une instance DOMDocument
$root = $xml_config_output->createDocument ( "", "", $dtd );
$root->encoding = "utf-8";
// Gestion de l'affichage (passage à la ligne à chaque noeud enfant de la racine
$root->formatOutput = true;
// Cr�ation de la racine et ajout au document
$config_node = $root->createElement ( 'config' );
$root->appendChild ( $config_node );
// On parcourt la liste des options
foreach ( $config as $nom_option => $option ) {
$option_node = $root->createElement ( 'option' );
$config_node->appendChild ( $option_node );
$nom_node = $root->createElement ( 'nom' );
$option_node->appendChild ( $nom_node );
$contenu = $root->createTextNode ( utf8_encode ( $nom_option ) );
$nom_node->appendChild ( $contenu );
$texte_affichage_node = $root->createElement ( 'texte_affichage' );
$option_node->appendChild ( $texte_affichage_node );
$contenu = $root->createTextNode ( utf8_encode ( $option [0] ) );
$texte_affichage_node->appendChild ( $contenu );
$valeur_node = $root->createElement ( 'valeur' );
$option_node->appendChild ( $valeur_node );
if (gettype( $option [1] )=='boolean'){
if ($option [1] ){
$option [1] = 'true';
}
else {
$option [1] = 'false';
}
}
$contenu = $root->createTextNode ( utf8_encode ( $option [1] ) );
$valeur_node->appendChild ( $contenu );
}
// Enregistrement du fichier
$root->save ( 'data/config/config.xml' );
} | true |
c3366b49d9985df67f97d4d7835f713e191cd594 | PHP | andrew-ngui/puzzle-games | /model/PegSolitaire.php | UTF-8 | 7,600 | 3.453125 | 3 | [] | no_license | <?php
require_once("Game.php");
class PegSolitaire extends Game {
public $size;
public $num;
public $pegs = array();
public $start; // the first click
public $end; // the 2nd click
public $rows;
public $cols;
public $pegsLeft;
// game board:
// 0 .... 6
// . .
// . .
// 42 .. 48
public function __construct() {
parent::__construct();
$this->start = NULL;
$this->end = NULL;
// dimensions of our board
$this->rows = 7;
$this->cols = 7;
$this->pegsLeft = 0;
// for simplicity of move calculating, the array is filled with values that are not applicable for clicking. This is due to the shape of the game board.
// 0 = empty, 1 = filled, 2 = not usable
$this->pegs = array(
array(2, 2, 1, 1, 1, 2, 2),
array(2, 2, 1, 1, 1, 2, 2),
array(1, 1, 1, 1, 1, 1, 1),
array(1, 1, 1, 0, 1, 1, 1),
array(1, 1, 1, 1, 1, 1, 1),
array(2, 2, 1, 1, 1, 2, 2),
array(2, 2, 1, 1, 1, 2, 2)
);
}
// handler for button being clicked
public function play($peg) {
// start timer if necessary
$this->startTimer();
// if a starting peg is not already selected
if ($this->start == NULL) {
if ($this->setSelected($peg) != false) {
$this->start = $peg;
}
} else {
// set our destination, make the move
$this->end = $peg;
// if the move was a valid move, increment moves made
$this->move();
// clear the attributes for the next move
$this->start = NULL;
$this->end = NULL;
}
return;
}
// update board and to indicate the peg is selected by player
// return true if valid selection, return false if not
public function setSelected($index) {
$coords = $this->indexToCoords($index);
$row = $coords[0];
$col = $coords[1];
if ($this->pegs[$row][$col] != 0) {
$this->pegs[$row][$col] = 1;
return true;
}
return false;
}
// return an array with x,y coordinate based on indices 0->48
public function indexToCoords($index) {
$row = 0;
$num = $index;
while($num >= $this->rows) {
$num = $num - $this->rows;
$row++;
}
$col = $index % $this->cols;
return array($row, $col);
}
// check that the move was valid: if valid, return the peg's coords that gets removed. if not, return false
public function IsValidMove($start, $end, $arr) {
// store in variables for clarity
// arr flag indicates need for conversion to array
if ($arr == true) {
$startCoord = $this->indexToCoords($start);
$endCoord = $this->indexToCoords($end);
} else {
$startCoord = $start;
$endCoord = $end;
}
$start_row = $startCoord[0];
$start_col = $startCoord[1];
$end_row = $endCoord[0];
$end_col = $endCoord[1];
// default values
$new_row = $end_row;
$new_col = $end_col;
// check were in bounds
if ($start_row < 0 || $start_col < 0 || $end_row < 0 || $end_col < 0 || $end_row > 6 || $end_col > 6) {
return false;
}
// check valid selection
if (($this->pegs[$start_row][$start_col] != 1) || ($this->pegs[$end_row][$end_col] != 0)) {
return false;
}
// going left
if (($start_row == $end_row) && ($end_col == $start_col -2)) {
$new_col = $end_col +1;
}
// going right
else if (($start_row == $end_row) && ($end_col == $start_col +2)) {
$new_col = $start_col+1;
}
// going up
else if (($start_col == $end_col) && ($end_row == $start_row -2)) {
$new_row = $end_row +1;
}
// going down
else if (($start_col == $end_col) && ($start_row == $end_row -2)) {
$new_row = $start_row +1;
}
// going up-left
else if (($end_row == $start_row -2) && ($end_col == $start_col -2)) {
$new_row = $end_row +1;
$new_col = $end_col +1;
}
// going up-right
else if (($end_row == $start_row -2) && ($end_col == $start_col +2)) {
$new_row = $end_row +1;
$new_col = $start_col +1;
}
// going down-left
else if (($end_row == $start_row +2) && ($end_col == $start_col -2)) {
$new_row = $start_row +1;
$new_col = $end_col +1;
}
// going down-right
else if (($end_row == $start_row +2) && ($end_col == $start_col +2)) {
$new_row = $start_row +1;
$new_col = $start_col +1;
} else { // not valid move
return false;
}
// check that there is a peg actually being hopped over
if ($this->pegs[$new_row][$new_col] != 1) {
return false;
}
// return our peg being hopped over
return array($new_row, $new_col);
}
// move the pegs stored in attributes
public function move() {
$rmPeg = $this->isValidMove($this->start, $this->end, true);
if ($rmPeg != false) {
// remove the peg that was hopped over
$this->pegs[$rmPeg[0]][$rmPeg[1]] = 0;
// put moved peg in ending position
$endPegCoords = $this->indexToCoords($this->end);
$this->pegs[$endPegCoords[0]][$endPegCoords[1]] = 1;
// remove peg in starting position
$startPegCoords = $this->indexToCoords($this->start);
$this->pegs[$startPegCoords[0]][$startPegCoords[1]] = 0;
$this->moves++;
}
}
// check if any given peg can be moved in any of the 8 directions
public function anyPossibleMoves($start) {
$row = $start[0];
$col = $start[1];
return ($this->isValidMove($start,array($row+2, $col), false) // down
|| $this->isValidMove($start,array($row-2, $col), false) // up
|| $this->isValidMove($start,array($row, $col+2), false) // right
|| $this->isValidMove($start,array($row, $col-2), false) // left
|| $this->isValidMove($start,array($row-2, $col-2), false) // up left
|| $this->isValidMove($start,array($row-2, $col+2), false) // up right
|| $this->isValidMove($start,array($row+2, $col-2), false) // down left
|| $this->isValidMove($start,array($row+2, $col+2), false) // down right
);
}
// iterate all remaining pegs to see if they can be moved
public function areMovesLeft() {
$this->pegsLeft = 0;
for($row1 = 0; $row1 < $this->rows; $row1++) {
for($col1= 0; $col1 < $this->cols; $col1++) {
if ($this->pegs[$row1][$col1] == 1) {
$this->pegsLeft++;
$peg = array($row1, $col1);
if ($this->anyPossibleMoves($peg)) {
return true;
}
}
}
}
return false;
}
public function isWin() {
if ($_SESSION['game']->areMovesLeft()== false) {
return true;
}
return false;
}
public function getStat() {
return $this->pegsLeft;
}
}
?> | true |
833b6e5c47e2947f9638676661cb305b518e8d72 | PHP | ManiiySosa/proyectoDesarrolloSoftware | /config/db.php | UTF-8 | 494 | 2.703125 | 3 | [] | no_license | <?php
class Database{
public static function connect(){
try{
$db = new mysqli('localhost', 'root', '', 'tienda_camisetas');
if (mysqli_connect_error()) {
throw new Exception("base de datos sin servicio ");
}
}catch(Exception $e){
echo "<script>alert('Error en la base de datos, intentelo de nuevo mas tarde');</script>";
header('Location:http://localhost/proyectoDesarrolloSoftware/views/error.php');
}
$db->query("SET NAMES 'utf8'");
return $db;
}
} | true |
bb1e60d70485d0e4c4c1a37c49365ef0ce353277 | PHP | fracz/git-exercises | /backend/controllers/AbstractController.php | UTF-8 | 1,505 | 2.640625 | 3 | [
"MIT"
] | permissive | <?php
namespace GitExercises\controllers;
use Exception;
use GitExercises\services\HasApp;
use GitExercises\services\JsonHelper;
use Slim\Exception\Stop;
abstract class AbstractController
{
use HasApp;
private $requestBody;
protected function getRequestBody()
{
return $this->requestBody;
}
protected function getFromRequest($name, $default = null)
{
return array_key_exists($name, $this->requestBody) ? $this->requestBody[$name] : $default;
}
protected function getParam($name, $defaultValue = null)
{
return $this->getApp()->request()->params($name, $defaultValue);
}
protected function hasAccess($resource, $privilege = null)
{
return $this->getApp()->acl->isAllowed($resource, $privilege);
}
public function __call($methodName, $args)
{
$this->requestBody = $this->getApp()->request()->getBody();
$action = $methodName . 'Action';
try {
$result = call_user_func_array([&$this, $action], $args);
JsonHelper::setResponse($this->getApp()->response(), $result, $this->getApp()->response()->getStatus());
} catch (Stop $e) { // list here exceptions that should not be caught
throw $e;
} catch (Exception $e) {
error_log($e);
JsonHelper::setResponse($this->getApp()->response(), [
'status' => 500,
'message' => $e->getMessage(),
], 500);
}
}
}
| true |
1e59b2b8cbf230801497eae1d858a4c488b855e5 | PHP | rahulyhg/latest | /module/Application/src/Application/Service/EventsServiceInterface.php | UTF-8 | 310 | 2.578125 | 3 | [] | no_license | <?php
namespace Application\Service;
interface EventsServiceInterface {
public function findAllPosts();
public function findPost($id);
public function savePost(\Application\Model\Entity\EventsInterface $data);
public function deletePost(\Application\Model\Entity\EventsInterface $data);
}
| true |
37969f67c295d964d616cc0ef26c6f8a927ed665 | PHP | walerij/mainweb | /models/CacheRecord.php | UTF-8 | 1,090 | 2.6875 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace app\models;
use Yii;
/**
* This is the model class for table "cache".
*
* @property integer $id
* @property string $cache_paysystem
* @property string $cache_number
* @property integer $user_id
*/
class CacheRecord extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'cache';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['user_id'], 'integer'],
[['cache_paysystem', 'cache_number'], 'string', 'max' => 255],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'cache_paysystem' => 'Cache Paysystem',
'cache_number' => 'Cache Number',
'user_id' => 'User ID',
];
}
public function addCache($UserForm, $record_id) {
$this->user_id = $record_id;
$this->cache_paysystem = $UserForm->cache_paysystem;
$this->cache_number = $UserForm->cache_number;
}
}
| true |
5a728f5c79eca31fe3c6b4a8c844ca31f30581b9 | PHP | yinanchuan/HHWechat | /lib/core/web.php | UTF-8 | 3,736 | 2.953125 | 3 | [] | no_license | <?php
/**
* web: a microframework for managing web requests.
*
* web maps url patterns to classes and allows you to install middleware objects
* that perform interrequest opertaions. Here is the general lifecycle of a
* reqeust according to web:
*
* 1. request received;
* 2. middleware objects instantiated,
* 3. handler class instantiated,
* 4. middleware 'run_before' event triggered,
* 5. handler method called,
* 6. middleware 'run_after' event triggered,
* 7. handler class destroyed,
* 8. middleware destroyed,
* 9. response flushed.
*
* Here is a simple use case: new web(array('$' => 'index'));
*
* Here is another one:
*
* $web = new web;
* $web->middleware['logger'] = new LoggerMiddleware;
* $urls = array(
* '$' => 'index',
* '\?add' => 'add',
* '\?id=([0-9]+)' => 'item',
* );
* $web->run($urls);
*
* web was written with an intentionally dumb api to encourage extension. The
* best place to start is at the dispatch() method. Code made blow up if not
* used with caution...
*
* @author eric diep <ediep@uwaterloo.ca>
* han xu <h8xu@uwaterloo.ca>
* @since php 5.2
*/
class web {
/**
* Heterogeneous list of middleware objects.
*
* These are standard classes that can have 'run_before' and/or 'run_after'
* methods that are called before and after the request handler method is
* triggered.
*/
public $middleware = array ();
/**
* The result as returned by the handler method.
*/
public $result = null;
function __construct($map = array(), $middleware = array()) {
foreach ( $middleware as $a ) {
$this->middleware [] = $a;
}
if (! empty ( $map )) {
$this->run ( $map );
}
}
function run($map = array(), $uri = null) {
$params = array ();
$action = '';
if (is_null ( $uri )) {
$uri = $_SERVER ['REQUEST_URI'];
if(('http://' . $_SERVER['SERVER_NAME'] . $uri) === APP_URL){ //$_SERVER['SERVER_PORT']
//print_r($uri);exit;
header ( 'Location: ' . APP_URL . 'index.php' );
exit;
}
$uri = substr($uri, 1); //去除开始/
$__temp = explode ( '?', $uri );
if(count($__temp) == 2){
//get参数
$_matches = explode ( '&', $__temp[1] );
foreach ( $_matches as $key => $val ) {
$__p = explode ( '=', $val );
if (count ( $__p ) == 2) {
$params [$__p [0]] = $__p [1];
} else {
$params [$__p [0]] = '';
}
}
}
$actionPos = 0;
$__temp2 = explode ( '/', $__temp[0] );
for ($i = 0; $i < count($__temp2); $i++) {
if(substr($__temp2[$i], -4) == '.php'){
$actionPos = $i;
break;
}
}
if(count($__temp2) > ($actionPos + 1)){
$action = $__temp2[$actionPos + 1];
}else{
$action = '*';
}
}
$isUrl = false;
$val = '';
foreach ( array_reverse ( $map ) as $key => $val ) {
if ($key == '.' . $action) {
$isUrl = true;
break;
}
}
if ($isUrl == false) {
header("Content-Type:text/html;charset=utf-8");
echo '无效的URL参数';
return false;
}
$client = new $val ( $this );
$this->trigger ( 'run_before' );
$this->result = $this->dispatch ( $client, $params );
$this->trigger ( 'run_after' );
unset ( $client );
return true;
}
function dispatch($client, $params = array()) {
return call_user_func_array ( array ($client, $_SERVER ['REQUEST_METHOD']), $params );
}
function trigger($name, $args = array()) {
array_unshift ( $args, $this );
foreach ( $this->middleware as $i ) {
if (method_exists ( $i, $name )) {
if (intval ( PHP_VERSION ) <= 4.1) {
call_user_method_array ( $name, $i, $args );
} else {
call_user_func_array ( array ($i, $name), $args );
}
}
}
}
}
?> | true |
fa474ff17f0c18c4fb37a819e11af2d460ed16e8 | PHP | mykhie/ePT-Repository | /database/crud/MailTemplate.php | UTF-8 | 23,083 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | <?php
namespace database\crud;
use database\core\mysql\DatabaseUtils;
use database\core\mysql\InvalidColumnValueMatchException;
use database\core\mysql\NullabilityException;
/**
* THIS SOURCE CODE WAS AUTOMATICALLY GENERATED ON Fri 03:16:43 09/12/2016
*
*
* DATABASE CRUD GENERATOR IS AN OPEN SOURCE PROJECT. TO IMPROVE ON THIS PROJECT BY
* ADDING MODULES, FIXING BUGS e.t.c GET THE SOURCE CODE FROM GIT (https://github.com/marviktintor/dbcrudgen/)
*
* DATABASE CRUD GENERATOR INFO:
*
* DEVELOPER : VICTOR MWENDA
* VERSION : DEVELOPER PREVIEW 0.1
* SUPPORTED LANGUAGES : PHP
* DEVELOPER EMAIL : vmwenda.vm@gmail.com
*
*/
/**
*
* MailTemplate
*
* Low level class for manipulating the data in the table mail_template
*
* This source code is auto-generated
*
* @author Victor Mwenda
* Email : vmwenda.vm@gmail.com
* Phone : +254(0)718034449
*/
class MailTemplate {
private $databaseUtils;
private $action;
private $client;
public function __construct($databaseUtils, $action = "", $client = "") {
$this->init($databaseUtils);
}
//Initializes
public function init($databaseUtils) {
//Init
$this->databaseUtils = $databaseUtils;
}
/**
* private class variable $_mailTempId
*/
private $_mailTempId;
/**
* returns the value of $mailTempId
*
* @return object(int|string) mailTempId
*/
public function _getMailTempId() {
return $this->_mailTempId;
}
/**
* sets the value of $_mailTempId
*
* @param mailTempId
*/
public function _setMailTempId($mailTempId) {
$this->_mailTempId = $mailTempId;
}
/**
* sets the value of $_mailTempId
*
* @param mailTempId
* @return object ( this class)
*/
public function setMailTempId($mailTempId) {
$this->_setMailTempId($mailTempId);
return $this;
}
/**
* private class variable $_mailPurpose
*/
private $_mailPurpose;
/**
* returns the value of $mailPurpose
*
* @return object(int|string) mailPurpose
*/
public function _getMailPurpose() {
return $this->_mailPurpose;
}
/**
* sets the value of $_mailPurpose
*
* @param mailPurpose
*/
public function _setMailPurpose($mailPurpose) {
$this->_mailPurpose = $mailPurpose;
}
/**
* sets the value of $_mailPurpose
*
* @param mailPurpose
* @return object ( this class)
*/
public function setMailPurpose($mailPurpose) {
$this->_setMailPurpose($mailPurpose);
return $this;
}
/**
* private class variable $_fromName
*/
private $_fromName;
/**
* returns the value of $fromName
*
* @return object(int|string) fromName
*/
public function _getFromName() {
return $this->_fromName;
}
/**
* sets the value of $_fromName
*
* @param fromName
*/
public function _setFromName($fromName) {
$this->_fromName = $fromName;
}
/**
* sets the value of $_fromName
*
* @param fromName
* @return object ( this class)
*/
public function setFromName($fromName) {
$this->_setFromName($fromName);
return $this;
}
/**
* private class variable $_mailFrom
*/
private $_mailFrom;
/**
* returns the value of $mailFrom
*
* @return object(int|string) mailFrom
*/
public function _getMailFrom() {
return $this->_mailFrom;
}
/**
* sets the value of $_mailFrom
*
* @param mailFrom
*/
public function _setMailFrom($mailFrom) {
$this->_mailFrom = $mailFrom;
}
/**
* sets the value of $_mailFrom
*
* @param mailFrom
* @return object ( this class)
*/
public function setMailFrom($mailFrom) {
$this->_setMailFrom($mailFrom);
return $this;
}
/**
* private class variable $_mailCc
*/
private $_mailCc;
/**
* returns the value of $mailCc
*
* @return object(int|string) mailCc
*/
public function _getMailCc() {
return $this->_mailCc;
}
/**
* sets the value of $_mailCc
*
* @param mailCc
*/
public function _setMailCc($mailCc) {
$this->_mailCc = $mailCc;
}
/**
* sets the value of $_mailCc
*
* @param mailCc
* @return object ( this class)
*/
public function setMailCc($mailCc) {
$this->_setMailCc($mailCc);
return $this;
}
/**
* private class variable $_mailBcc
*/
private $_mailBcc;
/**
* returns the value of $mailBcc
*
* @return object(int|string) mailBcc
*/
public function _getMailBcc() {
return $this->_mailBcc;
}
/**
* sets the value of $_mailBcc
*
* @param mailBcc
*/
public function _setMailBcc($mailBcc) {
$this->_mailBcc = $mailBcc;
}
/**
* sets the value of $_mailBcc
*
* @param mailBcc
* @return object ( this class)
*/
public function setMailBcc($mailBcc) {
$this->_setMailBcc($mailBcc);
return $this;
}
/**
* private class variable $_mailSubject
*/
private $_mailSubject;
/**
* returns the value of $mailSubject
*
* @return object(int|string) mailSubject
*/
public function _getMailSubject() {
return $this->_mailSubject;
}
/**
* sets the value of $_mailSubject
*
* @param mailSubject
*/
public function _setMailSubject($mailSubject) {
$this->_mailSubject = $mailSubject;
}
/**
* sets the value of $_mailSubject
*
* @param mailSubject
* @return object ( this class)
*/
public function setMailSubject($mailSubject) {
$this->_setMailSubject($mailSubject);
return $this;
}
/**
* private class variable $_mailContent
*/
private $_mailContent;
/**
* returns the value of $mailContent
*
* @return object(int|string) mailContent
*/
public function _getMailContent() {
return $this->_mailContent;
}
/**
* sets the value of $_mailContent
*
* @param mailContent
*/
public function _setMailContent($mailContent) {
$this->_mailContent = $mailContent;
}
/**
* sets the value of $_mailContent
*
* @param mailContent
* @return object ( this class)
*/
public function setMailContent($mailContent) {
$this->_setMailContent($mailContent);
return $this;
}
/**
* private class variable $_mailFooter
*/
private $_mailFooter;
/**
* returns the value of $mailFooter
*
* @return object(int|string) mailFooter
*/
public function _getMailFooter() {
return $this->_mailFooter;
}
/**
* sets the value of $_mailFooter
*
* @param mailFooter
*/
public function _setMailFooter($mailFooter) {
$this->_mailFooter = $mailFooter;
}
/**
* sets the value of $_mailFooter
*
* @param mailFooter
* @return object ( this class)
*/
public function setMailFooter($mailFooter) {
$this->_setMailFooter($mailFooter);
return $this;
}
/**
* Performs a database query and returns the value of mail_temp_id
* based on the value of $mail_temp_id,$mail_purpose,$from_name,$mail_from,$mail_cc,$mail_bcc,$mail_subject,$mail_content,$mail_footer passed to the function
*
* @param $mail_temp_id,$mail_purpose,$from_name,$mail_from,$mail_cc,$mail_bcc,$mail_subject,$mail_content,$mail_footer
* @return object (mail_temp_id)| null
*/
public function getMailTempId($mail_temp_id,$mail_purpose,$from_name,$mail_from,$mail_cc,$mail_bcc,$mail_subject,$mail_content,$mail_footer) {
$columns = array ('mail_temp_id','mail_purpose','from_name','mail_from','mail_cc','mail_bcc','mail_subject','mail_content','mail_footer');
$records = array ($mail_temp_id,$mail_purpose,$from_name,$mail_from,$mail_cc,$mail_bcc,$mail_subject,$mail_content,$mail_footer);
$mail_temp_id_ = $this->query_from_mail_template ( $columns, $records );
return sizeof($mail_temp_id_)>0 ? $mail_temp_id_ [0] ['mail_temp_id'] : null;
}
/**
* Performs a database query and returns the value of mail_purpose
* based on the value of $mail_temp_id passed to the function
*
* @param $mail_temp_id
* @return object (mail_purpose)| null
*/
public function getMailPurpose($mail_temp_id) {
$columns = array ('mail_temp_id');
$records = array ($mail_temp_id);
$mail_purpose_ = $this->query_from_mail_template ( $columns, $records );
return sizeof($mail_purpose_)>0 ? $mail_purpose_ [0] ['mail_purpose'] : null;
}
/**
* Performs a database query and returns the value of from_name
* based on the value of $mail_temp_id passed to the function
*
* @param $mail_temp_id
* @return object (from_name)| null
*/
public function getFromName($mail_temp_id) {
$columns = array ('mail_temp_id');
$records = array ($mail_temp_id);
$from_name_ = $this->query_from_mail_template ( $columns, $records );
return sizeof($from_name_)>0 ? $from_name_ [0] ['from_name'] : null;
}
/**
* Performs a database query and returns the value of mail_from
* based on the value of $mail_temp_id passed to the function
*
* @param $mail_temp_id
* @return object (mail_from)| null
*/
public function getMailFrom($mail_temp_id) {
$columns = array ('mail_temp_id');
$records = array ($mail_temp_id);
$mail_from_ = $this->query_from_mail_template ( $columns, $records );
return sizeof($mail_from_)>0 ? $mail_from_ [0] ['mail_from'] : null;
}
/**
* Performs a database query and returns the value of mail_cc
* based on the value of $mail_temp_id passed to the function
*
* @param $mail_temp_id
* @return object (mail_cc)| null
*/
public function getMailCc($mail_temp_id) {
$columns = array ('mail_temp_id');
$records = array ($mail_temp_id);
$mail_cc_ = $this->query_from_mail_template ( $columns, $records );
return sizeof($mail_cc_)>0 ? $mail_cc_ [0] ['mail_cc'] : null;
}
/**
* Performs a database query and returns the value of mail_bcc
* based on the value of $mail_temp_id passed to the function
*
* @param $mail_temp_id
* @return object (mail_bcc)| null
*/
public function getMailBcc($mail_temp_id) {
$columns = array ('mail_temp_id');
$records = array ($mail_temp_id);
$mail_bcc_ = $this->query_from_mail_template ( $columns, $records );
return sizeof($mail_bcc_)>0 ? $mail_bcc_ [0] ['mail_bcc'] : null;
}
/**
* Performs a database query and returns the value of mail_subject
* based on the value of $mail_temp_id passed to the function
*
* @param $mail_temp_id
* @return object (mail_subject)| null
*/
public function getMailSubject($mail_temp_id) {
$columns = array ('mail_temp_id');
$records = array ($mail_temp_id);
$mail_subject_ = $this->query_from_mail_template ( $columns, $records );
return sizeof($mail_subject_)>0 ? $mail_subject_ [0] ['mail_subject'] : null;
}
/**
* Performs a database query and returns the value of mail_content
* based on the value of $mail_temp_id passed to the function
*
* @param $mail_temp_id
* @return object (mail_content)| null
*/
public function getMailContent($mail_temp_id) {
$columns = array ('mail_temp_id');
$records = array ($mail_temp_id);
$mail_content_ = $this->query_from_mail_template ( $columns, $records );
return sizeof($mail_content_)>0 ? $mail_content_ [0] ['mail_content'] : null;
}
/**
* Performs a database query and returns the value of mail_footer
* based on the value of $mail_temp_id passed to the function
*
* @param $mail_temp_id
* @return object (mail_footer)| null
*/
public function getMailFooter($mail_temp_id) {
$columns = array ('mail_temp_id');
$records = array ($mail_temp_id);
$mail_footer_ = $this->query_from_mail_template ( $columns, $records );
return sizeof($mail_footer_)>0 ? $mail_footer_ [0] ['mail_footer'] : null;
}
/**
* Inserts data into the table[mail_template] in the order below
* array ('mail_temp_id','mail_purpose','from_name','mail_from','mail_cc','mail_bcc','mail_subject','mail_content','mail_footer')
* is mapped into
* array ($mail_temp_id,$mail_purpose,$from_name,$mail_from,$mail_cc,$mail_bcc,$mail_subject,$mail_content,$mail_footer)
* @return int 1 if data was inserted,0 otherwise
* if redundancy check is true, it inserts if the record if it never existed else.
* if the record exists, it returns the number of times the record exists on the relation
*/
public function insert_prepared_records($mail_temp_id,$mail_purpose,$from_name,$mail_from,$mail_cc,$mail_bcc,$mail_subject,$mail_content,$mail_footer,$redundancy_check= false, $printSQL = false) {
$columns = array('mail_temp_id','mail_purpose','from_name','mail_from','mail_cc','mail_bcc','mail_subject','mail_content','mail_footer');
$records = array($mail_temp_id,$mail_purpose,$from_name,$mail_from,$mail_cc,$mail_bcc,$mail_subject,$mail_content,$mail_footer);
return $this->insert_records_to_mail_template ( $columns, $records,$redundancy_check, $printSQL );
}
/**
* Delete data from the table[mail_template] in the order below
* array ('mail_temp_id','mail_purpose','from_name','mail_from','mail_cc','mail_bcc','mail_subject','mail_content','mail_footer')
* is mapped into
* array ($mail_temp_id,$mail_purpose,$from_name,$mail_from,$mail_cc,$mail_bcc,$mail_subject,$mail_content,$mail_footer)
* @return int number of deleted rows
*/
public function delete_prepared_records($mail_temp_id,$mail_purpose,$from_name,$mail_from,$mail_cc,$mail_bcc,$mail_subject,$mail_content,$mail_footer, $printSQL = false) {
$columns = array('mail_temp_id','mail_purpose','from_name','mail_from','mail_cc','mail_bcc','mail_subject','mail_content','mail_footer');
$records = array($mail_temp_id,$mail_purpose,$from_name,$mail_from,$mail_cc,$mail_bcc,$mail_subject,$mail_content,$mail_footer);
return $this->delete_record_from_mail_template( $columns, $records, $printSQL );
}
/**
* Returns the table name. This is the owner of these crud functions.
* The various crud functions directly affect this table
* @return string table name -> 'mail_template'
*/
public static function get_table() {
return 'mail_template';
}
/**
* This action represents the intended database transaction
*
* @return string the set action.
*/
private function get_action() {
return $this->action;
}
/**
* Returns the client doing transactions
*
* @return string the client
*/
private function get_client() {
return $this->client;
}
/**
* Used to calculate the number of times a record exists in the table mail_template
* It returns the number of times a record exists exists in the table mail_template
* @param array $columns
* @param array $records
* @param bool $printSQL
* @return mixed
*/
public function is_exists(Array $columns, Array $records, $printSQL = false) {
return $this->get_database_utils ()->is_exists ( $this->get_table (), $columns, $records, $printSQL );
}
/**
* Inserts data into the table mail_template
* if redundancy check is true, it inserts if the record if it never existed else.
* if the record exists, it returns the number of times the record exists on the relation
*
* @param array $columns
* @param array $records
* @param bool $redundancy_check
* @param bool $printSQL
* @return mixed
*/
public function insert_records_to_mail_template(Array $columns, Array $records,$redundancy_check = false, $printSQL = false) {
return $this->insert_records ( $this->get_table (), $columns, $records,$redundancy_check, $printSQL );
}
/**
* Inserts records in a relation
* The records are inserted in the relation columns in the order they are arranged in the array
*
* @param $records
* @param bool $printSQL
* @return bool|mysqli_result
* @throws NullabilityException
*/
public function insert_raw($records, $printSQL = false)
{
return $this->get_database_utils()->insert_raw_records($this->get_table(), $records, $printSQL);
}
/**
* Deletes all the records that meets the passed criteria from the table mail_template
* @param array $columns
* @param array $records
* @param bool $printSQL
* @return number of deleted rows
*/
public function delete_record_from_mail_template(Array $columns, Array $records, $printSQL = false) {
return $this->delete_record ( $this->get_table (), $columns, $records, $printSQL );
}
/**
* Updates all the records that meets the passed criteria from the table mail_template
*
* @param array $columns
* @param array $records
* @param array $where_columns
* @param array $where_records
* @param bool $printSQL
* @return number of updated rows
*/
public function update_record_in_mail_template(Array $columns, Array $records, Array $where_columns, Array $where_records, $printSQL = false) {
return $this->update_record ( $this->get_table (), $columns, $records, $where_columns, $where_records, $printSQL );
}
/**
* Gets an Associative array of the records in the table 'mail_template' that meets the passed criteria
*
* @param $distinct
* @param array $columns
* @param array $records
* @param string $extraSQL
* @param bool $printSQL
* @return array|mixed associative
*/
public function fetch_assoc_in_mail_template($distinct, Array $columns, Array $records, $extraSQL="", $printSQL = false) {
return $this->fetch_assoc ( $distinct, $this->get_table (),$columns, $records, $extraSQL , $printSQL );
}
/**
* Gets an Associative array of the records in the table mail_template that meets the passed criteria
*
* @param array $columns
* @param array $records
* @param string $extraSQL
* @param bool $printSQL
* @return array|mixed associative
*/
public function query_from_mail_template(Array $columns, Array $records,$extraSQL="", $printSQL = false) {
return $this->query ( $this->get_table (), $columns, $records,$extraSQL,$printSQL );
}
/**
* Gets an Associative array of the records in the table mail_template that meets the passed distinct criteria
*
* @param array $columns
* @param array $records
* @param string $extraSQL
* @param bool $printSQL
* @return array|mixed associative
*/
public function query_distinct_from_mail_template(Array $columns, Array $records,$extraSQL="", $printSQL = false) {
return $this->query_distinct ( $this->get_table (), $columns, $records,$extraSQL,$printSQL );
}
/**
* Performs a search in the table mail_template that meets the passed criteria
*
* @param array $columns
* @param array $records
* @param string $extraSQL
* @param bool $printSQL
* @return array|mixed associative
*/
public function search_in_mail_template(Array $columns, Array $records,$extraSQL="", $printSQL = false) {
return $this->search ( $this->get_table (), $columns, $records,$extraSQL, $printSQL );
}
/**
* Get Database Utils
*
* @return DatabaseUtils $this->databaseUtils
*/
public function get_database_utils() {
return $this->databaseUtils;
}
/**
* Deletes all the records that meets the passed criteria from the table [mail_template]
*
* @param $table
* @param array $columns
* @param array $records
* @param bool $printSQL
* @return bool|int|\mysqli_result number of deleted rows
* @throws InvalidColumnValueMatchException
* @throws NullabilityException
*/
private function delete_record($table, Array $columns, Array $records, $printSQL = false) {
return $this->get_database_utils ()->delete_record ( $table, $columns, $records, $printSQL );
}
/**
* Inserts data into the table mail_template
*
* if redundancy check is true, it inserts if the record if it never existed else.
* if the record exists, it returns the number of times the record exists on the relation
* @param $table
* @param array $columns
* @param array $records
* @param bool $redundancy_check
* @param bool $printSQL
* @return bool|mixed|\mysqli_result the number of times the record exists
* @throws NullabilityException
*/
private function insert_records($table, Array $columns, Array $records,$redundancy_check = false, $printSQL = false) {
if($redundancy_check){
if($this->is_exists($columns, $records) == 0){
return $this->get_database_utils ()->insert_records ( $table, $columns, $records, $printSQL );
} else return $this->is_exists($columns, $records);
}else{
return $this->get_database_utils ()->insert_records ( $table, $columns, $records, $printSQL );
}
}
/**
* Updates all the records that meets the passed criteria from the table mail_template
* @param $table
* @param array $columns
* @param array $records
* @param array $where_columns
* @param array $where_records
* @param bool $printSQL
* @return bool|\mysqli_result number of updated rows
* @throws NullabilityException
*/
private function update_record($table, Array $columns, Array $records, Array $where_columns, Array $where_records, $printSQL = false) {
return $this->get_database_utils ()->update_record ( $table, $columns, $records, $where_columns, $where_records, $printSQL );
}
/**
* Gets an Associative array of the records in the table mail_template that meets the passed criteria
* associative array of the records that are found after performing the query
* @param $distinct
* @param $table
* @param array $columns
* @param array $records
* @param string $extraSQL
* @param bool $printSQL
* @return array|null
* @throws InvalidColumnValueMatchException
* @throws NullabilityException
*/
private function fetch_assoc($distinct, $table, Array $columns, Array $records, $extraSQL="", $printSQL = false) {
return $this->get_database_utils ()->fetch_assoc ( $distinct, $table, $columns, $records,$extraSQL, $printSQL );
}
/**
* Gets an Associative array of the records in the table mail_template that meets the passed criteria
*
* @param $table
* @param array $columns
* @param array $records
* @param string $extraSQL
* @param bool $printSQL
* @return array
*/
private function query($table, Array $columns, Array $records,$extraSQL="",$printSQL = false) {
return $this->get_database_utils ()->query ( $table, $columns, $records,$extraSQL, $printSQL );
}
/**
* Gets an Associative array of the records in the table mail_template that meets the distinct passed criteria
* @param $table
* @param array $columns
* @param array $records
* @param string $extraSQL
* @param bool $printSQL
* @return array
*/
private function query_distinct($table, Array $columns, Array $records,$extraSQL="",$printSQL = false) {
return $this->get_database_utils ()->query_distinct ( $table, $columns, $records,$extraSQL, $printSQL );
}
/**
* Performs a search and returns an associative array of the records in the table mail_template that meets the passed criteria
*
* @param $table
* @param array $columns
* @param array $records
* @param string $extraSQL
* @param bool $printSQL
* @return array|null
* @throws InvalidColumnValueMatchException
* @throws NullabilityException
*/
private function search($table, Array $columns, Array $records,$extraSQL="", $printSQL = false) {
return $this->get_database_utils ()->search ( $table, $columns, $records, $extraSQL, $printSQL );
}
}
?>
| true |
141aafee00b33b3cf59a57bd92d214a531f3d22d | PHP | duke-libraries/drupal-dul-system | /libcatalog/libcatalog.xserver.item.inc | UTF-8 | 1,132 | 2.640625 | 3 | [] | no_license | <?php
class XServerItem {
public static $BARCODE = 'z30-barcode';
public static $SUBLIBRARY = 'z30-sub-library';
public static $COLLECTION = 'z30-collection';
public static $CALLNO_TYPE = 'z30-call-no-type';
public static $CALLNO = 'z30-call-no';
private $_xml;
function __construct($xmlElement) {
$this->_xml = $xmlElement;
watchdog('libcatalog.xserveritem', print_r($xmlElement, TRUE));
}
function getValueForTagName($tagName) {
if (($values = $this->_xml->xpath('//' . $tagName . '/text()')) !== FALSE) {
return (string) $values[0];
}
return NULL;
}
function __get($name) {
$v = $this->getValueForTagName($name);
if ($v == NULL) {
$trace = debug_backtrace();
trigger_error(
'Undefined property via __get(): ' . $name .
' in ' . $trace[0]['file'] .
' on line ' . $trace[0]['line'],
E_USER_NOTICE);
}
if ($name == XServerItem::$CALLNO) {
$matches = array();
if (preg_match('/\$\$h([^\$]+)/', $v, $matches) == 1) {
watchdog('libcatalog', print_r($matches, TRUE));
$v = $matches[1];
}
}
return $v;
}
function getXML() {
return $this->_xml;
}
}
| true |
2948fef45692346e56ceeac4a46e036f354f5e78 | PHP | kevinliposl/ProyectoGestion | /domain/Career.php | UTF-8 | 1,085 | 2.984375 | 3 | [] | no_license | <?php
class Career {
//Attributes
private $careerid;
private $careercode;
private $careername;
private $careergrade;
private $careerenclosureid;
function __construct() {
;
}
function getCareerid() {
return $this->careerid;
}
function getCareercode() {
return $this->careercode;
}
function getCareername() {
return $this->careername;
}
function getCareergrade() {
return $this->careergrade;
}
function getCareerenclosureid() {
return $this->careerenclosureid;
}
function setCareerid($careerid) {
$this->careerid = $careerid;
}
function setCareercode($careercode) {
$this->careercode = $careercode;
}
function setCareername($careername) {
$this->careername = $careername;
}
function setCareergrade($careergrade) {
$this->careergrade = $careergrade;
}
function setCareerenclosureid($careerenclosureid) {
$this->careerenclosureid = $careerenclosureid;
}
//End class Career
}
| true |
76395dc8ba548e4be433d30fe7c0d69324ef4981 | PHP | pablo2004/noticia | /View/Helper/FormatHelper.php | UTF-8 | 669 | 3 | 3 | [] | no_license | <?php
class FormatHelper extends AppHelper
{
public function formatCallback($record, $callback)
{
$return = "";
if(is_array($record) && is_callable($callback))
{
$return = call_user_func($callback, $record);
}
return $return;
}
public function formatTemplateCallback($records, $callback)
{
$result = "";
if(is_array($records))
{
foreach($records AS $record)
{
$result .= $this->formatCallback($record, $callback);
}
}
return $result;
}
}
?> | true |
d03d015322d17b19765227206e4f6c257027cd7c | PHP | Cash-Money-McCoy/COSC-412 | /wordpress/wp-content/plugins/woo-paypalplus/src/Order/OrderDataProviderFactory.php | UTF-8 | 2,121 | 2.5625 | 3 | [
"GPL-2.0-or-later",
"GPL-2.0-only",
"GPL-1.0-or-later",
"MIT"
] | permissive | <?php # -*- coding: utf-8 -*-
/*
* This file is part of the PayPal PLUS for WooCommerce package.
*/
namespace WCPayPalPlus\Order;
use Exception;
use OutOfBoundsException;
use RuntimeException;
use UnexpectedValueException;
use WC_Order;
use WC_Order_Refund;
use WCPayPalPlus\Payment\CartData;
use WCPayPalPlus\Payment\OrderData;
use WCPayPalPlus\Session\Session;
use WooCommerce;
/**
* Class OrderDataProviderFactory
* @package WCPayPalPlus\Order
*/
class OrderDataProviderFactory
{
/**
* @var OrderFactory
*/
private $orderFactory;
/**
* @var Session
*/
private $session;
/**
* @var WooCommerce
*/
private $wooCommerce;
/**
* OrderDataFactory constructor.
* @param OrderFactory $orderFactory
* @param Session $session
* @param WooCommerce $wooCommerce
*/
public function __construct(
OrderFactory $orderFactory,
Session $session,
WooCommerce $wooCommerce
) {
$this->orderFactory = $orderFactory;
$this->session = $session;
$this->wooCommerce = $wooCommerce;
}
/**
* @return OrderData|CartData
*/
public function create()
{
try {
$orderData = $this->retrieveOrderByRequest();
$orderData = new OrderData($orderData);
} catch (Exception $exc) {
$orderData = new CartData($this->wooCommerce->cart);
}
return $orderData;
}
/**
* @return WC_Order|WC_Order_Refund
* @throws OrderFactoryException
* @throws RuntimeException
* @throws OutOfBoundsException
* @throws UnexpectedValueException
*/
private function retrieveOrderByRequest()
{
$key = filter_input(INPUT_GET, 'key');
if (!$key) {
throw new RuntimeException('Key for order not provided by the current request.');
}
$order = $this->orderFactory->createByOrderKey($key);
// TODO Understand why the ppp_order_id is set twice.
$this->session->set(Session::ORDER_ID, $order->get_id());
return $order;
}
}
| true |
14d93dff3ca2fec8d552260ad7449e6b81881d39 | PHP | AzureCloudMonk/The-Art-of-Modern-PHP-8 | /src/Part2/Chapter6/equality.php | UTF-8 | 343 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace Book\Part2\Chapter6;
echo "\n30 == ' 30 ', " . \var_export(30 === ' 30 ', true) . "\n";
echo "\n30 === ' 30 ', " . \var_export(30 === ' 30 ', true) . "\n";
echo "\ntrue == ' 30 ', " . \var_export(true === ' 30 ', true) . "\n";
echo "\ntrue === ' 30 ', " . \var_export(true === ' 30 ', true) . "\n";
| true |
91a824bd0407ff8b55fb57226d97079cd45985c9 | PHP | janephp/janephp | /src/Component/OpenApi3/Tests/fixtures/github/expected/Model/Traffic.php | UTF-8 | 1,665 | 2.875 | 3 | [
"MIT"
] | permissive | <?php
namespace Github\Model;
class Traffic extends \ArrayObject
{
/**
* @var array
*/
protected $initialized = array();
public function isInitialized($property) : bool
{
return array_key_exists($property, $this->initialized);
}
/**
*
*
* @var \DateTime
*/
protected $timestamp;
/**
*
*
* @var int
*/
protected $uniques;
/**
*
*
* @var int
*/
protected $count;
/**
*
*
* @return \DateTime
*/
public function getTimestamp() : \DateTime
{
return $this->timestamp;
}
/**
*
*
* @param \DateTime $timestamp
*
* @return self
*/
public function setTimestamp(\DateTime $timestamp) : self
{
$this->initialized['timestamp'] = true;
$this->timestamp = $timestamp;
return $this;
}
/**
*
*
* @return int
*/
public function getUniques() : int
{
return $this->uniques;
}
/**
*
*
* @param int $uniques
*
* @return self
*/
public function setUniques(int $uniques) : self
{
$this->initialized['uniques'] = true;
$this->uniques = $uniques;
return $this;
}
/**
*
*
* @return int
*/
public function getCount() : int
{
return $this->count;
}
/**
*
*
* @param int $count
*
* @return self
*/
public function setCount(int $count) : self
{
$this->initialized['count'] = true;
$this->count = $count;
return $this;
}
} | true |
e10c789e550992fe2bcef652a16ec2b40f9808d9 | PHP | matheusbiagini/AliceFramework | /Infrastructure/Data/Session.php | UTF-8 | 1,717 | 2.71875 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace Infrastructure\Data;
class Session
{
private const APP_KEY = '_app_';
public function setAuthenticated() : self
{
return $this->set('auth', true);
}
public function setWebsiteAuthenticated() : self
{
return $this->set('authWebsite', true);
}
public function setWebsiteMultiFactorAuthenticated() : self
{
return $this->set('authWebsiteDisplayMultiFactor', true);
}
public function setDisabledWebsiteMultiFactorAuthenticated() : self
{
return $this->set('authWebsiteDisplayMultiFactor', false);
}
public function hasAuthenticated() : bool
{
return (bool) $this->get('auth', false);
}
public function hasWebsiteAuthenticated() : bool
{
return (bool) $this->get('authWebsite', false);
}
public function hasWebsiteMultiFactorAuthenticated() : bool
{
return (bool) $this->get('authWebsiteDisplayMultiFactor', false);
}
public function get(string $key, $default = null)
{
if (!isset($_SESSION[self::APP_KEY][$key])) {
return $default;
}
return $_SESSION[self::APP_KEY][$key];
}
public function set(string $key, $value) : self
{
$_SESSION[self::APP_KEY][$key] = $value;
return $this;
}
public function getAll() : array
{
return $_SESSION[self::APP_KEY];
}
public function destroy(bool $sessionDestroy = true) : void
{
$_SESSION[self::APP_KEY] = [];
if ($sessionDestroy) {
session_destroy();
}
}
public static function session() : self
{
return new self();
}
}
| true |
b480aa9b0849c2d3984c00e9d49868a29b07a0ab | PHP | RomainMarecat/sessions-api | /src/Traits/TimestampableTrait.php | UTF-8 | 1,634 | 2.609375 | 3 | [] | no_license | <?php
namespace App\Traits;
use Doctrine\ORM\Mapping as ORM;
trait TimestampableTrait
{
/**
* @var \DateTime
* @ORM\Column(name="created_at", type="datetime")
*/
private $createdAt;
/**
* @var \DateTime
* @ORM\Column(name="updated_at", type="datetime")
*/
private $updatedAt;
/**
* @return \DateTime
*/
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->createdAt;
}
/**
* @ORM\PrePersist
* @throws \Exception
*/
public function prePersist()
{
$this->setCreatedAt(new \DateTime());
$this->setUpdatedAt(new \DateTime());
}
/**
* @ORM\PreUpdate
* @throws \Exception
*/
public function preUpdate()
{
$this->setUpdatedAt(new \DateTime());
}
/**
* @param \DateTime $createdAt
* @return TimestampableTrait
* @throws \Exception
*/
public function setCreatedAt(\DateTime $createdAt = null)
{
if (!$createdAt) {
$createdAt = new \DateTime();
}
$this->createdAt = $createdAt;
return $this;
}
/**
* @return \DateTime
*/
public function getUpdatedAt(): ?\DateTimeInterface
{
return $this->updatedAt;
}
/**
* @param \DateTime|null $updatedAt
* @return TimestampableTrait
* @throws \Exception
*/
public function setUpdatedAt(\DateTime $updatedAt = null)
{
if (!$updatedAt) {
$updatedAt = new \DateTime();
}
$this->updatedAt = $updatedAt;
return $this;
}
}
| true |
ed5b07b8242da034e3687d53059281c7e55f2892 | PHP | sbeland13/twitterconnector | /twitterwebconnect.php | UTF-8 | 2,068 | 2.59375 | 3 | [
"MIT"
] | permissive | <?php
/*********************************************************************************************************/
/** Twitter Web Connector **/
/** Manages Oauth Authentication To Twitter Search API **/
/** Author Stephane Beland **/
/** Version 1.0 **/
/*********************************************************************************************************/
require_once("TwitterAPIExchange.php");
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
"oauth_access_token" => "",
"oauth_access_token_secret" => "",
"consumer_key" => "",
"consumer_secret" => ""
);
$url = "https://api.twitter.com/1.1/search/tweets.json";
/** Get Search Term From Query String **/
if (isset($_GET['q'])) {
$q = $_GET['q'];
}else{
// Fallback behaviour goes here
$q="@tableau";
}
/** Get max_id From Query String **/
if (isset($_GET['max_id'])) {
$max_id = $_GET['max_id'];
}else{
// Fallback behaviour goes here
$max_id="";
}
/** Get Count From Query String **/
if (isset($_GET['count'])) {
$count = $_GET['count'];
}else{
// Fallback behaviour goes here
$count="100";
}
/** Get result_type From Query String **/
if (isset($_GET['result_type'])) {
$result_type = $_GET['result_type'];
}else{
// Fallback behaviour goes here
$result_type="recent";
}
/** Get include_entities From Query String **/
if (isset($_GET['include_entities'])) {
$include_entities = $_GET['include_entities'];
}else{
// Fallback behaviour goes here
$include_entities="1";
}
/** Get Request From Twitter Search API **/
$requestMethod = "GET";
$getfield = "?q=" . urlencode($q) . "&count=" . $count . "&result_type=" . $result_type . "&max_id=" . $max_id . "&include_entities=" . $include_entities;
$twitter = new TwitterAPIExchange($settings);
$json= $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
echo $json;
?>
| true |
e2e380c2437d959dd5931c8d3aab629053071ee0 | PHP | HelitonLeno/app | /admin/app/User.php | UTF-8 | 1,373 | 2.9375 | 3 | [] | no_license | <?php
class User
{
private $conn;
//construtor user
function __construct($conn)
{
$this->conn = $conn;
}
//metodo para autenticar login na pagina de admin
public function login($anome, $asenha)
{
try {
$stmt = $this->conn->prepare("SELECT * FROM admin WHERE nome = :anome LIMIT 1");
$stmt->bindparam(':anome', $anome);
//$stmt->execute(array(':uname'=>$uname, ':umail'=>$umail));
$stmt->execute();
$adminLinha = $stmt->fetch(PDO::FETCH_ASSOC);
if ($stmt->rowCount() > 0) {
if ($adminLinha['senha'] == $asenha) {
$_SESSION['admin'] = $adminLinha['id'];
return true;
} else {
return false;
}
}
} catch (PDOException $e) {
echo $e->getMessage();
}
}
//Verifica se ja esta com a sessao aberta
public function estaLogado()
{
if (isset($_SESSION['admin'])) {
return true;
}
}
//redirecionar para outra pagina
public function redirecionar($url)
{
header("Location: $url");
}
//deslogar admin da pagina
public function logout()
{
session_destroy();
unset($_SESSION['admin']);
return true;
}
} | true |
20536d749bc6b1c0c645886745bf5884da906dab | PHP | markmercedes/AlgoTel | /src/ResourceManagers/Base.php | UTF-8 | 2,692 | 2.65625 | 3 | [] | no_license | <?php
namespace ResourceManagers;
use Utils\Arr;
class Base
{
const MODEL_CLASS = '';
const RESOURCE_LABEL = '';
const RESOURCES_LABEL = '';
const EDITABLE_ATTRIBUTES = [];
const LISTABLE_ATTRIBUTES = [];
const TOP_LIST_ACTIONS = ['new'];
const LISTABLE_ACTIONS = ['edit'];
const EDITABLE_ACTIONS = ['save', 'cancel'];
const CREATEABLE_ACTIONS = ['save', 'cancel'];
const ATTRIBUTE_TYPES = [];
protected $controller;
function labelFor($attribute)
{
$attrMeta = static::ATTRIBUTE_TYPES[$attribute] ?? [];
return Arr::get($attrMeta, 'label', $attribute);
}
function __construct($controller)
{
$this->controller = $controller;
}
function resourcePath()
{
return $this->controller->currentRoute();
}
function resourceLabel()
{
return static::RESOURCE_LABEL;
}
function resourcesLabel()
{
return static::RESOURCES_LABEL;
}
function listableAttributes()
{
return static::LISTABLE_ATTRIBUTES;
}
function editableAttributes()
{
return static::EDITABLE_ATTRIBUTES;
}
function formActions($model)
{
return $model->isNewRecord() ? static::CREATEABLE_ACTIONS : static::EDITABLE_ACTIONS;
}
function topListActions()
{
return static::TOP_LIST_ACTIONS;
}
function listableActions()
{
return static::LISTABLE_ACTIONS;
}
function build($attributes = [])
{
$modelClass = static::MODEL_CLASS;
return new $modelClass($attributes);
}
function find($id)
{
$modelClass = static::MODEL_CLASS;
return $modelClass::find($id);
}
function parseInputFor($attribute, $value)
{
$attrMeta = static::ATTRIBUTE_TYPES[$attribute] ?? [];
$type = Arr::get($attrMeta, 'type', 'String');
$attrClass = '\\ResourceManagers\\Attributes\\' . $type . 'Attribute';
return forward_static_call(array($attrClass, 'serialize'), $value);
}
function fieldFor($model, $attribute)
{
$attrMeta = static::ATTRIBUTE_TYPES[$attribute] ?? [];
$type = Arr::get($attrMeta, 'type', 'String');
$attrClass = '\\ResourceManagers\\Attributes\\' . $type . 'Attribute';
return new $attrClass($model, $attribute, $attrMeta);
}
function model()
{
$modelClass = static::MODEL_CLASS;
return forward_static_call_array([$modelClass, 'where'], func_get_args());
}
function items()
{
return $this->model();
}
function renderModelAction($model, $action, $context, $options = [])
{
$className = ucfirst($action) . 'Action';
$fullClassName = "\\ModelActions\\$className";
$modelAction = new $fullClassName($model, $this->resourcePath());
return $modelAction->render($context, $options);
}
}
| true |
46496bf6369811b3a3bc05e7ad60ab998abfae3d | PHP | dextermb/ledger | /src/Eve/Models/Shared/Mail.php | UTF-8 | 839 | 2.53125 | 3 | [] | no_license | <?php
namespace Eve\Models\Shared;
use Eve\Abstracts\Model;
use Eve\Exceptions\ApiException;
use Eve\Exceptions\JsonException;
use Eve\Exceptions\ModelException;
use Eve\Exceptions\NoAccessTokenException;
use Eve\Exceptions\NoRefreshTokenException;
class Mail extends Model
{
/** @var string $subject */
public $subject;
/** @var int $from */
public $from;
/** @var string $timestamp */
public $timestamp;
/** @var array $labels */
public $labels;
/** @var array $recipients */
public $recipients;
public function map()
{
return [
'mail_id' => Model\Map::set('id'),
];
}
/**
* @throws ApiException|JsonException|ModelException|NoAccessTokenException|NoRefreshTokenException
* @return Model
*/
public function from()
{
return (new \Eve\Collections\Character\Character)
->getItem($this->from);
}
} | true |
813518a08a46013cf890662738b88fecf8402286 | PHP | A-Marzouk/resume-manager | /app/Traits/Billable.php | UTF-8 | 603 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
/**
* Created by PhpStorm.
* User: Ahmed-pc
* Date: 9/22/2020
* Time: 10:54 AM
*/
namespace App\Traits;
use App\Subscription;
use App\Billing\paymentGatewayInfo;
trait Billable
{
public static function byStripeCustomerId($id){
$subscription = Subscription::where('stripe_customer_id', $id)->first();
if($subscription){
return $subscription->client;
}
$paymentGatewoayInfo = paymentGatewayInfo::where('stripe_customer_id', $id)->first();
if($paymentGatewoayInfo){
return $paymentGatewoayInfo->client;
}
}
} | true |
531b42eda2b98eaf9044306845458b691465dfec | PHP | Dora-Sellami/GestionEcole | /include/config.php | UTF-8 | 187 | 2.59375 | 3 | [] | no_license | <?php
// Connexion à la base de données
try
{
$dbh = new PDO('mysql:host=localhost;dbname=ecole', "root", null);
}
catch(Exception $e)
{
die('Erreur : '.$e->getMessage());
}
?> | true |
9e38044df0eecbf92dda8746b660165ab10c5206 | PHP | Gauerdia/Guwon-Ui-Son-Prototype | /PHP-Skripts/enterAnwesenheit.php | UTF-8 | 2,577 | 2.8125 | 3 | [] | no_license | <?php
$link = mysqli_connect("****", "****", "****", "****");
if (!$link) {
echo 'Verbindung schlug fehl';
}
if (mysqli_connect_errno()) {
echo 'Connection Error';
}
$body = file_get_contents('php://input');
$postvars = json_decode($body, true);
$heute = date("d-m-Y");
$username = "[" . $heute . "]" . $postvars["username"];
$username_wo_date = $postvars["username"];
$stunden = $postvars["username"] . ":" . $postvars["stunden"] . " Stunden";
$punkte = $postvars["punkte"];
$j = array( 'username'=>$username,'stunden'=>$stunden,'punkte'=>$punkte);
echo json_encode($j);
if(!mysqli_query($link, "SELECT Anwesenheit FROM Guwon_Schueler WHERE Anwesenheit_temp='Ja' ")){
echo ("Error description: " . mysqli_error($link));
}
$retval = mysqli_query($link, "SELECT * FROM Guwon_Schueler");
while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC))
{
// firstly, we check, if the person has been marked by the user
$tempanwesen = $row['Anwesenheit_temp'];
if($tempanwesen == 1){
//tempvalue takes the existing value of attendances, puts a break in
//and augments it with the incoming data from the user.
$tempvalue = $row['Anwesenheit'] . ";\n" . $username;
//temppunkte extends the existing score.
$temppunkte = $row['Overall_Score'] + $punkte;
$temp_anwesenheit_punkte = $row['Anwesenheit_Score'] + $punkte;
$tempid =$row['id'];
// Anwesenheit_num is an iterator to see fastly, how often someone's been
// at the training.
$prior_anwesenheit_num = $row['Anwesenheit_num'];
$query = "UPDATE Guwon_Schueler Set Anwesenheit = '$tempvalue', Anwesenheit_temp = 0,
Anwesenheit_num = $prior_anwesenheit_num + 1,
Anwesenheit_Score = '$temp_anwesenheit_punkte', Overall_Score = '$temppunkte' WHERE id = '$tempid' ";
if (mysqli_query($link, $query)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($link);
}
// then, we post into the Kalender-Table, so that the person can see his own
// attendances.
$vorname = $row['vorname'];
$nachname = $row['nachname'];
$query ="INSERT INTO Guwon_Kalender(vorname, nachname, custom_date, description)
VALUES('$vorname','$nachname','$heute','$stunden')";
if (mysqli_query($link, $query)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($link);
}
}
}
| true |
5c859546d30361c67dea39d64374e916fb38c319 | PHP | leo2012/wda-lecture-examples | /17.html_form.php | UTF-8 | 1,162 | 2.859375 | 3 | [] | no_license | <?php
include "db_secure.php";
if (!($connection = @ mysql_connect(DB_HOST, 'conference', 'conference'))) {
showerror();
}
$id = mysqlclean($_GET, "id", 11, $connection);
if (!isset($id)) {
die('no id given');
}
if (!mysql_select_db('conference', $connection)) {
showerror();
}
$query = "SELECT * FROM registrations2 WHERE id = {$id}";
// echo $query;
if (!$result = mysql_query($query)) {
showerror();
}
if (mysql_num_rows($result) == 1) {
$row = mysql_fetch_array($result, MYSQL_ASSOC);
} else {
// something bad has happened
exit;
}
?>
<html>
<head>
<title>Update Registration form</title>
</head>
<body>
<form action="17.write_query.php" method="POST">
Name: <input type="text" name="name" value="<?php echo $row['name']; ?>"><br>
Email: <input type="text" name="email" value="<?php echo $row['email']; ?>"><br>
Category:<select name="category">
<option value="1">Staff
<option value="2">Student
<option value="3">Other
</select><br>
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="submit">
</form>
</body>
</html>
| true |
dd6ce0b7c59b28e25a0ff1c79f3b842e4419be59 | PHP | newphper0703/360InterviewCourses | /innerFunc.php | UTF-8 | 219 | 2.765625 | 3 | [] | no_license | <?php
/**
* File innerFunc.php
* Created by PhpStorm.
* User: liuzhi1107
* Date: 2019/1/25
* Time: 18:05
*/
$a = 1;
$b = 2;
$c = 3;
print($a);
echo $a, $b, $c;
$arr = [$a, $b, $c];
print_r($arr);
var_dump($arr); | true |
0528354ad80ab3d2c3726c3eb205682b84cc5418 | PHP | AathmanT/AccidentReporting | /test/user-upload-img.php | UTF-8 | 1,833 | 2.90625 | 3 | [] | no_license | <!DOCTYPE html>
<html>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image">
<br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if (isset($_POST['submit'])) {
if (getimagesize($_FILES['image']['tmp_name']) == FALSE) {
echo 'failed';
} else {
$name = addslashes($_FILES['image']['name']);
$image = base64_encode(file_get_contents(addslashes($_FILES['image']['tmp_name'])));
save_image($name, $image);
}
}
display();
function save_image($name, $image)
{
$mysqli = new mysqli('localhost', 'root', '', 'accidentreporter');
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
if (!$mysqli -> query("insert into img(name,img) values('$name','$image')")) {
echo("Error description: " . $mysqli -> error);
}
$mysqli -> close();
}
function display(){
$mysqli = new mysqli('localhost', 'root', '', 'accidentreporter');
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
if ($results = $mysqli -> query("select * from img")) {
$num = mysqli_num_rows($results);
// for($i =0 ; $i<$num;$i++){
// $res = mysqli_fetch_array($results);
// $img = $res['image'];
// echo '<img src="data:image;base64,'.$img.'">';
// }
if($results->num_rows){
while($row=$results->fetch_object()){
echo '<img src="data:image;base64,'.$row->img.'">';
}
$results->free();
}
}else{
echo("Error description: " . $mysqli -> error);
}
$mysqli -> close();
}
| true |
4bf5ea3cc0db39ac31ccc2efed6d81c19d3f70a1 | PHP | rafidmahin20/Shop-Management-System | /Tonwi/control/employeeRegistration.php | UTF-8 | 2,862 | 2.59375 | 3 | [] | no_license | <?php
include("../db/empDb.php");
$validateName="";
$validateEmail="";
$validateUsername="";
$validatePassword ="";
$validateConfirmPassword ="";
$validateNid="";
$validateDob="";
$validateMobile="";
$validateAddress="";
$validateGender="";
$gender="";
$validateCheckbox="";
$checkbox="";
$flag=true;
$validateForm="";
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$name=$_REQUEST["name"];
$email=$_REQUEST["email"];
$username=$_REQUEST["username"];
$password=$_REQUEST["password"];
$confirmPassword=$_REQUEST["confirmPassword"];
$nid=$_REQUEST["nid"];
$dob=$_REQUEST["dob"];
$mobile=$_REQUEST["mobile"];
$address=$_REQUEST["address"];
//$gender=$_REQUEST["gender"];
if(empty($name))
{
$validateName="Please enter a valid name!";
$flag=false;
}
if(empty($email) || !preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/i", $email)){
$validateEmail="Please enter a valid e-mail!";
$flag=false;
}
if(empty($username) || !preg_match('/[a-zA-Z0-9._]{5,}$/', $username)){
$validateUsername="Please enter a valid Username!";
$flag=false;
}
if(empty($password) || strlen($password)<8 || !preg_match("/(?=.*[@#$%^&+=!]).*$/", $password)){
$validatePassword = "Please enter a valid password atleast that contains 8 characters & 1 special character!";
$flag=false;
}
if(empty($confirmPassword) || $password != $confirmPassword){
$validateConfirmPassword = "Password Does Not Matched!";
$flag=false;
}
if(!preg_match("/^[0-9]\d{12}$/",$nid)){
$validateNid="Please enter a valid NID Number!";
$flag=false;
}
if(empty($dob)){
$validateDob="Please Select a Date.";
$flag=false;
}
if(!preg_match("/^01\d{9}$/",$mobile)){
$validateMobile="Please enter a valid mobile number!";
$flag=false;
}
if(empty($address)){
$validateAddress="Please enter a valid Address!";
$flag=false;
}
if(!isset($_POST["gender"])){
$validateGender="Please Select Your Gender!";
$flag=false;
}
else{
$gender = $_REQUEST["gender"];
}
if(!isset($_POST['checkbox'])){
$validateCheckbox="Please agree to all terms & conditions";
$flag=false;
}
if($flag==true)
{
$connection = new db();
$conobj=$connection->OpenCon();
$userQuery=$connection->RegUser($conobj,"employee",$name, $email, $username, $password, $nid, $dob, $mobile, $address, $gender);
$connection->CloseCon($conobj);
}
else
{
$validateForm="Registration Failed";
}
}
?> | true |
60a84f5a6b42129dd01fc3c3bd6f37a606c15c5e | PHP | any88/proyecto1 | /modelo/PacienteServicio.php | UTF-8 | 1,571 | 2.796875 | 3 | [] | no_license | <?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of PacienteServicio
*
* @author MARGOTH TAPIA
*/
class PacienteServicio {
private $idps;
private $idpaciente;
private $idservicio;
private $fecha;
private $idtransaccion;
private $hora;
function __construct($idps, $idpaciente, $idservicio, $fecha, $idtransaccion,$hora) {
$this->idps = $idps;
$this->idpaciente = $idpaciente;
$this->idservicio = $idservicio;
$this->fecha = $fecha;
$this->idtransaccion = $idtransaccion;
$this->hora=$hora;
}
function getIdps() {
return $this->idps;
}
function getIdpaciente() {
return $this->idpaciente;
}
function getIdservicio() {
return $this->idservicio;
}
function getFecha() {
return $this->fecha;
}
function getHora() {
return $this->hora;
}
function getIdtransaccion() {
return $this->idtransaccion;
}
function setIdps($idps) {
$this->idps = $idps;
}
function setIdpaciente($idpaciente) {
$this->idpaciente = $idpaciente;
}
function setIdservicio($idservicio) {
$this->idservicio = $idservicio;
}
function setFecha($fecha) {
$this->fecha = $fecha;
}
function setIdtransaccion($idtransaccion) {
$this->idtransaccion = $idtransaccion;
}
}
| true |
d81a67b23ba9def3ffb926298d460ec617bcc975 | PHP | PrinsFrank/measurement-unit | /src/Length/Inch.php | UTF-8 | 593 | 3.109375 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace PrinsFrank\MeasurementUnit\Length;
use PrinsFrank\ArithmeticOperations\ArithmeticOperations;
class Inch extends Length
{
public static function getSymbol(): string
{
return '″';
}
public static function fromMeterValue(float $value, ArithmeticOperations $arithmeticOperations): self
{
return new self($arithmeticOperations->divide($value, 0.0254), $arithmeticOperations);
}
public function toMeterValue(): float
{
return $this->arithmeticOperations->multiply($this->value, 0.0254);
}
}
| true |
2afb29f6b1d20e664d56b3ca6ede2c2340646796 | PHP | manutdvncom/php0720e_project | /backend/configs/Database.php | UTF-8 | 359 | 2.78125 | 3 | [] | no_license | <?php
//Tên class sẽ trùng với tên file
class Database {
public function connection(){
try {
$conn = new PDO('mysql:host=localhost;dbname=php0720e_project;port=3306;charset=utf8',
'root','');
return $conn;
} catch (PDOException $e){
die('Lỗi: '.$e->getMessage());
}
}
} | true |
d7c4f6f5e23b503efcaa78ee2c7cfef10039ef98 | PHP | sanzhumu/xaircraft1.1 | /src/Console/Daemon/Daemon.php | UTF-8 | 6,062 | 2.546875 | 3 | [
"Unlicense"
] | permissive | <?php
/**
* Created by PhpStorm.
* User: lbob
* Date: 2015/12/23
* Time: 16:07
*/
namespace Xaircraft\Console\Daemon;
use Xaircraft\App;
use Xaircraft\Console\Process;
use Xaircraft\Core\IO\File;
use Xaircraft\DI;
use Xaircraft\Exception\ConsoleException;
use Xaircraft\Exception\DaemonException;
abstract class Daemon
{
private $started = false;
private $pidFilePath;
private $childProcesses = array();
protected $singleton = true;
protected $args;
private static $daemons = array();
public function __construct(array $args)
{
$this->pidFilePath = App::path('runtime') . '/daemon/' . get_called_class() . '.pid';
$this->args = $args;
$this->initialize();
}
public static function bind($name, $implement)
{
if (!isset(self::$daemons)) {
self::$daemons = array();
}
self::$daemons[$name] = $implement;
}
public static function make($argc, array $argv)
{
if ($argc > 1) {
$cmd = $name = $argv[2];
if (array_key_exists($name, self::$daemons)) {
$name = self::$daemons[$name];
} else {
$name = $name . 'Daemon';
}
unset($argv[0]);
unset($argv[1]);
unset($argv[2]);
try {
$daemon = DI::get($name, array('args' => self::parseArgs($argv)));
if ($daemon instanceof Daemon) {
return $daemon;
}
} catch (\Exception $ex) {
throw new ConsoleException("Daemon [$cmd] undefined.");
}
throw new ConsoleException("Class [$name] is not a Daemon.");
}
return null;
}
private static function parseArgs(array $args)
{
$results = array();
foreach ($args as $arg) {
if (preg_match('#(?<key>[a-zA-Z][a-zA-Z0-9\_]+)\=(?<value>[a-zA-Z0-9\_\\\/]+)#i', $arg, $matches)) {
if (array_key_exists('key', $matches)) {
$results[$matches['key']] = array_key_exists('value', $matches) ? $matches['value'] : null;
}
} else {
$results[] = $arg;
}
}
return $results;
}
public abstract function beforeStart();
public abstract function beforeStop();
public abstract function handle();
public function start()
{
if ($this->started) {
return;
}
$this->started = true;
global $stdin, $stdout, $stderr;
if ($this->singleton) {
$this->checkPidFile();
}
umask(0);
if (pcntl_fork() === 0) {
posix_setsid();
if (pcntl_fork() === 0) {
try {
chdir("/");
fclose(STDIN);
fclose(STDOUT);
fclose(STDERR);
$stdin = fopen("/dev/null", "r");
$stdout = fopen("/dev/null", "a");
$stderr = fopen("/dev/null", "a");
if ($this->singleton) {
$this->createPidFile();
}
$this->handle();
$this->onStop();
} catch (\Exception $ex) {
$this->onStop();
throw new DaemonException($this->getName(), $ex->getMessage(), $ex);
}
}
App::end();
}
}
public function stop()
{
if (!file_exists($this->pidFilePath)) {
return true;
}
$pid = file_get_contents($this->pidFilePath);
$pid = intval($pid);
if ($pid > 0 && posix_kill($pid, SIGKILL)) {
$this->onStop();
App::end();
}
throw new DaemonException($this->getName(), "The daemon process end abnormally.");
}
public function getPID()
{
if (!file_exists($this->pidFilePath)) {
return false;
}
$pid = file_get_contents($this->pidFilePath);
$pid = intval($pid);
return $pid;
}
public function getName()
{
return get_called_class();
}
public function fork($target)
{
$process = Process::fork($target);
$this->childProcesses[] = $process;
return $process;
}
private function initialize()
{
if (!function_exists("pcntl_signal_dispatch")) {
declare(ticks = 10);
}
$this->registeSignalHandler(function ($signal) {
switch ($signal) {
case SIGTERM:
case SIGHUP:
case SIGQUIT:
$this->onStop();
App::end();
break;
default:
return false;
}
return true;
});
if (function_exists("gc_enable")) {
gc_enable();
}
}
private function checkPidFile()
{
if (!file_exists($this->pidFilePath)) {
return true;
}
$pid = file_get_contents($this->pidFilePath);
$pid = intval($pid);
if ($pid > 0 && posix_kill($pid, 0)) {
throw new ConsoleException("The daemon process is already started.");
} else {
throw new ConsoleException("The daemon process end abnormally.");
}
}
private function createPidFile()
{
File::writeText($this->pidFilePath, posix_getpid());
}
private function onStop()
{
$this->beforeStop();
/** @var Process $process */
foreach ($this->childProcesses as $process) {
$process->stop();
}
if (file_exists($this->pidFilePath)) {
unlink($this->pidFilePath);
}
}
private function registeSignalHandler($closure)
{
pcntl_signal(SIGTERM, $closure, false);
pcntl_signal(SIGQUIT, $closure, false);
}
} | true |
d427686494ca82aaa4e7d52a64c9f3a332606507 | PHP | ellipsephp/resolvable-value | /src/Executions/ExecutionInterface.php | UTF-8 | 623 | 2.671875 | 3 | [
"MIT"
] | permissive | <?php declare(strict_types=1);
namespace Ellipse\Resolvable\Executions;
use ReflectionParameter;
interface ExecutionInterface
{
/**
* Return the value of the given factory by resolving the value of the given
* reflection parameter with the given tail and placeholders.
*
* @param callable $factory
* @param \ReflectionParameter $parameter
* @param array $tail
* @param array $placeholders
* @return mixed
*/
public function __invoke(callable $factory, ReflectionParameter $parameter, array $tail, array $placeholders);
}
| true |
bba16a2caeba6ba7e6af473f867f90bef7357bdb | PHP | marb61a/phpsocial | /register.php | UTF-8 | 6,173 | 2.515625 | 3 | [] | no_license | <?php
require 'config/config.php';
require 'includes/functions/email_exists.php';
// Register handler must come before login handler
require 'includes/form_handlers/register_handler.php';
require 'includes/form_handlers/login_handler.php';
if(isset($_SESSION["username"])){
header("Location: index.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Welcome to PHPSocial</title>
<link rel="stylesheet" type="text/css" href="assets/css/register_style.css">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="assets/js/register.js"></script>
</head>
<body>
<?php
// This determines which form to show the user
if($reg){
echo '<script>
$(document).ready(function(){
$("#first").hide();
$("#second").show();
})
</script>';
}
?>
<div class="wrapper">
<div class="login_box">
<div class="login-header">
<h1>PHPSocial</h1>
Login or Signup below!!!
</div>
<div id="first">
<form action="register,php" method="POST">
<input type="email" name="log_email" placeholder="Email Address" value="
<?php
if(isset($_SESSION['log_email'])){
echo($_SESSION['log_email']);
}
?>
" required>
<br>
<input type="password" name="log_password" placeholder="Password">
<br>
<input type="submit" name="login_button" value="Login">
<br>
<?php
if(in_array("Email or password was incorrect<br>", $error_array)) echo "Email or password is incorrect<br>";
?>
</form>
</div>
<div id="second">
<form action="register,php" method="POST">
<input type="text" name="reg_fname" placeholder="First Name" <?php
if(isset($_SESSION['reg_fname'])){
echo $_SESSION['reg_fname'];
}
?> required>
<br>
<?php if(in_array("Your first name must be between 2 and 25 characters long<br>", $error_array)) echo "Your first name must be between 2 and 25 characters long<br>";?>
<input type="text" name="reg_lname" placeholder="Last Name" <?php
if(isset($_SESSION['reg_lname'])){
echo $_SESSION['reg_lname'];
}
?> required>
<br>
<?php if(in_array("Your last name must be between 2 and 25 characters long<br>", $error_array)) echo "Your last name must be between 2 and 25 characters long<br>";?>
<input type="email" name="reg_email" placeholder="EMail" <?php
if(isset($_SESSION['reg_email'])){
echo $_SESSION['reg_email'];
}
?> required>
<br>
<?php if(in_array("Email already in use<br>", $error_array)) echo "Email already in use<br>";?>
<input type="email" name="reg_email2" placeholder="Confirm Email" <?php
if(isset($_SESSION['reg_email2'])){
echo $_SESSION['reg_email2'];
}
?> required>
<br>
<?php if(in_array("Email already in use<br>", $error_array)) echo "Email already in use<br>";
else if(in_array("Invalid Email format<br>", $error_array)) echo "Invalid Email format<br>";
else if(in_array("Emails do not match<br>", $error_array)) echo "Emails do not match<br>";?>
<input type="password" name="reg_password" placeholder="Password" required>
<br>
<input type="password" name="reg_password2" placeholder="Confirm Password" required>
<br>
<?php if(in_array("Your passwords do not match<br>", $error_array)) echo "Your passwords do not match<br>";
else if(in_array("Your password can only contain English characters and numbers<br>", $error_array)) echo "Your password can only contain English characters and numberst<br>";
else if(in_array("Your password must be between 5 and 30 characters long<br>", $error_array)) echo "Your password must be between 5 and 30 characters long<br>";?>
<input type="submit" name="register_button" value="Register">
<br>
<?php if(in_array("<span style='color:#14C800'>You Are Ready To Login</span><br>", $error_array)) echo "<span style='color:#14C800'>You Are Ready To Login</span><br>"; ?>
<a href="#" id="signin" class="signin">
Already have an account? Login here
</a>
</form>
</div>
<br>
</div>
</div>
</body>
</html> | true |
d58983b5839ba9a431a1769234237787da009154 | PHP | atmtk/php-xbase | /src/Record/FoxproRecord.php | UTF-8 | 651 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php declare(strict_types=1);
namespace XBase\Record;
use XBase\Enum\FieldType;
use XBase\Header\Column;
class FoxproRecord extends AbstractRecord
{
public function get(string $columnName)
{
$column = $this->table->getColumn($columnName);
switch ($column->type) {
case FieldType::GENERAL:
return $this->getGeneral($column);
default:
return parent::get($columnName);
}
}
protected function getGeneral(Column $column)
{
$this->checkType($column, FieldType::GENERAL);
return $this->getMemoObject($column->name)->getData();
}
}
| true |
e6536f97f20247b4e7e858b4966afa15505dbb55 | PHP | gcraig14/ucteswp | /wp-content/plugins/dahz-extender/extensions/modules/shortcodes/includes/params/parallax_option.php | UTF-8 | 15,304 | 2.5625 | 3 | [] | no_license | <?php
/**
*
*/
if( !class_exists( 'Dahz_Framework_Parallax_Option' ) ){
class Dahz_Framework_Parallax_Option{
public $settings = array();
public $value = '';
public $params = array();
public function __construct( $settings, $value ){
$this->settings( $settings );
$this->value( $value );
if( !empty( $value ) ){
$values = json_decode( urldecode( $value ), true );
$this->params( $values );
}
}
function settings( $settings = null ) {
if ( is_array( $settings ) ) {
$this->settings = $settings;
}
return $this->settings;
}
function setting( $key ) {
return isset( $this->settings[ $key ] ) ? $this->settings[ $key ] : '';
}
function value( $value = null ) {
if ( is_string( $value ) ) {
$this->value = $value;
}
return $this->value;
}
function params( $values = null ) {
if ( is_array( $values ) ) {
$this->params = $values;
}
return $this->params;
}
function param( $key, $default = '' ) {
return isset( $this->params[ $key ] ) ? $this->params[ $key ] : $default;
}
public function option_breakpoint( $value ) {
$breakpoints = dahz_shortcode_helper_get_field_option( 'breakpoint' );
$option = '';
foreach( $breakpoints as $label => $option_value ){
$option .= sprintf(
'
<option value="%1$s" %3$s>%2$s</option>
',
esc_attr( $option_value ),
esc_html( $label ),
selected( $option_value, $value, false )
);
}
return $option;
}
function render() {
$output = sprintf(
'
<div class="uk-grid-medium parallax-options-container" uk-grid>
<div class="uk-width-1-1" style="display: none;">
<textarea name="%1$s" class="%1$s %2$s_field wpb_vc_param_value">%3$s</textarea>
</div>
<div class="uk-width-1-2">
<div class="uk-flex-middle uk-grid-small parallax-options-range" uk-grid>
<div class="uk-width-1-1">
<label style="font-weight: 600;margin-bottom: 5px;display: block;">Horizontal Start</label>
</div>
<div class="uk-width-expand uk-first-column">
<input class="uk-range parallax-option" name="parallax-options-x-start-range" type="range" value="%4$s" min="-600" max="600" step="10">
</div>
<div class="uk-width-auto" style="max-width: 60px;">
<input value="%4$s" class="uk-input uk-form-width-xsmall" type="text" name="parallax-options-x-start">
</div>
</div>
</div>
<div class="uk-width-1-2">
<div class="uk-flex-middle uk-grid-small parallax-options-range" uk-grid>
<div class="uk-width-1-1">
<label style="font-weight: 600;margin-bottom: 5px;display: block;">Horizontal End</label>
</div>
<div class="uk-width-expand uk-first-column">
<input class="uk-range parallax-option" name="parallax-options-x-end-range" type="range" value="%5$s" min="-600" max="600" step="10">
</div>
<div class="uk-width-auto" style="max-width: 60px;">
<input value="%5$s" class="uk-input uk-form-width-xsmall" name="parallax-options-x-end" type="text" >
</div>
</div>
</div>
<div class="uk-width-1-2 uk-grid-margin-small">
<div class="uk-flex-middle uk-grid-small parallax-options-range" uk-grid>
<div class="uk-width-1-1 uk-grid-margin-small">
<label style="font-weight: 600;margin-bottom: 5px;display: block;">Vertical Start</label>
</div>
<div class="uk-width-expand uk-first-column">
<input class="uk-range parallax-option" name="parallax-options-y-start-range" type="range" value="%6$s" min="-600" max="600" step="10">
</div>
<div class="uk-width-auto" style="max-width: 60px;">
<input value="%6$s" class="uk-input uk-form-width-xsmall" name="parallax-options-y-start" type="text" >
</div>
</div>
</div>
<div class="uk-width-1-2 uk-grid-margin-small">
<div class="uk-flex-middle uk-grid-small parallax-options-range" uk-grid>
<div class="uk-width-1-1 uk-grid-margin-small">
<label style="font-weight: 600;margin-bottom: 5px;display: block;">Vertical End</label>
</div>
<div class="uk-width-expand uk-first-column">
<input class="uk-range parallax-option" type="range" name="parallax-options-y-end-range" value="%7$s" min="-600" max="600" step="10">
</div>
<div class="uk-width-auto" style="max-width: 60px;">
<input value="%7$s" class="uk-input uk-form-width-xsmall" name="parallax-options-y-end" type="text" >
</div>
</div>
</div>
<div class="uk-width-1-1 uk-grid-margin-small parallax-advance">
<div class="uk-margin" uk-grid>
<div class="uk-width-1-1">
<label style="font-weight: 600;margin-bottom: 5px;display: block;">Advance Settings</label>
</div>
<div class="uk-width-1-1">
<input value="%8$s" %19$s type="checkbox" class="parallax-option parallax-options-show-advance-settings" name="parallax-options-show-advance-settings"> Yes
</div>
</div>
</div>
<div class="uk-width-1-1 uk-grid-margin-small parallax-advance parallax-options-advance-settings %22$s">
<div class="uk-margin" uk-grid>
<div class="uk-width-1-2">
<div class="uk-flex-middle uk-grid-small parallax-options-range" uk-grid>
<div class="uk-width-1-1">
<label style="font-weight: 600;margin-bottom: 5px;display: block;">Scale Start</label>
</div>
<div class="uk-width-expand uk-first-column">
<input class="uk-range parallax-option" name="parallax-options-scale-start-range" type="range" value="%9$s" min="0" max="2" step="0.1">
</div>
<div class="uk-width-auto" style="max-width: 60px;">
<input class="uk-input uk-form-width-xsmall" value="%9$s" name="parallax-options-scale-start" type="text" >
</div>
</div>
</div>
<div class="uk-width-1-2">
<div class="uk-flex-middle uk-grid-small parallax-options-range" uk-grid>
<div class="uk-width-1-1">
<label style="font-weight: 600;margin-bottom: 5px;display: block;">Scale End</label>
</div>
<div class="uk-width-expand uk-first-column">
<input class="uk-range parallax-option" name="parallax-options-scale-end-range" type="range" value="%10$s" min="0" max="2" step="0.1">
</div>
<div class="uk-width-auto" style="max-width: 60px;">
<input class="uk-input uk-form-width-xsmall" value="%10$s" name="parallax-options-scale-end" type="text" >
</div>
</div>
</div>
<div class="uk-width-1-2 uk-grid-margin-small">
<div class="uk-flex-middle uk-grid-small parallax-options-range" uk-grid>
<div class="uk-width-1-1 uk-grid-margin-small">
<label style="font-weight: 600;margin-bottom: 5px;display: block;">Rotate Start</label>
</div>
<div class="uk-width-expand uk-first-column">
<input class="uk-range parallax-option" type="range" name="parallax-options-rotate-start-range" value="%11$s" min="0" max="360" step="10">
</div>
<div class="uk-width-auto" style="max-width: 60px;">
<input class="uk-input uk-form-width-xsmall" value="%11$s" name="parallax-options-rotate-start" type="text" >
</div>
</div>
</div>
<div class="uk-width-1-2 uk-grid-margin-small">
<div class="uk-flex-middle uk-grid-small parallax-options-range" uk-grid>
<div class="uk-width-1-1 uk-grid-margin-small">
<label style="font-weight: 600;margin-bottom: 5px;display: block;">Rotate End</label>
</div>
<div class="uk-width-expand uk-first-column">
<input class="uk-range parallax-option" type="range" name="parallax-options-rotate-end-range" value="%12$s" min="0" max="360" step="10">
</div>
<div class="uk-width-auto" style="max-width: 60px;">
<input class="uk-input uk-form-width-xsmall" value="%12$s" name="parallax-options-rotate-end" type="text" >
</div>
</div>
</div>
<div class="uk-width-1-2 uk-grid-margin-small">
<div class="uk-flex-middle uk-grid-small parallax-options-range" uk-grid>
<div class="uk-width-1-1 uk-grid-margin-small">
<label style="font-weight: 600;margin-bottom: 5px;display: block;">Opacity Start</label>
</div>
<div class="uk-width-expand uk-first-column">
<input class="uk-range parallax-option" name="parallax-options-opacity-start-range" type="range" value="%13$s" min="0" max="1" step="0.1">
</div>
<div class="uk-width-auto" style="max-width: 60px;">
<input class="uk-input uk-form-width-xsmall" value="%13$s" name="parallax-options-opacity-start" type="text" >
</div>
</div>
</div>
<div class="uk-width-1-2 uk-grid-margin-small">
<div class="uk-flex-middle uk-grid-small parallax-options-range" uk-grid>
<div class="uk-width-1-1 uk-grid-margin-small">
<label style="font-weight: 600;margin-bottom: 5px;display: block;">Opacity End</label>
</div>
<div class="uk-width-expand uk-first-column">
<input class="uk-range parallax-option" name="parallax-options-opacity-end-range" type="range" value="%14$s" min="0" max="1" step="0.1">
</div>
<div class="uk-width-auto" style="max-width: 60px;">
<input class="uk-input uk-form-width-xsmall" value="%14$s" name="parallax-options-opacity-end" type="text" >
</div>
</div>
</div>
<div class="uk-width-1-1 uk-grid-margin-small">
<div class="uk-flex-middle uk-grid-small parallax-options-range" uk-grid>
<div class="uk-width-1-1 uk-grid-margin-small">
<label style="font-weight: 600;margin-bottom: 5px;display: block;">Easing</label>
</div>
<div class="uk-width-expand uk-first-column">
<input class="uk-range parallax-option" name="parallax-options-easing-range" type="range" value="%15$s" min="0" max="2" step="0.1">
</div>
<div class="uk-width-auto" style="max-width: 60px;">
<input class="uk-input uk-form-width-xsmall" value="%15$s" name="parallax-options-easing" type="text" >
</div>
</div>
</div>
<div class="uk-width-1-1 uk-grid-margin-small">
<div class="uk-flex-middle uk-grid-small parallax-options-range" uk-grid>
<div class="uk-width-1-1 uk-grid-margin-small">
<label style="font-weight: 600;margin-bottom: 5px;display: block;">Viewport</label>
</div>
<div class="uk-width-expand uk-first-column">
<input class="uk-range parallax-option" name="parallax-options-viewport-range" type="range" value="%16$s" min="0" max="1" step="0.1">
</div>
<div class="uk-width-auto" style="max-width: 60px;">
<input class="uk-input uk-form-width-xsmall" value="%16$s" name="parallax-options-viewport" type="text" >
</div>
</div>
</div>
</div>
</div>
<div class="uk-width-1-1 uk-grid-margin-small parallax-advance">
<div class="uk-margin" uk-grid>
<div class="uk-width-1-1">
<label style="color: #999;display: block;font-style: italic;line-height: 20px;margin-top: 8px;clear: both;">%24$s</label>
</div>
</div>
</div>
<div class="uk-width-1-1 uk-grid-margin-small parallax-advance">
<div class="uk-margin" uk-grid>
<div class="uk-width-1-1">
<label style="font-weight: 600;margin-bottom: 5px;display: block;">Z Index</label>
</div>
<div class="uk-width-1-1">
<input value="%18$s" %21$s class="parallax-option" name="parallax-options-enable-z-index" type="checkbox">%25$s
</div>
</div>
</div>
<div class="uk-width-1-1 uk-grid-margin-small">
<div class="uk-margin" uk-grid>
<div class="uk-width-1-1">
<label style="font-weight: 600;margin-bottom: 5px;display: block;">Parallax Breakpoint</label>
</div>
<div class="uk-width-1-1">
<select class="parallax-option" name="parallax-options-breakpoint">
%23$s
</select>
</div>
<div class="uk-width-1-1">
<label style="color: #999;display: block;font-style: italic;line-height: 20px;margin-top: 8px;clear: both;">%26$s</label>
</div>
</div>
</div>
</div>
',
$this->setting( 'param_name' ), // 1
$this->setting( 'type' ), // 2
esc_attr( $this->value() ), // 3
esc_attr( $this->param( 'parallax-options-x-start-range', 0 ) ), // 4
esc_attr( $this->param( 'parallax-options-x-end-range', 0 ) ), // 5
esc_attr( $this->param( 'parallax-options-y-start-range', 0 ) ), // 6
esc_attr( $this->param( 'parallax-options-y-end-range', 0 ) ), // 7
esc_attr( $this->param( 'parallax-options-show-advance-settings', 'false' ) ), // 8
esc_attr( $this->param( 'parallax-options-scale-start-range', 1 ) ), // 9
esc_attr( $this->param( 'parallax-options-scale-end-range', 1 ) ), // 10
esc_attr( $this->param( 'parallax-options-rotate-start-range', 0 ) ), // 11
esc_attr( $this->param( 'parallax-options-rotate-end-range', 0 ) ), // 12
esc_attr( $this->param( 'parallax-options-opacity-start-range', 1 ) ), // 13
esc_attr( $this->param( 'parallax-options-opacity-end-range', 1 ) ), // 14
esc_attr( $this->param( 'parallax-options-easing-range', 0 ) ), // 15
esc_attr( $this->param( 'parallax-options-viewport-range', 0 ) ), // 16
esc_attr( $this->param( 'parallax-options-enable-repeat', 'false' ) ), // 17
esc_attr( $this->param( 'parallax-options-enable-z-index', 'false' ) ), // 18
esc_attr( checked( 'true', $this->param( 'parallax-options-show-advance-settings', 'false' ), false ) ), // 19
esc_attr( checked( 'true', $this->param( 'parallax-options-enable-repeat', 'false' ), false ) ), // 20
esc_attr( checked( 'true', $this->param( 'parallax-options-enable-z-index', 'false' ), false ) ), // 21
$this->param( 'parallax-options-show-advance-settings', 'false' ) !== 'true' ? 'uk-hidden' : '', // 22
$this->option_breakpoint( $this->param( 'parallax-options-breakpoint', 'false' ) ), // 23
__( ' Animate the element as long as the section is visible', 'upsob' ), // 24
__( ' Set a higher stacking order', 'upsob' ), // 25
__( ' Display the parallax effect only on this device width and larger', 'upsob' ) // 26
);
return $output;
}
}
}
vc_add_shortcode_param( 'parallax_options', 'dahz_framework_parallax_option_vc_params', DAHZEXTENDER_SHORTCODE_URI . 'assets/js/admin/dahz-vc-params.min.js' );
function dahz_framework_parallax_option_vc_params( $settings, $value ) {
$parallax_options = new Dahz_Framework_Parallax_Option( $settings, $value );
return $parallax_options->render();
}
| true |
6611e43929a5f29db706d95443ed66503d79f73e | PHP | Gasolene/Rum.tests | /app/code/ui/fbrowser.class.php | UTF-8 | 5,192 | 2.65625 | 3 | [] | no_license | <?php /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
// +----------------------------------------------------------------------+
// | PHP version 4.3.8, 4.3.9 (tested) |
// +----------------------------------------------------------------------+
// | Copyright (c) 2005 |
// +----------------------------------------------------------------------+
// | License: |
// | |
// | |
// | |
// | |
// +----------------------------------------------------------------------+
// | Version: 1.0.0 |
// | Modified: Apr 06, 2005 |
// +----------------------------------------------------------------------+
// | Author(s): Darnell Shinbine |
// | |
// +----------------------------------------------------------------------+
//
// $id$
namespace MyApp\UI;
/**
* TFbrowser
*
* Handles file browser control
* Preserves the application state
*
* @version $id$
* @author Darnell Shinbine
* @date Feb 15, 2005
* @package WebWidgets
*/
class FBrowser extends TreeView
{
/**
* Current path
* @access public
*/
var $path = '';
/**
* collection of file types to include
*/
var $filter;
/**
* specifies whether on the file type filter is on
*/
var $filterOn = false;
/**
* __construct
*
* @return void
* @access public
*/
function __construct( $controlId, $path = __ROOT__ ) {
parent::__construct( $controlId );
$this->path = $path;
$this->filter = new Collection;
}
/**
* onLoad
*
* called when control is loaded and processed
*
* @return bool true if successfull
* @access public
*/
function onLoad() {
parent::onLoad();
$this->rootNode = $this->_getNode( $this->path );
}
/**
* _getNode
*
* returns tree node
*
* @param string $path path root
* @return object TreeNode
* @access public
*/
function & _getNode( $path, $file='root' ) {
if( file_exists( $path )) {
$dir = opendir( $path );
if($dir) {
// create TreeNode
$TreeNode = new TreeNode( $file );
$TreeNode->textOrHtml = $file;
// loop through all files in directory level and add to tree
while( $file = readdir( $dir )) {
$newpath = "$path/$file"; // get path of current node
if( $file != '.' && $file != '..' ) { // ignore parent folders
// child is a folder so create new branch
if( is_dir( $newpath )) {
$childNode = $this->_getNode( $newpath, $file );
if($childNode) { // recursive
$TreeNode->addChild( $childNode );
unset( $childNode );
}
}
else
{
// child is a file so create new node
if( $this->filter->find( substr( strrchr( $file, '.' ), 1, strlen( strrchr( $file, '.' )))) || !$this->filterOn ) { // check against accepted file types
// get path to image source
if( strrchr( $file, '.' ) == '.txt' ) {
$imgSrc = $this->assets . '/treeview/text.gif';
}
elseif( strrchr( $file, '.' ) == '.jpg' ||
strrchr( $file, '.' ) == '.jpeg' ||
strrchr( $file, '.' ) == '.bmp' ||
strrchr( $file, '.' ) == '.gif' ||
strrchr( $file, '.' ) == '.tif' ||
strrchr( $file, '.' ) == '.png' ) {
$imgSrc = $this->assets . '/treeview/image.gif';
}
elseif( strrchr( $file, '.' ) == '.pdf' ) {
$imgSrc = $this->assets . '/treeview/pdf.gif';
}
elseif( strrchr( $file, '.' ) == '.html' ||
strrchr( $file, '.' ) == '.htm' ||
strrchr( $file, '.' ) == '.xml' ||
strrchr( $file, '.' ) == '.xsl' ||
strrchr( $file, '.' ) == '.asp' ||
strrchr( $file, '.' ) == '.php' ) {
$imgSrc = $this->assets . '/treeview/web.gif';
}
elseif( strrchr( $file, '.' ) == '.doc' ||
strrchr( $file, '.' ) == '.rtf' ) {
$imgSrc = $this->assets . '/treeview/word.gif';
}
elseif( strrchr( $file, '.' ) == '.zip' ||
strrchr( $file, '.' ) == '.rar' ) {
$imgSrc = $this->assets . '/treeview/zip.gif';
}
else {
$imgSrc = $this->assets . '/treeview/unknown.gif';
}
$childNode = new TreeNode( $file );
$childNode->textOrHtml = $file;
$childNode->imgSrc = $imgSrc;
$TreeNode->addChild( $childNode );
unset( $childNode );
}
}
}
}
closedir( $dir );
return $TreeNode;
}
}
return FALSE;
}
}
?> | true |
76bf0b8f89eb3f10b8c752594d150437c685613d | PHP | zyhwyl/whathebook | /app/models/UnitsTaskComplete.php | UTF-8 | 419 | 2.703125 | 3 | [] | no_license | <?php
class UnitsTaskComplete extends Eloquent{
public $table = 'units_task_complete';
public function registerDataInit($id,$task_id,$pub_user,$status){
$this->id=$id;
$this->task_id=$task_id;
$this->pub_user=$pub_user;
$this->status=$status;
}
public function task(){
return $this->belongsTo("CourseUnitTask","task_id");
}
public function user(){
return $this->belongsTo("User","pub_user");
}
} | true |
b342f1eabf8d279ac03102b7deba7088e26ada02 | PHP | vipxieliang/xieliangtest | /basic-master/protected/modules/mall/models/Item.php | UTF-8 | 13,767 | 2.65625 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/**
* This is the model class for table "{{item}}".
*
* The followings are the available columns in table '{{item}}':
* @property string $item_id
* @property string $category_id
* @property string $title
* @property string $sn
* @property string $unit
* @property integer $stock
* @property string $min_number
* @property string $market_price
* @property string $shop_price
* @property string $currency
* @property string $skus
* @property string $props
* @property string $props_name
* @property string $item_imgs
* @property string $prop_imgs
* @property string $pic_url
* @property string $desc
* @property string $location
* @property string $post_fee
* @property string $express_fee
* @property string $ems_fee
* @property integer $is_show
* @property integer $is_promote
* @property integer $is_new
* @property integer $is_hot
* @property integer $is_best
* @property integer $is_discount
* @property string $click_count
* @property integer $sort_order
* @property string $create_time
* @property string $update_time
* @property string $language
*/
class Item extends CActiveRecord {
/**
* Returns the static model of the specified AR class.
* @param string $className active record class name.
* @return Item the static model class
*/
public static function model($className = __CLASS__) {
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName() {
return '{{item}}';
}
/**
* @return array validation rules for model attributes.
*/
public function rules() {
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('title, min_number, desc, language, category_id', 'required'),
array('type_id, stock, is_show, is_promote, is_new, is_hot, is_best, is_discount, sort_order', 'numerical', 'integerOnly' => true),
array('category_id, market_price, shop_price, post_fee, express_fee, ems_fee', 'length', 'max' => 10),
array('title, pic_url', 'length', 'max' => 255),
array('sn', 'length', 'max' => 60),
array('unit, currency', 'length', 'max' => 20),
array('min_number', 'length', 'max' => 100),
array('location, language', 'length', 'max' => 45),
array('click_count, create_time, update_time', 'length', 'max' => 11),
array('skus, props, props_name, item_imgs, prop_imgs, desc', 'safe'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('item_id, category_id, title, sn, unit, stock, min_number, market_price, shop_price, currency, skus, props, props_name, item_imgs, prop_imgs, pic_url, desc, location, post_fee, express_fee, ems_fee, is_show, is_promote, is_new, is_hot, is_best, is_discount, click_count, sort_order, create_time, update_time, language', 'safe', 'on' => 'search'),
);
}
/**
* @return array relational rules.
*/
public function relations() {
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'category' => array(self::BELONGS_TO, 'Category', 'category_id'),
'image' => array(self::HAS_MANY, 'ItemImg', 'item_id'),
'type' => array(self::BELONGS_TO, 'ItemType', 'type_id'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels() {
return array(
'item_id' => 'ID',
'category_id' => '分类',
'category.name' => '分类',
'type_id' => '商品类型',
'title' => '商品标题',
'sn' => '商品货号',
'unit' => '计量单位',
'stock' => '库存',
'min_number' => '最少订货量',
'market_price' => '零售价',
'shop_price' => '批发价',
'currency' => '货币',
'skus' => '库存量单位',
'props' => '商品属性',
'props_name' => '商品属性名称',
'item_imgs' => '图片集',
'prop_imgs' => '属性图片集',
'pic_url' => '主图',
'desc' => '商品描述',
'location' => '商品所在地',
'post_fee' => '平邮费用',
'express_fee' => '快递费用',
'ems_fee' => 'Ems 费用',
'is_show' => '上架',
'is_promote' => '促销',
'is_new' => '新品',
'is_hot' => '热卖',
'is_best' => '精品',
'is_discount' => '会员打折',
'click_count' => '浏览次数',
'sort_order' => '排序',
'create_time' => '上架时间',
'update_time' => '更新时间',
'language' => '语言',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search() {
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria = new CDbCriteria;
$criteria->order = 'item_id desc, sort_order asc';
$criteria->compare('item_id', $this->item_id, true);
$criteria->compare('category_id', $this->category_id, true);
$criteria->compare('title', $this->title, true);
$criteria->compare('sn', $this->sn, true);
$criteria->compare('unit', $this->unit, true);
$criteria->compare('stock', $this->stock);
$criteria->compare('min_number', $this->min_number, true);
$criteria->compare('market_price', $this->market_price, true);
$criteria->compare('shop_price', $this->shop_price, true);
$criteria->compare('currency', $this->currency, true);
$criteria->compare('skus', $this->skus, true);
$criteria->compare('props', $this->props, true);
$criteria->compare('props_name', $this->props_name, true);
$criteria->compare('item_imgs', $this->item_imgs, true);
$criteria->compare('prop_imgs', $this->prop_imgs, true);
$criteria->compare('pic_url', $this->pic_url, true);
$criteria->compare('desc', $this->desc, true);
$criteria->compare('location', $this->location, true);
$criteria->compare('post_fee', $this->post_fee, true);
$criteria->compare('express_fee', $this->express_fee, true);
$criteria->compare('ems_fee', $this->ems_fee, true);
$criteria->compare('is_show', $this->is_show);
$criteria->compare('is_promote', $this->is_promote);
$criteria->compare('is_new', $this->is_new);
$criteria->compare('is_hot', $this->is_hot);
$criteria->compare('is_best', $this->is_best);
$criteria->compare('is_discount', $this->is_discount);
$criteria->compare('click_count', $this->click_count, true);
$criteria->compare('sort_order', $this->sort_order);
$criteria->compare('create_time', $this->create_time, true);
$criteria->compare('update_time', $this->update_time, true);
$criteria->compare('language', $this->language, true);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
public function getShow() {
echo $this->is_show == 1 ? CHtml::image(Yii::app()->request->baseUrl . '/images/yes.gif') : CHtml::image(Yii::app()->request->baseUrl . '/images/no.gif');
}
public function getPromote() {
echo $this->is_promote == 1 ? CHtml::image(Yii::app()->request->baseUrl . '/images/yes.gif') : CHtml::image(Yii::app()->request->baseUrl . '/images/no.gif');
}
public function getNew() {
echo $this->is_new == 1 ? CHtml::image(Yii::app()->request->baseUrl . '/images/yes.gif') : CHtml::image(Yii::app()->request->baseUrl . '/images/no.gif');
}
public function getHot() {
echo $this->is_hot == 1 ? CHtml::image(Yii::app()->request->baseUrl . '/images/yes.gif') : CHtml::image(Yii::app()->request->baseUrl . '/images/no.gif');
}
public function getBest() {
echo $this->is_best == 1 ? CHtml::image(Yii::app()->request->baseUrl . '/images/yes.gif') : CHtml::image(Yii::app()->request->baseUrl . '/images/no.gif');
}
public function getDiscount() {
echo $this->is_discount == 1 ? CHtml::image(Yii::app()->request->baseUrl . '/images/yes.gif') : CHtml::image(Yii::app()->request->baseUrl . '/images/no.gif');
}
public function beforeSave() {
if (parent::beforeSave()) {
if ($this->isNewRecord) {
$this->create_time = $this->update_time = time();
}
else
$this->update_time = time();
return true;
}
else
return false;
}
/**
* 得到商品标题
* @return type
*/
public function getTitle() {
return CHtml::link(F::msubstr($this->title, '0', '40', 'utf-8'), array('/item/view', 'id' => $this->item_id), array('title' => $this->title));
}
/**
* 得到商品URL地址
* @return string the URL that shows the detail of the item
*/
public function getUrl() {
if (F::utf8_str($this->title) == '1') {
$title = str_replace('/', '-', $this->title);
} else {
$pinyin = new Pinyin($this->title);
$title = $pinyin->full2();
$title = str_replace('/', '-', $title);
}
return Yii::app()->createUrl('item/view', array(
'id' => $this->item_id,
'title' => $title,
));
}
/**
* 得到购物收藏按钮
* @return type
*/
public function getBtnList() {
return CHtml::textField('qty', $this->min_number, array('style' => 'width:20px', 'size' => '2', 'maxlength' => '5', 'id' => 'qty_' . $this->item_id)) . ' '
. CHtml::link(CHtml::image(Yii::app()->request->baseUrl . '/images/btn_buy.gif'), '#', array('id' => 'btn-buy-' . $this->item_id, 'onclick' => 'fastBuy(this, ' . $this->item_id . ', $("#qty_' . $this->item_id . '").val())'
))
. ' ' . CHtml::link(CHtml::image(Yii::app()->request->baseUrl . '/images/btn_addwish.gif'), '#', array('id' => 'btn-addwish-' . $this->item_id, 'onclick' => 'addWish(this, ' . $this->item_id . ')'
));
}
/**
* 得到商品主图路径
* @return type
*/
public function getMainPicPath() {
$images = ItemImg::model()->findAllByAttributes(array('item_id' => $this->item_id));
foreach ($images as $k => $v) {
if ($v['position'] == 0) {
return '/upload/item/image/' . $v['url'];
}
}
}
/**
* 得到商品主图Url地址
* @return type
*/
public function getMainPicUrl() {
$img = $this->getMainPicPath();
if (file_exists(dirname(F::basePath()) . $img)) {
return F::baseUrl() . $this->getMainPicPath();
} else {
return $this->getHolderJs('350', '350');
}
}
/**
* 得到HolderJs
* @param type $width
* @param type $height
* @return type
*/
public function getHolderJs($width = '150', $height = '150', $text = 'No Picture') {
return 'holder.js/' . $width . 'x' . $height . '/text:' . $text;
}
/**
* 得到商品主图
* @return type
*/
public function getMainPic() {
$img = $this->getMainPicPath();
if (file_exists(dirname(F::basePath()) . $img)) {
$img_thumb = F::baseUrl() . ImageHelper::thumb(310, 310, $img, array('method' => 'resize'));
$img_thumb_now = CHtml::image($img_thumb, $this->title);
return CHtml::link($img_thumb_now, array('/item/view', 'id' => $this->item_id), array('title' => $this->title));
} else {
return CHtml::link(CHtml::image($this->getHolderJs('310', '310')), $this->getUrl(), array('title' => $this->title));
}
}
/**
* 得到商品小图,显示于购物车中
* @return type
*/
public function getSmallThumb() {
$img = $this->getMainPicPath();
if (file_exists(dirname(F::basePath()) . $img)) {
$img_thumb = F::baseUrl() . ImageHelper::thumb(50, 50, $img, array('method' => 'resize'));
$img_thumb_now = CHtml::image($img_thumb, $this->title);
return CHtml::link($img_thumb_now, array('/item/view', 'id' => $this->item_id), array('title' => $this->title));
} else {
return CHtml::link(CHtml::image($this->getHolderJs('50', '50')), $this->getUrl(), array('title' => $this->title));
}
}
/**
* 得到商品推荐缩略图
* @return type
*/
public function getRecommendThumb() {
$img = $this->getMainPicPath();
if (file_exists(dirname(F::basePath()) . $img)) {
$img_thumb = F::baseUrl() . ImageHelper::thumb(80, 80, $img, array('method' => 'resize'));
$img_thumb_now = CHtml::image($img_thumb, $this->title);
return CHtml::link($img_thumb_now, array('/item/view', 'id' => $this->item_id), array('title' => $this->title));
} else {
return CHtml::link(CHtml::image($this->getHolderJs('80', '80')), $this->getUrl(), array('title' => $this->title));
}
}
/**
* 得到商品列表缩略图
* @return type
*/
public function getListThumb() {
$img = $this->getMainPicPath();
if (file_exists(dirname(F::basePath()) . $img)) {
$img_thumb = F::baseUrl() . ImageHelper::thumb(150, 150, $img, array('method' => 'resize'));
$img_thumb_now = CHtml::image($img_thumb, $this->title);
return CHtml::link($img_thumb_now, array('/item/view', 'id' => $this->item_id), array('title' => $this->title));
} else {
return CHtml::link(CHtml::image($this->getHolderJs('150', '150')), $this->getUrl(), array('title' => $this->title));
}
}
/**
* 得到最近商品缩略图
* @return type
*/
public function getRecentThumb() {
$img = $this->getMainPicPath();
if (file_exists(dirname(F::basePath()) . $img)) {
$img_thumb = F::baseUrl() . ImageHelper::thumb(210, 210, $img, array('method' => 'resize'));
$img_thumb_now = CHtml::image($img_thumb, $this->title);
return CHtml::link($img_thumb_now, array('/item/view', 'id' => $this->item_id), array('title' => $this->title));
} else {
return CHtml::link(CHtml::image($this->getHolderJs('210', '210')), $this->getUrl(), array('title' => $this->title));
}
}
} | true |
eb167dbe58766691828fe61c7ea75bc2bc1b2a48 | PHP | jasonwatt/SMParser | /src/Traits/Song/Subtitle.php | UTF-8 | 762 | 3.015625 | 3 | [
"MIT"
] | permissive | <?php
namespace Zanson\SMParser\Traits\Song;
use Zanson\SMParser\SMException;
/**
* This text will appear underneath the main title of the
* song on the Select Music screen. e.g. "~Dirty Mix~" or "(remix)".
*
* Class Subtitle
*
* @package Zanson\SMParser\Traits\Song
*/
trait Subtitle
{
public $subtitle = '';
/**
* @return string
*/
public function getSubtitle() {
return $this->subtitle;
}
/**
* @param string $subtitle
*
* @return $this
* @throws SMException
*/
public function setSubtitle($subtitle) {
if (!is_string($subtitle)) {
throw new SMException("Subtitle must be a string");
}
$this->subtitle = $subtitle;
return $this;
}
} | true |
599507100709b2f0b782c3da67c156e457f92726 | PHP | reliv/rcm-php | /switch-user/src/Acl/DoesAclSayUserCanSU.php | UTF-8 | 708 | 2.671875 | 3 | [
"ISC"
] | permissive | <?php
namespace Rcm\SwitchUser\Acl;
use Rcm\Acl\AclActions;
use Rcm\Acl\IsAllowedByUser;
class DoesAclSayUserCanSU
{
protected $isAllowedByUser;
public function __construct(IsAllowedByUser $isAllowedByUser)
{
$this->isAllowedByUser = $isAllowedByUser;
}
/**
* Returns true if ACL says given user can SU. This does not mean the user should be allowed to though as there
* are other restrictions other than ACL that must be taken into account before allowing a user to SU.
*
* @return bool
*/
public function __invoke($user): bool
{
return $this->isAllowedByUser->__invoke(AclActions::EXECUTE, ['type' => 'switchUser'], $user);
}
}
| true |
c97750c82f73005b1dfc446580c119664ee397e5 | PHP | LukasSeglias/ticket-recognition-web | /public_html/components/tours/tours.php | UTF-8 | 1,227 | 2.828125 | 3 | [] | no_license | <?php
namespace CTI;
require_once './components/page.php';
class TourSearchPage implements Page {
private $context;
private $state;
function __construct($context) {
$this->context = $context;
}
public function update() {
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$description = strip_tags($_POST['description']);
$code = strip_tags($_POST['code']);
$filter = new TourSearchPageFilter($code, $description);
$results = $this->context->tourRepository()->findBy($filter->code, $filter->description);
$this->state = new TourSearchPageState($results, $filter);
} else {
$this->state = new TourSearchPageState([], new TourSearchPageFilter(NULL, NULL));
}
}
public function template() : string {
return 'tours/tours.html';
}
public function context() : array {
return [
'state' => $this->state
];
}
}
class TourSearchPageState {
public $items;
public $filter;
function __construct(array $items, TourSearchPageFilter $filter) {
$this->items = $items;
$this->filter = $filter;
}
}
class TourSearchPageFilter {
public $code;
public $description;
function __construct($code, $description) {
$this->code = $code;
$this->description = $description;
}
}
?> | true |
70cc1915336d31a631463ce013869b165ec444be | PHP | shayrm/PHP_backup_course | /PhpCourse/PhPCourseSession_05/Ses5_upload_file.php | UTF-8 | 1,148 | 2.859375 | 3 | [] | no_license | <?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//var_dump($_FILES);
if (!empty($_FILES["file_name"]["name"]))
{
$C_folder= getcwd();
$file_name=$_FILES["file_name"]["name"];
$file_temp=$_FILES["file_name"]["tmp_name"];
$path="c:\Temp";
chdir("c:\Temp");
$D_file = $file_name;
$D_folder=getcwd();
echo "<br>File name to upload is <h4>$file_name</h4>";
echo "<br> The current folder we use is <h4>$C_folder</h4>";
echo "<br> The file will be copy to: <h3>$D_folder</h3>";
echo "<hr>";
if(move_uploaded_file($file_temp, $D_file)){
echo "<br> The file was successfuly copy to the new location";
echo "<br>File name was: $file_name <br>and directory was $D_folder";
}
else {
echo "<br>There was a problem with copying the file";
echo "<br>File name was: $file_name <br>and directory was $D_file";
}
}
else {
echo "Error - No file was choosen";
}
?> | true |
83cfd2547674acaac7be2454d30b255e64ba8e72 | PHP | illuminate/process | /FakeProcessDescription.php | UTF-8 | 5,151 | 3.328125 | 3 | [
"MIT"
] | permissive | <?php
namespace Illuminate\Process;
use Symfony\Component\Process\Process;
class FakeProcessDescription
{
/**
* The process' ID.
*
* @var int|null
*/
public $processId = 1000;
/**
* All of the process' output in the order it was described.
*
* @var array
*/
public $output = [];
/**
* The process' exit code.
*
* @var int
*/
public $exitCode = 0;
/**
* The number of times the process should indicate that it is "running".
*
* @var int
*/
public $runIterations = 0;
/**
* Specify the process ID that should be assigned to the process.
*
* @param int $processId
* @return $this
*/
public function id(int $processId)
{
$this->processId = $processId;
return $this;
}
/**
* Describe a line of standard output.
*
* @param array|string $output
* @return $this
*/
public function output(array|string $output)
{
if (is_array($output)) {
collect($output)->each(fn ($line) => $this->output($line));
return $this;
}
$this->output[] = ['type' => 'out', 'buffer' => rtrim($output, "\n")."\n"];
return $this;
}
/**
* Describe a line of error output.
*
* @param array|string $output
* @return $this
*/
public function errorOutput(array|string $output)
{
if (is_array($output)) {
collect($output)->each(fn ($line) => $this->errorOutput($line));
return $this;
}
$this->output[] = ['type' => 'err', 'buffer' => rtrim($output, "\n")."\n"];
return $this;
}
/**
* Replace the entire output buffer with the given string.
*
* @param string $output
* @return $this
*/
public function replaceOutput(string $output)
{
$this->output = collect($this->output)->reject(function ($output) {
return $output['type'] === 'out';
})->values()->all();
if (strlen($output) > 0) {
$this->output[] = [
'type' => 'out',
'buffer' => rtrim($output, "\n")."\n",
];
}
return $this;
}
/**
* Replace the entire error output buffer with the given string.
*
* @param string $output
* @return $this
*/
public function replaceErrorOutput(string $output)
{
$this->output = collect($this->output)->reject(function ($output) {
return $output['type'] === 'err';
})->values()->all();
if (strlen($output) > 0) {
$this->output[] = [
'type' => 'err',
'buffer' => rtrim($output, "\n")."\n",
];
}
return $this;
}
/**
* Specify the process exit code.
*
* @param int $exitCode
* @return $this
*/
public function exitCode(int $exitCode)
{
$this->exitCode = $exitCode;
return $this;
}
/**
* Specify how many times the "isRunning" method should return "true".
*
* @param int $iterations
* @return $this
*/
public function iterations(int $iterations)
{
return $this->runsFor(iterations: $iterations);
}
/**
* Specify how many times the "isRunning" method should return "true".
*
* @param int $iterations
* @return $this
*/
public function runsFor(int $iterations)
{
$this->runIterations = $iterations;
return $this;
}
/**
* Turn the fake process description into an actual process.
*
* @param string $command
* @return \Symfony\Component\Process\Process
*/
public function toSymfonyProcess(string $command)
{
return Process::fromShellCommandline($command);
}
/**
* Conver the process description into a process result.
*
* @param string $command
* @return \Illuminate\Contracts\Process\ProcessResult
*/
public function toProcessResult(string $command)
{
return new FakeProcessResult(
command: $command,
exitCode: $this->exitCode,
output: $this->resolveOutput(),
errorOutput: $this->resolveErrorOutput(),
);
}
/**
* Resolve the standard output as a string.
*
* @return string
*/
protected function resolveOutput()
{
$output = collect($this->output)
->filter(fn ($output) => $output['type'] === 'out');
return $output->isNotEmpty()
? rtrim($output->map->buffer->implode(''), "\n")."\n"
: '';
}
/**
* Resolve the error output as a string.
*
* @return string
*/
protected function resolveErrorOutput()
{
$output = collect($this->output)
->filter(fn ($output) => $output['type'] === 'err');
return $output->isNotEmpty()
? rtrim($output->map->buffer->implode(''), "\n")."\n"
: '';
}
}
| true |
2472e31c2c44c508cc35dae7ec25fb308210e8d9 | PHP | Mohan-Patidar/Admin-and-user-login-in-php-and-mysql-database- | /user/adminlogin.php | UTF-8 | 1,511 | 2.625 | 3 | [] | no_license | <?php
include "dbcon.php";
session_start();
if(isset($_SESSION['user'])){
header("location: adminlogin.php");
}?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin</title>
</head>
<body>
<h1>Admin login</h1>
<form method="POST">
<?php if (isset($name_error)){?>
<p><?php echo $name_error?><p>
<?php }?>
Username:<input type="text" name="username" placeholder="Username" /><br>
Password:<input type="password" name="password" placeholder="Password"><br>
<input type="submit" name="login" value="Login">
</form>
<?php
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT id FROM admin WHERE name = '$username' and password = '$password'";
$result = mysqli_query($conn,$sql);
$row = mysqli_num_rows($result);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$active = $row['active'];
$count = mysqli_num_rows($result);
if ($count==1) {
session_register("username");
$_SESSION['name'] = $username;
header("location: retrieve.php");
}
else{
$name_error = "Your Login Name or Password is invalid";
header("location: adminlogin.php");
}
}
?>
<a href='index.php'>Back</a>
</body>
</html> | true |
2d4cc7221bc77580d2865694f8673e992d95d364 | PHP | npush/company | /shell/fixProductDescription.php | UTF-8 | 2,875 | 2.5625 | 3 | [] | no_license | <?php
/**
* Created by nick
* Project magento1.dev
* Date: 11/23/16
* Time: 11:44 AM
*/
require_once 'abstract.php';
class Mage_Shell_FixProductDescription extends Mage_Shell_Abstract{
/**
* Run script
*
*/
public function run(){
$this->fixDescriptionR('tooltops');
}
public function fixDescription(){
$count = 0;
$productIds = Mage::getModel('catalog/product')->getCollection()->getAllIds();
$product = Mage::getModel('catalog/product');
/** @var $product Mage_Catalog_Model_Product */
foreach($productIds as $productId){
try {
$product->load($productId);
$description = $product->getData('description');
//$description = preg_replace('/(<p><\/p>[\n\r]*)*/u','', $description);
$description = preg_replace('/<p><\/p>/u', '', $description);
$description = preg_replace('/[\n\r]{2,}/u', '', $description);
$product->setData('short_description', $description);
$product->setData('description', $description);
$product->save();
printf("Saved modified product: %s \n", $product->getSku());
$count++;
}catch (Mage_Core_Exception $e){
Mage::logException($e->getMessage());
}
}
printf("Modified %s products \n", $count);
}
public function fixDescriptionR(){
$collection = Mage::getResourceModel('catalog/product_collection')->addAttributeToSelect('description');
foreach($collection as $item) {
$productId = (int)$item->getId();
$description = $item->getDescription();
$description = preg_replace('/<p><\/p>/u', '', $description);
$description = preg_replace('/[\n\r]{2,}/u', '', $description);
$description = addslashes($description);
$resource = Mage::getSingleton('core/resource');
$writeConnection = $resource->getConnection('core_write');
$table = $resource->getTableName('catalog/product');
$query = "UPDATE `catalog_product_entity_text` SET VALUE = '{$description}' WHERE entity_id = '{$productId}' AND attribute_id = 73";
$writeConnection->query($query);
$query = "UPDATE `catalog_product_entity_text` SET VALUE = '{$description}' WHERE entity_id = '{$productId}' AND attribute_id = 72";
$writeConnection->query($query);
printf("Product : %s \n", $productId);
}
}
/**
* Retrieve Usage Help Message
*
*/
public function usageHelp()
{
return <<<USAGE
Usage: php -f FixProductDescription.php -- [options]
help This help
USAGE;
}
}
$shell = new Mage_Shell_FixProductDescription();
$shell->run(); | true |
af9652c300f454be85a89ec5a96d0f113a60a970 | PHP | aswitzer/oauth1 | /src/Signature/SignerInterface.php | UTF-8 | 579 | 2.984375 | 3 | [
"MIT"
] | permissive | <?php
namespace Risan\OAuth1\Signature;
interface SignerInterface
{
/**
* Get signer method name.
*
* @return string
*/
public function getMethod();
/**
* Check if the signer is key based.
*
* @return bool
*/
public function isKeyBased();
/**
* Create a signature for given request parameters.
*
* @param string $uri
* @param array $parameters
* @param string $httpMethod
*
* @return string
*/
public function sign($uri, array $parameters = [], $httpMethod = 'POST');
}
| true |
a4516780c740c22b3eec29b784b2c6900007e55f | PHP | ZacharyVasey/Internet_Software-Development_Project | /php/paymentinformation.php | UTF-8 | 1,568 | 2.671875 | 3 | [] | no_license | <?php
session_start();
$cardType=$_POST['paymentSelect'];
$cardNum=$_POST['cardNumberTxt'];
$date=$_POST['cardExpirationTxt'];
$userID = $_SESSION['userId'];
<<<<<<< HEAD
$productId = $_SESSION['cart']['1']['productId'];
$units = $_SESSION['cart']['1']['units'];
$totalPrice = $_POST['total'];
=======
>>>>>>> 2e2d8b91ed82376f6af28c57af69f000bd4e1300
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "cs3320";
//Connection
$conn = new mysqli($servername, $username, $password, $dbname);
//Error check
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
<<<<<<< HEAD
$sql1 = "INSERT INTO paymentinformation (userId, cardType, cardNumber, expDate) VALUES ('$userID', '$cardType', '$cardNum', '$date') ON DUPLICATE KEY UPDATE
cardType = '$cardType', cardNumber = '$cardNum', expDate = '$date'";
$sql2 = "INSERT INTO orders (userId, productId, quantity, totalPrice) VALUES ('$userID', '$productId', '$units', '$totalPrice')";
if($conn->query($sql1) === TRUE){
if($conn->query($sql2) === TRUE){
include("../html/ThankYou.html");
$_SESSION['cart']=array(array());
}
=======
$sql = "INSERT INTO paymentinformation (userId, cardType, cardNumber, expDate) VALUES ('$userID', '$cardType', '$cardNum', '$date') ON DUPLICATE KEY UPDATE
cardType = '$cardType', cardNumber = '$cardNum', expDate = '$date'";
if($conn->query($sql) === TRUE){
include("../html/ThankYou.html");
>>>>>>> 2e2d8b91ed82376f6af28c57af69f000bd4e1300
}
else{
echo "failed to write to database" . $conn->error;
}
/////$conn->close();
?> | true |
dfe4cad2cb53fef734eff06beb4d8a0f1e1cb748 | PHP | Vald0/la_huerta | /pruebas.php | UTF-8 | 2,546 | 3.359375 | 3 | [] | no_license | <!DOCTYPE html>
<html lang="es">
<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>La Huerta</title>
</head>
<body>
<?php
$productos = ($_GET["objectTicket"]);
$obj = json_decode($productos, true);
foreach ($obj as $k=>$v){
echo($obj[$k]['nombre']." $".$obj[$k]['precio']." /".$obj[$k]['unidad']."<br>"); // etc.
}
// for ($i = 1; $i <= count($obj); $i++) {
// echo($obj[i]['nombre'].$obj[i]['precio'].$obj[i]['unidad']);
// }
class MiClase
{
public $var1 = 'valor 1';
public $var2 = 'valor 2';
public $var3 = 'valor 3';
protected $protected = 'variable protegida';
private $private = 'variable privada';
function iterateVisible() {
echo "MiClase::iterateVisible:\n";
foreach ($this as $clave => $valor) {
print "$clave => $valor\n";
}
}
}
$clase = new MiClase();
foreach($clase as $clave => $valor) {
print "$clave => $valor\n";
}
echo "\n";
$clase->iterateVisible();
$amigos = array (array("nombre"=>"Pedro Torres", "direccion" =>"CL Mayor, 37","telefono"=>"8787907229"),
array("nombre"=>"fernando pascal", "direccion" =>"Enrique segoviano","telefono"=>"5807445"),
array("nombre"=>"edlein vaszques", "direccion" =>"Mar del norte","telefono"=>"8787907229"),
array("nombre"=>"edlein vaszques", "direccion" =>"Mar del norte","telefono"=>"8787907229"));
echo ("<table border='2' cellpadding='2' cellspacing='0'>");
echo("<tr>");
echo("<th>Numero</th>");
echo("<th>Nombre</th>");
echo("<th>Direccion</th>");
echo("<th>Telefono</th>");
echo("</tr>");
echo("<tr>");
echo("<td>0</td>");
echo("<td>".$amigos[0]["nombre"]."</td>");
echo("<td>".$amigos[0]["direccion"]."</td>");
echo("<td>".$amigos[0]["telefono"]."</td>");
echo("</tr>");
echo("<tr>");
echo("<td>1</td>");
echo("<td>".$amigos[1]["nombre"]."</td>");
echo("<td>".$amigos[1]["direccion"]."</td>");
echo("<td>".$amigos[1]["telefono"]."</td>");
echo("</tr>");echo("<tr>");
echo("<td>1</td>");
echo("<td>".$amigos[2]["nombre"]."</td>");
echo("<td>".$amigos[2]["direccion"]."</td>");
echo("<td>".$amigos[2]["telefono"]."</td>");
echo("</tr>");
echo("<tr>");
echo("<td>1</td>");
echo("<td>".$amigos[3]["nombre"]."</td>");
echo("<td>".$amigos[3]["direccion"]."</td>");
echo("<td>".$amigos[3]["telefono"]."</td>");
echo("</tr>");
echo("</table>");
?>
</body>
</html> | true |
17b9017819a59c24f2de3eb33869a07417dc5428 | PHP | wangchlxt/Swarm | /module/Application/src/Application/View/Helper/Utf8Filter.php | UTF-8 | 2,271 | 2.8125 | 3 | [] | no_license | <?php
/**
* Perforce Swarm
*
* @copyright 2013-2018 Perforce Software. All rights reserved.
* @license Please see LICENSE.txt in top-level readme folder of this distribution.
* @version 2017.4/1623486
*/
namespace Application\View\Helper;
use P4\Filter\Utf8;
use P4\Validate\MultibyteString;
use Zend\View\Helper\AbstractHelper;
class Utf8Filter extends AbstractHelper
{
protected $utf8Filter = null;
/**
* Filter utf-8 input, invalid UTF-8 byte sequences will be replaced with
* an inverted question mark.
*
* @param string|null $value the utf-8 input to filter
* @returns string the filtered result
*/
public function __invoke($value)
{
$this->utf8Filter = $this->utf8Filter ?: new Utf8;
return $this->utf8Filter->filter($value);
}
/**
* Convert the string into UTF8 and encode into json
*
* @param string $contents the content that couldn't be encode.
* @return json_encode The converted content and encoded into json
*/
public function convertToUTF8($contents)
{
// Attempt to json encode the content.
$expanded = json_encode($contents);
// build the jsonError array and added additional one if they exist.
$jsonErrors = array(JSON_ERROR_CTRL_CHAR, JSON_ERROR_UTF8);
if (defined('JSON_ERROR_UNSUPPORTED_TYPE')) {
$jsonErrors[] = JSON_ERROR_UNSUPPORTED_TYPE;
}
if (defined('JSON_ERROR_UTF16')) {
$jsonErrors[] = JSON_ERROR_UTF16;
}
$lastJsonError = json_last_error();
if (in_array($lastJsonError, $jsonErrors)) {
// Don't know whether other errors need to be circumvented
$converted = array();
foreach ($contents as $line => $content) {
// Convert content into multi byte encoding.
$converted[$line] = MultibyteString::convertEncoding($content, 'UTF-8');
}
if (defined('JSON_PARTIAL_OUTPUT_ON_ERROR')) {
$expanded = json_encode($converted, JSON_PARTIAL_OUTPUT_ON_ERROR);
} else {
$expanded = json_encode($converted);
}
}
return $expanded;
}
}
| true |
cb28b344f02b3961dcc28164b346b0e563f34fa1 | PHP | jkunggit/webcrawler_api | /config/routes.php | UTF-8 | 1,083 | 2.546875 | 3 | [] | no_license | <?php
use MyCrawler\CurlMultiCrawler;
//use Phalcon\Config;
$app->get('/api/crawler', function() use ($app, $config){
$url = $app->request->getQuery('url');
// make sure the url is provided
$url_parsed = parse_url($url);
$max_curls = 10;
if($url_parsed){
if($url_parsed["host"] == "agencyanalytics.com"){
$max_curls = 200;
}
if ( !isset($url_parsed["scheme"]) )
{
$url = "http://{$url}";
}
}
if (filter_var($url, FILTER_VALIDATE_URL) === FALSE) {
echo json_encode(array("error"=>"Invalid url!"));
}
else{
// only allow api call from our domain
header('Access-Control-Allow-Origin: '.$config['allowOriginUrls']);
header('Content-Type: application/json');
$crawler = new CurlMultiCrawler($max_curls, true);
$crawler->init_crawl_link($url);
echo json_encode($crawler->getPageCrawlData());
//$crawler->dump($crawler->getPageCrawlData());
// output what is already saved for faster developement
//sleep(1);
// echo file_get_contents( API_PATH . "/config/output.json");
}
}); | true |
f642ebf5bcccfe6be949da0784dee36363d28014 | PHP | mamogmx/pagopa.test | /inviarichiesta.php | UTF-8 | 2,328 | 2.53125 | 3 | [] | no_license | <?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
error_reporting(E_ERROR);
require_once "config.php";
$d = $_REQUEST["richiesta"];
if (!$d){
$result["error"] = Array("NO DATA");
header('Content-Type: application/json; charset=utf-8');
print json_encode($result);
die();
};
$data = json_decode($d,TRUE);
debug('REQUEST.txt',$data);
$iuv = randomKey(32);
$keys = Array("iuv");
$values = Array($iuv);
$fValues = Array("?");
$sqlRichiesta = "INSERT INTO richiesta(%s) VALUES(%s);";
$sqlPagamento = "INSERT INTO pagamenti(%s) VALUES(%s);";
$j = 0;
foreach($data as $k=>$v){
if (in_array($k,array_keys($richiesta))){
$keys[] = $richiesta[$k];
$values[] = $v;
$fValues[] = "?";
}
if ($k == "listaDatiSingoloPagamento" && is_array($v)){
debug('PAGAMENTI',$v);
for($j=0;$j<count($v);$j++){
$keysP[$j] = Array("iuv");
$valuesP[$j] = Array($iuv);
$fValuesP[$j] = Array("?");
foreach($v[$j] as $kk=>$vv){
$keysP[$j][] = $pagamenti[$kk];
$valuesP[$j][] = $vv;
$fValuesP[$j][] = "?";
}
}
}
}
debug('FIELDS.text',$keysP);
debug('FIELDS.text',$valuesP);
$result = Array("iuv" => $iuv);
$dbh = getDb();
$fields = implode(",",$keys);
$sql = sprintf($sqlRichiesta,$fields,implode(",",$fValues));
debug('SQL.text', $sql);
$stmt = $dbh->prepare($sql);
if (count($values)){
if(!$stmt->execute($values)){
$result["error"][] = "Errore nella Query $sqlRichiesta";
$result["error"][] = $stmt->errorInfo();
unset($result["iuv"]);
}
else{
foreach($keysP as $k => $v){
$sql = sprintf($sqlPagamento,implode(",",$v),implode(",",$fValuesP[$k]));
debug('SQL.text', $sql);
$stmt = $dbh->prepare($sql);
debug('VALUES.text', $valuesP[$k]);
if(!$stmt->execute($valuesP[$k])){
$result["error"][] = $stmt->errorInfo();
}
}
}
}
else{
$result["error"] = Array("NO DATA");
}
header('Content-Type: application/json; charset=utf-8');
print json_encode($result);
| true |
0de29cf5c5b2e3f12f73df94295a4c33b91e67bf | PHP | jeepin95/derbynet | /website/ajax/query.settings.inc | UTF-8 | 331 | 2.515625 | 3 | [
"MIT"
] | permissive | <settings>
<?php
$stmt = $db->prepare('SELECT itemkey, itemvalue FROM RaceInfo');
$stmt->execute(array());
foreach ($stmt as $row) {
echo ' <setting key=\''.htmlspecialchars($row['itemkey'], ENT_QUOTES, 'UTF-8').'\'>';
echo htmlspecialchars($row['itemvalue'], ENT_QUOTES, 'UTF-8');
echo '</setting>'."\n";
}
?>
</settings>
| true |
0272636b9c7be3bfc3d2a784855c0c53301dcdb6 | PHP | olesiavm/yii2-currency | /src/SiteRbc.php | UTF-8 | 1,045 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
namespace olesiavm\currency;
use yii\web\NotFoundHttpException;
class SiteRbc extends Site
{
const RBC_EUR = "EUR";
const RBC_USD = "USD";
/**
* Get url for parsing
*
* @param string $day
* @param string $currency
* @return string
*/
public function getUrl($day, $currency) {
$day = date("Y-m-d", strtotime($day));
$url = "https://cash.rbc.ru/cash/json/converter_currency_rate/?currency_from=" . $currency ."¤cy_to=RUR&source=cbrf&sum=1&date=" . $day;
return $url;
}
/**
* from rbc
*
* @param string $currency
* @param string $responseString
* @return string
* @throws NotFoundHttpException
*/
public function getCourseFromSite($currency, $responseString) {
$responseArray = \json_decode($responseString);
if ($responseArray->data->sum_result !== null) {
return $responseArray->data->sum_result;
}
throw new NotFoundHttpException('Rbc API data is changed');
}
}
| true |
01bcc9c42fbad4b0c82f5d47c886540c283957d5 | PHP | hb08/ASSL | /gmgrotto/app/controllers/CharController.php | UTF-8 | 28,674 | 3.15625 | 3 | [
"MIT"
] | permissive | <?php
class CharController extends Controller {
public function ran(){
// Get desired power level
$pl = Input::get('pl');
// PowerPoints Min
$min = $pl * 15;
// PowerPoints Max
$max = (($pl + 1) * 15)-1;
// Random from middle
$pp = User::rollDice($min, $max);
$miscArray = array();
// Functions
// Check Max Range
function checkMax($type, $check, $pl){
$max = 0;
$m = "";
if($type == 'attack' || $type == 'powers' || $type == 'defense' || $type == 'tough'|| $type == 'feats'){
$max = $pl;
}
if($type == 'comb/save' || $type == 'skills' || $type == 'abil'){
$max = $pl + 5;
}
if($check <= $max){
$m = "Pass";
}else {
$m = "Fail";
}
return $m;
}
// Check True
function checkTrue($check, $against){
if($check == $against){
return True;
}else { return False; }
}
// Get breakdown of how points will be spent.
function breakDown($type, $pp, $catList, $pl){
// Get initial count from list length
$cat = count($catList);
// Hold any exceptions to the lists
$exceptions = array();
// Divvy up a percentage to each category initially
if($type == 'base'){
$base = ceil($pp/10);
}else{
$base = 0;
}
$currentPP = $pp - ($base * $cat);
$resultsArray = array();
$misc = array();
$result = "";
// Loop to assign any remaining points
for($i = 0; $i < $currentPP; $i++ ){
// Check Types
if($type=='powers'){ // If it's a power type
$enough = $currentPP - $i;
$cost = DB::select('SELECT power_name, power_cost, no_rank FROM powersList;');
$roll = User::rollDice(0, $cat-1);
$testResult = $catList[$roll];
$except = 0;
$testCost = $cost[$roll]->power_cost;
// Do a quick check against exceptions
foreach($exceptions as $e){
// If this is an exception
if($e == $testResult){
// Add to counter
$except += 1;
}
}
// If there is not an exception
if($except == 0 && $enough >= $testCost){
$i = $i + $testCost - 1;
$result = $catList[$roll];
if($cost[$roll]->no_rank == 1){
array_push($exceptions, $result);
}
}else{
$i= $i-1;
$result = "";
}
if($enough == 0){
$i = $currentPP;
}
}elseif($type == 'feats' ){ // If it's a Feats type
$enough = $currentPP - $i;
$times = DB::select('SELECT feat_name, multiple FROM featsList;');
$roll = User::rollDice(0, $cat-1);
$testResult = $catList[$roll];
$except = 0;
// Check exceptions
foreach($exceptions as $e){
// If an exception
if($e == $testResult){
$except +=1;
}
}
// If no exception and it is worth the cost (Exclude sidekick as option due to constraints of making secondary lesser character)
if($except == 0 && $enough > 0 && $testResult != 'Sidekick'){
$result = $catList[$roll];
$testMultiple = $times[$roll]->multiple;
if($testMultiple == '0'){ // If you can't use it multiple times
array_push($exceptions, $result);
}
}else{
$i = $i-1;
$result = "";
}
}elseif($type == 'comb/save'){ // If it's a combat/save type
// Check how many points are left
$enough = $currentPP - $i;
// If there are 2+ points left
if($enough >= 2){
// Roll the full range
$roll = User::rollDice(0, ($cat-1));
$result = $catList[$roll];
// If you roll a 0 or 1
if($roll <2){
// Add an extra point to the i counter
$i += 1;
}
// If there are less than 2 points
}else{
// Only roll for 2+
$roll = User::rollDice(2, ($cat-1));
$result = $catList[$roll];
}
}else{ // Otherwise
// Roll full range
$roll = User::rollDice(0, ($cat-1));
$result = $catList[$roll];
}
if(!empty($result)){
array_push($resultsArray, $result);
}
}
// Array to hold final breakdown
$m = array();
// ReRoll Counter
$reRoll = 0;
// Cycle through list of categories, assigning points appropriately
foreach($catList as $c){
$basePoints = $base;
$newPoints = 0;
$mArray = array();
// Cycle through results array to give new points.
foreach($resultsArray as $r){
// if result is the same as this category
if($r == $c){
$newPoints +=1;
}
}
// Get new Total
$newTotal = $newPoints + $basePoints;
if($type=='abil'){
$fullTotal = 10 + $newTotal;
$modTotal = floor($newTotal/2);
$m = array_add($m, $c, $fullTotal, $modTotal);
}elseif($c == 'defense'){
$fullTotal = 10 + $newTotal;
$m = array_add($m, $c, $fullTotal);
}elseif($type != 'base' && $newTotal > 0){
// Check to see if this exceeds max
if(checkMax($type, $newTotal, $pl) == 'Pass'){
// If it does, add 10 for ability, add it to the array
if($type == 'abil'){
$fullTotal = 10 + $newTotal;
$modTotal = floor($newTotal/2);
$m = array_add($m, $c, $fullTotal, $modTotal);
// Otherwise times by 4 for skills
}elseif($type == 'skills'){
$total = $newTotal * 4;
$m = array_add($m, $c, $total);
// Otherwise add to array as is
}else{// If it does, add it to the array
$m = array_add($m, $c, $newTotal);
}
}else {
// If not, add to reRoll counter and create exception for this one
$reRoll +=1;
array_push($exceptions, $c);
}
}else{
if($newTotal > 1){
$m = array_add($m, $c, $newTotal); }
}
}
for($i = 0; $i < $reRoll; $i++ ){
$roll = User::rollDice(0,4);
$result = $catList[$roll];
foreach($exceptions as $e){
if(checkTrue($result, $e)){
$i = $i-1;
}else{
array_push($resultsArray, $result);
}
}
}
return $m;
}
// List of things to go through
$breakList = ['abil', 'comb/save', 'skills', 'feats', 'powers'];
// Breakdown overarching pointspread
$pointSpread = breakDown('base', $pp, $breakList, $pl);
// Hold returned details
$details = array();
// Spend points in pointspread
foreach($pointSpread as $key => $value){
if($key == 'abil'){
$abilList = ['str', 'dex', 'con', 'int', 'wis', 'cha'];
$abilBreakdown = breakDown('abil', $value, $abilList, $pl);
$details = array_add($details, 'abil' , $abilBreakdown);
}
if($key == 'comb/save'){
$combList = ['gen_attack', 'defense', 'will', 'fort', 'ref' ];
$combBreakdown = breakdown('comb/save',$value, $combList, $pl);
$details = array_add($details, 'comb/save', $combBreakdown);
}
if($key == 'skills'){
$skillList = DB::table('skillsList')->lists('skill_name');
$skillBreakdown = breakdown('skills', $value, $skillList, $pl);
$details = array_add($details, 'skills', $skillBreakdown);
}
if($key == 'powers'){
$powersList = DB::table('powersList')->lists('power_name');
$powersBreakdown = breakdown('powers', $value, $powersList, $pl);
$details = array_add($details, 'powers', $powersBreakdown);
}
if($key == 'feats'){
$featsList = DB::table('featsList')->lists('feat_name');
$featsBreakdown = breakdown('feats', $value, $featsList, $pl);
$details = array_add($details, 'feats', $featsBreakdown);
}
}
$initBonus = 0;
$toughBonus = 0;
// Count stats that modify others
foreach($details as $d){
if(isset($d['Improved Initiative'])){
$initBonus += (4*$d['Improved Initiative']);
}
if(isset($d['Enhanced Dexterity'])){
$initBonus += 1;
}
if(isset($d['Enhanced Constitution']) || isset($d['Defensive Roll'] )){
$toughBonus += 1;
}
}
// Adjust stats that need it
$tough = floor(($details['abil']['con']-10)/2) + $toughBonus;
$initiative = floor(($details['abil']['dex']-10)/2) + $initBonus;
// Get Basics
// Choose Random Height
$height = floor(User::rollDice(54,96)/12);
// Choose Random Weight
$weight = User::rollDice(100,300);
// Choose Random Age
$age = User::rollDice(18, 60);
$basics = array(
'power_level' => $pl,
'power_points' => $pp,
'height' => $height . " feet",
'weight' => $weight . " lbs",
'age' => $age,
'init' => $initiative,
'tough' => $tough
);
$details = array_add($details, 'basics' , $basics);
Session::put('details', $details);
Session::put('size', 'full');
return Redirect::to('/');
}
function editChar($charId){
// Gather All inputs into one variable
$input = Input::all();
$uid = Session::get('uid');
// Update CharList
DB::table('charList')->where('charId', $charId)
->update(array('charName' => $input['altId']));
// Update Char Basics
DB::table('char_basic')->where('charId', $charId)
->update( array(
'charId' => $charId,
'real_name' => $input['realName'],
'power_level' => $input['pl'],
'power_points' => $input['pps'],
'affiliation' => $input['affi'],
'ff' => $input['ff'],
'hero_total' => $input['hpt'],
'hero_current' => $input['hpc'],
'height' => $input['height'],
'weight' => $input['weight'],
'age' => $input['age']
)
);
// Update Char Abilities
DB::table('char_abilities')->where('char_id', $charId)
->update( array(
'char_Id' => $charId,
'str_rank' => $input['strRank'],
'str_mod' => $input['strMod'],
'dex_rank' => $input['dexRank'],
'dex_mod' => $input['dexMod'],
'con_rank' => $input['conRank'],
'con_mod' => $input['conMod'],
'int_rank' => $input['intRank'],
'int_mod' => $input['intMod'],
'wis_rank' => $input['wisRank'],
'wis_mod' => $input['wisMod'],
'cha_rank' => $input['chaRank'],
'cha_mod' => $input['chaMod']
)
);
// Update Char Combat
DB::table('char_comb')->where('charId', $charId)
->update( array(
'charId' => $charId,
'initiative' => $input['initiative'],
'gen_attack' => $input['attack'],
'knockback' => $input['knockback'],
'tough' => $input['toughMod'],
'defense' => $input['defense'],
'grapple' => $input['grapple'],
'melee' => $input['attack'],
'ranged' => $input['attack'],
'will' => $input['will'],
'fort' => $input['fort'],
'ref' => $input['reflex']
)
);
// Update Char Attacks If they exist
// Remove old
DB::table('char_attacks')->where('charId', $charId)->delete();
if(!empty($input['aa1_name']) && !empty($input['aa1_score'])){
DB::table('char_attacks')->insert( array(
'charId' => $charId,
'attack_name' => $input['aa1_name'],
'attack_score' => $input['aa1_score']
)
);
}
if(!empty($input['aa2_name']) && !empty($input['aa2_score'])){
DB::table('char_attacks')->insert( array(
'charId' => $charId,
'attack_name' => $input['aa2_name'],
'attack_score' => $input['aa2_score']
)
);
}
if(!empty($input['aa3_name']) && !empty($input['aa3_score'])){
DB::table('char_attacks')->insert( array(
'charId' => $charId,
'attack_name' => $input['aa3_name'],
'attack_score' => $input['aa3_score']
)
);
}
if(!empty($input['aa4_name']) && !empty($input['aa4_score'])){
DB::table('char_attacks')->insert( array(
'charId' => $charId,
'attack_name' => $input['aa4_name'],
'attack_score' => $input['aa4_score']
)
);
}
// Update Skills If They Exist
// Remove old
DB::table('char_skills')->where('charId', $charId)->delete();
// Put in new List
for($i = 1; $i <= 15; $i++){
$skillNumber = "skill" . $i;
$skillRank = 'skillRank' . $i;
$skillAbil = 'skillAbil' . $i;
if($input[$skillNumber] != ""){
$skillId = DB::table('skillsList')->where('skill_name', $input[$skillNumber])->pluck('skill_id');
DB::table('char_skills')->insert(array(
'charId' => $charId,
'skill_id' => $skillId,
'skill_total' => $input[$skillRank] + $input[$skillAbil],
'skill_ranks' => $input[$skillRank],
'skill_abil' => $input[$skillAbil]
));
}
}
// Update Feats If They Exist
// Remove old
DB::table('char_feats')->where('char_id', $charId)->delete();
// Put in new List
for($i = 1; $i <= 12; $i++){
$featNumber = "feat" . $i;
$featScore = $featNumber . "score";
if($input[$featNumber] != ""){
$featId = DB::table('featsList')->where('feat_name', $input[$featNumber])->pluck('feat_id');
DB::table('char_feats')->insert(array(
'char_id' => $charId,
'feat_id' => $featId,
'feat_ranks' => $input[$featScore]
));
}
}
// Update Powers
// Remove old
DB::table('char_powers')->where('char_id', $charId)->delete();
// Put in new List
for($i = 1; $i <= 6; $i++){
$powerNumber = "power" . $i;
$powerRank = "powerRank" . $i;
$powerNote = "powerNote" . $i;
if($input[$powerNumber] != ""){
$powerId = DB::table('powersList')->where('power_name', $input[$powerNumber])->pluck('power_id');
DB::table('char_powers')->insert(array(
'char_id' => $charId,
'power_id' => $powerId,
'power_ranks' => $input[$powerRank],
'notes' => $input[$powerNote]
));
}
}
// Update Drawbacks
// Remove old
DB::table('char_drawbacks')->where('char_id', $charId)->delete();
// Put in new List
if(!empty($input['db1'])){
DB::table('char_drawbacks')->insert( array(
'char_id' => $charId,
'drawback' => $input['db1'],
'db_cost' => $input['db1cost']
)
);
}
if(!empty($input['db2'])){
DB::table('char_drawbacks')->insert( array(
'char_id' => $charId,
'drawback' => $input['db1'],
'db_cost' => $input['db1cost']
)
);
}
Session::forget('charShow');
return Redirect::to('/');
}
function addChar() {
// Gather all inputs into one variable
$input = Input::all();
$uid = Session::get('uid');
// Add To CharList
DB::table('charList')->insert(
array('userid' => $uid, 'charName' => $input['altId'])
);
// Get Char ID for this new character
$charId = DB::table('charList')->where('charName', $input['altId'])->pluck('charId');
// Add To Char Basics
DB::table('char_basic')->insert( array(
'charId' => $charId,
'real_name' => $input['realName'],
'power_level' => $input['pl'],
'power_points' => $input['pps'],
'affiliation' => $input['affi'],
'ff' => $input['ff'],
'hero_total' => $input['hpt'],
'hero_current' => $input['hpc'],
'height' => $input['height'],
'weight' => $input['weight'],
'age' => $input['age']
)
);
// Add To Char Abilities
DB::table('char_abilities')->insert( array(
'char_Id' => $charId,
'str_rank' => $input['strRank'],
'str_mod' => $input['strMod'],
'dex_rank' => $input['dexRank'],
'dex_mod' => $input['dexMod'],
'con_rank' => $input['conRank'],
'con_mod' => $input['conMod'],
'int_rank' => $input['intRank'],
'int_mod' => $input['intMod'],
'wis_rank' => $input['wisRank'],
'wis_mod' => $input['wisMod'],
'cha_rank' => $input['chaRank'],
'cha_mod' => $input['chaMod']
)
);
// Add To Char Combat
DB::table('char_comb')->insert( array(
'charId' => $charId,
'initiative' => $input['initiative'],
'gen_attack' => $input['attack'],
'knockback' => $input['knockback'],
'tough' => $input['toughMod'],
'defense' => $input['defense'],
'grapple' => $input['grapple'],
'melee' => $input['attack'],
'ranged' => $input['attack'],
'will' => $input['will'],
'fort' => $input['fort'],
'ref' => $input['reflex']
)
);
// Add To Char Attacks If they exist
if(!empty($input['aa1_name']) && !empty($input['aa1_score'])){
DB::table('char_attacks')->insert( array(
'charId' => $charId,
'attack_name' => $input['aa1_name'],
'attack_score' => $input['aa1_score']
)
);
}
if(!empty($input['aa2_name']) && !empty($input['aa2_score'])){
DB::table('char_attacks')->insert( array(
'charId' => $charId,
'attack_name' => $input['aa2_name'],
'attack_score' => $input['aa2_score']
)
);
}
if(!empty($input['aa3_name']) && !empty($input['aa3_score'])){
DB::table('char_attacks')->insert( array(
'charId' => $charId,
'attack_name' => $input['aa3_name'],
'attack_score' => $input['aa3_score']
)
);
}
if(!empty($input['aa4_name']) && !empty($input['aa4_score'])){
DB::table('char_attacks')->insert( array(
'charId' => $charId,
'attack_name' => $input['aa4_name'],
'attack_score' => $input['aa4_score']
)
);
}
// Add to Skills If They Exist
$skillsCount= 0;
foreach($input as $key=>$value){
if(preg_match("/\bskill\d+/", $key)){
$skillsCount += 1;
}
}
if($skillsCount == 0){
$skillsCount = 15;
}
for($i = 1; $i <= $skillsCount; $i++){
$skillNumber = "skill" . $i;
$skillRank = 'skillRank' . $i;
$skillAbil = 'skillAbil' . $i;
if($input[$skillNumber] != "Skill Name" || $input[$skillNumber] != "" ){
$skillId = DB::table('skillsList')->where('skill_name', $input[$skillNumber])->pluck('skill_id');
if(!empty($skillId)){
DB::table('char_skills')->insert(array(
'charId' => $charId,
'skill_id' => $skillId,
'skill_total' => $input[$skillRank] + $input[$skillAbil],
'skill_ranks' => $input[$skillRank],
'skill_abil' => $input[$skillAbil]
));
}
}
}
$featsCount= 0;
foreach($input as $key=>$value){
if(preg_match("/\bfeat\d+\b/", $key)){
$featsCount += 1;
}
}
if($featsCount == 0){
$featsCount = 12;
}
// Add to Feats If They Exist
for($i = 1; $i <= $featsCount; $i++){
$featNumber = "feat" . $i;
$featScore = $featNumber . "score";
if($input[$featNumber] != "Feat Name" || $input[$featNumber] != ""){
$featId = DB::table('featsList')->where('feat_name', $input[$featNumber])->pluck('feat_id');
if(!empty($featId)){
DB::table('char_feats')->insert(array(
'char_id' => $charId,
'feat_id' => $featId,
'feat_ranks' => $input[$featScore]
));
}
}
}
$powersCount= 0;
foreach($input as $key=>$value){
if(preg_match("/\bpower\d+/", $key)){
$powersCount += 1;
}
}
if($powersCount == 0){
$powersCount = 6;
}
// Add to Powers If They Exist
for($i = 1; $i <= $powersCount; $i++){
$powerNumber = "power" . $i;
$powerRank = "powerRank" . $i;
$powerNote = "powerNote" . $i;
if($input[$powerNumber] != "Power Name" || $input[$powerNumber] != ""){
$powerId = DB::table('powersList')->where('power_name', $input[$powerNumber])->pluck('power_id');
if(!empty($powerId)){
DB::table('char_powers')->insert(array(
'char_id' => $charId,
'power_id' => $powerId,
'power_ranks' => $input[$powerRank],
'notes' => $input[$powerNote]
));
}
}
}
// Add to Drawbacks If They Exist
if(!empty($input['db1'])){
DB::table('char_drawbacks')->insert( array(
'char_id' => $charId,
'drawback' => $input['db1'],
'db_cost' => $input['db1cost']
)
);
}
if(!empty($input['db2'])){
DB::table('char_drawbacks')->insert( array(
'char_id' => $charId,
'drawback' => $input['db1'],
'db_cost' => $input['db1cost']
)
);
}
Session::forget('addChar');
Session::forget('details');
Session::forget('gen');
return Redirect::action('HomeController@display');
}
}
| true |
40e050f556831df27b7db448d9db7cea2401671f | PHP | ashique19/peer | /database/migrations/2016_05_26_172101_create_buyers_new_table.php | UTF-8 | 1,562 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBuyersNewTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('buyers_new', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('description', 255);
$table->string('url');
$table->string('image');
$table->decimal('price', 10, 2);
$table->integer('quantity');
$table->integer('from_country_id')->unsigned()->nullable();
$table->foreign('from_country_id')->references('id')->on('countries')->onDelete('set null');
$table->integer('to_country_id')->unsigned()->nullable();
$table->foreign('to_country_id')->references('id')->on('countries')->onDelete('set null');
$table->string('from_address', 200);
$table->string('to_address', 200);
$table->string('from_state', 50);
$table->string('to_state', 50);
$table->string('from_zip', 50);
$table->string('to_zip', 50);
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('buyers_new');
}
}
| true |
ba7384d06b0239bbd9af5f333cfe739adaf4c8e6 | PHP | chrodriguez/hydra-php-idp | /src/hydra_adapter.php | UTF-8 | 853 | 2.84375 | 3 | [] | no_license | <?php
class HydraAdapter {
private $pdo;
private $user_sql;
private $auth_sql;
public function __construct($opts) {
$this->db = $opts['pdo'];
$this->user_sql = $opts['user_sql'];
$this->auth_sql = $opts['auth_sql'];
}
public function doLogin($username, $password) {
$stm = $this->db->prepare($this->auth_sql);
$stm->execute([':username' => $username, ':password' => $password]);
$res = $stm->fetchAll();
return (count($res) == 1);
}
public function getIdTokenData($username) {
$stm = $this->db->prepare($this->user_sql);
$stm->execute([':username' => $username]);
$res = $stm->fetchAll();
if (count($res) != 1) throw new Exception("request a session for a user that doesn't exists");
$ret = array();
foreach($res[0] as $k => $v){
$ret[$k] = $v;
}
return $ret;
}
}
| true |
432241f2119191c73275d9706eeb50fa0461ffb7 | PHP | Kader93/DynamicForm | /tests/DynamicFormTest/Model/FileTest.php | UTF-8 | 1,516 | 2.703125 | 3 | [] | no_license | <?php
namespace DynamicFormTest\Model;
use DynamicForm\Model\FormConfigManager\File;
use PHPUnit_Framework_TestCase;
class FileTest extends PHPUnit_Framework_TestCase
{
protected static $filepath;
protected static $filetest;
protected static $strContentsfile;
public static function setUpBeforeClass()
{
self::$filepath = \DynamicForm\Module::$ModuleLocation . "/ressources/Json/membreForm.config.json";
self::$filetest = new File(self::$filepath);
}
public function testgetContentsFile()
{
$this->assertTrue(is_string(self::$filetest->getContentsFile()));
}
public function testgetArrayConfig()
{
$this->assertTrue(is_array(self::$filetest->getArrayConfig(self::$strContentsfile)));
}
public static function tearDownAfterClass()
{
self::$filepath = NULL;
}
/**
* @expectedException Exception
* @expectedExceptionMessage file doesn't exist or hasn't the good extension
*/
public function testExistConfig()
{
$filepath= "";
$filetest = new File($filepath);
$filetest->getContentsFile();
}
/**
* @expectedException Exception
* @expectedExceptionMessage parsing échoué
*/
public function testEchecParsing()
{
$str= "blabla";
$filepath = \DynamicForm\Module::$ModuleLocation . "/ressources/Json/membreForm.config.json";
$filetest = new File($filepath);
$filetest->getArrayConfig($str);
}
} | true |
1e8abba3911b9db988aa31c8f789b4db18a07926 | PHP | soleneantoine/theoriesecurite | /class/Version.php | UTF-8 | 1,811 | 3.0625 | 3 | [] | no_license | <?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of Version
*
* @author soleneantoine
*/
class Version {
var $numero;
var $estAttaque;
var $pdf;
var $groupe;
function Version($g,$n,$pdf) {
$this->numero = $n;
$this->estAttaque = "False";
$this->pdf = $pdf;
$this->groupe = $g;
}
public function getNumero() {
return $this->numero;
}
public function setNumero($numero) {
$this->numero = $numero;
}
public function getEstAttaque() {
return $this->estAttaque;
}
public function setEstAttaque($estAttaque) {
$this->estAttaque = $estAttaque;
}
public function getPdf() {
return $this->pdf;
}
public function setPdf($pdf) {
$this->pdf = $pdf;
}
public function getGroupe() {
return $this->groupe;
}
public function setGroupe($groupe) {
$this->groupe = $groupe;
}
public static function getVersions($orderBy = "numero", $asc_desc="DESC"){
$versions = array();
$resultats = MyPDO::get()->query("SELECT * FROM Version ORDER BY $orderBy $asc_desc");
$resultats->setFetchMode(PDO::FETCH_OBJ);
while( $ligne = $resultats->fetch() )
{
$version = new Version($ligne->groupe,$ligne->numero,$ligne->pdf);
array_push($versions, $version);
}
return $versions;
}
public static function getVersion($g,$n){
foreach (Version::getVersions() as $v){
if (( $v->getNumero() == $n) && ($v->getGroupe() == $g)) {
return $v;
}
}
return null;
}
//put your code here
}
?>
| true |
4d064bc609a5d3a356b63f85d9d982f08214c797 | PHP | linkjian/HarborSdk | /src/Sdk.php | UTF-8 | 2,225 | 2.734375 | 3 | [] | no_license | <?php
namespace Harbor;
use Harbor\Http\Client;
/**
* Class Sdk
* @package Harbor
* @property \Harbor\Services\Product product
* @property \Harbor\Services\Category category
* @property \Harbor\Services\Collection collection
* @property \Harbor\Services\Order order
* @property \Harbor\Services\Webhook webhook
* @property \Harbor\Services\ProductVariant productVariant
* @property \Harbor\Services\Inventories inventories
*/
class Sdk
{
/**
* @var array Config for creating clients
*/
private $config;
/**
* @var array
*/
private $services;
/**
* @var
*/
private $client;
/**
* Sdk constructor.
* @param $config
*/
public function __construct($config)
{
$this->config = $config;
$this->loadServices();
$this->createClient();
}
/**
* @param $name
*/
public function __get($name)
{
if (!array_key_exists($name, $this->services)) {
throw new \InvalidArgumentException("service $name not found");
}
if (!$this->services[$name]['object']) {
$this->createService($name);
}
return $this->services[$name]['object'];
}
protected function createClient()
{
$this->client = new Client($this->config);
}
protected function createService($name)
{
$service = $this->services[$name];
$this->services[$name]['object'] = new $service['class']($this->client);
}
protected function loadServices()
{
$services = array_filter(scandir(__DIR__ . '/Services'), function ($file) {
return !in_array($file, ['.','..']);
});
foreach ($services as $service) {
$service = explode('.', $service);
$name = array_shift($service);
$class = "Harbor\\Services\\$name";
if (!class_exists($class)) {
continue;
}
$this->services[lcfirst($name)]['class'] = $class;
$this->services[lcfirst($name)]['object'] = null;
}
}
/**
* @return array
*/
public function getServices(): array
{
return $this->services;
}
} | true |
c483cb5950f407b2a90a78f975bf419b763f1fbb | PHP | cmcclees/PHP-DVD-Laravel | /app/views/dvds/dvds-list.php | UTF-8 | 1,292 | 2.765625 | 3 | [] | no_license | <!doctype html>
<html>
<head>
<title>My Dvds</title>
<style>
.dvds table, .dvds td, .dvds th
{
border:1px solid black;
text-align:center;
padding-left:4px;
padding-right: 4px;
}
table {
width:100%;
}
h1 {
text-align: center;
}
</style>
</head>
<body>
<h1>My Dvds</h1>
<table class="dvds">
<th class="dvds">Title</th>
<th class="dvds">Genre</th>
<th class="dvds">Rating</th>
<th class="dvds">Label</th>
<th class="dvds">Sound</th>
<th class="dvds">Format</th>
<th class="dvds">Release Date</th>
<?php foreach ($dvds as $dvd) : ?>
<tr>
<td class="dvds"> <?php echo $dvd->title; ?></td>
<td class="dvds"> <?php echo $dvd->genre->genre_name; ?></td>
<td class="dvds"> <?php echo $dvd->rating->rating_name; ?></td>
<td class="dvds"> <?php echo $dvd->label->label_name; ?></td>
<td class="dvds"> <?php echo $dvd->sound->sound_name; ?></td>
<td class="dvds"> <?php echo $dvd->format->format_name; ?></td>
<td class="dvds"> <?php echo $dvd->release_date; ?></td>
</tr>
<?php endforeach; ?>
</table>
</body>
</html> | true |
1d6ab1405e7b4263f95230f0a8f33b460b3001e3 | PHP | alissoncs/descartemap-api | /src/Domain/Address.php | UTF-8 | 3,162 | 3.140625 | 3 | [] | no_license | <?php
namespace Domain;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
/** @ODM\EmbeddedDocument */
class Address {
/**
* @ODM\String
*/
private $street;
/**
* @ODM\Int
*/
private $number;
/**
* @ODM\String
*/
private $neighborhood;
/**
* @ODM\String
*/
private $city;
/**
* @ODM\String
*/
private $state;
/**
* @ODM\String
*/
private $country;
/**
* @ODM\String
*/
private $zipcode;
public function __construct($street = null, $number = null, $neighborhood = null, $city = null, $state = null) {
if(!is_null($street))
$this->setStreet($street);
if(!is_null($number))
$this->setNumber($number);
if(!is_null($neighborhood))
$this->setNeighborhood($neighborhood);
if(!is_null($city))
$this->setCity($city);
if(!is_null($state))
$this->setState($state);
}
public function setStreet($street) {
if(!is_string($street))
throw new \InvalidArgumentException('Invalid street');
$street = ucwords($street);
$this->street = $street;
}
public function getStreet() {
return $this->street;
}
public function setNumber($number) {
if(!is_int($number))
throw new \InvalidArgumentException('Invalid number');
$this->number = $number;
}
public function getNumber() {
return $this->number;
}
public function setNeighborhood($neighborhood) {
if(!is_string($neighborhood))
throw new \InvalidArgumentException('Invalid neighborhood');
$this->neighborhood = $neighborhood;
}
public function getNeighborhood() {
return $this->neighborhood;
}
public function setCity($city) {
if(!is_string($city))
throw new \InvalidArgumentException('Invalid city');
$this->city = $city;
}
public function getCity() {
return $this->city;
}
public function setState($state) {
if(!is_string($state))
throw new \InvalidArgumentException('Invalid state');
$this->state = $state;
}
public function getState() {
return $this->state;
}
public function setCountry($country) {
if(!is_string($country))
throw new \InvalidArgumentException('Invalid');
$this->country = $country;
}
public function getCountry() {
return $this->country;
}
public function setZipcode($zipcode) {
if(!is_string($zipcode))
throw new \InvalidArgumentException('Invalid');
$this->zipcode = $zipcode;
}
public function getZipcode() {
return $this->zipcode;
}
static public function create(array $data) {
$add = new self;
if(isset($data['street']))
$add->setStreet($data['street']);
if(isset($data['city']))
$add->setCity($data['city']);
if(isset($data['state']))
$add->setState($data['state']);
if(isset($data['country']))
$add->setCountry($data['country']);
if(isset($data['neighborhood']))
$add->setNeighborhood($data['neighborhood']);
if(isset($data['number'])) {
$add->setNumber((int)$data['number']);
}
if(isset($data['zipcode'])) {
$add->setZipcode($data['zipcode']);
}
return $add;
}
}
| true |
f53c2b07b69fd7f3f41ca4d4756168917540d7cf | PHP | symnoureddine/design-patterns | /Creational/Builder/ProductRepository.php | UTF-8 | 2,093 | 3.28125 | 3 | [
"Apache-2.0"
] | permissive | <?php
namespace DesignPatterns\Creational\Builder;
/**
* Repository that is responsible for retrieving product's data from database.
* It contains high level methods of such retrieval.
* An instance of concrete builder is used to implement these methods.
*
* It corresponds to `Director` in the Builder pattern.
*
* @author Vlad Riabchenko <contact@vria.eu>
*/
class ProductRepository
{
/**
* Query builder.
*
* @var QueryBuilder
*/
private $qb;
/**
* Constructeur
*
* @param QueryBuilder $qb
*/
public function __construct(QueryBuilder $qb)
{
$this->qb = $qb;
}
/**
* Find all products ordered by ascending price.
*
* @return mixed
*/
public function findAll()
{
return $this->qb
->createQuery('product')
->addOrderBy('price', QueryBuilder::ASC)
->getQuery();
}
/**
* Find products for carousel. It returns 3 products maximum that :
* - marked for a carousel,
* - cost at least 50,
* - ordered by descending creation date.
*
* @return mixed
*/
public function findForCarousel()
{
return $this->qb
->createQuery('product')
->andWhere('carousel', QueryBuilder::EQUALS, true)
->andWhere('rating', QueryBuilder::GREATER, 50)
->addOrderBy('created_at', QueryBuilder::DESC)
->setMaxResults(3)
->getQuery();
}
/**
* Find products for homepage. It returns 50 products that:
* - either in stock or in pre-order state,
* - cost greater then 100.99,
* - ordered by descending update date.
*
* @return mixed
*/
public function findForHomepage()
{
return $this->qb
->createQuery('product')
->andWhere('status', QueryBuilder::IN, ['in_stock', 'pre_order'])
->andWhere('price', QueryBuilder::GREATER, '100.99')
->addOrderBy('updated_at', QueryBuilder::DESC)
->setMaxResults(50)
->getQuery();
}
}
| true |
3216143d203b70735393a756be90900e60b96898 | PHP | maury91/NiiCMS | /_proto/func.php | WINDOWS-1252 | 6,059 | 2.953125 | 3 | [] | no_license | <?php
/*
Funzioni CMS
ultima modifica 19/03/2013 (v0.6.1)
*/
//Per evitare che ci siano casini se inclusa 2 volte
if (!function_exists("randword")) {
include('php4_5.php');
//Variabili globali
define('sitemail',$sitemail);
define('sitemailn',$sitemailn);
function randword($len) {
//Una parola alfanumerica casuale di lunghezza $len
$act = "";
for($I=0;$I<$len;$I++){
do{
$N = Ceil(rand(48,122));
}while(!((($N >= 48) && ($N <= 57)) || (($N >= 65) && ($N <= 90)) || (($N >= 97) && ($N <= 122))));
$act .= Chr ($N);
}
return $act;
}
function save__sub($k,$v,$d) {
//Identazione di un array (ricorsiva)
$tab = ''; for ($i=0;$i<$d;$i++) $tab.="\t";
$r = "\n$tab'$k' => array(";
$n = true;
foreach ($v as $x => $y) {
if ($n) $n = false; else $r .= ",";
if (is_array($y)) $r .= save__sub($x,$y,$d+1); else { if(is_numeric($x)) $r .= "'$y'"; else $r .= "'$x' => '$y'"; }
}
return $r.")";
}
function save_preload($newarr) {
//Salvataggio del file plugin.php con il suo contenuto identato
$r = "<?php\n\$ext_preload = array(";
$x=true;
foreach ($newarr as $k => $v) {
if ($x) $x = false; else $r .= ',';
$r .= save__sub($k,$v,1);
}
$r .= "\n);\n?>";
$f = fopen("_data/preloader.php","w");
fwrite($f,$r);
fclose($f);
}
function preload_ext($typ) {
include('_data/preloader.php');
$to_preload='';
if (($typ=='editor')||($typ=='all'))
foreach($ext_preload['editor'] as $k => $v) {
if(!isset($GLOBALS[$k.'_editor_has_preloaded'])) {
$GLOBALS[$k.'_editor_has_preloaded'] = true;
foreach($v as $j)
$to_preload.='<script src="'.$j.'" type="text/javascript"></script>';
}
}
if (($typ=='com')||($typ=='all'))
foreach($ext_preload['com'] as $k => $v) {
if(!isset($GLOBALS[$k.'_com_has_preloaded'])) {
$GLOBALS[$k.'_com_has_preloaded'] = true;
foreach($v as $j)
$to_preload.='<script src="'.$j.'" type="text/javascript"></script>';
}
}
return $to_preload;
}
function send_mail($email,$corpo,$oggetto,$emitt,$mmitt) {
//Invia una mail in HTML
$msg = "
<HTML>
<BODY>
".$corpo."
</BODY>
</HTML>";
$intestazioni = "MIME-Version: 1.0\r\n";
$intestazioni .= "Content-type: text/html; charset=iso-8859-1\r\n";
$intestazioni .= "From: ".$mmitt." <".$emitt.">\r\n";
return mail($email, $oggetto, $msg , $intestazioni );
}
function cms_send_mail($email,$corpo,$oggetto) {
//Invia una mail con le impostazioni del CMS
return send_mail($email,$corpo,$oggetto,sitemail,sitemailn);
}
function list_dir($directory) {
//Lista di tutte le cartelle dentro una directory
$dirs= array();
if ($handle = opendir($directory."/"))
{
while ($file = readdir($handle))
{
if (is_dir($directory."/{$file}"))
{
if ($file != "." & $file != "..") $dirs[] = $file;
}
}
}
closedir($handle);
reset($dirs);
sort($dirs);
reset($dirs);
return $dirs;
$valore = '';
}
function is_empty_dir($path) {
//Restituisce se una cartella vuota
$dh = @opendir($path);
while (false !== ($file = readdir($dh))) {
if ($file == '.' || $file == '..') {
continue;
} else {
closedir($dh);
return false;
}
}
closedir($dh);
return true;
}
function fext($filename) {
//Estensione di un file
$path_info = pathinfo($filename);
if (isset($path_info['extension']))
return strtolower($path_info['extension']);
else
return '';
}
function list_files($directory,$filter='*') {
//Lista di tutti i files dentro una directory
$ff = strtolower($filter);
$files= array();
$filtre = $ff == '*';
if (!$filtre) { $xx = substr_count($ff,";"); $ff = explode(';',$ff,$xx+1); }
if ($handle = opendir($directory."/"))
{
while ($file = readdir($handle))
{
if (!is_dir($directory."/{$file}"))
{
if (($file != "." & $file != "..")&&($filtre))
$files[] = $file;
else
if (($file != "." & $file != "..")&&(in_array(fext($file),$ff))) $files[] = $file;
}
}
}
closedir($handle);
reset($files);
sort($files);
reset($files);
return $files;
}
function download_file($filename) {
//Download FORZATO di un file
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
$file_extension = strtolower(substr(strrchr($filename,"."),1));
if ( ! file_exists( $filename ) )
{
echo "ERROR: File not found.";
}
else
{
switch( $file_extension )
{
case "pdf": $ctype="application/pdf"; break;
case "exe": $ctype="application/octet-stream"; break;
case "zip": $ctype="application/zip"; break;
case "doc": $ctype="application/msword"; break;
case "xls": $ctype="application/vnd.ms-excel"; break;
case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
default: $ctype="application/force-download";
}
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: $ctype");
header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile("$filename");
exit(0);
}
}
function veryurl($url) {
//Link compreso di http:// iniziale
$a = is_link($url);
if (!$a)
return 'http://'.$_SERVER['SERVER_NAME'].script_dir.'/'.$url;
else
return $url;
}
function cms_time() {
//Orario del cms
return time()+$GLOBALS['cms_time'];
}
function del_dir($dir) {
//Eliminazione di una cartella e di tutto il suo contenuto
$handle = opendir($dir);
while (false !== ($file = readdir($handle))) {
if(is_file($dir.$file)){
unlink($dir.$file);
}
else if (($file != '.')&&($file != '..'))
del_dir($dir.$file.'/');
}
$handle = closedir($handle);
@rmdir($dir);
return !file_exists($dir);
}
}
?> | true |
d616acca624b45aa83e76b639c6720be4827910a | PHP | CGCE/information-home-page | /submit.php | UTF-8 | 1,633 | 2.734375 | 3 | [] | no_license | <?php
ini_set('display_errors',1);
error_reporting(999);
require_once "config.php";
require_once "vendor/CJDB.php";
$data=$_POST["data"];
$token=$_POST["token"];
$db=new CJDBH();
$db->prepare("REPLACE INTO `{$config['dbtable']}` SET `token`=:token, `token-field`=:tokenField, `field`=:field, `value`=:value");
foreach($data as $elem){
// Met les dates au format SQL
if(strpos($elem["field"],"_date_")){
// Si une date au format FR est donnée, on la converti au format SQL et on ajoute un champ date_en correspondant pour qu'il ne soit pas vide si on recharge le formulaire
if(substr($elem["field"],-2)=="fr"){
// Conversion
$dateReplace='\3-\2-\1';
// Nouveau champ date_en
$date2=array("field"=>substr($elem["field"],0,-2)."en");
}
// Même chose si date EN donnée
if(substr($elem["field"],-2)=="en"){
// Conversion
$dateReplace='\3-\1-\2';
// Nouveau champ date_fr
$date2=array("field"=>substr($elem["field"],0,-2)."fr");
}
// Conversion de la date (FR ou EN) en SQL
$elem["value"]=preg_replace('/([0-9]*)\/([0-9]*)\/([0-9]*)/', $dateReplace, $elem['value']);
// Enregistrement du nouveau champ date_fr ou date_en
$tmp=array(":token"=>$token,":tokenField"=>$token."-".$date2['field'],":field"=>$date2['field'],":value"=>htmlentities($elem['value'],ENT_QUOTES|ENT_IGNORE,"utf-8"));
$db->execute($tmp);
}
// Enregistrement des infos dans la base de données
$tmp=array(":token"=>$token,":tokenField"=>$token."-".$elem['field'],":field"=>$elem['field'],":value"=>htmlentities($elem['value'],ENT_QUOTES|ENT_IGNORE,"utf-8"));
$db->execute($tmp);
}
echo json_encode("");
?> | true |
1ff8795c07482edb5bca3cddb2d91bf83f44c85a | PHP | smontieltorres/examenLaravel | /app/Http/Livewire/UserList.php | UTF-8 | 1,026 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\User;
use Illuminate\Support\Facades\Hash;
class UserList extends Component
{
public $Edit = false, $Create = false;
public function render()
{
//variable de usuarios, pasada a la vista para renderizar la lista de usuarios
$users = User::all();
/*return de funcion, aqui se devuelve la vista al navegador, junto a la variable especificada por el metodo compact*/
return view('livewire.user-list', compact("users"));
}
public function getAction($id){
$this->Edit=true;
//Envia un evento con el id para identificar al usuario a editar//
$this->emit("edit", $id);
}
//funcion de deleteUser, toma un id pasado por la vista y elimina el usuario de la base de datos//
public function deleteUser($id){
//Busca al usuario especificado//
$User = User::find($id);
//Elmina al usuario seleccionado//
$User->delete($id);
}
}
| true |