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
65cbb44b1bc784f404cbc34a9e6c5eb7ae67a429
PHP
MilaHG/SF_Boutique3_2018
/src/BoutiqueBundle/Entity/Produit.php
UTF-8
5,118
2.53125
3
[ "MIT", "BSD-3-Clause" ]
permissive
<?php namespace BoutiqueBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Produit * * @ORM\Table(name="produit") * @ORM\Entity(repositoryClass="BoutiqueBundle\Repository\ProduitRepository") * */ class Produit { /** * @var integer * * @ORM\Column(name="id_produit", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $idProduit; /** * @var string * * @ORM\Column(name="reference", type="string", length=20, nullable=false) */ private $reference; /** * @var string * * @ORM\Column(name="categorie", type="string", length=20, nullable=false) */ private $categorie; /** * @var string * * @ORM\Column(name="titre", type="string", length=20, nullable=false) */ private $titre; /** * @var string * * @ORM\Column(name="description", type="text", length=65535, nullable=false) */ private $description; /** * @var string * * @ORM\Column(name="couleur", type="string", length=20, nullable=false) */ private $couleur; /** * @var string * * @ORM\Column(name="taille", type="string", length=5, nullable=false) */ private $taille; /** * @var string * * @ORM\Column(name="public", type="string", length=5, nullable=false) */ private $public; /** * @var string * * @ORM\Column(name="photo", type="string", length=250, nullable=true) */ private $photo; /** * @var float * * @ORM\Column(name="prix", type="float", precision=10, scale=0, nullable=false) */ private $prix; /** * @var integer * * @ORM\Column(name="stock", type="integer", nullable=false) */ private $stock; /** * @return int */ public function getIdProduit() { return $this->idProduit; } /** * @param int $idProduit * @return Produit */ public function setIdProduit($idProduit) { $this->idProduit = $idProduit; return $this; } /** * @return string */ public function getReference() { return $this->reference; } /** * @param string $reference * @return Produit */ public function setReference($reference) { $this->reference = $reference; return $this; } /** * @return string */ public function getCategorie() { return $this->categorie; } /** * @param string $categorie * @return Produit */ public function setCategorie($categorie) { $this->categorie = $categorie; return $this; } /** * @return string */ public function getTitre() { return $this->titre; } /** * @param string $titre * @return Produit */ public function setTitre($titre) { $this->titre = $titre; return $this; } /** * @return string */ public function getDescription() { return $this->description; } /** * @param string $description * @return Produit */ public function setDescription($description) { $this->description = $description; return $this; } /** * @return string */ public function getCouleur() { return $this->couleur; } /** * @param string $couleur * @return Produit */ public function setCouleur($couleur) { $this->couleur = $couleur; return $this; } /** * @return string */ public function getTaille() { return $this->taille; } /** * @param string $taille * @return Produit */ public function setTaille($taille) { $this->taille = $taille; return $this; } /** * @return string */ public function getPublic() { return $this->public; } /** * @param string $public * @return Produit */ public function setPublic($public) { $this->public = $public; return $this; } /** * @return string */ public function getPhoto() { return $this->photo; } /** * @param string $photo * @return Produit */ public function setPhoto($photo) { $this->photo = $photo; return $this; } /** * @return float */ public function getPrix() { return $this->prix; } /** * @param float $prix * @return Produit */ public function setPrix($prix) { $this->prix = $prix; return $this; } /** * @return int */ public function getStock() { return $this->stock; } /** * @param int $stock * @return Produit */ public function setStock($stock) { $this->stock = $stock; return $this; } #------------------------------------------# }
true
76ac229b20bb604cae4c16b90219d851e4d35690
PHP
zhyunfe/phpnote
/app/Http/Controllers/PhpDesignPatterns/Behavioral/Mediator/Colleague.php
UTF-8
439
2.765625
3
[]
no_license
<?php /** * Created by PhpStorm. * User: zhyunfe * Date: 2018/4/8 * Time: 下午3:56 */ /** * Class Colleague * Colleague是一个抽象类,该类对象虽彼此协同却不知彼此,只知中介者Mediator类 */ class Colleague { /** * @var * 确保子类不变化 */ protected $mediator; public function setMediator(MediatorInterface $mediator) { $this->mediator = $mediator; } }
true
1912e7a214ead1db29738e316f560a0b8e104a21
PHP
stoyantodorovbg/PHP-Web-Development-Basics
/OOP Basics Exercises/problem6/Tyre.php
UTF-8
200
3.28125
3
[ "MIT" ]
permissive
<?php class Tyre { public $pressure; public $age; function __construct($pressure, $age) { $this -> pressure = doubleval($pressure); $this -> age = intval($age); } }
true
87720518182630d08c307d7a8069ddb7e088d7ec
PHP
sa-n-ya2013/TestToWork
/app/Category.php
UTF-8
2,096
2.703125
3
[ "MIT" ]
permissive
<?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Category extends Model { use SoftDeletes; /** * @var string */ protected $table = 'categories'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'description', 'user_id', 'parent_id' ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'deleted_at', 'updated_at', 'parent_id', 'user_id' ]; /** * Проверяет категорию на удаление. Если одна из родительских категорий удалена, то эта тоже считается удаленной. */ public function isDelete() { $parents = $this->parents(); foreach($parents as $parent) { if (!is_null($parent->deleted_at)) { return true; } } return false; } /** * Возвращает список родительских категорий, включая удаленные * * @return array */ public function parents() { $parent = Category::withTrashed()->find($this->parent_id); if (is_null($parent)) { return [$this]; } return array_merge([$this], $parent->parents()); } public function parent() { return $this->belongsTo(self::class); } public function goods() { return $this->hasMany(Good::class); } public function children() { return $this->hasMany(self::class, 'parent_id'); } public function delete() { foreach ($this->children as $child){ if (!$child->delete()) { return false; } } foreach ($this->goods as $good){ if (!$good->delete()) { return false; } } return parent::delete(); } }
true
bd1036a1cfd480a7b55e25030252b84d8c6baf79
PHP
Tobithy/cs313-php
/web/prove_03_shopping_cart/shopping_cart_common_php.php
UTF-8
1,853
3.125
3
[]
no_license
<?php // create the items_in_cart aray if it doesn't exist yet. if (!isset($_SESSION['items_in_cart'])) { $_SESSION['items_in_cart'] = array(); } // Define array of items to buy. This could be changed to an array of item objects // if we create an item class at some point. Right now it's just a 2d array that has a short key and // a description $available_items = array( array("snes-excellent", "Super Nintendo Entertainment System, excellent condition"), array("mario-kart-good", "SNES Mario Kart, good condition, fully tested and working"), array("super-mario-world-excellent", "SNES Super Mario World, excellent condition, fully tested and working"), array("tetris-and-dr-mario-excellent", "SNES Tetris & Dr. Mario, excellent condition, fully tested and working"), array("star-fox-good", "SNES Star Fox, good condition, fully tested and working"), array("star-fox-excellent", "SNES Star Fox, excellent condition, fully tested and working") ); // Function test_input // Cleans user entered data so it can be safely used elsewhere. From w3schools // Input // $data - potentially unclean data // Returns cleaned data (whitespace before and after removed, backslashes removed, and // special characters replaced with html codes. function clean_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } // Function issetandfilled // Short function to check if a variable is set (not NULL) and it has data (it's not empty). // Use the trim function so that data that only consists of spaces is considered empty. // Input // $data - variable to be tested // Returns TRUE if it passes both tests, FALSE if not. function issetandfilled($data) { if (!isset($data)) return false; if (empty(trim($data))) return false; return true; } ?>
true
80418a0d59bea7079708ae86a2305b07257ee46f
PHP
jhinukk/PHP
/Demo1/oop/abstraction.php
UTF-8
316
3.546875
4
[]
no_license
<?php abstract class car{ public abstract function carname(); public abstract function price(); } class taxi extends car { public function carname() { return "Maruti"." <br>"; } public function price() { return "650000"."<br>"; } } $sprots=new taxi(); echo $sprots->carname(); echo $sprots->price(); ?>
true
da00b62eccb952d46ed731ec8b9bfdb97bbef91f
PHP
priyankamsp/php-learnings
/task1.php
UTF-8
379
3.4375
3
[]
no_license
<?php $vowels = array("a","e","i","o","u"); $words = "Best Website for Tamil Typing, Tamil Translation and English to Tamil Dictionar"; $length = strlen($words); $count = 0; for($i=0;$i< $length; $i++) { $count = (in_array(strtolower($words{$i}),$vowels)) ? ($count + 1 ) : ($count + 0); } echo "There are {$count} vowels in given words"; ?>
true
db3ccb747b5417325430f7dc098567f50c644212
PHP
burningmantech/ranger-clubhouse-api
/app/Models/PersonRole.php
UTF-8
5,568
2.546875
3
[ "Apache-2.0" ]
permissive
<?php namespace App\Models; use App\Lib\ClubhouseCache; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; /** * @property int person_id * @property int role_id */ class PersonRole extends ApiModel { protected $table = 'person_role'; public function person(): BelongsTo { return $this->belongsTo(Person::class); } public function role(): BelongsTo { return $this->belongsTo(Role::class); } /** * Find all held roles for the given person * * @param int $personId * @return Collection */ public static function findRolesForPerson(int $personId): Collection { return PersonRole::select('role.id', 'role.title') ->where('person_id', $personId) ->join('role', 'role.id', 'person_role.role_id') ->orderBy('role.title') ->get(); } /** * Find all the role ids for the given person * * @param int $personId * @return array */ public static function findRoleIdsForPerson(int $personId): array { return PersonRole::where('person_id', $personId)->pluck('role_id')->toArray(); } /** * Does the person have the role? * * @param $personId * @param $roleId * @return bool */ public static function haveRole($personId, $roleId): bool { return DB::table('person_role')->where(['person_id' => $personId, 'role_id' => $roleId])->exists(); } /** * Remove all roles from a person in response to status change, add back * the default roles if requested. * * @param int $personId person id to change the roles * @param string|null $reason * @param int $action */ public static function resetRoles(int $personId, ?string $reason, int $action) { $removeIds = self::findRoleIdsForPerson($personId); if ($action == Person::ADD_NEW_USER) { $addIds = []; $ids = Role::where('new_user_eligible', true)->pluck('id')->toArray(); foreach ($ids as $roleId) { $key = array_search($roleId, $removeIds); if ($key !== false) { unset($removeIds[$key]); } else { $addIds[] = $roleId; } } PersonRole::addIdsToPerson($personId, $addIds, $reason); } PersonRole::removeIdsFromPerson($personId, $removeIds, $reason); } /** * Remove roles from a person. Log the action. * * @param int $personId person to remove * @param mixed $ids roles to remove * @param ?string $message reason for removal */ public static function removeIdsFromPerson(int $personId, mixed $ids, ?string $message) { if (empty($ids)) { return; } DB::table('person_role')->where('person_id', $personId)->whereIn('role_id', $ids)->delete(); ActionLog::record(Auth::user(), 'person-role-remove', $message, ['role_ids' => array_values($ids)], $personId); self::clearCache($personId); } /** * Add roles to a person. Log the action. * * @param int $personId person to remove * @param array $ids roles to remove * @param ?string $message reason for addition */ public static function addIdsToPerson(int $personId, mixed $ids, ?string $message) { $addedIds = []; foreach ($ids as $id) { // Don't worry if there is a duplicate record. if (DB::affectingStatement("INSERT IGNORE INTO person_role SET person_id=?,role_id=?", [$personId, $id]) == 1) { $addedIds[] = $id; } } if (!empty($addedIds)) { ActionLog::record(Auth::user(), 'person-role-add', $message, ['role_ids' => array_values($ids)], $personId); self::clearCache($personId); } } /** * Log changes to person_role * * @param int $personId person idea * @param int $id role id to log * @param string $action action taken - usually, 'add' or 'remove' * @param ?string $reason optional reason for action ('schedule add', 'trainer removed', etc.) */ public static function log(int $personId, int $id, string $action, ?string $reason = null) { ActionLog::record(Auth::user(), 'person-role-' . $action, $reason, ['role_id' => $id], $personId); } /** * Clear the roles cache for the given person. * * @param int $personId * @return void */ public static function clearCache(int $personId): void { ClubhouseCache::forget(self::cacheKey($personId)); } /** * Get the cache key for the given person * @param int $personId * @return string */ public static function cacheKey(int $personId): string { return 'person-role-' . $personId; } /** * Obtain the cache roles for a person * * @param int $personId * @return mixed */ public static function getCache(int $personId): mixed { return ClubhouseCache::get(self::cacheKey($personId)); } /** * Put the cached roles for a person * * @param int $personId * @param mixed $roles */ public static function putCache(int $personId, mixed $roles): void { ClubhouseCache::put(self::cacheKey($personId), $roles); } }
true
0d0861fd3182f9a697d7e2a313efb480e8f78e2a
PHP
hardcoded74/elliott-forum
/src/addons/ThemeHouse/UIX/XF/Repository/Style.php
UTF-8
2,278
2.578125
3
[]
no_license
<?php namespace ThemeHouse\UIX\XF\Repository; /** * Class Style * @package ThemeHouse\UIX\XF\Repository */ class Style extends XFCP_Style { /** * @param array $products * @return array */ public function prepareTHStyles(array $products) { $productIdMap = []; foreach ($products as $key => &$product) { $productIdMap[$product['id']] = $key; $product['installed'] = false; } unset($product); $productIds = array_keys($productIdMap); $styles = $this->findStylesByTHProductIds($productIds); foreach ($styles as $style) { if (isset($productIdMap[$style->th_product_id_uix])) { $key = $productIdMap[$style->th_product_id_uix]; $product = $products[$key]; $product['isOutdated'] = $this->isTHStyleOutdated($style, $product); $product['installed'] = $style; $products[$key] = $product; } } return $products; } /** * @param array $productIds * @return \XF\Mvc\Entity\ArrayCollection */ public function findStylesByTHProductIds(array $productIds) { return $this->finder('XF:Style')->where('th_product_id_uix', $productIds)->fetch(); } /** * @param \XF\Entity\Style $style * @param array $product * @return bool */ protected function isTHStyleOutdated(\XF\Entity\Style $style, array $product) { /** @var \ThemeHouse\UIX\XF\Entity\Style $style */ if (version_compare($style->th_product_version_uix, $product['latest_version']) === -1) { return true; } return false; } /** * @param array $versions * @return array */ public function prepareTHVersions(array $versions) { preg_match('/^\d.\d.\d/', \XF::$version, $match); $xfVersionMinorRelease = $match[0]; $minorReleaseVersions = []; foreach ($versions as $version) { preg_match('/^\d.\d.\d/', $version['version'], $match); if ($match[0] === $xfVersionMinorRelease) { $minorReleaseVersions[] = $version; } } return $minorReleaseVersions; } }
true
722474159af9b0c1123838c8f68bb5a72ea4986a
PHP
GB-CodeDreams/Statist
/web-interface/ai/view/register.php
UTF-8
3,102
2.75
3
[]
no_license
<?/* Шаблон страницы регистрации администратора ======================= $user - пользователь, регистрирующийся от имени администартора */?> <?php $instUsers = Users::Instance(); global $link; // Обработка отправки формы. if (!empty($_POST)){ $login = mysqli_real_escape_string($link, $_POST['login']); $username = mysqli_real_escape_string($link, $_POST['username']); $password = mysqli_real_escape_string($link, $_POST['password']); $password2 = mysqli_real_escape_string($link, $_POST['password2']); $user = $instUsers->GetByLogin($login); if($_POST['password'] != $_POST['password2']){ $err = 'Пароли не совпадают!'; }elseif(is_array($user)){ $err = 'Такой пользователь уже существует!'; }else{ $instUsers->NewUser($login, $password, $username); header('Location: index.php'); die(); } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Интерфейс администратора</title> <link rel="stylesheet" type="text/css" media="screen" href="view/style.css" /> </head> <body> <h1><?php echo "$title"; ?></h1> <br> <?php if(isset($user)){ echo 'Привет, '.$user['username'].'.<br/><br/><a href="index.php?r=user/logout">Выход</a>'; }else{ echo '<a href="index.php?r=user/login">Вход</a>'; }?> | <a href="../../web-interface/ui/php/index.php?c=statistic&act=general_statistics">Панель пользователя</a> | <a href="index.php?r=admin/sites">Справочник сайтов</a> | <a href="index.php?r=admin/persons">Справочник личностей</a> | <hr/> <h2 align="center">Новый пользователь</h2> <?if(isset($err)) echo '<h3 class="stop">' . $err . '</h3><br/>';?> <form method="post"> <fieldset> <legend>Введите свои данные</legend> <table id="logtable"> <tr> <td><label for="logname">Логин:</label></td> <td><input type="email" size="50" id="login" placeholder="login@mail.ru" name="login" /></td> </tr> <tr> <td><label for="name">Имя:</label></td> <td><input type="text" size="50" id="login" name="username" /></td> </tr> <tr> <td><label for="password">Пароль:</label></td> <td><input type="password" size="50" id="login" name="password" /></td> </tr> <tr> <td><label for="password">Повторите пароль:</label></td> <td><input type="password" size="50" id="login" name="password2" /></td> </tr> <tr> <td colspan="2" id="login2"><input type="submit" value="Отправить" /></td> </tr> </table> </fieldset> </form> <hr/> </body> </html>
true
d4865f6148cdbbc74c9e4df15f00315c6607a74c
PHP
Innmind/BlackBox
/tests/Set/Composite/CombinationTest.php
UTF-8
3,629
2.703125
3
[ "MIT" ]
permissive
<?php declare(strict_types = 1); namespace Tests\Innmind\BlackBox\Set\Composite; use Innmind\BlackBox\Set\{ Composite\Combination, Value, Dichotomy, }; use PHPUnit\Framework\TestCase; class CombinationTest extends TestCase { public function testToArray() { $combination = new Combination(Value::immutable('foo')); $this->assertSame(['foo'], $combination->unwrap()); } public function testAdd() { $combination = new Combination(Value::immutable('foo')); $combination2 = $combination->add(Value::immutable('baz')); $this->assertInstanceOf(Combination::class, $combination2); $this->assertNotSame($combination, $combination2); $this->assertSame(['foo'], $combination->unwrap()); $this->assertSame(['baz', 'foo'], $combination2->unwrap()); } public function testIsImmutableIfAllValuesAreImmutable() { $immutable = new Combination(Value::immutable(42)); $immutable = $immutable->add(Value::immutable(24)); $mutable = $immutable->add(Value::mutable(static fn() => new \stdClass)); $immutable = $immutable->add(Value::immutable(66)); $this->assertTrue($immutable->immutable()); $this->assertFalse($mutable->immutable()); } public function testCombinationIsShrinkableAsLongAsAtLeastOneValueIsShrinkable() { $nonShrinkable = new Combination(Value::immutable(42)); $nonShrinkable = $nonShrinkable->add(Value::immutable(24)); $nonShrinkable = $nonShrinkable->add(Value::immutable(66)); $this->assertFalse($nonShrinkable->shrinkable()); $shrinkable = new Combination(Value::immutable(42)); $shrinkable = $shrinkable->add(Value::immutable( 24, new Dichotomy( static fn() => Value::immutable(12), static fn() => Value::immutable(23), ), )); $shrinkable = $shrinkable->add(Value::immutable(66)); $this->assertTrue($shrinkable->shrinkable()); } public function testShrinkUsesFirstTwoValuesThatAreShrinkableToBuildItsOwnDichotomy() { $combination = new Combination(Value::immutable( 66, new Dichotomy( static fn() => Value::immutable(33), static fn() => Value::immutable(65), ), )); $combination = $combination->add(Value::immutable( 24, new Dichotomy( static fn() => Value::immutable(12), static fn() => Value::immutable(23), ), )); $combination = $combination->add(Value::immutable(42)); $shrinked = $combination->shrink(); $this->assertIsArray($shrinked); $this->assertCount(2, $shrinked); $this->assertInstanceOf(Combination::class, $shrinked['a']); $this->assertInstanceOf(Combination::class, $shrinked['b']); $this->assertSame( [42, 12, 66], $shrinked['a']->unwrap(), ); $this->assertSame( [42, 24, 33], $shrinked['b']->unwrap(), ); $this->assertSame( [42, 12, 33], $shrinked['a']->shrink()['a']->unwrap(), ); $this->assertSame( [42, 12, 65], $shrinked['a']->shrink()['b']->unwrap(), ); $this->assertSame( [42, 23, 33], $shrinked['b']->shrink()['b']->unwrap(), ); $this->assertSame( [42, 12, 33], $shrinked['b']->shrink()['a']->unwrap(), ); } }
true
4d4275711aa2a3d08b532748cac9e032dbb6a5e5
PHP
robertogallea/php-fatturapa
/src/Model/Ordinaria/FatturaElettronicaBody/DatiGenerali/DatiSAL.php
UTF-8
1,494
2.640625
3
[]
no_license
<?php /** * Created by PhpStorm. * User: Roberto Gallea * Date: 14/03/2019 * Time: 21:38 */ namespace Robertogallea\FatturaPA\Model\Ordinaria\FatturaElettronicaBody\DatiGenerali; use Robertogallea\FatturaPA\Exceptions\InvalidValueException; use Robertogallea\FatturaPA\Traits\Traversable; use Sabre\Xml\Reader; use Sabre\Xml\Writer; use Sabre\Xml\XmlSerializable; class DatiSAL implements XmlSerializable { use Traversable; /** @var string */ protected $RiferimentoFase; private function traverse(Reader $reader) { $children = $reader->parseInnerTree(); foreach($children as $child) { if ($child['name'] === '{}RiferimentoFase') { $this->RiferimentoFase = $child['value']; } } } function xmlSerialize(Writer $writer) { $data = array(); $this->RiferimentoFase ? $data['RiferimentoFase'] = $this->RiferimentoFase : null; $writer->write($data); } /** * @return string */ public function getRiferimentoFase() { return $this->RiferimentoFase; } /** * @param string $RiferimentoFase * @return DatiSAL */ public function setRiferimentoFase($RiferimentoFase) { if (strlen($RiferimentoFase) > 3) { throw new InvalidValueException("RiferimentoFase must be a string of maximum 2 characters"); } $this->RiferimentoFase = $RiferimentoFase; return $this; } }
true
1421a225ccffcf988ac76a0bca4678452d94ffa8
PHP
sergeytkachenko/robot-labyrinth
/app/modules/public/controllers/RobotController.php
UTF-8
1,046
2.71875
3
[]
no_license
<?php class RobotController extends \MVC\Controller{ public function moveAction() { $mapCoordinates = json_decode($this->getParam('map')); $history = json_decode($this->getParam('history')); $absoluteHistory = json_decode($this->getParam('absoluteHistory')); $currentCell = json_decode($this->getParam('currentCell')); $finishCell = json_decode($this->getParam('finishCell')); $map = new Labyrinth\Map(); $map->setCoordinates($mapCoordinates); try { $robot = new Labyrinth\Alex($map, $currentCell, $finishCell); $robot->setHistory($history); $robot->setAbsoluteHistory($absoluteHistory); $move = $robot->move(); } catch (Exception $e) { return array( 'success' => false, 'msg' => $e->getMessage() ); } return array( 'move' => $move, 'history' => $robot->getHistory(), 'success' => true ); } }
true
43d0b7a87336da6cde8666059930e0de93e8d0ed
PHP
mgerson/filemanager3
/filemanager3.php
UTF-8
835
3.3125
3
[]
no_license
<?php $path = dirname(__FILE__); $file = $path.'/files/exemplo.txt'; $content = ''; if (file_exists($file) && is_readable($file)) { $lista = file($file); for ($i = 0; $i < count($lista); $i++) { // separa cada elemento e guarda em um array temporario $tmp = explode(', ', $lista[$i]); // atribui cada elemento do array temporario ao novo array $lista[$i] = array('apelido' => $tmp[0], 'outrosnomes' => rtrim($tmp[1])); //rtrim para evitar que crie um espaco depois do enter no texto $content = $lista; } } else { $content = 'O ficheiro solicitado nao foi encontrado ou esta protegido'; } ?> <html> <head> <title>file</title> </head> <body> <p><b><?php print_r($content);?></b></p> </body> </html>
true
9cd247151573f0f55a4a6a407ffc31b232ff040e
PHP
pilot114/vk-apigen
/src/Method/Messages/GetConversationsById.php
UTF-8
1,809
2.75
3
[]
no_license
<?php namespace VkApigen\Method\Messages; /** * Returns conversations by their IDs */ class GetConversationsById extends \VkApigen\BaseMethod { protected $params = []; protected $accessTokenType; public function __construct($client, $defaultQuery, string $accessTokenType = null) { $this->accessTokenType = $accessTokenType; parent::__construct($client, $defaultQuery); } public function isAvailable() { return in_array($this->accessTokenType, ['user', 'group']); } public function call() { return $this->onCall('messages.getConversationsById'); } /** * Destination IDs. "For user: 'User ID', e.g. '12345'. For chat: '2000000000' + 'chat_id', e.g. '2000000001'. For community: '- community ID', e.g. '-12345'. " * * {"type":"array","items":{"type":"integer"},"maxItems":100} */ public function peer_ids(array $peer_ids) : self { $this->params['peer_ids'] = $peer_ids; return $this; } /** * Return extended properties * * {"type":"bool"} */ public function _extended(bool $extended) : self { $this->params['extended'] = $extended; return $this; } /** * Profile and communities fields to return. * * {"type":"array","items":{"$ref":"objects.json#\/definitions\/base_user_group_fields"}} */ public function _fields(array $fields) : self { $this->params['fields'] = $fields; return $this; } /** * Group ID (for group messages with group access token) * * {"type":"int","format":"int64","minimum":0,"entity":"owner"} */ public function _group_id(int $group_id) : self { $this->params['group_id'] = $group_id; return $this; } }
true
5b0ce83ec6afd459a319fdc043609cec29169399
PHP
awesomite/stack-trace
/examples/read-arguments.php
UTF-8
1,899
2.640625
3
[ "MIT" ]
permissive
<?php /* * This file is part of the awesomite/stack-trace package. * * (c) Bartłomiej Krukowski <bartlomiej@krukowski.me> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ require \implode(\DIRECTORY_SEPARATOR, array(__DIR__, '..', 'vendor', 'autoload.php')); require_once __DIR__ . \DIRECTORY_SEPARATOR . 'StackTracePrinter.php'; /** * @internal * * @param $arg1 * @param $arg2 */ function myFirstFunction($arg1, $arg2) { $callable = function () { mySecondFunction('foo', 'bar'); }; \call_user_func($callable, 'redundant'); } /** * @internal * * @param $foo * @param $bar */ function mySecondFunction($foo, $bar) { myThirdFunction(\tmpfile(), \M_PI); } /** * @internal * * @param $argument1 * @param $argument2 */ function myThirdFunction($argument1, $argument2) { $printer = new StackTracePrinter(); $printer->printStackTrace(); } myFirstFunction('hello', 'world'); /* Output: #1 Awesomite\StackTrace\StackTraceFactory->create($stepLimit, $ignoreArgs) Place in code: (...)/stack-trace/examples/StackTracePrinter.php:26 Arguments: undefined (default 0) undefined (default false) #2 StackTracePrinter->printStackTrace() Place in code: (...)/stack-trace/examples/read-arguments.php:49 #3 myThirdFunction($argument1, $argument2) Place in code: (...)/stack-trace/examples/read-arguments.php:37 Arguments: resource #11 of type stream M_PI #4 mySecondFunction($foo, $bar) Place in code: (...)/stack-trace/examples/read-arguments.php:24 Arguments: “foo” “bar” #5 {closure}() Place in code: (...)/stack-trace/examples/read-arguments.php:26 Arguments: “redundant” #6 myFirstFunction($arg1, $arg2) Place in code: (...)/stack-trace/examples/read-arguments.php:52 Arguments: “hello” “world” */
true
6318472ce22cf7ecb7ab0177a9040da01d8be975
PHP
whafeez/cricktest
/database/migrations/2020_02_01_121728_create_team_final_score_table.php
UTF-8
970
2.578125
3
[]
no_license
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateTeamFinalScoreTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('team_final_score', function (Blueprint $table) { $table->bigIncrements('id'); $table->integer('team'); $table->integer('score'); $table->integer('wickets'); $table->double('overs'); $table->unsignedBigInteger('match_id'); $table->unsignedBigInteger('season_id'); $table->foreign('match_id')->references('id') ->on('matches'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('team_final_score'); } }
true
1e039d38b60653d398bf58e7ea7139708ec1e7f8
PHP
aditnanda/native-crud-with-bug
/index.php
UTF-8
1,052
2.609375
3
[]
no_license
<?php include_once('koneksi.php'); $q = mysqli_query($koneksi, "SELECT * FROM users"); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <a href="form_submit.php">Tambah Data</a> <table> <thead> <tr> <th>Nama</th> <th>Kelas</th> <th>Aksi</th> </tr> </thead> <tbody> <?php while ($row = mysqli_fetch_assoc($q)) { ?> <tr> <td><?= $row['name'] ?></td> <td><?= $row['class'] ?></td> <td> <a href="form_submit.php?action=ubah&id=<?= $row['id'] ?>">Ubah</a> <a href="submit.php?action=hapus&id=<?= $row['id'] ?>">Hapus</a> </td> </tr> <?php } ?> </tbody> </table> </body> </html>
true
d942ab9c6b12159bb0e11796dd3c23cbb1a43401
PHP
ActiveWafl/Extensions
/Users/UserAuthentication/SignonHandlers/Database.php
UTF-8
7,961
2.71875
3
[]
no_license
<?php namespace Wafl\Extensions\Users\UserAuthentication\SignonHandlers; use DblEj\Application\IApplication, Exception; class Database implements ISignonHandler { private $_settings = ["UserTable"=>"Users", "UserTableKeyField"=>"UserId", "UserTableKeyIsAuto"=>true, "SessionTable"=>"Sessions", "UsernameColumn"=>"Username", "PasswordColumn"=>"Password", "SessionIdColumn"=>"SessionId", "PasswordHashType"=>"","PasswordSalt"=>"", "PasswordSaltType"=>"Append"]; /** * * @var IApplication */ private $_app; private $_dataStorage; public function Initialize(IApplication $application) { $this->_app = $application; $this->_dataStorage = $this->_app->GetStorageEngine($this->_settings["DataConnection"]); if (!$this->_dataStorage) { throw new Exception("Cannot run the database signon handler without a DataStorage connection."); } if (!$this->_dataStorage->DoesLocationExist($this->_settings["UserTable"]) || !$this->_dataStorage->DoesLocationExist($this->_settings["SessionTable"])) { if ($this->_settings["UserTableKeyField"]==$this->_settings["UsernameColumn"]) { $sqlFileName = "Database_RedundantUserId"; } elseif ($this->_settings["UsernameColumn"]==$this->_settings["PasswordColumn"]) { $sqlFileName = "Database_RedundantUsername"; } elseif ($this->_settings["PasswordColumn"]==$this->_settings["UserTableKeyField"]) { $sqlFileName = "Database_RedundantPassword"; } else { $sqlFileName = "Database"; } if (is_a($this->_dataStorage,"\\Wafl\\Extensions\\Storage\\SqlServer")) { $sql = file_get_contents(__DIR__.DIRECTORY_SEPARATOR."Sql".DIRECTORY_SEPARATOR."$sqlFileName.mssql"); } else { $sql = file_get_contents(__DIR__.DIRECTORY_SEPARATOR ."Sql".DIRECTORY_SEPARATOR."$sqlFileName.sql"); } $sql = \str_replace("{\$USERS_TABLE}", $this->_settings["UserTable"], $sql); $sql = \str_replace("{\$SESSIONS_TABLE}", $this->_settings["SessionTable"], $sql); $sql = \str_replace("{\$USERID_COLUMN}", $this->_settings["UserTableKeyField"], $sql); $sql = \str_replace("{\$USERNAME_COLUMN}", $this->_settings["UsernameColumn"], $sql); $sql = \str_replace("{\$PASSWORD_COLUMN}", $this->_settings["PasswordColumn"], $sql); $sql = \str_replace("{\$SESSIONID_COLUMN}", $this->_settings["SessionIdColumn"], $sql); $this->_dataStorage->DirectScriptExecute($sql, true); $this->_dataStorage->UpdateStorageLocations(); } } public function Get_SignonFields() { return ["Username","Password"]; } public function SignUp($fieldValues) { $username = $fieldValues["Username"]; $password = $fieldValues["Password"]; $dupUser = $this->_dataStorage->GetData($this->_settings["UserTable"], $this->_settings["UsernameColumn"], $username); if (!$dupUser) { return $this->_dataStorage->StoreData($this->_settings["UserTable"], [$this->_settings["UsernameColumn"],$this->_settings["PasswordColumn"]], [$this->_settings["UsernameColumn"]=>$username, $this->_settings["PasswordColumn"]=>$password], $this->_settings["UserTableKeyField"], $this->_settings["UserTableKeyIsAuto"]); } else { throw new Exception("The user already exists"); } } public function SignOn($fieldValues, $sessionId) { $returnArray = ["SessionId"=>$sessionId]; //sso providers may return a token or something. We just give back our session id since that is our persistance key. if (isset($fieldValues["Username"])) { $userRow = $this->_dataStorage->GetData($this->_settings["UserTable"], $this->_settings["UsernameColumn"], $fieldValues["Username"]); if (!is_null($userRow) && $userRow[$this->_settings["PasswordColumn"]] == $this->_getHash($fieldValues["Password"])) { //delete old sessions $this->_dataStorage->DeleteData($this->_settings["SessionTable"], $this->_settings["SessionIdColumn"], $sessionId); $this->_dataStorage->StoreData($this->_settings["SessionTable"], [$this->_settings["SessionIdColumn"],$this->_settings["UserTableKeyField"]], [$this->_settings["SessionIdColumn"]=>$sessionId, $this->_settings["UserTableKeyField"]=>$userRow[$this->_settings["UserTableKeyField"]]], $this->_settings["SessionIdColumn"]); } else { $returnArray = null; } } return $returnArray; } public function SignOff($sessionTokens, $killSessions = true) { if ($killSessions) { $phpSessionId = $sessionTokens["SessionId"]; $this->_dataStorage->DeleteData($this->_settings["SessionTable"], $this->_settings["SessionIdColumn"], $phpSessionId); } } public function IsSignedOn($sessionTokens) { $phpSessionId = $sessionTokens["SessionId"]; $sessionRow = $this->_dataStorage->GetData($this->_settings["SessionTable"], $this->_settings["SessionIdColumn"], $phpSessionId); return $sessionRow!=null; } public function Configure($settingName, $settingValue) { $this->_settings[$settingName] = $settingValue; } public function Get_RequiredSettings() { return ["DataConnection"]; } public function Get_OptionalSettings() { return ["UserTable","SessionTable","UsernameColumn","UserTableKeyField","UserTableKeyIsAuto,","PasswordColumn","SessionIdColumn","PasswordHashType","PasswordSalt","PasswordSaltType"]; } private function _getHash($password) { switch ($this->_settings["PasswordHashType"]) { case "md5": switch ($this->_settings["PasswordSaltType"]) { case "Append": $password = md5($password.$this->_settings["PasswordSalt"]); case "Prepend": $password = md5($this->_settings["PasswordSalt"].$password); case "HashAppend": $password = md5($password.md5($this->_settings["PasswordSalt"])); case "HashPrepend": $password = md5(md5($this->_settings["PasswordSalt"]).$password); } break; case "sha1": switch ($this->_settings["PasswordSaltType"]) { case "Append": $password = sha1($password.$this->_settings["PasswordSalt"]); case "Prepend": $password = sha1($this->_settings["PasswordSalt"].$password); case "HashAppend": $password = sha1($password.sha1($this->_settings["PasswordSalt"])); case "HashPrepend": $password = sha1(sha1($this->_settings["PasswordSalt"]).$password); } break; } return $password; } public function GetUserIdentifier($sessionTokens) { $phpSessionId = $sessionTokens["SessionId"]; $sessionRow = $this->_dataStorage->GetData($this->_settings["SessionTable"], $this->_settings["SessionIdColumn"], $phpSessionId); if ($sessionRow) { $userRow = $this->_dataStorage->GetData($this->_settings["UserTable"], $this->_settings["UserTableKeyField"], $sessionRow[$this->_settings["UserTableKeyField"]]); } else { $userRow = null; } return $userRow?$userRow[$this->_settings["UserTableKeyField"]]:null; } }
true
d8d5b4b48a54cd2fe74d64ab2072dad75298895e
PHP
ljphalen/jinli
/gamehall/gamedev/Source/Modules/Admin/Model/ContractModel.class.php
UTF-8
1,026
2.78125
3
[]
no_license
<?php /** * 合同模型 * @author noprom */ class ContractModel extends Model { protected $trueTableName = 'contract'; // 合同状态 public static $status = array( '0' => '未申请', '1' => '申请中', '-1' => '申请不通过', '2' => '扫描件未回传', '3' => '审核中', '-2' => '审核不通过', '4' => '审核通过', '-3' => '已过期', '5' => '即将到期', ); /** * 获得状态 * @param int $status */ public static function getStatus($status=null) { return self::$status[$status]; } /** * 获得合同类型 * @param null $type */ public static function getContractType($type=null){ $type = intval($type); return $type ? '续签合同':'主合同'; } /** * 获得商务对接人 * @param null $type */ public static function getJoiner($id){ $joiner = M('contract_contact')->find($id); return $joiner['name']; } }
true
6ec13f7d0a36b7dd6eec18ffea714ba4ce215dcf
PHP
ronv/the-black
/kirby/vendor/getkirby/toolkit/lib/sql.php
UTF-8
22,449
2.953125
3
[ "MIT", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php /** * SQL * * SQL Query builder * * @package Kirby Toolkit * @author Bastian Allgeier <bastian@getkirby.com>, Lukas Bestle <lukas@getkirby.com> * @link http://getkirby.com * @copyright Bastian Allgeier * @license http://www.opensource.org/licenses/mit-license.php MIT License */ class Sql { // list of literals which should not be escaped in queries public static $literals = array('NOW()', null); // sql formatting methods, defined below public static $methods = array(); // the parent database connection and database query public $database; public $dbquery; // list of bindings by sql query string that defines them protected $bindings = array(); /** * Constructor * * @param Database $database * @param Database\Query $dbquery Database query that is used to set the bindings directly */ public function __construct($database, $dbquery = null) { $this->database = $database; $this->dbquery = $dbquery; } /** * Sets and returns query-specific bindings * * @param string $query SQL query string that contains the bindings * @param array $values Array of bindings to set (null to get the bindings) * @return array */ public function bindings($query, $values = null) { if(is_null($values)) { return a::get($this->bindings, $query, array()); } else { if(!is_null($query)) $this->bindings[$query] = $values; // directly register bindings if possible if($this->dbquery) $this->dbquery->bindings($values); } } /** * Calls an SQL method using the correct database type * * @param string $method * @param array $arguments * @return mixed */ public function __call($method, $arguments) { $type = $this->database->type(); if(isset(static::$methods[$type][$method])) { $method = static::$methods[$type][$method]; } else { // fallback to shared method if(!isset(static::$methods['_shared'][$method])) { throw new Error('SQL method ' . $method . ' is not defined for database type ' . $type); } $method = static::$methods['_shared'][$method]; } // pass the sql object as first argument array_unshift($arguments, $this); return call($method, $arguments); } /** * Registers a method for a specified database type * The function must take this SQL object as first parameter and set bindings on it * * @param string $name * @param callable $function * @param string $type 'mysql', 'sqlite' or '_shared' */ public static function registerMethod($name, $function, $type = '_shared') { if(!isset(static::$methods[$type])) static::$methods[$type] = array(); static::$methods[$type][$name] = $function; } } /** * Returns a randomly generated binding name * * @param string $label String that contains lowercase letters and numbers to use as a readable identifier * @return string */ sql::registerMethod('generateBindingName', function($sql, $label) { // make sure that the binding name is valid to prevent injections if(!preg_match('/^[a-z0-9]+$/', $label)) $label = 'invalid'; return ':' . $label . '_' . uniqid(); }); /** * Builds a select clause * * @param array $params List of parameters for the select clause. Check out the defaults for more info. * @return string */ sql::registerMethod('select', function($sql, $params = array()) { $defaults = array( 'table' => '', 'columns' => '*', 'join' => false, 'distinct' => false, 'where' => false, 'group' => false, 'having' => false, 'order' => false, 'offset' => 0, 'limit' => false, ); $options = array_merge($defaults, $params); $query = array(); $bindings = array(); $query[] = 'SELECT'; // select distinct values if($options['distinct']) $query[] = 'DISTINCT'; // validate table if(!$sql->database->validateTable($options['table'])) throw new Error('Invalid table ' . $options['table']); // columns if(empty($options['columns'])) { $query[] = '*'; } else if(is_array($options['columns'])) { // validate columns $columns = array(); foreach($options['columns'] as $column) { list($table, $columnPart) = $sql->splitIdentifier($options['table'], $column); if(!$sql->database->validateColumn($table, $columnPart)) { throw new Error('Invalid column ' . $column); } $columns[] = $sql->combineIdentifier($table, $columnPart); } $query[] = implode(', ', $columns); } else { $query[] = $options['columns']; } // table $query[] = 'FROM ' . $sql->quoteIdentifier($options['table']); // join if(!empty($options['join'])) { foreach($options['join'] as $join) { $joinType = ltrim(strtoupper(a::get($join, 'type', '')) . ' JOIN'); if(!in_array($joinType, array( 'JOIN', 'INNER JOIN', 'OUTER JOIN', 'LEFT OUTER JOIN', 'LEFT JOIN', 'RIGHT OUTER JOIN', 'RIGHT JOIN', 'FULL OUTER JOIN', 'FULL JOIN', 'NATURAL JOIN', 'CROSS JOIN', 'SELF JOIN' ))) throw new Error('Invalid join type ' . $joinType); // validate table if(!$sql->database->validateTable($join['table'])) throw new Error('Invalid table ' . $join['table']); // ON can't be escaped here $query[] = $joinType . ' ' . $sql->quoteIdentifier($join['table']) . ' ON ' . $join['on']; } } // where if(!empty($options['where'])) { // WHERE can't be escaped here $query[] = 'WHERE ' . $options['where']; } // group if(!empty($options['group'])) { // GROUP BY can't be escaped here $query[] = 'GROUP BY ' . $options['group']; } // having if(!empty($options['having'])) { // HAVING can't be escaped here $query[] = 'HAVING ' . $options['having']; } // order if(!empty($options['order'])) { // ORDER BY can't be escaped here $query[] = 'ORDER BY ' . $options['order']; } // offset and limit if($options['offset'] > 0 || $options['limit']) { if(!$options['limit']) $options['limit'] = '18446744073709551615'; $offsetBinding = $sql->generateBindingName('offset'); $bindings[$offsetBinding] = $options['offset']; $limitBinding = $sql->generateBindingName('limit'); $bindings[$limitBinding] = $options['limit']; $query[] = 'LIMIT ' . $offsetBinding . ', ' . $limitBinding; } $query = implode(' ', $query); $sql->bindings($query, $bindings); return $query; }); /** * Builds an insert clause * * @param array $params List of parameters for the insert clause. See defaults for more info. * @return string */ sql::registerMethod('insert', function($sql, $params = array()) { $defaults = array( 'table' => '', 'values' => false, ); $options = array_merge($defaults, $params); $query = array(); $bindings = array(); // validate table if(!$sql->database->validateTable($options['table'])) throw new Error('Invalid table ' . $options['table']); $query[] = 'INSERT INTO ' . $sql->quoteIdentifier($options['table']); $query[] = $sql->values($options['table'], $options['values'], ', ', false); $query = implode(' ', $query); $sql->bindings($query, $bindings); return $query; }); /** * Builds an update clause * * @param array $params List of parameters for the update clause. See defaults for more info. * @return string */ sql::registerMethod('update', function($sql, $params = array()) { $defaults = array( 'table' => '', 'values' => false, 'where' => false, ); $options = array_merge($defaults, $params); $query = array(); $bindings = array(); // validate table if(!$sql->database->validateTable($options['table'])) throw new Error('Invalid table ' . $options['table']); $query[] = 'UPDATE ' . $sql->quoteIdentifier($options['table']) . ' SET'; $query[] = $sql->values($options['table'], $options['values']); if(!empty($options['where'])) { // WHERE can't be escaped here $query[] = 'WHERE ' . $options['where']; } $query = implode(' ', $query); $sql->bindings($query, $bindings); return $query; }); /** * Builds a delete clause * * @param array $params List of parameters for the delete clause. See defaults for more info. * @return string */ sql::registerMethod('delete', function($sql, $params = array()) { $defaults = array( 'table' => '', 'where' => false, ); $options = array_merge($defaults, $params); $query = array(); $bindings = array(); // validate table if(!$sql->database->validateTable($options['table'])) throw new Error('Invalid table ' . $options['table']); $query[] = 'DELETE FROM ' . $sql->quoteIdentifier($options['table']); if(!empty($options['where'])) { // WHERE can't be escaped here $query[] = 'WHERE ' . $options['where']; } $query = implode(' ', $query); $sql->bindings($query, $bindings); return $query; }); /** * Builds a safe list of values for insert, select or update queries * * @param string $table Table name * @param mixed $values A value string or array of values * @param string $separator A separator which should be used to join values * @param boolean $set If true builds a set list of values for update clauses * @param boolean $enforceQualified Always use fully qualified column names * @return string */ sql::registerMethod('values', function($sql, $table, $values, $separator = ', ', $set = true, $enforceQualified = false) { if(!is_array($values)) return $values; if($set) { $output = array(); $bindings = array(); foreach($values as $key => $value) { // validate column list($table, $column) = $sql->splitIdentifier($table, $key); if(!$sql->database->validateColumn($table, $column)) { throw new Error('Invalid column ' . $key); } $key = $sql->combineIdentifier($table, $column, $enforceQualified !== true); if(in_array($value, sql::$literals, true)) { $output[] = $key . ' = ' . (($value === null)? 'null' : $value); continue; } elseif(is_array($value)) { $value = json_encode($value); } $valueBinding = $sql->generateBindingName('value'); $bindings[$valueBinding] = $value; $output[] = $key . ' = ' . $valueBinding; } $sql->bindings(null, $bindings); return implode($separator, $output); } else { $fields = array(); $output = array(); $bindings = array(); foreach($values as $key => $value) { // validate column list($table, $column) = $sql->splitIdentifier($table, $key); if(!$sql->database->validateColumn($table, $column)) { throw new Error('Invalid column ' . $key); } $key = $sql->combineIdentifier($table, $column, $enforceQualified !== true); $fields[] = $key; if(in_array($value, sql::$literals, true)) { $output[] = ($value === null)? 'null' : $value; continue; } elseif(is_array($value)) { $value = json_encode($value); } $valueBinding = $sql->generateBindingName('value'); $bindings[$valueBinding] = $value; $output[] = $valueBinding; } $sql->bindings(null, $bindings); return '(' . implode($separator, $fields) . ') VALUES (' . implode($separator, $output) . ')'; } }); /** * Creates the sql for dropping a single table * * @param string $table * @return string */ sql::registerMethod('dropTable', function($sql, $table) { // validate table if(!$sql->database->validateTable($table)) throw new Error('Invalid table ' . $table); return 'DROP TABLE ' . $sql->quoteIdentifier($table); }); /** * Creates a table with a simple scheme array for columns * Default version for MySQL * * @todo add more options per column * @param string $table The table name * @param array $columns * @return string */ sql::registerMethod('createTable', function($sql, $table, $columns = array()) { $output = array(); $keys = array(); $bindings = array(); foreach($columns as $name => $column) { // column type if(!isset($column['type'])) throw new Error('No column type given for column ' . $name); switch($column['type']) { case 'id': $template = '{column.name} INT(11) UNSIGNED NOT NULL AUTO_INCREMENT'; $column['key'] = 'PRIMARY'; break; case 'varchar': $template = '{column.name} varchar(255) {column.null} {column.default}'; break; case 'text': $template = '{column.name} TEXT'; break; case 'int': $template = '{column.name} INT(11) UNSIGNED {column.null} {column.default}'; break; case 'timestamp': $template = '{column.name} TIMESTAMP {column.null} {column.default}'; break; default: throw new Error('Unsupported column type: ' . $column['type']); } // null if(a::get($column, 'null') === false) { $null = 'NOT NULL'; } else { $null = 'NULL'; } // indexes/keys $key = false; if(isset($column['key'])) { $column['key'] = strtoupper($column['key']); // backwards compatibility if($column['key'] === 'PRIMARY') $column['key'] = 'PRIMARY KEY'; if(in_array($column['key'], array('PRIMARY KEY', 'INDEX'))) { $key = $column['key']; $keys[$name] = $key; } } // default value $defaultBinding = null; if(isset($column['default'])) { $defaultBinding = $sql->generateBindingName('default'); $bindings[$defaultBinding] = $column['default']; } $output[] = trim(str::template($template, array( 'column.name' => $sql->quoteIdentifier($name), 'column.null' => $null, 'column.default' => r(!is_null($defaultBinding), 'DEFAULT ' . $defaultBinding), ))); } // combine columns $inner = implode(',' . PHP_EOL, $output); // add keys foreach($keys as $name => $key) { $inner .= ',' . PHP_EOL . $key . ' (' . $sql->quoteIdentifier($name) . ')'; } // make it a string $query = 'CREATE TABLE ' . $sql->quoteIdentifier($table) . ' (' . PHP_EOL . $inner . PHP_EOL . ')'; $sql->bindings($query, $bindings); return $query; }); /** * Creates a table with a simple scheme array for columns * SQLite version * * @todo add more options per column * @param string $table The table name * @param array $columns * @return string */ sql::registerMethod('createTable', function($sql, $table, $columns = array()) { $output = array(); $keys = array(); $bindings = array(); foreach($columns as $name => $column) { // column type if(!isset($column['type'])) throw new Error('No column type given for column ' . $name); switch($column['type']) { case 'id': $template = '{column.name} INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE'; break; case 'varchar': $template = '{column.name} TEXT {column.null} {column.key} {column.default}'; break; case 'text': $template = '{column.name} TEXT {column.null} {column.key} {column.default}'; break; case 'int': $template = '{column.name} INTEGER {column.null} {column.key} {column.default}'; break; case 'timestamp': $template = '{column.name} INTEGER {column.null} {column.key} {column.default}'; break; default: throw new Error('Unsupported column type: ' . $column['type']); } // null if(a::get($column, 'null') === false) { $null = 'NOT NULL'; } else { $null = 'NULL'; } // indexes/keys $key = false; if(isset($column['key'])) { $column['key'] = strtoupper($column['key']); // backwards compatibility if($column['key'] === 'PRIMARY') $column['key'] = 'PRIMARY KEY'; if(in_array($column['key'], array('PRIMARY KEY', 'INDEX'))) { $key = $column['key']; $keys[$name] = $key; } } // default value $default = null; if(isset($column['default'])) { // Apparently SQLite doesn't support bindings for default values $default = "'" . $sql->database->escape($column['default']) . "'"; } $output[] = trim(str::template($template, array( 'column.name' => $sql->quoteIdentifier($name), 'column.null' => $null, 'column.key' => r($key && $key != 'INDEX', $key), 'column.default' => r(!is_null($default), 'DEFAULT ' . $default), ))); } // combine columns $inner = implode(',' . PHP_EOL, $output); // make it a string $query = 'CREATE TABLE ' . $sql->quoteIdentifier($table) . ' (' . PHP_EOL . $inner . PHP_EOL . ')'; // set bindings for our first query $sql->bindings($query, $bindings); // add index keys foreach($keys as $name => $key) { if($key != 'INDEX') continue; $indexQuery = 'CREATE INDEX ' . $sql->quoteIdentifier($table . '_' . $name) . ' ON ' . $sql->quoteIdentifier($table) . ' (' . $sql->quoteIdentifier($name) . ')'; $query .= ';' . PHP_EOL . $indexQuery; } return $query; }, 'sqlite'); /** * Splits a (qualified) identifier into table and column * * @param $table string Default table if the identifier is not qualified * @param $identifier string * @return array */ sql::registerMethod('splitIdentifier', function($sql, $table, $identifier) { // split by dot, but only outside of quotes $parts = preg_split('/(?:`[^`]*`|"[^"]*")(*SKIP)(*F)|\./', $identifier); switch(count($parts)) { // non-qualified identifier case 1: return array($table, $sql->unquoteIdentifier($parts[0])); // qualified identifier case 2: return array($sql->unquoteIdentifier($parts[0]), $sql->unquoteIdentifier($parts[1])); // every other number is an error default: throw new Error('Invalid identifier ' . $identifier); } }); /** * Unquotes an identifier (table *or* column) * * @param $identifier string * @return string */ sql::registerMethod('unquoteIdentifier', function($sql, $identifier) { // remove quotes around the identifier if(in_array(str::substr($identifier, 0, 1), array('"', '`'))) $identifier = str::substr($identifier, 1); if(in_array(str::substr($identifier, -1), array('"', '`'))) $identifier = str::substr($identifier, 0, -1); // unescape duplicated quotes return str_replace(array('""', '``'), array('"', '`'), $identifier); }); /** * Combines an identifier (table and column) * Default version for MySQL * * @param $table string * @param $column string * @param $values boolean Whether the identifier is going to be used for a values clause * Only relevant for SQLite * @return string */ sql::registerMethod('combineIdentifier', function($sql, $table, $column, $values = false) { return $sql->quoteIdentifier($table) . '.' . $sql->quoteIdentifier($column); }); /** * Combines an identifier (table and column) * SQLite version * * @param $table string * @param $column string * @param $values boolean Whether the identifier is going to be used for a values clause * Only relevant for SQLite * @return string */ sql::registerMethod('combineIdentifier', function($sql, $table, $column, $values = false) { // SQLite doesn't support qualified column names for VALUES clauses if($values) return $sql->quoteIdentifier($column); return $sql->quoteIdentifier($table) . '.' . $sql->quoteIdentifier($column); }, 'sqlite'); /** * Quotes an identifier (table *or* column) * Default version for MySQL * * @param $identifier string * @return string */ sql::registerMethod('quoteIdentifier', function($sql, $identifier) { // * is special if($identifier === '*') return $identifier; // replace every backtick with two backticks $identifier = str_replace('`', '``', $identifier); // wrap in backticks return '`' . $identifier . '`'; }); /** * Quotes an identifier (table *or* column) * SQLite version * * @param $identifier string * @return string */ sql::registerMethod('quoteIdentifier', function($sql, $identifier) { // * is special if($identifier === '*') return $identifier; // replace every quote with two quotes $identifier = str_replace('"', '""', $identifier); // wrap in quotes return '"' . $identifier . '"'; }, 'sqlite'); /** * Returns a list of tables for a specified database * MySQL version * * @param string $database The database name * @return string */ sql::registerMethod('tableList', function($sql, $database) { $bindings = array(); $databaseBinding = $sql->generateBindingName('database'); $bindings[$databaseBinding] = $database; $query = 'SELECT TABLE_NAME AS name FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ' . $databaseBinding; $sql->bindings($query, $bindings); return $query; }, 'mysql'); /** * Returns a list of tables of the database * SQLite version * * @param string $database The database name * @return string */ sql::registerMethod('tableList', function($sql, $database) { return 'SELECT name FROM sqlite_master WHERE type = "table"'; }, 'sqlite'); /** * Returns a list of columns for a specified table * MySQL version * * @param string $database The database name * @param string $table The table name * @return string */ sql::registerMethod('columnList', function($sql, $database, $table) { $bindings = array(); $databaseBinding = $sql->generateBindingName('database'); $bindings[$databaseBinding] = $database; $tableBinding = $sql->generateBindingName('table'); $bindings[$tableBinding] = $table; $query = 'SELECT COLUMN_NAME AS name FROM INFORMATION_SCHEMA.COLUMNS '; $query .= 'WHERE TABLE_SCHEMA = ' . $databaseBinding . ' AND TABLE_NAME = ' . $tableBinding; $sql->bindings($query, $bindings); return $query; }, 'mysql'); /** * Returns a list of columns for a specified table * SQLite version * * @param string $database The database name * @param string $table The table name * @return string */ sql::registerMethod('columnList', function($sql, $database, $table) { // validate table if(!$sql->database->validateTable($table)) throw new Error('Invalid table ' . $table); return 'PRAGMA table_info(' . $sql->quoteIdentifier($table) . ')'; }, 'sqlite');
true
1580b921c2d7c45fd491de862c8e964be24036b9
PHP
tonga54/jumping_inflables
/app/core/View.php
UTF-8
248
2.71875
3
[]
no_license
<?php class Views{ function __construct($view,$data = null,$data1 = null,$data2 = null){ if(file_exists("./view/" . $view . ".php")){ require("./view/" . $view . ".php"); }else{ die("Vista no encontrada"); } } } ?>
true
57041b9bd488f2f2012b947410bef25a449ea253
PHP
ADmad/cakephp-i18n
/src/View/Widget/TimezoneWidget.php
UTF-8
2,312
2.8125
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace ADmad\I18n\View\Widget; use Cake\View\Form\ContextInterface; use Cake\View\Widget\SelectBoxWidget; use DateTimeZone; /** * Input widget class for generating a selectbox of timezone. */ class TimezoneWidget extends SelectBoxWidget { /** * {@inheritDoc} * * ### Options format * * `$data['options']` is expected to be associative array of regions for which * you want identifiers list. The key will be used as optgroup. * Eg. `['Asia' => DateTimeZone::ASIA, 'Europe' => DateTimeZone::EUROPE]` * * @param array $data Data to render with. * @param \Cake\View\Form\ContextInterface $context The current form context. * @return string A generated select box. * @throws \RuntimeException when the name attribute is empty. */ public function render(array $data, ContextInterface $context): string { $data['options'] = $this->_identifierList($data['options'] ?? []); return parent::render($data, $context); } /** * Converts list of regions to identifiers list. * * @param array $options List of regions * @return array */ protected function _identifierList(array $options): array { if (empty($options)) { $options = [ 'Africa' => DateTimeZone::AFRICA, 'America' => DateTimeZone::AMERICA, 'Antarctica' => DateTimeZone::ANTARCTICA, 'Arctic' => DateTimeZone::ARCTIC, 'Asia' => DateTimeZone::ASIA, 'Atlantic' => DateTimeZone::ATLANTIC, 'Australia' => DateTimeZone::AUSTRALIA, 'Europe' => DateTimeZone::EUROPE, 'Indian' => DateTimeZone::INDIAN, 'Pacific' => DateTimeZone::PACIFIC, 'UTC' => DateTimeZone::UTC, ]; } $identifiers = []; foreach ($options as $name => $region) { $list = (array)DateTimeZone::listIdentifiers($region); /** @psalm-suppress InvalidScalarArgument */ $identifiers[$name] = array_combine($list, $list); } if (count($identifiers) === 1) { $identifiers = current($identifiers); } return $identifiers; } }
true
ea189ec569501fb4a84b454eada7c6c92b9369eb
PHP
lazarocosta/FEUP_LBAW
/lbaw1655/proto/api/tickets/editaccount.php
UTF-8
1,503
2.703125
3
[]
no_license
<?php include_once('../../database/users.php'); /** * EDIT ACCOUNT */ if ($_GET["acao"] == "edit") { $name = trim(strip_tags($_POST["name"])); $address = trim(strip_tags($_POST["address"])); $pass = trim(strip_tags($_POST["password"])); $confirmPass = trim(strip_tags($_POST["confirmPassword"])); $phone = trim(strip_tags($_POST["phone"])); if($pass != "" && $pass != $confirmPass){ $_SESSION['error_messages'][] = 'The passwords must match.'; header('Location: ../../pages/authentication/homepage.php'); exit; } try { editProfile($_SESSION['iduser'],$name, $address, $password,$phone); $_SESSION['success_messages'][] = 'Profile updated with success.'; header('Location: ../../pages/users/profile.php'); exit(); } catch (PDOException $e) { $_SESSION['error_messages'][] = 'Could not update profile. Please try again.'; header('Location: ../../pages/authentication/homepage.php'); exit; } } /** * DELETE ACCOUNT */ if ($_GET["acao"] == "delete") { try { deleteAccount($_SESSION['iduser']); include_once('../authentication/logout.php'); $_SESSION['success_messages'][] = 'Account deleted successfully.'; } catch (PDOException $e) { $_SESSION['error_messages'][] = 'Access denied.'; header('Location: ../../pages/authentication/homepage.php'); exit; } } header('Location: ../../pages/authentication/homepage.php');
true
0dcaa7b189420abfac4d3feecccf948b1e02a276
PHP
medvedevanatalya/app-restaurant
/app/Http/Controllers/UserController.php
UTF-8
2,437
2.578125
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use App\Models\Order; use App\Models\User; use Illuminate\Http\Request; class UserController extends Controller { public function index() { $curUser = auth()->user(); //все сотрудники $users = User::all(); return view('users.index', compact('curUser', 'users')); } //информация о сотруднике public function show(Request $request, $id) { $user = User::find($id); if (!$user) return redirect('/'); //$orders - все заказы сотрудника, $ordersCount - кол-во всех заказов, $ordersDone - кол-во выполненных, $ordersNotDone - кол-во не выполненных $orders = Order::where('user_id', $id); $ordersCount = $orders->count(); $ordersCountDone = $orders->where('status', true)->count(); $ordersCountNotDone = $ordersCount - $ordersCountDone; //последние 5 выполненных заказов $latest_orders = $orders->where('status', true)->take(5); return view('users.show', compact('user', 'orders', 'ordersCount', 'ordersCountDone', 'ordersCountNotDone')); } public function edit($id) { $user = User::find($id); return view('auth.register', compact('user')); } public function update(Request $request, User $user) { $data = $this->validated($request, $user); if($data['position_id'] == 1) { $role = 'administrator'; } else{ $role = 'personnel'; } $user['role'] = $role; $user->update($data); return redirect()->route('users.show', $user); } public function destroy($id) { $user = User::find($id); $user->delete(); return redirect()->route('users.index'); } protected function validated(Request $request, User $user = null) { $rules = [ 'name' => 'required|min:5|max:100|unique:users', 'email' => 'required', 'full_name' => 'required', 'position_id' => 'nullable', 'address' => 'nullable', 'phone_number' => 'nullable', ]; if($user) $rules['name'] .= ',name,' . $user->id; return $request->validate($rules); } }
true
64453a33157769e481e9aa82b7e15a55667631c9
PHP
preethamb97/simple-php-Rest-API
/queries/internal/user.php
UTF-8
1,786
2.96875
3
[]
no_license
<?php class user { public function getUsersDetail() { $sql = "SELECT * FROM user"; $result = database::getAll($sql, array()); return $result; } public function getOneUserDetail($userId, $options=array()) { $sql = "SELECT * FROM user WHERE user_id=:userId"; $result = database::getOne($sql, array('userId'=>$userId)); return $result; } public function insertUser($options) { $sql = "INSERT INTO user "; $sql .= "( ".implode(", ", array_keys($options))." ) VALUES "; $sql .= "( :".implode(", :", array_keys($options))." )"; $result = database::insertOne($sql, $options); return $result; } public function updateUser($userId, $options) { $sql = "UPDATE user SET "; foreach ($options as $key => $value) { $sql .= $key."=".$value.", "; } $sql = rtrim($sql, ', '); $sql = "WHERE user_id=:userId"; $options['user_id'] = $userId; $result = database::updateOne($sql, $options); } public function deleteUser($userId) { $sql = "DELETE FROM user WHERE user_id = :userId"; $result = database::deleteOne($sql, array('userId'=>$userId)); return $result; } public function getLoginUserDetail($userId, $password, $options=array()) { $sql = "SELECT * FROM user WHERE user_id=:userId AND password=:password"; $result = database::getOne($sql, array('userId'=>$userId, 'password'=>$password)); return $result; } public function checkIfUserNameExists($username, $options=array()) { $sql = "SELECT * FROM user WHERE user_name=:username"; $result = database::getOne($sql, array('username'=>$username)); return $result; } } ?>
true
08ffae90446ac978bbffbfaa2ae178b6a2377bb6
PHP
koenhoeymans/AnyMark
/src/Api/PatternConfigLoaded.php
UTF-8
1,106
2.84375
3
[ "BSD-2-Clause" ]
permissive
<?php namespace AnyMark\Api; /** * This event is thrown after the configuration of the patterns is loaded. It * allows for the modification of the configuration of the pattern order and * the patterns that are used. */ interface PatternConfigLoaded { /** * Set the implementation that should be used for a given pattern name. This can * be a class name or an object. * * @param string|object $implementation The class name or object. */ public function setImplementation(string $name, $implementation): void; /** * Adds a pattern to the configuration. It can be added to an alias * or as a subpattern, choosing where to place it. * * This method uses a fluent interface and is followed by `ToAliasOrParent` * * Example: * * $configuration * ->add('strong') * ->toAlias('inline') * ->last(); * * $configuration * ->add('strong') * ->toParent('italic') * ->first(); */ public function add(string $name): ToAliasOrParent; }
true
23d6e705c111f608e8340d094b902f71dce9e5b2
PHP
Lex95/php-oop-2
/creditCard.php
UTF-8
720
3.46875
3
[]
no_license
<?php require_once "validator.php"; class creditCard { private $nomeCarta; private $saldo; use Validator; public function __construct($nome, $saldo) { $this->isValidName($nome); $this->nomeCarta = $nome; $this->isValidNumber($saldo); $this->saldo = $saldo; } public function getNome() { return $this->nomeCarta; } public function getSaldo() { return $this->saldo; } public function effettuaPagamento($costo) { if ($costo > $this->saldo) { return "Pagamento fallito: saldo carta insufficiente"; } else { $this->saldo -= $costo; return "Pagamento riuscito"; } } } ?>
true
2dc5ec14fa9dbf7ac6264173dd4f5f14a6ab9f9d
PHP
xup6m6fu04/Fat-Free-Practice
/app/Controllers/ClassController.php
UTF-8
8,129
2.671875
3
[]
no_license
<?php namespace App\Controllers; use App\Services\ClassService; use App\Services\ClassStudentService; use App\Services\ClassTeacherService; use App\Services\SchoolService; use App\Services\StudentService; use App\Traits\LoggerTrait; use Carbon\Carbon; use Exception; use Monolog\Logger; class ClassController extends Controller { protected $f3; protected $db; protected $classService; protected $schoolService; protected $classStudentService; protected $classTeacherService; protected $studentService; use LoggerTrait; public function __construct() { global $f3; $this->f3 = $f3; $this->db = $f3->get('db'); $this->classService = new ClassService(); $this->schoolService = new SchoolService(); $this->classStudentService = new ClassStudentService(); $this->classTeacherService = new ClassTeacherService(); $this->studentService = new StudentService(); } public function pageClass() { try { $school_id = ($this->f3->get('GET.school_id')) ?? false; $school = $this->schoolService->getSchoolBySchoolId($school_id); if (!$school) { throw new Exception('School Not Found'); } $key_word = ($this->f3->get('GET.key_word')) ?? false; if ($key_word) { $key_word = '%' . $key_word . '%'; } $data_nums = $this->classService->countClassesBySchoolIdAndKeyWord($school_id, $key_word); $page = ($this->f3->get('GET.page')) ?? 1; $per = ($this->f3->get('GET.per')) ?? 20; $args = paginate($data_nums, $page, $per); $args['school_id'] = $school_id; $classes = $this->classService->getClassBySchoolIdAndParams($args, $key_word); $this->f3->set('school', $school); $this->f3->set('classes', $classes); $this->f3->set('page', $args); $this->template('class.html'); } catch (Exception $ex) { $this->Log($ex, Logger::ERROR); $this->template('school.html'); } } public function pageClassStudent() { try { $class_id = ($this->f3->get('GET.class_id')) ?? false; $class = $this->classService->getClassByClassId($class_id); if (!$class) { throw new Exception('Class Not Found'); } $school = $this->schoolService->getSchoolBySchoolId($class->school_id); if (!$school) { throw new Exception('School Not Found'); } $key_word = ($this->f3->get('GET.key_word')) ?? false; if ($key_word) { $key_word = '%' . $key_word . '%'; } $class_students = $this->classStudentService->getByClassId($class_id); if (!$class_students) { $class = []; $students = []; } else { $string = ''; foreach ($class_students as $csv) { $string .= "'" . $csv->student_id . "',"; } $string = substr($string, 0, -1); $students = $this->studentService->getStudentsInStudentId($string, $key_word); } $page = ($this->f3->get('GET.page')) ?? 1; $per = ($this->f3->get('GET.per')) ?? 20; $args = paginate(count($students), $page, $per); $this->f3->set('school', $school); $this->f3->set('class', $class); $this->f3->set('class_students', $students); $this->f3->set('page', $args); $this->template('class_student.html'); } catch (Exception $ex) { $this->Log($ex, Logger::ERROR); $this->template('school.html'); } } public function pageClassTeacher() { try { $class_id = ($this->f3->get('GET.class_id')) ?? false; $class = $this->classService->getClassById($class_id); if (!$class) { throw new Exception('Class Not Found'); } $school = $this->schoolService->getSchoolById($class->school_id); if (!$school) { throw new Exception('School Not Found'); } $key_word = ($this->f3->get('GET.key_word')) ?? false; if ($key_word) { $key_word = '%' . $key_word . '%'; } $data_nums = $this->vClassTeacherService->countByClassId($class_id, $key_word); $page = ($this->f3->get('GET.page')) ?? 1; $per = ($this->f3->get('GET.per')) ?? 20; $args = paginate($data_nums, $page, $per); $class_teachers = $this->vClassTeacherService->getByClassId($class_id, $key_word); $this->f3->set('school', $school); $this->f3->set('class', $class); $this->f3->set('class_teachers', $class_teachers); $this->f3->set('page', $args); $this->template('class_teacher.html'); } catch (Exception $ex) { $this->Log($ex, Logger::ERROR); $this->template('school.html'); } } public function addClass() { try { // 新增一個班級 $args = []; $args['class_id'] = ($this->f3->get('POST.class_id')) ?? false; $args['school_id'] = ($this->f3->get('POST.school_id')) ?? false; $args['name'] = ($this->f3->get('POST.name')) ?? false; $args['enable'] = ($this->f3->get('POST.enable')) ?? false; // 新增資料 $this->classService->addClass($args); return_json(['type' => 'success']); } catch (Exception $ex) { $this->Log($ex, Logger::ERROR); return_json([ 'type' => 'error', 'message' => $ex->getMessage() ]); } } public function editClass() { try { // 編輯一個班級 $args = []; $args['class_id'] = ($this->f3->get('POST.class_id')) ?? false; $args['name'] = ($this->f3->get('POST.name')) ?? false; $args['enable'] = ($this->f3->get('POST.enable')) ?? false; $args['updated_at'] = Carbon::now(); $this->classService->editClass($args['class_id'], $args); return_json([ 'type' => 'success' ]); } catch (Exception $ex) { $this->Log($ex, Logger::ERROR); return_json([ 'type' => 'error', 'message' => $ex->getMessage() ]); } } public function getClassBySchoolId() { try { $school_id = ($this->f3->get('POST.school_id')) ?? false; $class = $this->classService->getClassBySchoolId($school_id); if (!$class) { throw new Exception('Class Not Found'); } return_json([ 'type' => 'success', 'class' => to_Array_two($class) ]); } catch (Exception $ex) { $this->Log($ex, Logger::ERROR); return_json([ 'type' => 'error', 'message' => $ex->getMessage() ]); } } public function getClassByClassId() { try { $class_id = ($this->f3->get('POST.class_id')) ?? false; $class = $this->classService->getClassByClassId($class_id, 'load'); if (!$class) { throw new Exception('Class Not Found'); } return_json([ 'type' => 'success', 'class' => to_Array($class) ]); } catch (Exception $ex) { $this->Log($ex, Logger::ERROR); return_json([ 'type' => 'error', 'message' => $ex->getMessage() ]); } } }
true
5ff1dc38af0a41b265e4db5ae307f8fd449e8f59
PHP
silasrm/MyZendAssets
/FileUpload/Form.php
UTF-8
650
2.9375
3
[]
no_license
<?php /** * Handle file uploads via regular form post (uses the $_FILES array) * @url https://raw.github.com/valums/file-uploader/master/server/php.php */ class FileUpload_Form { /** * Save the file to the specified path * @return boolean TRUE on success */ function save( $path ) { if( !move_uploaded_file( $_FILES['qqfile']['tmp_name'], $path ) ) { return false; } return true; } function getName() { return $_FILES['qqfile']['name']; } function getSize() { return $_FILES['qqfile']['size']; } }
true
f0ebb7bb0ea0dc2ae29644198cc08366ac60344b
PHP
nexts-corp/58-KMUTNB-EBUDGET
/apps/budget/interfaces/IBudgetTrackingService.php
TIS-620
998
2.828125
3
[ "MIT" ]
permissive
<?php namespace apps\budget\interfaces; /** * @name BudgetTrackingService * @uri /budgetTracking * @description BudgetTrackingService */ interface IBudgetTrackingService { /** * @name getInfoTracking * @uri /getInfoTracking * @param String budgetType Description ҳ * @param String quater Description * @param String year Description . * @return String[] listTracking * @description ʴŻԹ */ public function getInfoTracking($budgetType, $quater, $year); /** * @name saveTracking * @uri /saveTracking * @param String[] objBudget Description šõԴ jsonArrOBJECT * @return boolean status * @description ѹ֡šõԴ */ public function saveTracking($objBudget); }
true
b624ec6f1b13c92da9f0ab3d389a866e5ecc1b79
PHP
nadj851/Circuit_Voyage
/Circuit/CircuitAPI.php
UTF-8
976
2.578125
3
[]
no_license
<?php require_once("../includes/init.php"); require_once("../includes/modele.inc.php"); $tabRes = array(); global $tabRes; $requete = "SELECT * FROM circuit "; $tabRes['action'] = "afficherCircuits"; $param = ""; if (isset($_GET['idCircuit'])) { $_SESSION["idCircuit"]=$_GET['idCircuit']; $param = $_GET['idCircuit']; $requete=$requete." WHERE idCircuit=?"; } else if (isset($_GET['idThem'])) { $param = $_GET['idThem']; $requete=$requete." WHERE idThematique=?"; } $params = array(); if ($param !== "") { $params = array($param); } try { $unModele = new circuitModel($requete, $params); $stmt = $unModele->executer(); $tabRes['affichageCircuits'] = array(); while ($ligne = $stmt->fetch(PDO::FETCH_OBJ)) { $tabRes['affichageCircuits'][] = $ligne; } } catch (Exception $e) { $tabRes['affichageCircuits'][] = $e; } finally { unset($unModele); } echo json_encode($tabRes);
true
6f6c38173b345c696d701210716c2531bf44be22
PHP
pawlowskim/brzoza
/ui/account.php
UTF-8
1,633
2.578125
3
[]
no_license
<?php if(!isset($_SESSION["name"])){ echo "NOPE!"; exit; } ?> <table border="1" width="750px"> <tr> <th>Data ost. nieudanego logowania</th> <th>Data ost. udanego logowania</th> <th>Liczba nieudanych logowań od ost. udanego logowania</th> <th>Ilość możliwych prób logowania</th> <th>Tryb logowania</th> </tr> <?php include_once('backend/messageRepository.php'); $msgRepo = new messageRepository(); $rows = $msgRepo -> getAccountInfo($_SESSION["id"]); $login_mode = ' nieograniczony '; while($row = mysql_fetch_assoc($rows)){ $attempts = $row["attempts"]; $mode = $row["login_mode"]; if ($row["login_mode"] == 1){ $login_mode = ' Logowanie z ograniczoną ilością prób '; } echo "<tr><td align='center'>".$row["last_failed"]."</td><td align='center'>".$row["last_success"]."</td> </td><td align='center'>".$row["failed"]."</td><td align='center'>".$row["attempts"]."</td><td align='center'>".$login_mode."</td></tr>"; } ?> </table> <br/><br/> <form action="backend/api.php" method="get"> <input type="hidden" name="action" value="logintype" /> Ilość możliwych prób: <input type="number" name="attempts" value="<?php echo $attempts ?>" /> <input type="radio" name="new_mode"<?php if ($mode == 1) echo "checked";?> value="1"/>Tryb z ograniczoną ilością prób logowania <input type="radio" name="new_mode"<?php if ($mode == 0) echo "checked";?> value="0"/>Tryb bez ograniczeń prób logowania<br/> <input type="submit" name="login_mode_change" value="Zapisz"/> </form>
true
92d6e67e9f952bdf3cdabcb9c3a1bb8b86e9b0ba
PHP
borfirbora/merdo
/mert.techredio.com/index.php
UTF-8
1,648
2.671875
3
[]
no_license
<?php include('header.php'); ?> <?php $ad = $_POST['ad']; $mesaj = $_POST['mesaj']; if(isset($_POST['gonder'])){ if(empty($_POST['ad'])){ echo'<div role="alert"><p>Heeey, Adın ne? Yazmayı unuttun!</p></div>'; } elseif(empty($_POST['mesaj'])){ echo'<div role="alert"><p>Heeeey? Mesajın nedir? Onu yazmadın.</p></div>'; } else { echo'<div role="alert"><p>Mesajın gönderildi, Teşekkürler '.$_POST['ad'].'</p></div>'; touch("iletisim-formu.txt"); // dosya oluşturur $f=fopen("iletisim-formu.txt","a"); // dosyayı yazmak üzere açar fwrite($f," <p>adı: $ad</p> <p>Mesajı:</p><p>$mesaj</p> "); fclose($f); // yazmayı bitirdiği için dosyayı kapatır. } } ?> <main> <h2 id="mert-ozer"><strong>Mert özer</h2></strong> <p>Merhaba arkadaşlar. Ben mert. <strong>Techredio</strong> sitesinin tek geliştiricisiyim. Bu sayfada, teknoloji de dahil olmak üzere, benim hakkımda da yazılmış yazıları, hayatımı, videolarımı vb. içerikleri bulacaksınız.</p> <p>Hadi <strong>yola</strong> çıkalım!!!</p> <h3 id="aklna-taklan-birsey-mi-var">Aklına takılan birşey mi var?</h3> <p>Bana</p> <p><strong><a href="mailto:ozermert26@gmail.com">E-posta gönder</a></p></strong> <p>Veya</p> <p><strong>Aşağıdaki formu kullan</strong></p> <h2>İletişim formu</h2> <form method="POST" name="iletisim"> Ad-soyad: <input name="ad" placeholder="Ad-soyad"><br> <textarea cols="30" rows=50" name="mesaj" placeholder="Mesajınız"></textarea><br> <input name="gonder" type="submit" value="Mesajı gönder"> </form> </main> <?php include'footer.php'; ?>
true
bc99673b90e22e20ea9c42af951d9b9e8b44b0d6
PHP
YuweiXiao/SE228-Web
/iter1/application/controllers/admin/Admin.php
UTF-8
573
2.609375
3
[]
no_license
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Admin extends CI_Controller { var $data = array(); /** * Constructor * Autoload: auth */ public function __construct() { parent::__construct(); $this->load->model('user_model'); $this->load->model('book_model'); } /** * Check admin auth, load dashboard. */ public function index() { if(!$this->auth->is_admin()) redirect('login','refresh'); $this->data['name'] = $this->session->userdata('user')['name']; $this->load->view('admin/dashboard', $this->data); } }
true
9ca5e5dc97230bbef09939a5df4b1aab64f303df
PHP
ReqApi/phptea
/Old/phpobj.php
UTF-8
5,120
3.46875
3
[]
no_license
<?php class cli { private $handle = null; private $line = null; public function __construct() { $this->handle = fopen("php://stdin", "r"); $this->line = ""; } public function inp(){ $line = trim(fgets($this->handle)); return $line; } public function out($string = "Lol, what?", $type = "n", $br = 1){ sleep(1.7); $brString = ""; while($br > 0){ $brString .= "\n"; $br--; } switch($type) { case "n": //normal output echo $brString.$string.$brString; break; case "p": //prompt output if ($string != ""){ // if no output, ignore echo $brString.$string.$brString; } echo $brString."> "; return $this->inp(); //break; } } //public function } class chk extends cli { public function inpContains( $prompt = "this is a prompt", $q = array( array( "bounce", "jump", "hop"), array( "walk", "stroll", "ambulate",)), $outcome = array( -1 => "failure", 0 => "invalid", 1 => "success A", 2 => "success B")){ $option = 0; $failure = $outcome[$option]; $output = $outcome[$option]; $returnVal = ""; while ($output == $failure) { //echo $info["prompt"] . "\n"; $inpString = $this->out($prompt, "p"); //retrieve user input and put it in variable //echo $impstring; foreach($q as $key => $action){ foreach ($action as $word){ if(stristr($inpString, $word)) { //$option = $action + 1; $output = $outcome[$key + 1]; // . "\n"; break(1); } } } if($output == $failure){ $this->out($output); return $inpString; } } $this->out($output); return $inpString; } } class character { private $name = null; private $description = null; private $species = null; private $hp = null; private $itemsCarried = array(); //array of items as objects private $cli_interaction_object; public function __construct($cli_interaction_object, $name, $species = "Unknown creature.", $hp = 10, $itemsCarried = "Nothing.", $description = "You're not sure if anyone knows what this is."){ $this->name = $name; $this->species = $species; $this->hp = $hp; $this->itemsCarried = $itemsCarried; $this->description = $description; $this->cli_interaction_object = $cli_interaction_object; } public function say($speech_string) { return $this->cli_interaction_object->out($this->name.": ". $speech_string); } public function ask($speech_string){ return $this->cli_interaction_object->out($this->name.": ". $speech_string, "p"); } public function getVar($varName){ return $this->{$varName}; } public function updateVar($varName, $newVal){ if ($varName == "name" || $varName == "descrpition"|| $varname == "speices"|| $varName == "hp" || $varName == "itemsCarried"){ $this->{$varName} = $newVal; return true; }else{ return false; } } } class player extends character { } $cli = new cli(); $chk = new chk(); $knettenba = new character($cli, "CAT", "Cat", 22, "Bugger all."); $knettenba->ask("I SPEeAAK. MROWL."); $knettenba->say("Hello, my name is ".$knettenba->getVar("name")."."); $knettenba->updateVar("name", "TWAT"); $knettenba->say("Hello, my name is ".$knettenba->getVar("name")."."); //cho $cli->out("", "p"); $chk->inpContains("What are birds?", array(array("We just don't know", "don't know,", "I don't know")), array("BOLLOCKS!", "We just don't know.")); $chk->inpContains( "You walk into x room. In the room is a table. On the table is a loaf of BREAD.", array(array("eat","bread"), array("leave", "exit"),array("knife", "cut", "chop", "slice")), array(0 => "NONSENSE", 1 => "You eat the bread. OMNOMNOM", "You fuck RIGHT OFF. You have no interest in this silly room.", "You realise kthere is a bread knife! Such fun! You carefully slice the bread and eat it. OM TO THE NOM TO THE NOM. Yes. Good.")); $chk->inpContains( "Having enjoyed the delicious bread, you look around you. There is a cat under the table.", array(array("pet", "stroke", "touch", "play"),array("eat", "kick"), array("leave", "exit")), array(0 => "NONSENSE", 1 => "You pet the cat. The cat is happy. You wish that for you, happiness was so simple.", "You monster.", "Oh fine. I didn't want you to play this game anyway.")); $cli->out("The cat is a magic cat. You can tell this because of its pointy purple hat with stars on it. Magic cats, as everybody knows, can talk."); $x = true; $name = $knettenba->ask("Hello oddly hairless one. What is your name?", "p"); while($x){ if(stristr($name, " ")){ $name=$knettenba->ask("Nobody should have more than one name. That's just pretentious! \n What's your name?", "p"); }elseif($name == null || $name == ""){ $name=$knettenba->ask("I said, what is your name?! That's not a name, that's nothing!", "p"); }else{ $x=false; } } $player = new player($cli, $name); $cli->out("Hello ".$player->name."! That's a silly name but I guess it will do..."); /* if($guyHairCut = "short"){ echo "Awwww. It looked nicer before."; }elseif($womanOrNBHaircut = "short"){ echo "Yes. This. More of this please."; } */ ?>
true
1356811ea7758691d58ae9997d6540885911fe09
PHP
Shobit1502/php-notes
/DataTypes.php
UTF-8
435
3.34375
3
[]
no_license
<?php echo "data types in php<br>"; echo "Integer<br>"; echo "Float<br>"; echo "boolean <br> ";/* i.e. true and false */ echo" Object,Array,Null<br>"; /* var dump function tells details about the variable */ $opinion=true; echo"var_dump($opinion)<br>"; echo var_dump($opinion); echo "<br>"; $friends=array("rohan","nikki",24,54,"rajam"); echo var_dump($friends); echo "<br>"; echo "$friends[0]"; $DEFAULT=NULL; ?>
true
fcc251f95d4ad211cc3750e1f66629da7cc200b5
PHP
PhpFastWeb/phpfastweb
/src/columns/validation_rules/validation_unique.class.php
WINDOWS-1250
975
2.71875
3
[]
no_license
<?php class validation_unique extends avalidation_rule implements ivalidation_rule { protected $invalid_message_text = ''; public function __construct($invalid_message_text='') { $this->invalid_message_text = $invalid_message_text; } function check_column(icolumn $column) { if ($this->skip_validation($column)) return $this->validates; if (!$column->has_changed()) return true; $val = $column->get_value(); //Comprobamos si existe en la base de datos $e = website::$database->exist_row2($column->get_table()->table_name,$column->get_column_name(),$val); if ($e) { $this->invalidate(); if ($this->invalid_message_text == '') { $this->messages[] = "El campo '".$column->get_title()."' debe tener un valor nico, pero ya exite otro registro con el valor '".$val."'."; } else { $this->messages[] = $this->invalid_message_text; } } return $this->validates; } } ?>
true
4cad7a7eab291a3a148c586566a745063126f7a4
PHP
danielgaleano1/invoice_management
/database/migrations/2019_11_21_042921_create_collaborators_table.php
UTF-8
1,146
2.609375
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateCollaboratorsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('collaborators', function (Blueprint $table) { $table->bigIncrements('id'); $table->unsignedBigInteger('profile_id'); $table->unsignedBigInteger('city_id'); $table->unsignedInteger('code')->unique(); $table->string('name', 200); $table->string('address', 200); $table->string('phone', 50); $table->string('email', 200)->unique(); $table->string('password', 200); $table->timestamps(); $table->foreign('profile_id')->references('id')->on('profiles'); $table->foreign('city_id')->references('id')->on('cities'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('collaborators'); } }
true
68d6b680908f434df2c11ec4bd65eede8071a058
PHP
mikerosevelt/CI3-Inventory-App
/application/controllers/Auth.php
UTF-8
8,965
2.5625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php defined('BASEPATH') or exit('No direct script access allowed'); class Auth extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('User'); } public function index() { // check if user already login cannot visit Login page. if ($this->session->userdata('email')) { redirect('dashboard'); } $this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email'); $this->form_validation->set_rules('password', 'Password', 'required|trim'); if ($this->form_validation->run() == false) { $data['title'] = 'Login Page | Inventory App'; $this->load->view('templates/auth/header', $data); $this->load->view('auth/login'); $this->load->view('templates/auth/footer'); } else { $this->_login(); } } private function _login() { $email = $this->input->post('email', true); $password = $this->input->post('password', true); $user = $this->db->get_where('users', ['email' => $email])->row_array(); if ($user && $user['deletedAt'] == null) { if (password_verify($password, $user['password'])) { $data = [ 'email' => $user['email'], 'role_id' => $user['role_id'] ]; // USER LOG $userlog = $this->db->get_where('user_logs', ['user_id' => $user['id']])->row_array(); $datalog = [ 'user_id' => $user['id'], 'ip_address' => $this->input->ip_address(), 'host' => gethostbyaddr($this->input->ip_address()), 'user_agent' => $this->input->user_agent(), 'last_login' => time() ]; if ($userlog['user_id'] == $user['id']) { $this->db->set('ip_address', $this->input->ip_address()); $this->db->set('host', gethostbyaddr($this->input->ip_address())); $this->db->set('user_agent', $this->input->user_agent()); $this->db->set('last_login', time()); $this->db->where('user_id', $user['id']); $this->db->update('user_logs'); } else { $this->db->insert('user_logs', $datalog); } $this->session->set_userdata($data); redirect('dashboard'); } else { $this->session->set_flashdata( 'message', '<div class="alert alert-danger alert-dismissible fade show" role="alert"> Wrong password! <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div>' ); redirect('auth'); } } else { $this->session->set_flashdata( 'message', '<div class="alert alert-danger alert-dismissible fade show" role="alert"> User is not exist. <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div>' ); redirect('auth'); } } public function register() { // check if user already login cannot visit Register page. if ($this->session->userdata('email')) { redirect('dashboard'); } $this->form_validation->set_rules('name', 'Name', 'required|trim'); $this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email|is_unique[users.email]', [ 'is_unique' => 'Email is already registered!' ]); $this->form_validation->set_rules('password', 'Password', 'required|trim|min_length[5]|matches[password2]', [ 'matches' => 'Password do not match', 'min_length' => 'Password is too short' ]); $this->form_validation->set_rules('password2', 'Confirm Password', 'required|trim|matches[password]'); if ($this->form_validation->run() == false) { $data['title'] = 'Register Page | Inventory App'; $this->load->view('templates/auth/header', $data); $this->load->view('auth/register'); $this->load->view('templates/auth/footer'); } else { $this->User->createNewAccount(); $this->session->set_flashdata( 'message', '<div class="alert alert-success alert-dismissible fade show" role="alert"> <strong>Hooray!</strong> Your account has been created. <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div>' ); redirect('auth'); } } public function forgotPassword() { // check if user already login cannot visit Login page. if ($this->session->userdata('email')) { redirect('dashboard'); } $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email'); if ($this->form_validation->run() == false) { $this->index(); } else { $email = $this->input->post('email'); $user = $this->db->get_where('users', ['email' => $email])->row_array(); if ($user) { // token for reset link $token = base64_encode(random_bytes(32)); $user_token = [ 'email' => $email, 'token' => $token, 'createdAt' => time() ]; $this->db->insert('user_token', $user_token); $this->_sendEmail($token); $this->session->set_flashdata( 'message', '<div class="alert alert-success alert-dismissible fade show" role="alert"> We have sent you a link to reset your password. <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div>' ); redirect('auth'); } else { $this->session->set_flashdata( 'message', '<div class="alert alert-danger alert-dismissible fade show" role="alert"> User not found! <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div>' ); redirect('auth'); } } } private function _sendEmail($token) { $this->email->from('admin@inventory.app', 'Admin Inventory App'); // from email and from name. $this->email->to($this->input->post('email')); $this->email->subject('User Activation'); $this->email->message('Click to reset your account password : <a href="' . base_url() . 'auth/resetpassword?email=' . $this->input->post('email') . '&token=' . urlencode($token) . '"> Activate</a>'); if ($this->email->send()) { return true; } else { echo $this->email->print_debugger(); die; } } public function resetPassword() { $email = $this->input->get('email'); $token = $this->input->get('token'); $user = $this->db->get_where('users', ['email' => $email])->row_array(); if ($user) { $user_token = $this->db->get_where('user_token', ['token' => $token])->row_array(); if ($user_token) { $this->session->set_userdata('reset_email', $email); // set input email user in session $this->changePassword(); } else { $this->session->set_flashdata('message', '<div class="alert alert-danger" role="alert">Reset password failed! wrong token.</div>'); redirect('auth'); } } else { $this->session->set_flashdata('message', '<div class="alert alert-danger" role="alert">Reset password failed! wrong email.</div>'); redirect('auth'); } } public function changePassword() { // check user email that want to reset password if (!$this->session->userdata('reset_email')) { redirect('auth'); } $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[3]|matches[password2]'); $this->form_validation->set_rules('password2', 'Confirm Password', 'trim|required|min_length[3]|matches[password1]'); if ($this->form_validation->run() == false) { $data['title'] = 'Change Password'; $this->load->view('templates/auth_header', $data); $this->load->view('auth/change-password'); $this->load->view('templates/auth_footer'); } else { $password = password_hash($this->input->post('password1'), PASSWORD_DEFAULT); $email = $this->session->userdata('reset_email'); $this->db->set('password', $password); $this->db->where('email', $email); $this->db->update('users'); $this->session->unset_userdata('reset_email'); $this->session->set_flashdata('message', '<div class="alert alert-success" role="alert">Password has been changed.</div>'); redirect('auth'); } } public function logout() { $data = ['email', 'role_id']; $this->session->unset_userdata($data); $this->session->set_flashdata('message', '<div class="alert alert-success" role="alert">You have been logout.</div>'); redirect('auth'); } }
true
7ff2aceeb8ad1fa9c1eab301b6786c9b77c57aab
PHP
Shurikoz/yii2-SPB
/backend/controllers/SiteController.php
UTF-8
5,401
2.53125
3
[]
no_license
<?php namespace backend\controllers; use backend\models\Book; use backend\models\BookCategoryList; use backend\models\Category; use backend\models\Feedback; use common\models\LoginForm; use igogo5yo\uploadfromurl\UploadFromUrl; use Yii; use yii\data\Pagination; use yii\filters\AccessControl; use yii\filters\VerbFilter; use yii\web\Controller; /** * Site controller */ class SiteController extends Controller { /** * {@inheritdoc} */ public function behaviors() { return [ 'access' => [ 'class' => AccessControl::className(), 'rules' => [ [ 'actions' => ['login', 'error'], 'allow' => true, ], [ 'actions' => ['logout', 'index', 'feedback', 'parser'], 'allow' => true, 'roles' => ['@'], ], ], ], 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'logout' => ['post'], ], ], ]; } /** * {@inheritdoc} */ public function actions() { return [ 'error' => [ 'class' => 'yii\web\ErrorAction', ], ]; } /** * Displays homepage. * * @return string */ public function actionIndex() { return $this->render('index'); } /** * @param $link * @return string */ public function actionParser($link) { // $link = 'https://gitlab.com/prog-positron/test-app-vacancy/-/raw/master/books.json'; // $link = getcwd() . '\backend\web\books.json'; $json = file_get_contents($link); $data = json_decode($json, true); //Создание категорий foreach ($data as $item) { Category::setCategory($item["categories"]); } //Запись книг в базу и создание категорий foreach ($data as $item) { //проверим существование книги по артикулу и заголовку //если запись существует, пропустим итерацию $title = isset($item["title"]) ? $item["title"] : ''; $isbn = isset($item["isbn"]) ? $item["isbn"] : ''; $checkExistBook = Book::checkExistBook($title, $isbn); if ($checkExistBook) { continue; } else { isset($item["authors"]) ? $authors = str_replace(['"', ',', '[', ']'], ['', ', ', '', ''], json_encode($item["authors"])) : $authors = ''; $book = new Book(); $book->title = isset($item["title"]) ? $item["title"] : ''; $book->isbn = isset($item["isbn"]) ? $item["isbn"] : ''; $book->pageCount = isset($item["pageCount"]) ? $item["pageCount"] : ''; $book->publishedDate = isset($item["publishedDate"]) ? date(time(), strtotime($item["publishedDate"]["\$date"])) : ''; // $book->thumbnailUrl = $item["thumbnailUrl"]; $book->shortDescription = isset($item["shortDescription"]) ? $item["shortDescription"] : ''; $book->longDescription = isset($item["longDescription"]) ? $item["longDescription"] : ''; $book->status = isset($item["status"]) ? $item["status"] : ''; $book->authors = $authors; if ($book->save(false)) { //заполнение промежуточной таблицы с категориями BookCategoryList::setBookCategoryList($item["categories"], $book->id); //загрузка изображений if (isset($item["thumbnailUrl"])){ $file = UploadFromUrl::initWithUrl($item["thumbnailUrl"]); $book->uploadLinkImage($book->id, $file); } } } } return $this->render('parser'); } /** * Displays feedback page. * * @return string */ public function actionFeedback() { $query = Feedback::find(); $pages = new Pagination(['totalCount' => $query->count(), 'pageSize' => 10]); $model = $query->offset($pages->offset)->limit($pages->limit)->all(); return $this->render('feedback', [ 'model' => $model, 'pages' => $pages ]); } /** * Login action. * * @return string */ public function actionLogin() { if (!Yii::$app->user->isGuest) { return $this->goHome(); } $this->layout = 'blank'; $model = new LoginForm(); if ($model->load(Yii::$app->request->post()) && $model->login()) { return $this->goBack(); } else { $model->password = ''; return $this->render('login', [ 'model' => $model, ]); } } /** * Logout action. * * @return string */ public function actionLogout() { Yii::$app->user->logout(); return $this->goHome(); } }
true
f33a85c028d0f7754495a217b766e01fe85801d1
PHP
richardjonesnz/moodle-report_teachers_classes
/classes/local/class_list.php
UTF-8
3,701
2.640625
3
[]
no_license
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Return a teacher and all the courses they have that role in. * * @package report * @subpackage teachers_classes * @author richard f jones richardnz@outlook.com * @copyright 2021 richard f jones <richardnz@outlook.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace report_teachers_classes\local; use renderable; use renderer_base; use templatable; use stdClass; class class_list implements renderable, templatable { protected $heading; protected $teachername; public function __construct($heading, $teachername) { $this->heading = $heading; $this->teachername = $teachername; } protected function validate_teacher() { global $DB; // Set up the expression for partial matches to the input form. $namefilter = '%' . $this->teachername . '%'; $sql = "SELECT ra.id AS id, c.id AS courseid, c.fullname, u.id AS userid, u.firstname, u.lastname, ra.roleid FROM mdl_course AS c JOIN mdl_context AS ctx ON c.id = ctx.instanceid JOIN mdl_role_assignments AS ra ON ra.contextid = ctx.id JOIN mdl_user AS u ON u.id = ra.userid WHERE (ra.roleid = :r1 OR ra.roleid = :r2) AND u.lastname LIKE '$namefilter'"; $courses = $DB->get_records_sql($sql, ['r1' => 3, 'r2' => 4]); var_dump($courses); // Check that some courses are returned. if (!$courses) { return get_string('nodata', 'report_teachers_classes'); } // Check only one teacher returned. $userids = array(); foreach ($courses as $course) { $userids[] = $course->userid; } if (count(array_unique($userids)) != 1) { return get_string('narrowsearch', 'report_teachers_classes'); } return $courses; } function export_for_template(renderer_base $output) { $courses = self::validate_teacher(); $table = new stdClass(); // Heading $table->heading = $this->heading; // Table headers. $table->tableheaders = [ get_string('firstname', 'report_teachers_classes'), get_string('lastname', 'report_teachers_classes'), get_string('courseid', 'report_teachers_classes'), get_string('fullname', 'report_teachers_classes'), ]; if (!is_string($courses)) { // Build the data rows. foreach ($courses as $course) { $data = array(); $data[] = $course->firstname; $data[] = $course->lastname; $data[] = $course->courseid; $data[] = $course->fullname; $table->tabledata[] = $data; } $table->message = get_string('searchresults', 'report_teachers_classes'); } else { $table->message = $courses; $table->tabledata = null; } return $table; } }
true
fcac12d38b84f5a2c522442b4b36dbf3557bb22c
PHP
kaunas-coding-school/csba_laravel
/tests/ApiRequests.php
UTF-8
1,340
2.734375
3
[ "MIT" ]
permissive
<?php namespace Tests; use Illuminate\Http\Response; trait ApiRequests { protected function jsonGet(string $path, int $expectedStatus = 200, ?array $headers = []): array { return $this->jsonRequest('GET', $path, [], $expectedStatus, $headers); } protected function jsonRequest( string $method, string $path, array $data, int $expectedStatus = 200, ?array $headers = [] ): array { $headers = $headers ?? []; /** @var Response $response */ $response = $this->json($method, $path, $data, $headers); self::assertEquals($expectedStatus, $response->status(), (string)$response->getContent()); return $this->decodeBody((string)$response->getContent()); } private function decodeBody(string $content): array { return json_decode($content, true, 512, JSON_THROW_ON_ERROR); } protected function jsonPost(string $path, array $data = [], int $expectedStatus = 200, ?array $headers = []): array { return $this->jsonRequest('POST', $path, $data, $expectedStatus, $headers); } protected function jsonPut(string $path, array $data = [], int $expectedStatus = 200, ?array $headers = []): array { return $this->jsonRequest('PUT', $path, $data, $expectedStatus, $headers); } }
true
5186dca0ea3bfecaff38b242e2292d4eee1eca4d
PHP
AngeloR/killinging
/class/Fight.php
UTF-8
3,803
3.21875
3
[]
no_license
<?php class Fight { private $first; private $second; private $winner; private $loser; private $player; private $monster; private $flee; private $rounds; public function __construct($attacker1,$attacker2) { if($attacker1->agi > $attacker2->agi) { $this->first = $attacker1; $this->second = $attacker2; } else { $this->second = $attacker1; $this->first = $attacker2; } $this->setPlayerAndMonster(); $this->flee = false; } public function setPlayerAndMonster() { if(is_null($this->first('player_id'))) { $this->player = 'second'; $this->monster = 'first'; } else { $this->player = 'first'; $this->monster = 'second'; } } public function canContinue() { return ($this->first->current_hp > 0 && $this->second->current_hp > 0); } public function attack() { $damage = $this->calculateDamage($this->first,$this->second); $this->second->current_hp -= $damage; $str .= ' for '.$damage.' damage.<br>'; if(!$this->withinBounds($this->second['hp'],0,$this->second['max_hp'])) { $this->second['hp'] = $this->forceBounds($this->second['hp'],0,$this->second['max_hp']); $this->winner = 'first'; $this->loser = 'second'; echo $str; return; } echo $str; $str = $this->second['name'].' attacks '.$this->first['name']; $damage = $this->calculateDamage($this->second,$this->first); $this->first['hp'] -= $damage; $str .= ' for '.$damage.' damage.<br>'; if(!$this->withinBounds($this->first['hp'],0,$this->first['max_hp'])) { $this->first['hp'] = $this->forceBounds($this->first['hp'],0,$this->first['max_hp']); $this->winner = 'second'; $this->loser = 'first'; echo $str; return; } echo $str; } public function monsterAttack() { $m = $this->monster; $p = $this->player; $monster = $this->$m; $player = $this->$p; $str = $monster['name'].' attacks '.$player['name']; $damage = $this->calculateDamage($monster,$player); $player['hp'] -= $damage; $str .= ' for '.$damage.' damage.<br>'; if(!$this->withinBounds($player['hp'],0,$player['max_hp'])) { $player['hp'] = $this->forceBounds($player['hp'],0,$player['max_hp']); $this->winner = $m; $this->loser = $p; $this->$p = $player; echo $str; return; } echo $str; } public function flee() { $player = $this->player(); $monster = $this->monster(); $rand = rand(1,$player['agility'])+(0.25*$player['luck']); $rand2 = rand(1,$monster['agility']); if($rand > $rand2) { $m = $this->monster; $monster['hp'] = 0; $this->$m = $monster; $this->winner = $this->player; $this->loser = $this->monster; $this->flee = true; return true; } return false; } public function escaped() { return $this->flee; } public function withinBounds($value,$lower,$upper) { return ($value > $lower && $value < $upper); } public function forceBounds($value,$lower,$upper) { $value = ($value < $lower)?$lower:$value; $value = ($value > $upper)?$upper:$value; return $value; } public function winner() { $x = $this->winner; return $this->$x; } public function loser() { $x = $this->loser; return $this->$x; } public function first($key = null) { return $this->first[$key]; } public function second($key = null) { return $this->second[$key]; } public function player() { $x = $this->player; return $this->$x; } public function monster() { $x = $this->monster; return $this->$x; } private function calculateDamage($attacker,$defender) { $attack = ($attacker['strength'] < $defender['defence'])?1:$attacker['strength'] - $defender['defence']; if($this->wasCritical($attacker)) { $attack *= 2; } return $attack; } private function wasCritical($attacker) { $luck = rand(0,100); return ($luck <= $attacker['luck']); } }
true
7707edd8283fb2a60bb41c9dbde23758daf203f7
PHP
Mikhail11/New_Version
/includes/core/CommonFunctions.php
UTF-8
10,474
3.234375
3
[]
no_license
<?php /// Статический класс с общими полезными методами, использующимися на всем портале /** * @author Anthony Boutinov */ class CommonFunctions { /// Эквивалент SQL функции NVL (NullValue) /** * Возвращает переданное значение если оно есть либо второй параметр, * если значение === NULL. По умолчанию, возвращает пустую строку, * если переданного значения не существует. * * @author Anthony Boutinov * * @param mixed $value Входное значение, которое может не существовать (=== null) * @param mixed $replacement (Опционально) Значение, которое подставить, если первый параметр окажется null. По умолчанию, пустая строка * @retval mixed Возвращаемое значение */ public static function NVL($value, $replacement = '') { return $value === null ? $replacement : $value; } /// Получить из данного массива его в виде текстовой строки с заданным форматированием /** * @author Anthony Boutinov * * @param array $array Массив * @param bool $doKeys (Опционально) Выводить ли названия ключей. По умолчанию, НЕТ * @param bool $wrapTopMostArray (Опционально) Оборачивать ли скобками корневой массив. По умолчанию, ДА * @param bool $hugValues (Опционально) Оборачивать ли кавычками значения, если они не являются числовыми. По умолчанию, ДА * @param string $wrapperLeft (Опционально) Вид левой скобки, оборачивающей массив * @param string $wrapperRight (Опционально) Вид правой скобки, оборачивающей массив * @param string $valueHuggerLeft (Опционально) Вид левых кавычек, оборачивающих значения * @param string $valueHuggerRight (Опционально) Вид правых кавычек, оборачивающих значения * @param string $keyHuggers (Опционально) Вид кавычек, оборачивающих ключи * @param string $keyFollowers (Опционально) Вид разделителя между ключом и значением, например " => " * @param string $keyValuePairWrapperLeft (Опционально) Вид левой скобки, оборачивающей пару ключ-значение * @param string $keyValuePairWrapperRight (Опционально) Вид правой скобки, оборачивающей пару ключ-значение * @param bool $isTopmost (Опционально) Является ли текущий массив корневым, внутри которого находятся вложенные массивы (всегда true, значение меняется только при рекурсивном выполнении функции) * * @retval string Строка с содержимым массива в заданном форматировании */ public static function arrayToString( $array, $doKeys = false, $wrapTopMostArray = true, $hugValues = true, $wrapperLeft = null, $wrapperRight = null, $valueHuggerLeft = null, $valueHuggerRight = null, $keyHuggers = null, $keyFollowers = null, $keyValuePairWrapperLeft = null, $keyValuePairWrapperRight = null, $isTopmost = true ) { // default values if ($wrapperLeft == null) { $wrapperLeft = '['; } if ($wrapperRight == null) { $wrapperRight = ']'; } if ($valueHuggerLeft == null) { $valueHuggerLeft = '\''; } if ($valueHuggerRight == null) { $valueHuggerRight = '\''; } if ($keyHuggers == null) { $keyHuggers = '\''; } if ($keyFollowers == null) { $keyFollowers = ','; } if ($keyValuePairWrapperLeft == null) { $keyValuePairWrapperLeft = '['; } if ($keyValuePairWrapperRight == null) { $keyValuePairWrapperRight = ']'; } $out = ( ($wrapTopMostArray == true || $isTopmost == false) ? $wrapperLeft : '' ); $i = 0; foreach ($array as $key => $value) { $localValueHuggers = ( $hugValues == true ? (is_numeric($value) || is_array($value) ? ['', ''] : [$valueHuggerLeft, $valueHuggerRight]) : ['', ''] ); $out = $out.($i++ == 0 ? '' : ',').( $doKeys == true ? $keyValuePairWrapperLeft.$keyHuggers.$key.$keyHuggers.$keyFollowers : '' ).$localValueHuggers[0].( is_array($value) ? CommonFunctions::arrayToString( $value, $doKeys, $wrapTopMostArray, $hugValues, $wrapperLeft, $wrapperRight, $valueHuggerLeft, $valueHuggerRight, $keyHuggers, $keyFollowers, $keyValuePairWrapperLeft, $keyValuePairWrapperRight, false ) : $value ).$localValueHuggers[1].( $doKeys ? $keyValuePairWrapperRight : '' ); } $out = $out.( ($wrapTopMostArray == true || $isTopmost == false) ? $wrapperRight : '' ); return $out; } /// Полуить из таблицы (2D массива) массив, выбрав только одну колонку /** * Из заданного массива с результатами SQL запроса получить * упрощенный массив, где значением выбирается только одна колонка * таблицы с ключом по некоторой другой колонке таблицы (если указано). * * @author Anthony Boutinov * * @param array $array Массив * @param string $valueSubKey Название колонки, которую использовать в качестве значений массива * @param string $newKeyFromValueSubKey Название колонки, которую использовать в качестве ключей массива. По умолчанию, остаются те ключи, которые были в первоначальном массиве (ничего, если неассоциативный массив или прежние значения ассоциативного массива). * @retval array */ public static function extractSingleValueFromMultiValueArray($array, $valueSubKey, $newKeyFromValueSubKey = null) { $out = array(); foreach ($array as $key => $value) { $k = $newKeyFromValueSubKey === null ? $key : $value[$newKeyFromValueSubKey]; $out[$k] = $value[$valueSubKey]; } return $out; } /// Перенаправить на заданную страницу /** * @author Anthony Boutinov * @param string $page Название страницы */ public static function redirect($page, $append_base_url = true) { if ($append_base_url) { $base_url = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}"; header("Location: $base_url/$page"); } else { header("Location: $page"); } exit(); } /// Начинается ли строка $haystack со строчки $needle /** * @author Anthony Boutinov * * @param string $needle Строка, которую ищем * @param string $haystack Строка, в которой ищем * @retval bool */ public static function startsWith($needle, $haystack) { // search backwards starting from haystack length characters from the end return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== FALSE; } /// Оканчивается ли строка $haystack строчкой $needle /** * @author Anthony Boutinov * * @param string $needle Строка, которую ищем * @param string $haystack Строка, в которой ищем * @retval bool */ public static function endsWith($needle, $haystack) { // search forward starting from end minus needle length characters return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== FALSE); } /// Проверяет, является ли user agent старым Андроидом /** * Check to see it the user agent is Android and if so then * check the version number to see if it is lower than 4.0.0 * or passed parameter * * @author https://gist.github.com/Abban * @param string $version (Опционально) Версия. По умолчанию, 4.0.0 * @retval bool */ public static function isOldAndroid($version = '4.0.0'){ if(strstr($_SERVER['HTTP_USER_AGENT'], 'Android')){ preg_match('/Android (\d+(?:\.\d+)+)[;)]/', $_SERVER['HTTP_USER_AGENT'], $matches); return version_compare($matches[1], $version, '<='); } } /// Поддерживает ли браузер современный CSS /** * @author Anthony Boutinov * @retval bool */ public static function supportsModernCSS() { return !CommonFunctions::isOldAndroid('2.3'); } /// Сгенерировать случайную строку заданной длины /** * @author Stephen Watkins http://stackoverflow.com/users/151382/stephen-watkins * * @param int $length (Опционально) Требуемая длина. По умолчанию, 10 * @retval string Строка вида [a-zA-Z0-9]+ */ public static function generateRandomString($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } return $randomString; } } ?>
true
8493ba40f6528beb6c60338eac5a8e3c761e77d6
PHP
lefevbre-organization/eShopOnContainers
/src/Web/POC/test-nextcloud/nextcloud/custom_apps/mail/vendor/rubix/ml/src/NeuralNet/Network.php
UTF-8
248
2.625
3
[ "MIT", "LicenseRef-scancode-free-unknown", "CC-BY-NC-4.0", "AGPL-3.0-only" ]
permissive
<?php namespace Rubix\ML\NeuralNet; use Traversable; interface Network { /** * Return the layers of the network. * * @return \Traversable<\Rubix\ML\NeuralNet\Layers\Layer> */ public function layers() : Traversable; }
true
419b68d20f5eb0d67773927ac8adcc4f9e0059df
PHP
GavinSmyth/InTheKitchen1
/inthekitchen/hello/registration.php
UTF-8
593
2.578125
3
[]
no_license
<?php session_start(); $con = mysqli_connect('localhost','root','','registration'); if(!$con){ die("db error"); echo "database not connected"; }else{ echo "database successful"; } // mysqli_select_db($con,'registration'); $name = $_POST['user']; $pass = $_POST['password']; $s = "select * from usertable where name = '$name' "; $result = mysqli_query($con, $s); $num = mysqli_num_rows($result); if($num==1){ echo"username taken"; }else{ $reg= "insert into usertable(name, password) values('$name', '$pass')"; mysqli_query($con, $reg); echo"registration successful"; } ?>
true
fda91ee7001bc7ba2ad17f6a8a4078bf2db36657
PHP
HGthecode/thinkphp-apidoc
/src/generator/ParseTemplate.php
UTF-8
13,163
2.578125
3
[ "MIT" ]
permissive
<?php declare(strict_types = 1); namespace hg\apidoc\generator; use hg\apidoc\Utils; use think\facade\App; class ParseTemplate { public function compile($path,$params) { $filePath = $path; $tplContent = Utils::getFileContent($filePath); $tplContent = $this->replaceForeach($tplContent,$params); $tplContent = $this->replaceParams($tplContent,$params); $tplContent = $this->replaceIf($tplContent,$params); $tplContent = preg_replace("/\s+\r\n/is", "\r\n", $tplContent); return $tplContent; } /** * 替换变量 * @param $tplContent * @param $params * @return array|string|string[]|null */ protected function replaceParams($tplContent,$params){ $key = '{$%%}'; $pattern = '#' . str_replace('%%', '(.+?)' , preg_quote($key, '#')) . '#'; $tplContent = preg_replace_callback($pattern, function ($matches)use ($params){ $k = $matches[1]; if (strpos($k, '(') !== false){ $tagArr = explode("(", $k); $fun = $tagArr[0]; $k = str_replace(")", "",$tagArr[1] ); $v = $this->getObjectValueByKeys($params,$k); if ($fun === "lower"){ return Utils::lower($v); }else if ($fun === "snake"){ return Utils::snake($v); }else if ($fun === "lcfirst"){ return lcfirst($v); }else if ($fun === "count"){ return count($v); } } $value = $this->getObjectValueByKeys($params,$k); if (is_bool($value)){ return $value==true?'true':'false'; }else if (is_array($value)){ return $k; } return $value; }, $tplContent); return $tplContent; } /** * 替换if内容 * @param $tplContent * @param $params * @return array|mixed|string|string[] * @throws \Exception */ protected function replaceIf($tplContent,$params){ $res = []; $label = "if"; $labelList = $this->parseLabel($tplContent,$label); if (!empty($labelList) && count($labelList)>0){ foreach ($labelList as $item) { $itemStr =$item; $ifChildren= $this->parseLabel($itemStr,$label,"children"); if (!empty($ifChildren) && count($ifChildren)>0){ foreach ($ifChildren as $ifChild){ $itemChildrenContent= $this->getIfContent($ifChild); $itemStr = str_replace($ifChild, $itemChildrenContent,$itemStr ); } } $itemContent= $this->getIfContent($itemStr); $tplContent = str_replace($item, $itemContent,$tplContent ); } } return $tplContent; } protected function parseForeach($str,$params){ if (preg_match('#{foreach (.+?) as (.+?)=>(.+?)}#s', $str, $matches)){ $complete = $matches[0]; $condition = $matches[1]; $keyField = str_replace("$", "",$matches[2] ); $itemField = str_replace("$", "",$matches[3] ); $conditionKey = str_replace("$", "",$condition ); $forListData = $this->getObjectValueByKeys($params,$conditionKey); $contentStr = str_replace($complete, "",$str); $contentStr = substr($contentStr,0,-10); return [ 'list'=>$forListData, 'keyField'=>$keyField, 'itemField'=>$itemField, 'content'=>$contentStr ]; } return []; } /** * 获取所有foreach标签 * @param $str * @return array * @throws \Exception */ protected function getAllForeachLabel($str){ $tree = []; $label = "foreach"; $labelList = $this->parseLabel($str,$label); if (!empty($labelList) && count($labelList)>0){ foreach ($labelList as $itemLabel) { $labelChildrenList = $this->parseLabel($itemLabel,$label,"children"); if (!empty($labelChildrenList) && count($labelChildrenList)>0){ $childrenList = []; foreach ($labelChildrenList as $item) { $childrenList[]=[ 'str'=>$item, 'children' => [] ]; } $tree[]=[ 'str'=>$itemLabel, 'children' => $childrenList ]; }else{ $tree[]=[ 'str'=>$itemLabel, 'children' => [] ]; } } } return $tree; } // 解析foreach protected function replaceForeach($html,$params,$level=""){ $allLabelData= $this->getAllForeachLabel($html); $res = []; if (count($allLabelData)>0){ // 遍历每个foreach标签 foreach ($allLabelData as $labelItem) { $itemStr = $labelItem['str']; $forOption = $this->parseForeach($labelItem['str'],$params); $itemContent=""; if (!empty($forOption['list']) && count($forOption['list'])>0){ // 处理每行数据 foreach ($forOption['list'] as $rowKey=>$row) { $rowData = [$forOption['itemField']=>$row,$forOption['keyField']=>$rowKey]; $rowParams = array_merge($params,$rowData); // 存在子标签,处理子标签 if (!empty($labelItem['children']) && count($labelItem['children'])>0){ $itemStrContent = ""; foreach ($labelItem['children'] as $childLabel){ $childContents = ""; $childStr = $childLabel['str']; $childDataList = $this->parseForeach($childLabel['str'],$rowParams); // 处理子标签数据 if (!empty($childDataList['list']) && count($childDataList['list'])>0){ foreach ($childDataList['list'] as $childDataKey=>$childDataItem) { // 子标签每行数据 $childDataItemData = [$childDataList['itemField']=>$childDataItem,$childDataList['keyField']=>$childDataKey,]; $contentsStr= $this->getForContent($childDataList['content'],array_merge($rowParams,$childDataItemData)); $contentsStr =ltrim($contentsStr,"\r\n"); if (!empty(Utils::trimEmpty($contentsStr))){ $childContents.= $contentsStr; } } } $itemStrContent.= str_replace($childLabel['str'], $childContents,$forOption['content']); } $rowContent=$this->replaceParams($itemStrContent,$rowParams); $itemContentStr=$this->replaceIf($rowContent,$rowParams); if (!empty(Utils::trimEmpty($itemContentStr))){ $itemContent.= $itemContentStr; } }else{ $rowContent=$this->getForContent($forOption['content'],$rowParams); if (empty(Utils::trimEmpty($rowContent))){ $rowContent= ""; } $itemContent.= $rowContent; } $itemContent =trim($itemContent,"\r\n"); } } $html = str_replace($labelItem['str'], $itemContent,$html ); } } return $html; } /** * 获取foreach内容 * @param $str * @param $params * @return array|mixed|string|string[] * @throws \Exception */ protected function getForContent($str,$params){ $content = $str; if (!empty($params)){ $content = $this->replaceParams($content,$params); $content = $this->replaceIf($content,$params); } return $content; } /** * 获取if条件的内容 * @param $str * @return mixed|string */ protected function getIfContent($str){ if (preg_match('#{if (.+?)}(.*?){/if}#s', $str, $matches)){ if (eval("return $matches[1];")){ // 条件成立 return $matches[2]; } } return ""; } /** * 解析指定标签 * @param $str * @param $label * @param string $level * @return array * @throws \Exception */ protected function parseLabel($str,$label,$level=""){ // 后面的 flag 表示记录偏移量 preg_match_all('!({/?'.$label.' ?}?)!', $str, $matches, PREG_OFFSET_CAPTURE); // 用数组来模拟栈 $stack = []; $top = null; $result = []; foreach ($matches[0] as $k=>[$match, $offset]) { // 当取标签内容时,排除第一个和最后一个标签 if ($level === 'children' && ($k==0 || $k>=count($matches[0])-1)){ continue; } // 判断匹配到的如果是 开始标签 if ($match === '{'.$label.' ') { $stack[] = $offset; // 记录开始的位置 if ($top === null) { $top = $offset; } // 如果不是 } else { // 从栈底部拿一个出来 $pop = array_pop($stack); // 如果取出来的是 null 就说明存在多余的 标签 if ($pop === null) { throw new \Exception('语法错误,存在多余的 {/'.$label.'} 标签'); } // 如果取完后栈空了 if (empty($stack)) { // offset 是匹配到的开始标签(前面)位置,加上内容的长度 $newOffset = $offset + strlen($match)-$top; // 从顶部到当前的偏移就是这个标签里的内容 $result[] = substr($str, $top, $newOffset); // 重置 top 开始下一轮 $top = null; } } } // 如果运行完了,栈里面还有东西,那就说明缺少闭合标签。 if (!empty($stack)) { throw new \Exception('语法错误,存在未闭合的 {/'.$label.'} 标签'); } return $result; } /** * 根据keys获取对象中的值 * @param $array * @param $keyStr * @param string $delimiter * @return mixed|null */ public function getObjectValueByKeys($array, $keyStr, $delimiter = '.') { $keys = explode($delimiter, $keyStr); if (preg_match_all('#\[(.+?)]#s', $keyStr, $matches)){ $value = $array; if (!empty($matches[1])){ $matchesIndex=0; foreach ($keys as $keyItem) { if (strpos($keyItem, '[') !== false) { $tagArr = explode("[", $keyItem); if (!empty($value[$tagArr[0]]) && !empty($value[$tagArr[0]][$matches[1][$matchesIndex]])){ $value =$value[$tagArr[0]][$matches[1][$matchesIndex]]; }else{ $value =null; break; } $matchesIndex=$matchesIndex+1; }else{ $value =$value[$keyItem]; } } } return $value; }else if (sizeof($keys) > 1) { $value = $array; foreach ($keys as $key){ if (!empty($value[$key])){ $value = $value[$key]; }else{ $value =null; break; } } return $value; } else { return $array[$keyStr] ?? null; } } }
true
d18aec795d33ef5a550ef537fc460104eb9ad89a
PHP
barrosgabriel/Colegio-exercicio
/cadTurma.php
UTF-8
1,503
2.8125
3
[]
no_license
<?php $error= ""; include("db.php"); if (isset($_POST['registrar'])) { $desc= $_POST['desc']; $vagas= $_POST['vagas']; $prof= $_POST['prof']; if (strlen($desc) < 10) { $error= "<h2 style= 'color:red'>Descrição de turma muito curta</h2>"; }else if (strlen($prof) < 3) { $error= "<h2 style= 'color:red'>Nome do professor muito curto</h2>"; }else{ $query = mysql_query("INSERT INTO turma(`descricao`, `vagas`, `professor`) VALUES('$desc','$vagas','$prof')"); $error= "<h2 style= 'color:green'>Aluno(a) cadastrado com sucesso!</h2>"; } } ?> <!DOCTYPE html> <html> <head> <title>Cadastro turma</title> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <?php include("header.php"); ?> <center> <h1>Registre-se</h1> <div class="panel"> <?php echo "$error"; ?> <form method="POST"> <table width="17%"> <tr> <td style="float: left;">Descrição:</td> <td><input type="text" name="desc" placeholder="Descrição" required></td> </tr> <tr> <td style="float: left;">Quantidade de vagas:</td> <td><input type="name" name="vagas" placeholder="Quantidade de vagas" required></td> </tr> <tr> <td style="float: left;">Nome do professor:</td> <td><input type="name" name="prof" placeholder="Nome do professor" required></td> </tr> </table> <tr> <input type="submit" name="registrar" value="Registrar" style="width: 17%"> </tr> </form> </body> </html>
true
a89081d30ed8d23a9a9e75d2f5c87bd21ef0436f
PHP
NagendraPasupula/Online-Book-Store-with-cloud
/ebook_detail.php
UTF-8
7,260
2.609375
3
[]
no_license
<?php include 'header.php';?> <?php include_once 'config.php';?> <?php $ID = $_GET["ID"]; $quer = "select * from votes where BookID=$ID;"; $dat = $conn->query($quer); $mydata[] = "['option', 'value']"; if(mysqli_num_rows($dat)>0){ while($r = $dat->fetch_assoc()){ $mydata = array("3 to 6 hrs"=>$r['3_6'], "1 to 3 hrs"=>$r['1_3'], "0 to 1 hrs"=>$r['0_1'], "6 to 9 hrs"=>$r['6_9']); } }else{ $mydata = array("3 to 6 hrs"=>0, "1 to 3 hrs"=>100, "0 to 1 hrs"=>0, "6 to 9 hrs"=>0); } $total = $mydata["1 to 3 hrs"]+$mydata["0 to 1 hrs"]+$mydata["3 to 6 hrs"]+$mydata["6 to 9 hrs"]; ?> <!DOCTYPE html> <html lang="en"> <head> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {packages: ['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { // Define the chart to be drawn. var data = new google.visualization.DataTable(); data.addColumn('string', 'Options'); data.addColumn('number', 'Percentage'); data.addRows([ ['0 to 1 hrs', <?php echo ($mydata["0 to 1 hrs"]/$total);?>], ['1 to 3 hrs', <?php echo ($mydata["1 to 3 hrs"]/$total);?>], ['3 to 6 hrs', <?php echo ($mydata["3 to 6 hrs"]/$total);?>], ['6 to 9 hrs', <?php echo ($mydata["6 to 9 hrs"]/$total);?>] ]); var options = { title: 'User polls: Time to read e-book:', width: 350, height: 270, is3D:true, legend:'none' }; // // Instantiate and draw the chart. var chart = new google.visualization.PieChart(document.getElementById('chart_div')); chart.draw(data, options); } </script> </head> <body> <script src="https://www.google.com/jsapi"></script> <div id="all"> <div id="content"> <?php $sql = "SELECT * FROM ebooks WHERE BookID=$ID and del=0;"; $result = $conn->query($sql); ?> <?php if ($result->num_rows > 0) { ?> <?php while($row = $result->fetch_assoc()) { ?> <div id="hot"> <div class="container" > <div class="panel panel-default"> <div class="panel-body"> <div class="col-md-12"> <div class="col-md-3"> <?php echo ' <img src="https://storage.googleapis.com/justbooks/ebooks/images/'.$row["Image"].'" alt="" height="300" width="200" class="img-responsive">'; ?> </div> <div class="col-md-5"> <h3 style="color:lightseagreen" ><?php echo $row["title"]; ?></h3> <span>by <?php echo $row["Author"]; ?></span></br> <h4 class="price"><strong>Price:$<?php echo $row["Price"];?></strong></h4></br> <span ><strong>Category:</strong><?php echo $row["Genre"];?></span></br> <span ><strong>Avearge Time to read book:</strong><?php echo ($row["pages"]*4);?> min</span></br> <div> <?php $count=$row["Rating"]; for($x = 0; $x <$count; $x++){ echo ' <span><img src="https://storage.googleapis.com/justbooks/images/stars2.jpg" alt="" style="float:left;" class="img-responsive"></span>'; } for($x = 0; $x <(5-$count); $x++){ echo ' <span><img src="https://storage.googleapis.com/justbooks/images/stars1.jpg" alt="" style="float:left;" class="img-responsive"></span>'; } ?> </div></br> <?php if (!(isset($_COOKIE["user"]))){ ?> <a class="btn btn-primary navbar-btn " onclick="myFunction()" ><i class="fa fa-shopping-cart"></i><span class="hidden-sm">Check out & Download</span></a> <?php } else{ ?> <a href="ebook_basket.php?ID=<?php echo $ID; ?>" class="btn btn-primary navbar-btn " ><i class="fa fa-shopping-cart"></i><span class="hidden-sm">Check out & Download</span></a> <?php } ?> <a class="btn btn-primary navbar-btn " onclick="window.open('https://storage.googleapis.com/justbooks/ebooks/<?php echo $ID; ?>.pdf', '_blank', 'fullscreen=yes'); return false;"><i class="fa fa-book"></i><span class="hidden-sm">Read sample</span></a> </div> <div class="col-md-4" id="chart_div"> </div> </div> </div> </div> </div> <!-- /.container --> </div> <!-- /#hot --> <?php } } else { echo "0 results"; } ?> <div id="advantages"> <div class="container"> <div class="same-height-row"> <div class="col-sm-4"> <div class="box same-height clickable"> <div class="icon"><i class="fa fa-heart"></i> </div> <h3><a href="#">We love our customers</a></h3> <p>We are known to provide best possible service ever</p> </div> </div> <div class="col-sm-4"> <div class="box same-height clickable"> <div class="icon"><i class="fa fa-tags"></i> </div> <h3><a href="#">Best prices</a></h3> <p>Best Prices on all the books guaranteed</p> </div> </div> <div class="col-sm-4"> <div class="box same-height clickable"> <div class="icon"><i class="fa fa-thumbs-up"></i> </div> <h3><a href="#">100% satisfaction guaranteed</a></h3> <p>Free returns on everything for 2 months.</p> </div> </div> </div> <!-- /.row --> </div> <!-- /.container --> </div> <!-- /#advantages --> <!-- *** ADVANTAGES END *** --> </div> <!-- /#content --> <!-- *** FOOTER *** _________________________________________________________ --> <?php include 'footer.php';?> </div> <!-- /#all --> <!-- *** SCRIPTS TO INCLUDE *** _________________________________________________________ --> <script> function myFunction() { alert("Please Login to purchase!!"); } </script> <script src="js/jquery-1.11.0.min.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/jquery.cookie.js"></script> <script src="js/waypoints.min.js"></script> <script src="js/modernizr.js"></script> <script src="js/bootstrap-hover-dropdown.js"></script> <script src="js/owl.carousel.min.js"></script> <script src="js/front.js"></script> </body> </html>
true
7ae15f472ba527a4093d43e30f050029a529093e
PHP
q312700254/fastdfs4php
/src/Traits/DeleteTrait.php
UTF-8
790
2.640625
3
[]
no_license
<?php /** * Created by PhpStorm. * User: WUC * Date: 2018/5/16 * Time: 16:43 */ namespace FastDFS\Traits; trait DeleteTrait { /** * 根据组名,文件名删除文件 * @param string $group_name * @param string $remote_filename * @return bool */ public function storage_delete_file(string $group_name, string $remote_filename):bool { return $this->fastDFS->storage_delete_file($group_name, $remote_filename, $this->tracker, $this->storage); } /** * 根据文件id删除文件 * @param string $file_id * @return bool */ public function storage_delete_file1(string $file_id):bool { return $this->fastDFS->storage_delete_file1($file_id, $remote_filename, $this->tracker, $this->storage); } }
true
a85962bfe979cc13c0a8d8ed02db9a2df9ea2508
PHP
turkprogrammer/php-objects-patterns-practice-5-rus
/src/ch04/batch05/Runner.php
UTF-8
427
2.671875
3
[]
no_license
<?php declare(strict_types=1); namespace vitaliyviznyuk\popp5rus\ch04\batch05; class Runner { /** * @return void */ public static function run(): void { $product = new ShopProduct(); } public static function run2() { $consultancy = new Consultancy(); } public static function run3() { $document = Document::create(); print_r($document); } }
true
02e12c4b620b933bce55c8dd560d96f0907c9ea1
PHP
tlayh/TwitterApi
/lib/Twitter/Api/OAuthConsumer.php
UTF-8
390
3.109375
3
[ "MIT" ]
permissive
<?php namespace Twitter\Api; class OAuthConsumer { public $key; public $secret; function __construct($key, $secret, $callbackUrl=NULL) { $this->key = $key; $this->secret = $secret; $this->callbackUrl = $callbackUrl; } function __toString() { return "OAuthConsumer[key=$this->key,secret=$this->secret]"; } }
true
cbf57cc57cba5e1636b4e2b9ffc55d2748b216fd
PHP
efri-yang/MyProject
/src/MyPhpProject/GongNengModule/MianXiangDuiXiang/destruct-1.php
UTF-8
267
3.484375
3
[]
no_license
<?php class MyDestructableClass{ function __construct(){ print "In MyDestructableClass-constructor"."<br/>"; $this->name="MyDestructableClass"; } function __destruct(){ print "Destroying ".$this->name."\n"; } } $obj=new MyDestructableClass(); ?>
true
a921fb33cb6ee4ef859beda197da172592173a5f
PHP
Fatima1160801/BZU_transportation-
/database/migrations/2021_03_24_195704_create_cabs_table.php
UTF-8
944
2.59375
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateCabsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('cabs', function (Blueprint $table) { $table->id(); $table->enum('cab-type', ['taxi','van','bus']); $table->string('cab-Number'); $table->tinyinteger('seat-num'); $table->string('license'); $table->string('insurance'); $table->foreignId('driver_id')->constrained()->onDelete('cascade')->onUpdate('cascade'); $table->string('machineNumber'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('cabs'); } }
true
0130a7130db329ecc1ddcc978093311e94db37b5
PHP
bingo-soft/jabe
/src/Impl/El/FixedValue.php
UTF-8
908
2.859375
3
[ "MIT" ]
permissive
<?php namespace Jabe\Impl\El; use Jabe\ProcessEngineException; use Jabe\Delegate\{ BaseDelegateExecutionInterface, ExpressionInterface, VariableScopeInterface }; class FixedValue implements ExpressionInterface { private $value; public function __construct($value) { $this->value = $value; } public function getValue(VariableScopeInterface $variableScope, ?BaseDelegateExecutionInterface $contextExecution = null) { return $this->value; } public function setValue($value, ?VariableScopeInterface $variableScope = null, ?BaseDelegateExecutionInterface $contextExecution = null): void { throw new ProcessEngineException("Cannot change fixed value"); } public function getExpressionText(): ?string { return strval($this->value); } public function isLiteralText(): bool { return true; } }
true
515f6d8ebab6278d16167734d30fbb116dbdbe51
PHP
kratijhindal/infosec2
/php_basics/for.php
UTF-8
89
2.75
3
[]
no_license
<?php $i = 0; $num =10; for($i=0;$i<10;$i++){ echo "the value of $i <br>"; } ?>
true
f654389319d7621bd9bb915428040459b7576af4
PHP
predatorpc/callex
/models/CallbackAutoCalls.php
UTF-8
2,751
2.703125
3
[ "BSD-3-Clause" ]
permissive
<?php /** * Created by PhpStorm. * User: rr * Date: 15.12.17 * Time: 9:35 */ namespace app\models; use yii\base\Model; class CallbackAutoCalls extends Model { const PATH_DONE = ''; public function startCallback(){ //открываем папку и читаем из нее файлы // если файл прочитан и все сохранено то удаляем файл // е сли нет то оставляем его там $files = $this->getFiles(); if(!empty($files)){ // открываем файл и ищем по шаблону номер телефона и дату foreach ($files as $file){ if(file_exists($file)){ $content = file_get_contents($file); if(!empty($content)){ preg_match('/(?P<name_phone>(#phone))(?P<phone>([\d]{11}))(?P<name_date>(#date))(?P<date>([\d-]{10}))/', $content, $matches); if(!empty($matches['phone']) && !empty($matches['date'])){ //ищем клиента и создаем ему комментарий с типом авто обзвон $phone = preg_replace('/(\+7)|(\()|(\))|(-)|(\s)|(^8)/','',$matches['phone']); $client = Clients::find()->where(['like', 'phone', '%'.$phone])->one(); if(!empty($client)){ // создаем комментарий и удаляем файл $comment = New Comments(); $comment->client_id = $client->id; $comment->action_id = 1; $comment->text = 'Автоматический обзвон '.Date('d.m.Y', strtotime($matches['date'])) ; $comment->status = 1 ; $client->last_call = Date('Y-m-d H:i:s'); if($comment->save(true) && $client->save(true)){ //удаляем файл $this->delFile($file); } } } } } } } } private function getFiles(){ $fileList = glob(self::PATH_DONE.'/*.call'); if(!empty($fileList)){ return $fileList; } return false; } private function delFile($file=false){ if(!empty($file)){ if(unlink($file)){ return true; } } return false; } }
true
f9726e2fb7c97bcef4931308e3dcccf60d0af7cb
PHP
MansonOrYmc/youyao99
/QA/system/classes/apf/Component.php
UTF-8
5,748
2.578125
3
[ "MIT" ]
permissive
<?php /** * APF 组件类,所有页面显示的基础类 * added by htlv */ abstract class APF_Component { /** * 组件构造函数,每个组件都有父组件,最早的祖先组件是一个页面类 * @param APF_Component $parent 父组件对象 * @param int $html_id 组件id */ public function __construct($parent=NULL, $html_id=NULL) { $this->parent = $parent; $this->html_id = $html_id; } /** * 获取父组件 * @return APF_Component */ public function get_parent() { return $this->parent; } /** * 父组件 * @var APF_Component */ private $parent; // /** * 获取组件id * @return string */ public function get_html_id() { return $this->html_id; } /** * 组件id * @var int */ private $html_id; /** * 注册javascript路径,每个路径对应单独的js文件 * @return array */ public static function use_javascripts() { return array(); } /** * 注册css路径,每个路径对应单独的css文件 */ public static function use_styles() { return array(); } /** * 注册javascript路径,所有js文件将合并到名为页面类的js中。 */ public static function use_boundable_javascripts() { return array(); } /** * 注册css路径,所有css文件将合并到名为页面类的css中。 */ public static function use_boundable_styles() { return array(); } /** * 注册子组件 * @return array */ public static function use_component() { return array(); } /* begin 2010-11-04 by Jock*/ public static function use_inline_styles(){ return false; } public static function prefetch_javascripts(){ return array(); } public static function prefetch_styles(){ return array(); } public static function prefetch_images(){ return array(); } /* end 2010-11-04 by Jock*/ /* add by Jock 2011-05-20 */ public static function use_inline_scripts(){ return false; } /** * 设置参数,不知何用 * @param unknown_type $params */ public function set_params($params=array()) { $this->params = $params; } /** * 获取参数 * @return array */ public function get_params() { return $this->params; } /** * 获取指定参数 * @param string $name */ public function get_param($name) { return $this->params[$name]; } /** * 参数槽 * @var array */ private $params; /** * 设置页面变量 * @param string $name 变量名 * @param unknown_type $value */ public function assign_data($name, $value) { $this->data[$name] = $value; } /** * 获取所有页面变量 */ public function get_data() { return $this->data; } /** * 变量槽 * @var array */ private $data = array(); /** * 载入组件显示页面 */ public function execute() { $view = $this->get_view(); if ($view) { $f = apf_classname_to_path(get_class($this)).$view.'.phtml'; $file = "component/".$f; global $G_LOAD_PATH,$cached_files; if (defined('CACHE_PATH')) { $cf = apf_class_to_cache_file($f,"component"); if (file_exists($cf)) { $this->render($cf); return; } } foreach ($G_LOAD_PATH as $path) { if (file_exists($path.$file)) { $this->render($path.$file); if (defined('CACHE_PATH')) { apf_save_to_cache($f,"component",$path.$file); } break; } } } } /** * 开始输出脚本 */ public function script_block_begin() { ob_start(); } /** * 结束脚本输出 * @param unknown_type $order */ public function script_block_end($order=0) { $content = ob_get_contents(); APF::get_instance()->register_script_block($content,$order); ob_end_clean(); } /** * 获取页面框架名称 */ abstract public function get_view(); /** * 渲染页面,也就是载入文件…… * 设置所有页面变量,保证phtml的php脚本可以引用 * @param string $file 文件路径 */ protected function render($file) { foreach ($this->get_params() as $key => $value) { $$key = $value; } // 设置变量 foreach ($this->data as $key=>$value) { $$key = $value; } // 预设请求类和响应类变量,其实大可不必 $request = APF::get_instance()->get_request(); $response = APF::get_instance()->get_response(); // 渲染???就是include,够高端吧。 include($file); } /** * 实例化组件对象 * @return APF_Component */ public function component($class, $params=array()) { return APF::get_instance()->component($this, $class, $params); } /** * 获取组件的页面类 * @return APF_Page */ protected function get_page() { $object = $this->get_parent(); while ($object) { if ($object instanceof APF_Page) { return $object; } $object = $object->get_parent(); } return NULL; } }
true
bed0016adfa429bfa272a982c55e74181273efa9
PHP
katherto/WEB128
/Practice/Radio Buttons from Array/dynamicRadio.php
UTF-8
725
2.890625
3
[]
no_license
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Choose your State</title> </head> <body> <h2>Dynamic Radio Buttons</h2> <form action="dynamicRadio.php" method="POST"> Pick your State:<br> <?php $states = array("Kansas" => 'KS', "Missouri" => 'MO', "Iowa" => 'IA', "Nebraska" => 'NE', "Maryland" => 'MD', "California" => 'CA'); foreach($states as $key => $value) { echo '<input name="state" type="radio" value="' . $value . '" /> '. $key .'<br />'; } ?> <input type="submit" value="Submit"> </form> </body> </html>
true
3972832b279525292510ac28b37eb4d144058092
PHP
devvyhac/farmapropos
/accounts/signup.php
UTF-8
5,892
2.765625
3
[]
no_license
<?php // session_start(); // if (isset($_SESSION['id']) && isset($_SESSION['email']) && isset($_SESSION['username'])) { // header("Location: ../account"); // } // if ($_SERVER['REQUEST_METHOD'] == "POST") { // require_once "process.php"; // $process = new Process(); // $result = $process->signup($_POST); // $error = $process->get_error(); // } if (isset($_SESSION['id']) && isset($_SESSION['email']) && isset($_SESSION['username'])) { header("Location: ../account"); } if (!empty($_SESSION['units']) || !empty($_SESSION['funding'])) { if (isset($_SESSION['id']) && isset($_SESSION['email']) && isset($_SESSION['username'])) { header("Location: ../account"); } if ($_SERVER['REQUEST_METHOD'] == "POST") { require_once "process.php"; $process = new Process(); $result = $process->signup($_POST, $_SESSION); $error = $process->get_error(); } } elseif (empty($_GET['funding']) && empty($_GET['units'])) { unset($_SESSION['funding']); unset($_SESSION['units']); if ($_SERVER['REQUEST_METHOD'] == "POST") { require_once "process.php"; $process = new Process(); $result = $process->signup($_POST); $error = $process->get_error(); } } function format($str){ $str = filter_var($str, FILTER_SANITIZE_STRING); return $str; } ?> <?php require_once "includes/head.php" ?> <?php if(isset($error["empty_err"])) : ?> <h4 <?php echo (isset($error["empty_err"]) ? "class=error-msg" : ""); ?>><?php echo $error["empty_err"] ?></h4> <?php elseif(isset($error["wrong_email"])) : ?> <h4 <?php echo (isset($error["wrong_email"]) ? "class=error-msg" : ""); ?>><?php echo $error["wrong_email"] ?></h4> <?php elseif(isset($error["name_error"])) : ?> <h4 <?php echo (isset($error["name_error"]) ? "class=error-msg" : ""); ?>><?php echo $error["name_error"] ?></h4> <?php elseif(isset($error["phone_error"])) : ?> <h4 <?php echo (isset($error["phone_error"]) ? "class=error-msg" : ""); ?>><?php echo $error["phone_error"] ?></h4> <?php elseif(isset($error["user_error"])) : ?> <h4 <?php echo (isset($error["user_error"]) ? "class=error-msg" : ""); ?>><?php echo $error["user_error"] ?></h4> <?php elseif(isset($error["password_error"])) : ?> <h4 <?php echo (isset($error["password_error"]) ? "class=error-msg" : ""); ?>><?php echo $error["password_error"] ?></h4> <?php else : ?> <h4><?php echo ""; ?></h4> <?php endif;?> <h2 class="title bg-dark">Farm Apropos - Sign Up <i class="fa fa-user-plus"></i></h2> <form method="POST" action="<?php echo "signup" ?>" > <div class="row row-space"> <div class="col-2"> <div class="input-group"> <label class="label">first name</label> <input class="input--style-4" type="text" name="first_name" value="<?php isset($_POST['first_name']) ? print format($_POST['first_name']) : print ""; ?>" required title="Please Fill in This Field!"> </div> </div> <div class="col-2"> <div class="input-group"> <label class="label">last name</label> <input class="input--style-4" type="text" name="last_name" value="<?php isset($_POST['last_name']) ? print format($_POST['last_name']) : print ""; ?>" required title="Please Fill in This Field!"> </div> </div> </div> <div class="row row-space"> <div class="col-2"> <div class="input-group"> <label class="label">Email</label> <input class="input--style-4" type="text" name="email" value="<?php isset($_POST['email']) ? print format($_POST['email']) : print ""; ?>" required title="Please Fill in This Field!"> </div> </div> <div class="col-2"> <div class="input-group"> <label class="label">Phone Number</label> <input class="input--style-4" type="text" name="phone" value="<?php isset($_POST['phone']) ? print format($_POST['phone']) : print ""; ?>" required title="Please Fill in This Field!"> </div> </div> </div> <div class="row row-space"> <div class="col-2"> <div class="input-group"> <label class="label">Birthday</label> <div class="input-group-icon"> <input class="input--style-4 js-datepicker" type="text" name="birthday" value="<?php isset($_POST['birthday']) ? print format($_POST['birthday']) : print ""; ?>" required title="Please Fill in This Field!"> <i class="zmdi zmdi-calendar-note input-icon js-btn-calendar"></i> </div> </div> </div> <div class="col-2"> <div class="input-group"> <label class="label">Gender</label> <div class="rs-select2 js-select-simple select--no-search"> <select name="gender" value="<?php isset($_POST['gender']) ? print format($_POST['gender']) : print ""; ?>" required title="Please Fill in This Field!"> <option selected="selected">Male</option> <option>Female</option> </select> <div class="select-dropdown"></div> </div> </div> </div> </div> <div class="row row-space"> <div class="col-2"> <div class="input-group"> <label class="label" for="username">Username</label> <input class="input--style-4" type="text" name="username" required value="<?php isset($_POST['username']) ? print format($_POST['username']) : print ""; ?>" title="Please Fill in This Field!"> </div> </div> <div class="col-2"> <div class="input-group"> <label class="label" for="password">Password</label> <input class="input--style-4" type="password" name="password" required value="<?php isset($_POST['password']) ? print format($_POST['password']) : print ""; ?>" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters" required> </div> </div> </div> <div class="p-t-15 submit-area"> <button class="btn btn--radius-2 btn--blue" type="submit">Register</button> <span>Already have an Account?</span> <a href="login">Login</a> </div> <?php require_once "includes/footer.php" ?>
true
88a76765c240993bee78beca8ca783f2753ba66e
PHP
IgzyyJere/php_XML
/njuskalo/vivio/vivo2/vivoAplikacije/prikazKlijenta.php
UTF-8
1,852
2.546875
3
[]
no_license
<?php // brisanje podatka / if ( $_GET['obrisi'] ) { if ( $p['razina'] == 1 ) { $upit = "DELETE FROM `".$tabela."` WHERE id = '".$_GET['obrisi']."'"; mysql_query ( $upit ); } else { $upit = "UPDATE `".$tabela."` SET obrisano = 1 WHERE id = '".$_GET['obrisi']."'"; mysql_query ( $upit ); } } // spajanje na nekretninu if ( $_GET['spojeno'] ) { $upit = "UPDATE `".$tabela."` SET `spojeno` = '".$_GET['spojeno']."' WHERE `id` = '".$_GET['id']."'"; mysql_query ( $upit ); } // unos izmjena u podatke if ( $_GET['izmjeni'] ) { $izuzeci = array ( "submit", "continue", "akcija", "stranica", "id", "napravi" ); mysql_query ( vivoPOSTizmjena ( $_POST, $tabela, $izuzeci, $_GET['izmjeni'] )); //echo vivoPOSTizmjena ( $_POST, "klijentistanovi", $izuzeci, $_POST['id'] ); } // unos podataka u bazu if ( $_POST['napravi'] == "unos" ) { $izuzeci = array ( "submit", "continue", "akcija", "stranica", "id", "napravi" ); mysql_query ( vivoPOSTunos ( $_POST, $tabela, $izuzeci, $_POST['id'] )); //echo vivoPOSTunos ( $_POST, "klijentistanovi", $izuzeci, $_POST['id'] ); } // slanje podatka u arhivu / if ( $_GET['arhiva'] ) { $upit = "UPDATE `".$tabela."` SET arhiva = '1' WHERE id = '".$_GET['arhiva']."'"; mysql_query ( $upit ); } $upit = "SELECT id, imeIPrezime, aktivno, spojeno FROM ".$tabela." WHERE grupa = '".$grupa."' AND ( obrisano IS NULL OR obrisano = '0' ) AND ( arhiva IS NULL OR arhiva = '0' ) ORDER BY id DESC LIMIT ".$startIndex.", ".$poStranici.""; $odgovori = mysql_query ( $upit ); $i = 0; while ( $podaci = mysql_fetch_assoc ( $odgovori )) { if ( $i % 2 ) { $back = "darkLine"; } else { $back = "lightLine"; } prikaziKlijenta ( $podaci, $back, $tabela ); $i++; } ?>
true
cf2736edbe318baa21a9014b4ac6bea8cfb85f8f
PHP
avishka964/grill-island-wdp
/controllers/profile.php
UTF-8
1,408
2.578125
3
[]
no_license
<?php session_start(); // Report all PHP errors error_reporting(E_ALL); if(isset($_POST['update-profile'])){ include_once("../config/DatabaseConn1.php"); $userNewName = $_POST['username']; $userNewEmail = $_POST['useremail']; $userNewPassword = $_POST['userpassword']; $userNewConfirmPassword = $_POST['userconfirmpassword']; if(empty($userNewName) && empty($userNewEmail) && empty($userNewPassword) && empty($userNewConfirmPassword)){ header('Location: ../update_profile.php?error=emptyNameAndEmail'); exit; }else if(strlen($userNewPassword) < 6){ header('Location: ../update_profile.php?error=passwordNotStrong'); exit; }else if($userNewPassword !== $userNewConfirmPassword){ header('Location: ../update_profile.php?error=passwordNotMatch'); exit; }else if(!filter_var($userNewEmail, FILTER_VALIDATE_EMAIL)){ header('Location: ../update_profile.php?error=emailNotValid'); exit; }else{ $loggedInUser = $_SESSION['email']; $hash_update_password = md5($userNewPassword); $sql = "UPDATE customers SET name ='$userNewName', email = '$userNewEmail' , password = '$hash_update_password' WHERE email = '$loggedInUser'"; $results = mysqli_query($connection,$sql); header('Location: logout.php?success=userUpdated'); exit; } } ?>
true
df2a80f688aea0bac1ef7427313c40b715b9b999
PHP
SeanMcA/GetGolfCourses
/index1.php
UTF-8
4,194
2.546875
3
[]
no_license
<html> <head> <title>Getting General course info!</title> </head> <body> <?php set_time_limit(0); //database connection parameters $databaseAddress = "localhost"; $username = "root"; $password = ""; $database = "zelusitc_GolfCourses"; $table = "course"; $file = "10500-11999.csv"; //place this before any script you want to calculate time $time_start = microtime(true); $counter = 0; if (($handle = fopen($file, "r")) !== FALSE) { while (($data = fgetcsv($handle, 0, ",")) !== FALSE) { //fgetcsv(file,line length,separator,enclosure) if($counter % 100 == 0){ echo "Lines number " . $counter . "<br>"; ob_flush(); flush(); } //Connect to MySql database $mysqli = new mysqli($databaseAddress, $username, $password, $database); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } for ($c=0; $c < 1; $c++) { $coursesUrl = "https://api.swingbyswing.com/v1/courses?access_token=gAAAAFaJFRgbsYAARqSxWZZ6Nzcnku6H6Tsa06bbwIoF09_ojtLdk7XV4kCG_UQoIR-j6g_Ct6ajx_IVvLQpOqHkw5srSmAcSduBvyY6cILpLJrygDDdgs9gUNooH_cmoeS7TUeFm5n9s1N6yVGdnqxd1KZ_PFk-qS5Yp4hWWMg7bVYSFAEAAIAAAACNFsL04O4t9Tf-6KAXjBBaheLSkldNUhHUI34KqX_SA9GG_6fFJCcH7RzgnjIPvbi2KFyP0xJ_B_YFs60L9eFDugQNzh21PQUXVYo_IuG56xKyfngw2b6yA8iQQ5RyPUqWWDcwwmDDrgztIpIkV5A2XoLy-3sU0QujwWngUnkkuRrnzCwQnsjKDps1-ZDjZjolb7ZmH7sW0SW890Mp7OAD9rocZ4Fny9xrORE6dIEZGCWk-6pXk-ysZt_-BUuONe5DylEzVRhg8_Tlcl0ekfWQAHEtYiLFOy8l2Z0tBhYCy8Jrpnrekj1jAdOZ7czSUIk5m4zl3HBTJ1_C1koclolOVSmXc5LcdY3nmN-DeeIezw&lat=" . $data[0] . "&lng=" . $data[1] . "&to=600&activeOnly=yes"; $properUrl = html_entity_decode($coursesUrl); $json = file_get_contents($properUrl); $obj = json_decode($json); for($x = 0; $x < sizeof($obj->courses); $x++){ $courseName = $obj->courses[$x]->name; //echo "Course name is: " . $courseName . "<br>"; $courseId = $obj->courses[$x]->courseId; //echo "CourseId is: " . $courseId . "<br>"; $courseLatitude = $obj->courses[$x]->lat; //echo "courseLatitude is: " . $courseLatitude . "<br>"; $courseLongitude = $obj->courses[$x]->lng; //echo "courseLongitude is: " . $courseLongitude . "<br>"; $distanceFromMeKilometers = $obj->courses[$x]->distanceFromMeKilometers; //echo "distanceFromMeKilometers is: " . $distanceFromMeKilometers . "<br>"; $distanceFromMeMiles = $obj->courses[$x]->distanceFromMeMiles; //echo "distanceFromMeMiles is: " . $distanceFromMeMiles . "<br>"; $website = $obj->courses[$x]->website; //echo "website is: " . $website . "<br>"; $measurementType = $obj->courses[$x]->measurementType; //echo "measurementType is: " . $measurementType . "<br>"; $measurementTypeId = $obj->courses[$x]->measurementTypeId; //echo "measurementTypeId is: " . $measurementTypeId . "<br>"; $holeCount = $obj->courses[$x]->holeCount; //echo "holeCount is: " . $holeCount . "<br>"; $addr1 = $obj->courses[$x]->addr1; //echo "addr1 is: " . $addr1 . "<br>"; $addr2 = $obj->courses[$x]->addr2; //echo "addr2 is: " . $addr2 . "<br>"; $city = $obj->courses[$x]->city; //echo "city is: " . $city . "<br>"; $country = $obj->courses[$x]->country; //echo "country is: " . $country . "<br>"; $query = "INSERT IGNORE INTO course( CourseName, courseId, courseLatitude, courseLongitude, distanceFromMeKilometers, distanceFromMeMiles, website, measurementType, measurementTypeId, holeCount, addr1, addr2, city, country ) VALUES ( '". $courseName ."', '". $courseId ."', '". $courseLatitude ."', '". $courseLongitude ."', '". $distanceFromMeKilometers ."', '". $distanceFromMeMiles ."', '". $website ."', '". $measurementType ."', '". $measurementTypeId ."', '". $holeCount ."', '". $addr1 ."', '". $addr2 ."', '". $city ."', '". $country ."' )"; //echo $query . "<br>"; $mysqli->query($query); } $counter++; }// for loop /* close connection */ $mysqli->close(); } fclose($handle); echo "Final Lines number " . $counter . "<br>"; } $time_end = microtime(true); //dividing with 60 will give the execution time in minutes other wise seconds $execution_time = ($time_end - $time_start)/60; //execution time of the script echo '<b>Total Execution Time:</b> '.$execution_time.' Mins'; ?> </body> </html>
true
d3d3583bc18797fc0f0c6d1683554fb27c37f567
PHP
gabrielpcruz/filldatabase
/src/Http/Api/Tables.php
UTF-8
1,017
2.609375
3
[ "MIT" ]
permissive
<?php namespace App\Http\Api; use App\Http\ControllerApi; use Illuminate\Database\Capsule\Manager; use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; class Tables extends ControllerApi { /** * @param Request $request * @param Response $response * @return Response */ public function tables(Request $request, Response $response): Response { $connection = Manager::connection('filldatabase'); $tables = $connection->select("show full tables where Table_Type != 'VIEW'"); return $this->responseJSON($response, $this->tratarTables($tables)); } /** * @param $tablesQuery * @return array */ private function tratarTables($tablesQuery): array { $tables = []; foreach ($tablesQuery as $table) { $key = array_keys((array) $table); $key = reset($key); $tables[] = $table->{$key}; } return $tables; } }
true
b2d8132454887119186f48a5ca7dd55ebea721b3
PHP
DuckThom/code-wookies
/php/php7test.php
UTF-8
427
3.65625
4
[]
no_license
<?php declare(strict_types=1); class Hoi { public static function foo(): string { return "bar"; } public static function bar(): int { return 1; } public static function foobar(): float { return true; } } echo "Hoi::foo() - "; var_dump(Hoi::foo()); echo "Hoi::bar() - "; var_dump(Hoi::bar()); echo "Hoi::foobar() - "; try { var_dump(Hoi::foobar()); } catch (TypeError $e) { var_dump($e->getMessage()); }
true
84eb84a16a36319fabbb6b2014b97fcced6e893b
PHP
Ahmedtgd/trunk2
/app/AuthenticateUser.php
UTF-8
3,083
2.578125
3
[]
no_license
<?php namespace App; use App\Models\User; use Illuminate\Contracts\Auth\Guard; use Illuminate\Support\Facades\Redirect; use Illuminate\Support\Facades\URL; use Laravel\Socialite\Contracts\Factory as Socialite; use App\Http\Controllers\TokenController; use Request; use Session; class AuthenticateUser { /** * @var Socialite */ private $socialite; /** * @var User */ private $users; /** * @var Guard */ private $auth; private $URL; /** * @param Socialite $socialite * @param User $users * @param Guard $auth */ public function __construct(Socialite $socialite, User $users, Guard $auth) { $this->socialite = $socialite; $this->users = $users; $this->auth = $auth; $this->URL = URL::previous(); } /** * @param $hasCode string URL Parameter * @param $provider string Facebook, Github, Twitter, Linkedin * @param string $redirect * @return \Illuminate\Http\RedirectResponse|\Symfony\Component\HttpFoundation\RedirectResponse */ public function execute( $hasCode, $provider, $redirect ,$requestSource='') { //Check if code parameter is set. if ( !$hasCode ) return $this->getAuthorizationFirst( $provider ); $data=$this->getProviderUser( $provider ); if (empty($data->email) or !isset($data->email) or $data->email==null) { return view('common.generic') ->with('message_type','error') ->with('message','Please provide email permissions.') ; } //Get user data from provider $user = $this->users->findByEmailOrCreate($this->getProviderUser( $provider )); //Get user interface $this->auth->login($user, true); //Redirects to kleenso products. //return redirect('/sub-cat-details/1/15'); if( !empty($redirect) ) { return redirect($redirect); } // $customURL=url('/create_new_buyer'); if ($this->URL==$customURL) { # code... // Session::put('fbloginStatus','success'); return redirect('buyer/dashboard'); } // return response()->json(['status'=>'success','long_message'=>'You have been successfully signed in through facebook']); return redirect('/'); } /** * @param $provider * @return \Symfony\Component\HttpFoundation\RedirectResponse */ private function getAuthorizationFirst( $provider ) { //Pass scope in order to authorize fb user to publish return $this->socialite->driver( $provider )->scopes([ 'email', 'public_profile', 'user_friends', 'publish_actions', ])->redirect(); } /** * Get authenticated user from provider * @param $provider * @return \Laravel\Socialite\Contracts\User */ private function getProviderUser($provider) { return $this->socialite->driver( $provider )->user(); } }
true
63ef07324f67098d59419f4870ddb125aeee6a40
PHP
Getteli/apipagseguro
/Legacy - PAGSEGURO - Checkout transparente/_assets/pagseguro/consult_pagseguro.php
UTF-8
1,615
2.609375
3
[ "MIT" ]
permissive
<?php // charset header('Content-Type: text/html; charset=utf-8'); // header('Content-Type: text/xml;'); // chama a configuracao include("config.php"); $Referencia = '83783783737'; // GET $Url="https://ws.sandbox.pagseguro.uol.com.br/v2/transactions?email=".EMAIL_PAGSEGURO."&token=".TOKEN_SANDBOX."&reference=".$Referencia; $Curl = curl_init($Url); curl_setopt($Curl,CURLOPT_HTTPHEADER,array("Content-Type: application/x-www-form-urlencoded; charset=UTF-8")); curl_setopt($Curl,CURLOPT_SSL_VERIFYPEER,false); curl_setopt($Curl,CURLOPT_RETURNTRANSFER,true); $Retorno = curl_exec($Curl); curl_close($Curl); $Xml = simplexml_load_string($Retorno); // var_dump($Xml); // echo $Retorno; echo "Ordem decrescente (o mais recente para o mais antigo):<br />"; // 90 dias para a devolucao do dinheiro // 120 dias para buscar o codigo da transacao, data mais antiga sera necessario verificar extrato da transacao na conta do pagseguro foreach($Xml->transactions as $Transactions){ foreach($Transactions as $Transaction){ if ( $Transaction->status == 6 || $Transaction->status == 7 || $Transaction->status == 8 ) { }else{ echo "Código: <a href='consult_advanced_pagseguro.php?code=". $Transaction->code ."'>". $Transaction->code ."</a>"; echo " | "; if ( $Transaction->status == 3 || $Transaction->status == 4 || $Transaction->status == 5 ) { echo "<a href='estorn_pagseguro.php?code=". $Transaction->code ."'>Estornar compra</a>"; }else{ echo "<a href='cancel_pagseguro.php?code=". $Transaction->code ."'>Cancelar compra</a>"; } echo "<hr/>"; } } }
true
751c6900bbf000bdde4e7c32f3e2d7b4d1fcc55a
PHP
chabby-hao/laravel_admin
/app/Models/BiDeliveryOrder.php
UTF-8
3,674
2.609375
3
[]
no_license
<?php namespace App\Models; /** * App\Models\BiDeliveryOrder * * @property int $id * @property int $user_id * @property int $state 状态,0=代工厂处理,1=已完成,2=已作废 * @property int $ship_no 出货单号 * @property int $order_id * @property string|null $part_number 料号 * @property int $fact_id 工厂id(其实就是user_id) * @property \Carbon\Carbon|null $delivery_date 出货日期 * @property int $delivery_quantity 出货数量 * @property int $brand_id 品牌id * @property int $ebike_type_id 车型id * @property int $battery_type 电池型号 * @property \Carbon\Carbon|null $created_at * @property \Carbon\Carbon|null $updated_at * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\BiDeliveryOrder whereBrandId($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\BiDeliveryOrder whereCreatedAt($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\BiDeliveryOrder whereDeliveryDate($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\BiDeliveryOrder whereDeliveryQuantity($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\BiDeliveryOrder whereEbikeTypeId($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\BiDeliveryOrder whereFactId($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\BiDeliveryOrder whereId($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\BiDeliveryOrder whereOrderId($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\BiDeliveryOrder wherePartNumber($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\BiDeliveryOrder whereShipNo($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\BiDeliveryOrder whereState($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\BiDeliveryOrder whereUpdatedAt($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\BiDeliveryOrder whereUserId($value) * @mixin \Eloquent * @property string|null $actuall_date 实际出货日期 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\BiDeliveryOrder whereActuallDate($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\BiDeliveryOrder whereBatteryType($value) */ class BiDeliveryOrder extends \App\Models\Base\BiDeliveryOrder { protected $fillable = [ 'user_id', 'state', 'ship_no', 'order_id', 'part_number', 'fact_id', 'delivery_date', 'delivery_quantity', 'brand_id', 'ebike_type_id', 'battery_type', ]; protected $dates = []; const DELIVERY_ORDER_STATE_INIT = 0;//待工厂处理 const DELIVERY_ORDER_STATE_FINISH = 1;//已完成 const DELIVERY_ORDER_STATE_CANCEL = 2;//已作废 const BATTERY_TYPE_XINPU = 1;//新普 const BATTERY_TYPE_AIBIKE = 2;//艾比克 const BATTERY_TYPE_ZHONGLI = 3;//中锂 const BATTERY_TYPE_HUIKANG = 4;//惠康锂电 public static function getBatteryTypeMap() { $map = [ self::BATTERY_TYPE_XINPU => '新普', self::BATTERY_TYPE_AIBIKE => '艾比克', self::BATTERY_TYPE_ZHONGLI => '中锂', self::BATTERY_TYPE_HUIKANG => '惠康', ]; return $map; } public static function getStateTypeName($type = null) { $map = [ self::DELIVERY_ORDER_STATE_INIT =>'待工厂处理', self::DELIVERY_ORDER_STATE_FINISH =>'已完成', self::DELIVERY_ORDER_STATE_CANCEL =>'已作废', ]; return $type === null ? $map : $map[$type]; } }
true
e36614ea92b82b0f58a2e0f2e43f62a2fa3268f1
PHP
jamesonyemi/code_challenge
/gradingStudent.php
UTF-8
1,126
3.84375
4
[]
no_license
<?php /* * Complete the 'gradingStudents' function below. * * The function is expected to return an INTEGER_ARRAY. * The function accepts INTEGER_ARRAY grades as parameter. */ function gradingStudents($grades) { // Write your code here $isRoundedGrade = []; for ($i = 0; $i < count($grades); $i++) { $difference = IsMultipleOfFive($grades[$i]); $finalGrade = $difference + $grades[$i]; if (($difference < 3) && ($finalGrade >= 40)) { array_push($isRoundedGrade,$finalGrade); } else { array_push($isRoundedGrade,$grades[$i]); } } return $isRoundedGrade; } function IsMultipleOfFive($x) { $counter = 0; while ($x % 5 != 0) { $x++; $counter++; } return $counter; } $fptr = fopen(getenv("OUTPUT_PATH"), "w"); $grades_count = intval(trim(fgets(STDIN))); $grades = array(); for ($i = 0; $i < $grades_count; $i++) { $grades_item = intval(trim(fgets(STDIN))); $grades[] = $grades_item; } $result = gradingStudents($grades); fwrite($fptr, implode("\n", $result) . "\n"); fclose($fptr);
true
bbebb8b2925951cb24dfcc380872c2dd6a35db8d
PHP
hanneskod/readme-tester
/src/Attribute/DeclareDirective.php
UTF-8
489
2.515625
3
[ "Unlicense" ]
permissive
<?php declare(strict_types=1); namespace hanneskod\readmetester\Attribute; #[\Attribute(\Attribute::IS_REPEATABLE | \Attribute::TARGET_ALL)] class DeclareDirective extends PrependCode { private string $directive; public function __construct(string $directive) { parent::__construct("declare($directive);"); $this->directive = $directive; } public function asAttribute(): string { return self::createAttribute($this->directive); } }
true
41fec0f0b188bf1e7e1a2c68cbcec8aab3111686
PHP
cybspace/gbphp
/L6/private/db_tasks.php
UTF-8
6,723
2.75
3
[]
no_license
<?php include_once __DIR__ . '/../config/main.php'; include_once 'dependencies.php'; /******************************************* file_props_arr = [ 'id' => null 'file_name' => $file_name, 'url' => $file_url, 'thumbnail_url' => $file_thumbnail_url, 'alt_url' => $file_alt_url ]; ********************************************/ function manage_connection ($close = false) { include_once __DIR__ . '/../config/main.php'; static $CURRENT_CONNECTION; static $CONNECTION_PARAMS = [ 'host' => '127.0.0.1', 'user' => 'root', 'passw' => '1q2we34r', 'db' => 'gbphp_db' ]; $current_thread = mysqli_thread_id($CURRENT_CONNECTION); if (is_null($current_thread) && $close === false) { $CURRENT_CONNECTION = mysqli_connect( $CONNECTION_PARAMS['host'], $CONNECTION_PARAMS['user'], $CONNECTION_PARAMS['passw'], $CONNECTION_PARAMS['db'] ); } else if (!is_null($current_thread) && $close) { mysqli_close($CURRENT_CONNECTION); }; return $CURRENT_CONNECTION; }; function check_if_row_exists_by_attr ($attr_value, $table, $attr) { $conn = manage_connection(); $select = "SELECT * FROM {$table} WHERE {$attr} = '{$attr_value}';"; $result = mysqli_query($conn, $select); $result_arr = mysqli_fetch_all($result); return (count($result_arr) > 0); }; function save_file_props_in_db ($file_props_arr) { if (!is_array($file_props_arr) && !isset($file_props_arr)) return false; $conn = manage_connection(); $is_exist = check_if_row_exists_by_attr($file_props_arr['url'], 't_site_resources', 'url'); if (!$is_exist) { $insert = "INSERT INTO t_site_resources (url, thumbnail_url) VALUES ('{$file_props_arr['url']}', '{$file_props_arr['thumbnail_url']}');"; } else { return false; }; $result = mysqli_query($conn, $insert); $id_resource = mysqli_insert_id($conn); if ($id_resource !== 0) { $insert = "INSERT INTO t_site_images (id_resource, img_name) VALUES ({$id_resource}, '{$file_props_arr['file_name']}');"; $result = mysqli_query($conn, $insert); $id_resource = mysqli_insert_id($conn); }; return $id_resource !== 0 ? true : false; }; function select_all_file_props_from_db () { $conn = manage_connection(); $file_props_arr = null; $select = "SELECT img.id, img_name as file_name, url, thumbnail_url, img_views as views FROM gbphp_db.t_site_images img JOIN gbphp_db.t_site_resources url ON img.id_resource = url.id ORDER BY img_views DESC;"; $result = mysqli_query($conn, $select); $file_props_arr = mysqli_fetch_all($result, MYSQLI_ASSOC); return $file_props_arr; }; function select_single_file_props_by_attr ($attr_name, $attr_value) { $conn = manage_connection(); $file_props_arr = null; $select = "SELECT img.id, img_name as file_name, url, thumbnail_url, img_views as views FROM gbphp_db.t_site_images img JOIN gbphp_db.t_site_resources url ON img.id_resource = url.id WHERE {$attr_name} = '{$attr_value}';"; $result = mysqli_query($conn, $select); $file_props_arr = mysqli_fetch_assoc($result); return $file_props_arr; }; function increase_img_view_count_by_attr ($attr_name, $attr_value) { $conn = manage_connection(); $file_props_arr = null; $select = "SELECT img_views FROM gbphp_db.t_site_images img WHERE {$attr_name} = '{$attr_value}';"; $result = mysqli_query($conn, $select); $row_arr = mysqli_fetch_assoc($result); $views = $row_arr['img_views'] + 1; $update = "UPDATE gbphp_db.t_site_images SET img_views = {$views} WHERE {$attr_name} = '{$attr_value}';"; $result = mysqli_query($conn, $update); return $views; }; function save_comment_in_db ($comment_attrs) { if (!is_array($comment_attrs) && !isset($comment_attrs)) return false; $conn= manage_connection(); $commentee = $comment_attrs['commentee']; $comment = $comment_attrs['comment']; $id_subject = $comment_attrs['id_subject']; $insert = "INSERT INTO t_site_comments (id_subject, commentee, comment) VALUES ({$id_subject}, '{$commentee}', '{$comment}');"; $result = mysqli_query($conn, $insert); $id_resource = mysqli_insert_id($conn); return $id_resource !== 0 ? true : false; }; function select_all_comments_from_db_by_id_subj ($id_subject) { if (!isset($id_subject)) return null; $conn = manage_connection(); $comments = null; $select = "SELECT commentee, comment, dt_ins, id_subject FROM gbphp_db.t_site_comments WHERE id_subject = {$id_subject};"; $result = mysqli_query($conn, $select); $comments = mysqli_fetch_all($result, MYSQLI_ASSOC); return $comments; }; function select_all_products_from_db () { $conn = manage_connection(); $products = null; $select = "SELECT p.id, p.product_name as name, p.product_short_desc as short_desc, p.product_full_desc as full_desc, p.product_price as price, res.url, res.thumbnail_url FROM gbphp_db.t_site_product p JOIN gbphp_db.t_product_images pi on pi.id_product = p.id JOIN gbphp_db.t_site_images img on img.id = pi.id_image JOIN gbphp_db.t_site_resources res on res.id = img.id_resource;"; $result = mysqli_query($conn, $select); $products = mysqli_fetch_all($result, MYSQLI_ASSOC); return $products; }; function select_single_product_by_attr ($attr_name, $attr_value) { $conn = manage_connection(); $product = null; $select = "SELECT p.id, p.product_name as name, p.product_short_desc as short_desc, p.product_full_desc as full_desc, p.product_price as price, res.url, res.thumbnail_url FROM gbphp_db.t_site_product p JOIN gbphp_db.t_product_images pi on pi.id_product = p.id JOIN gbphp_db.t_site_images img on img.id = pi.id_image JOIN gbphp_db.t_site_resources res on res.id = img.id_resource WHERE {$attr_name} = '{$attr_value}';"; $result = mysqli_query($conn, $select); $product = mysqli_fetch_assoc($result); return $product; };
true
b28d2b5d36ac648029f83fb90e76fc46733b49fc
PHP
mattbit/eloquent-sortable
/src/Spatie/EloquentSortable/Sortable.php
UTF-8
2,174
3.109375
3
[ "MIT" ]
permissive
<?php namespace Spatie\EloquentSortable; use Illuminate\Database\Eloquent\Builder; trait Sortable { /** * Set the order attribute on the model. * * @param int $value */ public function setOrder($value) { $key = $this->determineOrderColumnName(); $this->attributes[$key] = $value; } /** * Modify the order column value * * @param $model */ public function setHighestOrderNumber($model) { $orderColumnName = $this->determineOrderColumnName(); $model->$orderColumnName = $this->getHighestOrderNumber(); } /** * Determine the column name of the order column * * @return string */ protected function determineOrderColumnName() { if (! isset($this->sortable['order_column_name']) || $this->sortable['order_column_name'] == '') { $orderColumnName = 'order_column'; } else { $orderColumnName = $this->sortable['order_column_name']; } return $orderColumnName; } /** * Determine the order value for the new record * * @return int */ public function getHighestOrderNumber() { return ((int) self::max($this->determineOrderColumnName())) + 1; } /** * Let's be nice and provide an ordered scope * * @param Builder $query * @return mixed */ public function scopeOrdered(Builder $query) { return $query->orderBy($this->determineOrderColumnName()); } /** * This function reorders the records: the record with the first id in the array * will get order 1, the record with the second it will get order 2, ... * * @param array $ids * @throws SortableException */ public static function setNewOrder($ids) { if (! is_array($ids)) { throw new SortableException('You must pass an array to setNewOrder'); } $newOrder = 1; foreach($ids as $id) { $model = self::find($id); $model->setOrder($newOrder++); $model->save(); } } }
true
eb2b6722af132f9a416e68c8b952415f2ddeb060
PHP
StevenGabule/PHP-Code-Practice
/array/arrays.php
UTF-8
809
3.515625
4
[]
no_license
<?php // single array of variable // $months = array('January', 'Febrary', 'March', 'April', 'May'); // echo $months[1]; // $tuts_sites = array('Net', 'Design', 'Wordpress', 'Coding'); // print_r($stuts_sites); // Associative Array $tuts_sites = array( 'net' => 'http://facebook.com', 'design' => 'http://Design.com', 'wordpress' => 'http://wordpress.com', 'coding' => 'http://livetocode.com', ); ?> <!DOCTYPE html> <html> <head> <title>Arrays</title> </head> <body> <h1>Arrays</h1> <ul> <?php // foreach($tuts_sites as $sites => $url) { // echo "<li><a href=\"{$url}\">" . ucwords($sites) . "+</a></li>"; // } ?> <?php foreach($tuts_sites as $sites => $url) : ?> <li><a href="<?= $url; ?>"><?= ucwords($sites); ?></a></li> <?php endforeach; ?> </ul> </body> </html>
true
679c630bbff921f63b808113091db680426f4cc1
PHP
Ziptastic/ziptastic-php
/tests/IntegrationTest.php
UTF-8
1,569
2.671875
3
[ "MIT" ]
permissive
<?php use PHPUnit\Framework\TestCase; use Ziptastic\Client; /** * @group integration */ class IntegrationTest extends TestCase { private $apiKey; public function setUp() { $this->apiKey = getenv('ZIPTASTIC_API_KEY'); if (!$this->apiKey) { $this->markTestSkipped('No API Key.'); } } public function testForwardLookup() { $lookup = Client::create($this->apiKey); $l = $lookup->forward(48038); $this->assertResult($l); } public function testReverseLookup() { $lookup = Client::create($this->apiKey); $l = $lookup->reverse(42.331427, -83.0457538, 1000); $this->assertResult($l); } /** * @expectedException Ziptastic\Exception */ public function testException() { $lookup = Client::create($this->apiKey); $lookup->forward('hello'); } private function assertResult(array $l) { foreach ($l as $model) { $this->assertInternalType('string', $model['county']); $this->assertInternalType('string', $model['city']); $this->assertInternalType('string', $model['state']); $this->assertInternalType('string', $model['state_short']); $this->assertInternalType('string', $model['postal_code']); $this->assertInternalType('double', $model['latitude']); $this->assertInternalType('double', $model['longitude']); $this->assertInstanceOf(\DateTimeZone::class, $model['timezone']); } } }
true
ee3d0117f933431d213e8bef3d0c5c7b9f4a6d3b
PHP
molchanov-andrew/Localotto
/backend/widgets/image/Select2Banner.php
UTF-8
1,082
2.546875
3
[]
no_license
<?php namespace backend\widgets\image; use common\models\records\Banner; use Yii; class Select2Banner extends Select2Image { const SELECT2BANNER_CLASS_NAME = 'select2-banner-widget'; public function init() { $this->options['class'] = (isset($this->options['class']) && is_string($this->options['class'])) ? $this->options['class'].' '.self::SELECT2BANNER_CLASS_NAME : self::SELECT2BANNER_CLASS_NAME; parent::init(); } public function imagesToArray(){ $array = []; $arrayAdditionalOptionsLogoImage = []; foreach ($this->data as $banner) { /** @var Banner $banner */ $array[$banner->id] = $banner->link; $bannerImagePath = $banner->image === null ? null : $banner->image->filePath; $arrayAdditionalOptionsLogoImage[$banner->id] = ['data-image-src' => Yii::$app->params['frontendUrl'] . $bannerImagePath]; } $this->options['options'] = $arrayAdditionalOptionsLogoImage; $this->options['prompt'] = 'No image'; $this->data = $array; } }
true
0f5d6bd0625e47c39c4ff02f3825d2a03db12f77
PHP
webn716/car
/common/models/Baoyang.php
UTF-8
2,744
2.703125
3
[ "BSD-3-Clause" ]
permissive
<?php namespace common\models; use Yii; /** * This is the model class for table "baoyang". * * @property integer $id * @property integer $uid * @property integer $car_id * @property integer $type * @property integer $last_licheng * @property integer $zhouqi * @property string $last_date * @property string $content */ class Baoyang extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'baoyang'; } /** * @inheritdoc */ public function rules() { return [ [['id', 'uid', 'car_id', 'type', 'last_licheng', 'zhouqi', 'last_date', 'content'], 'required'], [['id', 'uid', 'car_id', 'type', 'last_licheng', 'zhouqi'], 'integer'], [['last_date'], 'safe'], [['content'], 'string'], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'uid' => 'Uid', 'car_id' => 'Car ID', 'type' => 'Type', 'last_licheng' => 'Last Licheng', 'zhouqi' => 'Zhouqi', 'last_date' => 'Last Date', 'content' => 'Content', ]; } //关联表 public function getType() { return $this->hasOne(BaoyangType::className(),['id'=>'type']); } /* score=-1 未设定,score>0 进度条百分比 保养分两种规则: 1.里程,5千公里,默认 2.周期,6个月,优先判断 */ public static function getBaoyangList($uid) { $list = self::find()->where(['uid' => $uid])->asArray()->all(); //将索引设置成保养类型 $baoyang_list = []; if(!empty($list)) foreach($list as $item) { $type = $item['type']; $baoyang_list[$type] = $item; } $type_list = BaoyangType::find()->orderby(['sort' => 'asc'])->asArray()->all(); if(!empty($type_list)) { foreach($type_list as &$type) { $id = $type['id']; //进度 if(!empty($baoyang_list) && !empty($baoyang_list[$id])) { $last_licheng = $baoyang_list[$id]['last_licheng']; $zhouqi = $baoyang_list[$id]['zhouqi']; $last_date = $baoyang_list[$id]['last_date']; if($zhouqi && $last_date) { } } else { $type['score'] = -1; } } } return $list; } }
true
c75e4c8e8ac091821548a62b098abd37f4ea22fb
PHP
PTSDLQA/Vulnerabilities
/PHP/4 ERROR PROCESSING/2 Detection of Error Condition Without Action/php/MOPAS_1_no_action_on_error.php
UTF-8
277
3.328125
3
[]
no_license
<?php /** * MOPAS Detection of Error Condition Without Action Example 1 */ function inverse($x) { if (!$x) { throw new Exception('Division by zero'); } return 1/$x; } try { echo inverse(5) . "\n"; echo inverse(0) . "\n"; } catch (Exception $e) { // do nothing } ?>
true
b0429ae0b1473abbe33483f5ac8c73151e8d5909
PHP
vladimir-doroshenko/PadCMS-backend
/application/include/AM/Component/Record/Auth/Login.php
UTF-8
2,634
2.53125
3
[]
no_license
<?php /** * @file * AM_Component_Record_Auth_Login class definition. * * LICENSE * * $DOXY_LICENSE * * @author $DOXY_AUTHOR * @version $DOXY_VERSION */ /** * Login record component * @ingroup AM_Component * @todo refactoring */ class AM_Component_Record_Auth_Login extends Volcano_Component_Record { /** * @param AM_Controller_Action $oActionController */ public function __construct(AM_Controller_Action $oActionController) { $aControls = array(); $aControls[] = new Volcano_Component_Control($oActionController, 'login', 'Login',array(array('require'))); $aControls[] = new Volcano_Component_Control_Password($oActionController, 'password', 'Password',array(array('require'))); parent::__construct($oActionController, 'component', $aControls); } /** * @return boolean */ public function isSubmitted() { return $this->isSubmitted; } /** * @return boolean */ public function operation() { return $this->isSubmitted ? $this->validate() : false; } /** * @return boolean */ public function validate() { $this->actionController->oAcl->getStorage()->clear(); if (!parent::validate()) { return false; } $sUserLogin = $this->controls['login']->getValue(); $sUserPassword = $this->controls['password']->getValue(); $oAuth = Zend_Auth::getInstance(); $oAuthAdapter = new Zend_Auth_Adapter_DbTable(); $oAuthAdapter->setTableName('user') ->setIdentityColumn('login') ->setCredentialColumn('password') ->setCredentialTreatment('MD5(?)'); $oAuthAdapter->setIdentity($sUserLogin) ->setCredential($sUserPassword); $oSelect = $oAuthAdapter->getDbSelect(); $oSelect->where('user.deleted = ?', 'no') ->joinLeft('client', 'client.id = user.client', array('client_title' => 'client.title')); $oResult = $oAuth->authenticate($oAuthAdapter); if ($oResult->isValid()) { $aResult = (array) $oAuthAdapter->getResultRowObject(); $aResult['role'] = ($aResult['is_admin'] == 0) ? 'user' : 'admin'; $oAuth->getStorage()->write($aResult); return true; } else { $this->errors[] = 'Invalid login or password'; return false; } } /** * @return void */ public function show() { $this->view->errors = $this->getErrors(); return parent::show(); } }
true
d5bce514778d047928abc2a30728109cb0e89b70
PHP
christian-heiko/hey
/src/Hey/ServerConfig.php
UTF-8
1,152
2.71875
3
[]
no_license
<?php /** * Created by PhpStorm. * User: christian-heiko * Date: 26.06.17 * Time: 19:02 */ namespace Hey; class ServerConfig { public $serversPath; public $configsPath; public $errorLogPath; public $devDomainName; public $excludedServers = []; public $publicFolders = ['web', 'public']; public $infoFiles = ['package.json', 'composer.json']; public $excludedDbs = ['information_schema', 'mysql', 'performance_schema']; /** * @param array $config * @return ServerConfig */ public static function initByArray(array $config){ $configInstance = new self(); foreach($config as $key => $value) { $configInstance->{$key} = $value; } return $configInstance; } public function excludeServer($name){ $this->excludedServers[] = $name; return $this; } public function addPublicFolderName($name){ $this->publicFolders[] = $name; } public function addInfoFileName($name) { $this->infoFiles[] = $name; } public function excludeDb($name) { $this->excludedDbs[] = $name; } }
true
e47393aaffb787bcf2b75eca13a487a39a7fc26d
PHP
matsubo/server-setup-script
/archive/mailadmin/classes/ListScheduleAction.php
UTF-8
2,496
2.65625
3
[]
no_license
<?php /* ** Mail address register * * 2004/8/8 matsu@ht.sfc.keio.ac.jp */ require_once("DB.php"); require_once("config.inc"); class ListScheduleAction{ function ListScheduleAction(){ } function execute(){ global $cfg; $data = array(); ## Connect to DB $dbh = DB::connect($cfg['dsn']); if (DB::isError($dbh)) { trigger_error("Cannot connect: ".DB::errorMessage($dbh), E_USER_ERROR); } ## Get data $query = "SELECT s_id, s_logid, s_status, s_start, s_schedule, s_end FROM `schedule` ORDER BY s_start DESC"; $result = $dbh->query($query); if(DB::isError($result)){ trigger_error($query." : ".DB::errorMessage($result), E_USER_ERROR); } ## Make data while ($row = $result->fetchRow( DB_FETCHMODE_ASSOC ) ) { ## Select not yet proceeding /* $query = "SELECT COUNT(record.r_id) as num FROM `record`,`group`,`log` WHERE log.l_logid=".$row['s_logid']." AND log.l_groupid=group.g_group_id AND group.g_group_id=record.r_group_id"; $result2 = $dbh->query($query); if(DB::isError($result2)){ trigger_error($query." : ".DB::errorMessage($result2), E_USER_ERROR); } $row2 = $result2->fetchRow(DB_FETCHMODE_ASSOC); ## Select proceeded $query = "SELECT COUNT(record.r_id) as num FROM `record`,`group`,`log` WHERE log.l_logid=".$row['s_logid']." AND log.l_groupid=group.g_group_id AND group.g_group_id=record.r_group_id"; $result3 = $dbh->query($query); if(DB::isError($result3)){ trigger_error($query." : ".DB::errorMessage($result3), E_USER_ERROR); } $row3 = $result3->fetchRow(DB_FETCHMODE_ASSOC); #print $query; */ $query = "SELECT group.g_title, group.g_group_id FROM `group`,`log` WHERE log.l_logid=".$row['s_logid']." AND log.l_groupid=group.g_group_id"; $result4 = $dbh->query($query); if(DB::isError($result4)){ trigger_error($query." : ".DB::errorMessage($result4), E_USER_ERROR); } $row4 = $result4->fetchRow(DB_FETCHMODE_ASSOC); array_push($data, array( 's_id' =>$row['s_id'], 's_logid' =>$row['s_logid'], 's_status' =>$row['s_status'], 's_start' =>$row['s_start'], 's_schedule' =>$row['s_schedule'], 's_end' =>$row['s_end'], #'sent' =>$row3['num'], #'yet_sent' =>$row2['num'], 'g_title' =>$row4['g_title'], 'g_group_id' =>$row4['g_group_id'], ) ); } return $data; } } ?>
true
0161f020d874e2f110c850b81d8d9468ed9a1f64
PHP
monocerus1990/test2_php
/CA5/model/orders_db.php
UTF-8
3,790
2.671875
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. */ function select_all_orders($pageNum) { global $db; $query = "SELECT * FROM orders ORDER BY order_date LIMIT ".($pageNum-1).",1"; $statement = $db->prepare($query); try { $statement->execute(); } catch (Exception $ex) { //******************************************** } $orders = $statement->fetchAll(); $statement->closeCursor(); return $orders; } function count_orderNum(){ global $db; $query = "SELECT COUNT(1) FROM orders"; $statement = $db->prepare($query); try { $statement->execute(); } catch (Exception $ex) { //******************************************** } $count = $statement->fetchAll(); $statement->closeCursor(); return $count; } function insert_order($order_id, $order_date, $principal_id, $order_deadline) { global $db; $query = "INSERT INTO orders (order_id, order_date, principal_id, order_deadline )" . "VALUES (:order_id, :order_date, :principal_id, :order_deadline)"; $statement = $db->prepare($query); $statement->bindValue(":order_id", $order_id); $statement->bindValue(":order_date", $order_date); $statement->bindValue(":principal_id", $principal_id); $statement->bindValue(":order_deadline", $order_deadline); try { $statement->execute(); } catch (Exception $ex) { //include '../view/main_select.php'; exit(); } $statement->closeCursor(); } function update_order_by_id($orderId, $order_date, $order_deadline) { global $db; $query = "UPDATE orders SET order_date='" . $order_date . "'," . " order_deadline='" . $order_deadline . "' WHERE order_id = '" . $orderId . "'"; $statement = $db->prepare($query); try { $statement->execute(); } catch (Exception $ex) { //include '../view/main_select.php'; exit(); } $statement->closeCursor(); } function select_order_by_id($order_id) { global $db; $query = "SELECT * FROM orders WHERE order_id = " . $order_id; $statement = $db->prepare($query); try { $statement->execute(); } catch (Exception $ex) { //******************************************** } $order = $statement->fetchAll(); $statement->closeCursor(); return $order; } function delete_by_id($orderId){ global $db; $query = "DELETE FROM orders WHERE order_id='".$orderId."'"; $statement = $db->prepare($query); try { $statement->execute(); } catch (Exception $ex) { //include '../view/main_select.php'; exit(); } $statement->closeCursor(); } function order_statement(){ global $db; $query = "SELECT " . "orders.order_id, " . "employees.first_name, " . "employees.last_name," . "items.item_name," . "items.item_price," . "order_items.quantity " . "FROM " . "orders," . "employees," . "items," . "order_items " . "WHERE " . "employees.user_id = orders.principal_id " . "AND " . "items.item_id = order_items.items_id " . "AND " . "order_items.order_id = orders.order_id"; $statement = $db->prepare($query); try { $statement->execute(); } catch (Exception $ex) { //******************************************** } $orderStatement = $statement->fetchAll(); $statement->closeCursor(); return $orderStatement; }
true
f01f323f107d7112d0f22b422d8b60c6746a62db
PHP
endikamanoso/iaw-2017-18
/practicas/practica10/json/loteria.php
UTF-8
1,375
2.578125
3
[]
no_license
<?php header("Content-type: application/json"); echo "{"; echo "\"premios\":["; echo "{"; echo "\"tipo\":\"primero\","; echo "\"cantidad\":400000,"; echo "\"numeros\":["; echo mt_rand(0,99999); echo "]"; echo "},"; echo "{"; echo "\"tipo\":\"segundo\","; echo "\"cantidad\":125000,"; echo "\"numeros\":["; echo mt_rand(0,99999); echo "]"; echo "},"; echo "{"; echo "\"tipo\":\"tercero\","; echo "\"cantidad\":50000,"; echo "\"numeros\":["; echo mt_rand(0,99999); echo "]"; echo "},"; echo "{"; echo "\"tipo\":\"cuarto\","; echo "\"cantidad\":20000,"; echo "\"numeros\":["; echo mt_rand(0,99999); echo ","; echo mt_rand(0,99999); echo "]"; echo "},"; echo "{"; echo "\"tipo\":\"cuarto\","; echo "\"cantidad\":6000,"; echo "\"numeros\":["; echo mt_rand(0,99999); for($i=1;$i<=7;$i++) { echo ","; echo mt_rand(0, 99999); } echo "]"; echo "}"; echo "]"; echo "}"; ?>
true
d7000a998f2352609ba37748a2970b86b4524f1d
PHP
VladmirCac/Projeto_3-Estagio-PDW
/admin/beckuoService/CategoriaService.php
UTF-8
3,907
2.65625
3
[]
no_license
<?php /* Aqui será o código referente aos serviços do Objeto autor*/ // Organizador dos passos acessados pelas telas através do GET. $passo = (isset($_GET['passo'])) ? $_GET['passo'] : 'listar'; switch ($passo) { case 'cadastrar': {cadastrarCategoria(); break;} case 'alterar': {alterarCategoria(); break;} case 'alterarStatus': {alterarStatus(); break;} default: case 'listar': {listarCategoria(); break;} } // função responsável por listar a categoria em formado de tabela. function listarCategoria(){ /* aqui devemos fazer a consulta para buscar todos as categorias e lista-las de acordo com o formato abaixo */ ?> <table class="table table-bordered table-striped"> <thead class="thead-dark"> <tr> <th>Editar</th> <th>Add. Descricao</th> <th>Codigo</th> <th>Nome</th> <th>Status</th> </tr> </thead> <tr class="lcategoria"> <td> <!-- os atributos nomeAutor e codigoAutor dos buttons devem ser alimentado com seus respectivos dados para auxilizar nos modais de exclusão e alteração. --> <button type="button" nomeCategoria=<?php echo '"...."'; ?> codigoCategoria=<?php echo '"...."'; ?> data-toggle="modal" data-target="#editarCategoriaModal"> <i class="fa fa-pencil-square-o text-primary" style="font-size: 150%;"></i> </button> </td> <td> <button type="button" nomeCategoria=<?php echo '"...."'; ?> codigoCategoria=<?php echo '"...."'; ?>data-toggle="modal" data-target="#addDescricaoModal"> <i class="fa fa-plus text-success" style="font-size: 150%;"></i> </button> </td> <td> <?php echo "...."; ?> </td> <td> <?php echo "...."; ?> </td> <td> <!-- Aqui deverar ser exibido a cor do botão de acordo com o status, lembrando de inclir o codigo da descrição no attr codigoDescricao --> <?php if (true) { //se o status estuver ativo statusCategoriaDescricao == 1 echo '<button type="button" codigoCategoria="...." statusDescricao="..."><i class="fa fa-power-off text-success" style="font-size: 150%;"></i></button>'; }else{ //se o status estuver ativo statusCategoriaDescricao == 0 echo '<button type="button" codigoCategoria="...." statusDescricao="..."><i class="fa fa-power-off text-danger" style="font-size: 150%;"></i></button>'; } ?> </td> </tr> <table> <?php } function cadastrarCategoria(){ //ADICIONAR UMA CATEGORIA $nomeCadastroParaIncluir = $_POST['cadastroCategoria']; if (true){ echo "<div class='alert alert-success espacoForm'><strong> Cadastro da categoria ".$nomeCadastroParaIncluir." realizada com sucesso!</strong></div>"; } else { echo "<div class='alert alert-danger espacoForm'><strong> Erro ao tentar cadastrar ".$nomeCadastroParaIncluir."</strong> Ocorreu um erro.</div>"; } } function alterarCategoria() { // DEVEMOS ALTERAR A CATEGORIA $codigoParaAlterar = $_POST['textCodigoCategoria']; $nomeEdicaoCategoria = $_POST['textCategoria']; if (true){ echo '<div class="alert alert-success"><strong> A categoria "'.$nomeEdicaoCategoria.'" editado com sucesso!'.$codigoParaAlterar.'</strong> </div>'; }else{ echo "<div class='alert alert-danger espacoForm'><strong>Edição não realizada!</strong> Ocorreu um erro.</div>"; } } function alterarStatus() { /* Aqui deveremos alternar o status da Categoria, se tiver 1 ficar 0 e se tiver 0 ficar 1 */ $codigoParaAlterar = $_GET['codigo']; $statusAutal = $_GET['status']; if (true){ echo '<div class="alert alert-success"><strong> Status do codigo "'.$codigoParaAlterar.'" alterado com sucesso!</strong> </div>'; }else{ echo "<div class='alert alert-danger espacoForm'><strong>Edição não realizada!</strong> Ocorreu um erro.</div>"; } } ?>
true
d928287d96d7a1454ae3d673c19b808014ce530e
PHP
madaputraa/php-crud
/proses_edit.php
UTF-8
850
2.5625
3
[]
no_license
<?php // memanggil file koneksi.php untuk melakukan koneksi database include 'koneksi.php'; // membuat variabel untuk menampung data dari form $id = $_POST['id']; $nama_produk = $_POST['nama_produk']; $harga_beli = $_POST['harga_beli']; $harga_jual = $_POST['harga_jual']; $query = "UPDATE produk SET nama_produk = '$nama_produk', harga_beli = '$harga_beli', harga_jual = '$harga_jual'"; $query .= "WHERE id = '$id'"; $result = mysqli_query($koneksi, $query); // periska query apakah ada error if(!$result){ die ("Query gagal dijalankan: ".mysqli_errno($koneksi). " - ".mysqli_error($koneksi)); } else { //tampil alert dan akan redirect ke halaman index.php //silahkan ganti index.php sesuai halaman yang akan dituju echo "<script>alert('Data berhasil diubah.');window.location='halamanadmin.php';</script>"; } ?>
true
91e1fe0182ac45c18fe83424c047e214bb28d9c2
PHP
MarioBlazek/extending-symfony
/src/MB/Bundle/GithubAuthBundle/Security/Github/AuthenticationProvider.php
UTF-8
1,413
2.78125
3
[]
no_license
<?php namespace MB\Bundle\GithubAuthBundle\Security\Github; use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; class AuthenticationProvider implements AuthenticationProviderInterface { private $userProvider; public function __construct($userProvider) { $this->userProvider = $userProvider; } /** * Attempts to authenticate a TokenInterface object. * * @param TokenInterface $token The TokenInterface instance to authenticate * * @return TokenInterface An authenticated TokenInterface instance, never null * * @throws AuthenticationException if the authentication fails */ public function authenticate(TokenInterface $token) { $email = $token->getCredentials(); $user = $this->userProvider->loadOrCreate($email); // log the user in $newToken = new GithubUserToken($user->getRoles); $newToken->setUser($user); $newToken->setAuthenticated(true); return $newToken; } /** * Checks whether this provider supports the given token. * * @param TokenInterface $token A TokenInterface instance * * @return bool true if the implementation supports the Token, false otherwise */ public function supports(TokenInterface $token) { return $token instanceof GithubUserToken; } }
true
cd4d1512e6588dc4e457c289f3552e0d419f9968
PHP
markwell/cpvdvfu-1
/users/volunteers/loginVolunteer.php
UTF-8
2,271
2.625
3
[]
no_license
<?php include_once $_SERVER['DOCUMENT_ROOT']."/cpvdvfu/system/bd.php"; function checkAndAuthUser($login, $password) { function generateCode($length = 6) { $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIFJKLMNOPRQSTUVWXYZ0123456789"; $code = ""; $clen = strlen($chars) - 1; while (strlen($code) < $length) { $code .= $chars[mt_rand(0, $clen)]; } return $code; } $error = ""; # Вытаскиваем из БД запись, у которой логин равняеться введенному $password = md5($password);//шифруем пароль $query = mysql_query("SELECT VolunteerID, Password FROM Volunteers WHERE Email='$login'"); $data = mysql_fetch_array($query); $ID = $data['VolunteerID']; # Сравниваем пароли if ($data['Password'] === $password) { # Генерируем случайное число и шифруем его $hash = md5(generateCode(10)); # Записываем в БД новый хеш авторизации $query = "UPDATE Volunteers SET Hash='$hash' WHERE VolunteerID='$ID'"; $result = mysql_query($query); # Ставим куки setcookie("id", $ID, time() + 60 * 60 * 24 * 30, "/", "localhost"); //аргумент "localhost" говорит нам что кукисы будут сохранятся в домене localhost setcookie("hash", $hash, time() + 60 * 60 * 24 * 30, "/", "localhost"); setcookie("username", $login, time() + 60 * 60 * 24 * 30, "/", "localhost"); return null; } else { $error = "Неправильные имя пользователя или пароль. Пожалуйста, попробуйте еще раз."; return $error; } } function authUser() { if (isset($_POST['submitlogin'])) { $error = checkAndAuthUser(trim($_POST['email']), $_POST['password']); if (is_null($error)) { header('Location:/cpvdvfu/users/volunteers/checkUserVolunteer.php'); //ссылка на страницу проверки пользователя } else { echo $error; } } } authUser(); ?>
true
5471a3f1ed6849050f6e785f74b34546c503212a
PHP
Leexy/projetPHP
/lib/Entity/Hit.php
UTF-8
1,124
3.03125
3
[]
no_license
<?php namespace Entity; //represente un tir d'un des deux joueurs dans une partie class Hit extends Base { public function getX() { return $this->data['x']; } public function getY() { return $this->data['y']; } public function getUserId() { return $this->data['user_id']; } public function getGameId() { return $this->data['game_id']; } public function getPosition() { return ['x' => $this->getX(), 'y' => $this->getY()]; } public function setUserId($userId) { $this->data['user_id'] = $userId; } public function setGameId($gameId) { $this->data['game_id'] = $gameId; } public function isSuccess() { return !empty($this->data['success']); } public function setSuccess($success) { $this->data['success'] = (bool) $success; } public function hasDestroyed() { return !empty($this->data['destroyed']); } public function setDestroyed($destroyed) { $this->data['destroyed'] = (bool) $destroyed; } }
true
c674d6d0793d0f93b1263cd36a807abd0e04e49d
PHP
snyff/TVsite
/show.php
UTF-8
2,216
2.515625
3
[]
no_license
<?php session_start(); require_once("config.php"); $showID = $_SERVER['QUERY_STRING']; $result = mysql_fetch_array(mysql_query("select * from item where itemID = '$showID'")); $result2 = mysql_query("select * from episode where itemID = '$showID'"); ?> <html> <head> <title>Mbete TV</title> <link href="episodes.css" rel="stylesheet" type="text/css" /> </head> <body> <div class="header"><img src="logo.png" /><a href="/mbetetv" class="schedule">Schedule</a><a href="/mbetetv/shows" class="schedule">Shows</a><a href="/mbetetv/clips.php" class="schedule">Clips</a> <?php if($_SESSION['username'] =="") { ?> <a href="/mbetetv/login.php" class="schedule">Login</a></div> <?php } else { ?> <a href="/mbetetv/logout.php" class="schedule">Logout</a></div> <?php } ?> </div> <div class="left"> <div id="coming_up_header"><?php echo $result['name'];?></div> <div id="episode"> <?php ?> <table border="0"> <tr> <td /><img src="images/<?php echo $result['thumbnail'];?>"> <td /><?php echo $result['name']."<br />";?> <?php echo $result['info'];?><br /><br /><br /><br /> <?php if($_SESSION['username'] == "") { ?> <i><a href="/mbetetv/login.php" >Login to add episodes</a></i> <?php } else { ?> <a href="/mbetetv/addepisode.php?<?php echo $showID;?>">Add episode</a> <?php } ?> </tr> </table> <div id="horizontal_line"></div> Episodes<br /><br /> <?php if(mysql_num_rows($result2) ==0) { echo "No episodes coming up, try later!!"; } while($query = mysql_fetch_array($result2)) { $episodeID = $query['episodeID']; $slot_data = mysql_fetch_array(mysql_query("select * from slot where episodeID = '$episodeID'")); echo $slot_data['date']." - <span class='time'>".$slot_data['start']."</span> to <span class='time'>".$slot_data['end']."</span><a href='/mbetetv/clips.php?$episodeID' title='click here to view video clip' ><u> ".$query['info']."</u></a><br />"; echo "<div id='horizontal_line'></div>"; } ?> <div> </div> </body> </html>
true
0254ba53408f7ddb92f8aadca6f8923a83240698
PHP
ZikulaGroupware/Main
/src/lib/viewplugins/modifier.yesno.php
UTF-8
1,691
2.734375
3
[]
no_license
<?php /** * Copyright Zikula Foundation 2009 - Zikula Application Framework * * This work is contributed to the Zikula Foundation under one or more * Contributor Agreements and licensed to You under the following license: * * @license GNU/LGPLv3 (or at your option, any later version). * @package Zikula_View * @subpackage Template_Plugins * * Please see the NOTICE file distributed with this source code for further * information regarding copyright and licensing. */ /** * Zikula_View modifier to turn a boolean value into a suitable language string * * Example * * {$myvar|yesno|safetext} returns Yes if $myvar = 1 and No if $myvar = 0 * * @param string $string The contents to transform. * @param boolean $images Display the yes/no response as tick/cross. * * @return string Rhe modified output. */ function smarty_modifier_yesno($string, $images = false) { if ($string != '0' && $string != '1') return $string; if ($images) { $view = Zikula_View::getInstance(); require_once $view->_get_plugin_filepath('function','img'); $params = array('modname' => 'core', 'set' => 'icons/extrasmall'); } if ((bool)$string) { if ($images) { $params['src'] = 'button_ok.png'; $params['alt'] = $params['title'] = __('Yes'); return smarty_function_img($params, $view); } else { return __('Yes'); } } else { if ($images) { $params['src'] = 'button_cancel.png'; $params['alt'] = $params['title'] = __('No'); return smarty_function_img($params, $view); } else { return __('No'); } } }
true
4d91c56fefbefd4276db0b990d142a01fc7be7f8
PHP
LithiumHosting/larageo-plugin
/src/LithiumDev/LaraGeo/LaraGeo.php
UTF-8
5,769
3.015625
3
[ "MIT" ]
permissive
<?php namespace LithiumDev\LaraGeo; use Cache; use GuzzleHttp\Client; use GuzzleHttp\Exception\ConnectException; class LaraGeo { /** * Is the current IP stored in the cache? * * @var bool */ public $isCached = false; /** * The URL of the geoPlugin API (json). * * @var string */ protected $url = 'http://www.geoplugin.net/json.gp'; private $ip; /** * Return all the information in an array. * * @param null $ip * * @return array Info from the IP parameter * @throws \LithiumDev\LaraGeo\LaraGeoException */ public function getInfo($ip = null) { if (is_null($ip)) { $ip = request()->getClientIp(); } $this->ip = $ip; $hex = $this->ipToHex($this->ip); if ($hex === false) { throw new LaraGeoException('The IP ' . $this->ip . ' appears to be invalid'); } // Check if the IP is in the cache if (Cache::has($hex)) { $this->isCached = true; } // Cache::forget($hex); // Use the IP info stored in cache or store it $ipInfo = Cache::remember($hex, 10080, function () { return $this->fetchInfo(); }); $ipInfo->geoplugin_cached = $this->isCached; return $ipInfo; } /** * Return a hex string of the current IP. Used as the key for cache storage. * * @param $ipAddress * * @return bool|string */ private function ipToHex($ipAddress) { $hex = ''; if (strpos($ipAddress, ',') !== false) { $splitIp = explode(',', $ipAddress); $ipAddress = trim($splitIp[0]); } $isIpV6 = false; $isIpV4 = false; if (filter_var($ipAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false) { $isIpV6 = true; } elseif (filter_var($ipAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false) { $isIpV4 = true; } if (! $isIpV4 && ! $isIpV6) { return false; } // IPv4 format if ($isIpV4) { $parts = explode('.', $ipAddress); for ($i = 0; $i < 4; $i++) { $parts[ $i ] = str_pad(dechex($parts[ $i ]), 2, '0', STR_PAD_LEFT); } $ipAddress = '::' . $parts[0] . $parts[1] . ':' . $parts[2] . $parts[3]; $hex = implode('', $parts); } // IPv6 format else { $parts = explode(':', $ipAddress); // If this is mixed IPv6/IPv4, convert end to IPv6 value if (filter_var($parts[ count($parts) - 1 ], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false) { $partsV4 = explode('.', $parts[ count($parts) - 1 ]); for ($i = 0; $i < 4; $i++) { $partsV4[ $i ] = str_pad(dechex($partsV4[ $i ]), 2, '0', STR_PAD_LEFT); } $parts[ count($parts) - 1 ] = $partsV4[0] . $partsV4[1]; $parts[] = $partsV4[2] . $partsV4[3]; } $numMissing = 8 - count($parts); $expandedParts = []; $expansionDone = false; foreach ($parts as $part) { if (! $expansionDone && $part == '') { for ($i = 0; $i <= $numMissing; $i++) { $expandedParts[] = '0000'; } $expansionDone = true; } else { $expandedParts[] = $part; } } foreach ($expandedParts as &$part) { $part = str_pad($part, 4, '0', STR_PAD_LEFT); } $ipAddress = implode(':', $expandedParts); $hex = implode('', $expandedParts); } // Validate the final IP if (! filter_var($ipAddress, FILTER_VALIDATE_IP)) { return false; } return strtolower(str_pad($hex, 32, '0', STR_PAD_LEFT)); } // function ip2bin($ip) // { // $ipbin = ''; // if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false) // return base_convert(ip2long($ip),10,2); // if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false) // return false; // if(($ip_n = inet_pton($ip)) === false) return false; // $bits = 15; // 16 x 8 bit = 128bit (ipv6) // while ($bits >= 0) // { // $bin = sprintf("%08b",(ord($ip_n[$bits]))); // $ipbin = $bin.$ipbin; // $bits--; // } // return $ipbin; // } /** * Fetch the info from IP using CURL or file_get_contents. * @throws \LithiumDev\LaraGeo\LaraGeoException * @return object */ private function fetchInfo() { $response = null; $params = []; $url = $this->url; if (! empty($this->ip)) { $params['ip'] = $this->ip; } try { $client = new Client; $response = $client->get($url, ['query' => $params]); $data = json_decode($response->getBody()); } catch (ConnectException $e) { throw new LaraGeoException('Curl Connection Issue, try again later.'); } if ($data->geoplugin_status === 404 || empty($data)) { throw new LaraGeoException('Invalid Response, check the IP and try again.'); } return $data; } }
true
baee8df9a3dd329e8c52db710befb796e3ec4c98
PHP
YohannMaiVan/Panier
/controlers/login.php
UTF-8
776
2.796875
3
[]
no_license
<?php session_start(); require '../model/model.php'; if (isset($_POST["login"])) { //appeler la fonction qui verifie si mail et mdp sont bien remplis $userConnected = login($_POST["mail"], $_POST["password"]); // la fonction renvoie un chiffre considéré comme true si ils sont bien remplis et on passe dans le if if ($userConnected) { // il faut co l'utilisateur: $_SESSION["user_id"] = $userConnected; header('location: ../index.php'); } else { // il faut s'assurer qu'il n'y a pas de session: détruire troutes variables de sessions et fermer la session unset($_SESSION); session_destroy(); // et on redirige vers la page d'accueil pour afficher à nouveau le form de conexxion header('location: ../index.php'); } } ?>
true
9ef0c57ab7933f899fce3534f81cb94a34423542
PHP
habb0/mobbo
/application/classes/filesyste/ZipFile.class.php
UTF-8
4,132
3.3125
3
[ "Apache-2.0" ]
permissive
<?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 ZipFile * * @author RADIO */ class ZipFile { /* creates a compressed zip file */ public static function create_zip($files = array(), $destination = '', $overwrite = false) { //if the zip file already exists and overwrite is false, return false if (file_exists($destination) && !$overwrite) { return false; } //vars $valid_files = array(); //if files were passed in... if (is_array($files)) { //cycle through each file foreach ($files as $file) { //make sure the file exists if (file_exists($file)) { $valid_files[] = $file; } } } //if we have good files... if (count($valid_files)) { //create the archive $zip = new ZipArchive(); if ($zip->open($destination, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE ) !== true) { return false; } //add the files foreach ($valid_files as $file) { $zip->addFile($file, $file); } //debug //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status; //close the zip -- done! $zip->close(); //check to make sure the file exists return file_exists($destination); } else { return false; } } public static function processUnZip($sourceFileName, $destinationPath) { if (stristr(PHP_OS, 'WIN')) { if (self::unZipOnWindows($sourceFileName, $destinationPath)) return 1; } else { if (self::unZipOnLinux($sourceFileName, $destinationPath)) return 1; } } /** * Function: unZipOnWindows($sourceFileName,$destinationPath) * Unzipping a zip file on windows * @param string $sourceFileName, source zip file name with absolute path * @param string $destinationPath, destination fath for unzipped file (absolute path) */ private static function unZipOnWindows($sourceFileName, $destinationPath) { $directoryPos = strrpos($sourceFileName, '/'); $directory = substr($sourceFileName, 0, $directoryPos + 1); $dir = opendir($directory); $info = pathinfo($sourceFileName); if (strtolower($info['extension']) == 'zip') { $zip = new ZipArchive; $response = $zip->open($sourceFileName); if ($response === TRUE) { $zip->extractTo($destinationPath); $zip->close(); return 1; } } closedir($dir); } /** * Function: unZipOnLinux($sourceFileName,$destinationPath) * Unzipping a zip file on linux * @param string $sourceFileName, source zip file name with absolute path * @param string $destinationPath, destination fath for unzipped file (absolute path) */ private static function unZipOnLinux($sourceFileName, $destinationPath) { $directoryPos = strrpos($sourceFileName, '/'); $directory = substr($sourceFileName, 0, $directoryPos + 1); $dir = opendir($directory); $info = pathinfo($sourceFileName); if (strtolower($info['extension']) == 'zip') { system('unzip -q ' . $sourceFileName . ' -d ' . $destinationPath); return 1; } closedir($dir); } }
true
49a33373e6734f18b0112ea4dd4cdcdead8fd0a0
PHP
taniko/saori
/src/Console/InitCommand.php
UTF-8
1,897
2.609375
3
[ "MIT" ]
permissive
<?php namespace Taniko\Saori\Console; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Taniko\Saori\Util; class InitCommand extends Command { protected function configure() { $this ->setName('init') ->setDescription('Initialize') ; } protected function execute(InputInterface $input, OutputInterface $output) { try { if (is_dir($this->paths['local'])) { throw new \Exception("directory({$this->paths['local']}) already exists"); } elseif (is_dir($this->paths['public'])) { throw new \Exception("directory({$this->paths['public']}) already exists"); } elseif (is_dir($this->paths['contents'])) { throw new \Exception("directory({$this->paths['contents']}) already exists"); } Util::putYamlContents( "{$this->root}/config/env.yml", [ 'title' => 'Sample Blog', 'author'=> 'John Doe', 'local' => 'http://localhost:8000', 'public'=> 'http://localhost:8000', 'theme' => 'saori', 'lang' => 'en', 'link' => [ 'GitHub' => 'https://github.com', 'Twitter' => 'https://twitter.com' ], 'feed' => [ 'type' => 'atom', 'number' => 50 ] ] ); $output->writeln('<info>done</info>'); $result = 0; } catch (\Exception $e) { $output->writeln("<error>{$e->getTraceAsString()}</error>"); $result = 1; } return $result; } }
true
0321467af80d915d34c3571c520062e426b0fe5e
PHP
mbutelle/skeleton-4
/src/FileSystem/Domain/Model/FileRepositoryInterface.php
UTF-8
232
2.6875
3
[]
no_license
<?php namespace App\FileSystem\Domain\Model; interface FileRepositoryInterface { public function save(File $file): void; public function get(string $reference): ?File; public function delete(string $reference): void; }
true
7f1af76f62d8a8a85c1d6bddcf398e6cc6293abf
PHP
ViktorKITP/schedule
/server/parserXLS_.php
UTF-8
3,424
2.890625
3
[]
no_license
<?php /** * Created by IntelliJ IDEA. * User: Viktor * Date: 13.02.2016 * Time: 1:17 */ //если не загрузился- ну дапустим ошибка загрузки файла- надо сделать чтобы парсил старое или выдавал старое include_once 'Classes/PHPExcel.php'; require_once('listGroups.php'); require_once('workDB.php'); require_once('filter.php'); require_once('finder.php'); class parser { /** @var workDB */ public $db = null; public $filterGroup = null; public $filterDay =null; public $arrFindGroup = null; public $arrFindTime = null; public $arrFindDay = null; public $sheet = null; public $arrMerge = null; public $filterObj = null; public $temp = null; /** * parser constructor. * @param $db */ function __construct($db,$f) { $this->db = $db; $this->filterObj=new filter(); $this->filterGroup = $this->filterObj->getFilterGroup(); $this->filterDay = $this->filterObj->getFilterDay(); //test $t=new finder($f); // $t->testEcho($t->g); // $objPHPExcel = PHPExcel_IOFactory::load($f); /* function getSheets($fileName) { try { $fileType = PHPExcel_IOFactory::identify($fileName); $objReader = PHPExcel_IOFactory::createReader($fileType); $objPHPExcel = $objReader->load($fileName); $sheets = []; foreach ($objPHPExcel->getAllSheets() as $sheet) { $sheets[$sheet->getTitle()] = $sheet->toArray(); } return $sheets; } catch (Exception $e) { die($e->getMessage()); } }*/ //$this->temp=$objPHPExcel->getAllSheets(); // echo '<pre>'; // echo $this->temp; // echo '</pre>'; //$this->filter = $this->createFilter(); // echo 'constr'; } /** * @param $file_name * @throws PHPExcel_Exception */ function parserXLS() { } /** * @param $rowIterator */ // public $i=0; /* function lastRow(PHPExcel_Worksheet $sheet, $indexCellDAY) { //получаем индекс последней строки в ЛИСТЕ $higestRow = $sheet->getHighestRow(); for ($i = $indexCellDAY; $i <= $higestRow; $i++) { $tempRow = $sheet->getCellByColumnAndRow(0, $i)->getFormattedValue(); if (mb_strtoupper(trim($tempRow)) == "СУББОТА") return ++$i; } } function saveColumn($indexColumn, $indexRow, PHPExcel_Worksheet $sheet, $indexCellDAY) { $tempLastRow = $this->lastRow($sheet, $indexCellDAY); //заносим в новую PHPExcel_Worksheet расписанице do { $value = $sheet->getCell($indexColumn . $indexRow)->getFormattedValue(); $day = $sheet->getCellByColumnAndRow(0, $indexRow)->getFormattedValue();; $time = $sheet->getCellByColumnAndRow(1, $indexRow)->getFormattedValue();; echo '$value=' . $value; echo "day=$day"; echo 'time=' . $time; print_r($this->db, true); $this->db->saveSchedule($day, $time, $value); $indexRow++; } while ($indexRow !== $tempLastRow); }*/ }
true
30074c7528dca4d90b536666b77a144c56c3e23e
PHP
Yonam/SiteInforAfrique
/connexion.php
UTF-8
1,551
2.59375
3
[]
no_license
<!DOCTYPE html> <!--[if lt IE 9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <?php $bdd = new PDO('mysql:host=127.0.0.1;dbname=espace_membre', 'root', ''); if(isset($_POST['formconexion'])) { $mailconnect = htmlspecialchars($_POST['mailconnect']); $mdpconnect = sha1($_POST['mdpconnect']); if(!empty($mailconnect AND !empty($mdpconnect))) { $requser = $bdd->prepare("SELECT * FROM membres WHERE mail= ? AND motdepasse = ?"); $requser -> execute-array($mailconnect); if($userexist) { # code... } else { $erreur = "Mauvais mail ou mauvais mot de passe"; } } else { $erreur = "Tous les champs doivent être completés"; } } ?> <html> <head> <meta charset="UTF-8"> <title>...</title> </head> <body> <div align="center"> <h2>Connexion</h2> <br/><br/> <form method="POST" action=""> <input type="text" name="mailconnect" placeholder="Mail" /> <input type="password" name="mdpconnect" placeholder="Mot de passe" /> <input type="submit" name="formconexion" value="Se connecter !" /> </form> <?php //fonction d'erreur if (isset($erreur)) { echo '<font color=red>' .$erreur. "</font>"; } ?> </div> </body> </html>
true
cc3806e20d17816eea2c2a75e14f99f42aa43b63
PHP
web-complete/core
/src/factory/AbstractFactory.php
UTF-8
780
3.09375
3
[ "MIT" ]
permissive
<?php namespace WebComplete\core\factory; use WebComplete\core\utils\container\ContainerInterface; /** * Class AbstractFactory */ abstract class AbstractFactory { /** * @var ContainerInterface */ private $container; /** * @param ContainerInterface $container */ public function __construct(ContainerInterface $container) { $this->container = $container; } /** * Get an instance * * @param $name * @return mixed */ protected function get($name) { return $this->container->get($name); } /** * Create an instance * * @param $name * @return mixed */ protected function make($name) { return $this->container->make($name); } }
true
555fefd5e06db2fb61fc88d9ac9959733a864fd9
PHP
kristinaNik/documents-calculation-challenge
/skeleton/src/Command/CsvImportCommand.php
UTF-8
3,032
2.921875
3
[]
no_license
<?php namespace App\Command; use App\Entity\Currency; use App\Handlers\CurrencyHandler; use App\Handlers\FileHandler; use App\Services\CalculateService; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; class CsvImportCommand extends Command { /** * @var string */ protected static $defaultName = 'csv:import'; /** * @var CalculateService */ private $calculateService; /** * @var FileHandler */ private $fileHandler; /** * @var CurrencyHandler */ private $currencyHandler; /** * CsvImportCommand constructor. * * @param CalculateService $calculateService * @param FileHandler $fileHandler * @param CurrencyHandler $currencyHandler */ public function __construct(CalculateService $calculateService, FileHandler $fileHandler, CurrencyHandler $currencyHandler) { parent::__construct(); $this->calculateService = $calculateService; $this->fileHandler = $fileHandler; $this->currencyHandler = $currencyHandler; } /** * Configure the command arguments */ protected function configure() { $this ->setDescription('Imports a mock csv data and calculates the the sum of all the documents') ->addArgument('file_path',InputArgument::REQUIRED, 'path to csv file') //{src/Data/data.csv} ->addArgument('currencies', InputArgument::REQUIRED, 'currencies') ->addArgument('output_currency',InputArgument::REQUIRED, 'output currency') ->addOption('vat', null,InputOption::VALUE_OPTIONAL, 'Option description') ; } /** * @param InputInterface $input * @param OutputInterface $output * * @return int * @throws \Exception */ protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $fileData = $this->fileHandler->getCsvData($input->getArgument('file_path')); $currencyData = $this->currencyHandler->getCurrencies($input->getArgument('currencies')); $this->calculateService->setData($fileData); $this->calculateService->setCurrencies($currencyData); $calculations = $this->calculateService->getTotals($input->getOption('vat'), $input->getArgument('output_currency')); $io->success($this->displayCalculatedResult($calculations)); return 0; } /** * @param $calculations * @return string */ private function displayCalculatedResult($calculations) { $output = ''; foreach ($calculations as $customer => $total) { $output = sprintf('%s - %s', $customer, $total); } return $output; } }
true
061fef5be5440484ac3964fa5c2ca9720c7f7591
PHP
cristibaluta/sdk.ralcr
/api.ralcr/filesystem/deleteDirectory.php
UTF-8
905
2.59375
3
[ "MIT" ]
permissive
<?php session_start(); if ($_SESSION['hash'] != $_POST['hash']) die("error::Session expired!"); // Emulate register_globals on if (!ini_get('register_globals')) { $superglobals = array($_SERVER, $_ENV, $_FILES, $_COOKIE, $_POST, $_GET); if (isset($_SESSION)) { array_unshift($superglobals, $_SESSION); } foreach ($superglobals as $superglobal) { extract($superglobal, EXTR_SKIP); } ini_set('register_globals', true); } $dir = "../../".$_POST["path"]; $dir = (substr($dir, -1) == "/") ? substr($dir, 0, -1) : $dir; function unlinkRecursive($dir) { if (!$dh = @opendir($dir)) return "error::This is not a directory!"; while (false !== ($obj = readdir($dh))) { if($obj == '.' || $obj == '..') continue; if (!@unlink($dir.'/'.$obj)) unlinkRecursive($dir.'/'.$obj); } closedir($dh); @rmdir($dir); return true; } echo unlinkRecursive( $dir );
true