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
eed0342e5fc08d6fc9c10a5213d87d93964508f0
PHP
JesusMGF/laravelVueLibrary
/app/Http/Controllers/Api/CategorieController.php
UTF-8
3,062
2.515625
3
[]
no_license
<?php namespace App\Http\Controllers\Api; use App\Categorie; use App\Item; use Illuminate\Http\Request; use App; use App\Http\Controllers\Controller; use Illuminate\Http\Response; class CategorieController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { try { $categories = Categorie::all(); if ($categories){ return response()->json($categories, Response::HTTP_OK); } return response()->json(['message' => 'No categories'], Response::HTTP_NO_CONTENT); }catch (\Exception $e){ return response()->json(['message' => $e->getMessage()], Response::HTTP_BAD_REQUEST); } } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function store(Request $request) { try { $newCategorie = new Categorie; $newCategorie->name = $request->name; $newCategorie->save(); if ($newCategorie){ return response()->json($newCategorie, Response::HTTP_OK); } return response()->json(['message' => 'No category'], Response::HTTP_NO_CONTENT); }catch (\Exception $e){ return response()->json(['message' => $e->getMessage()], Response::HTTP_BAD_REQUEST); } } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Categorie $categorie * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { try { $categorie = Categorie::find($id); $categorie->name = $request->name; $categorie->save(); if ($categorie){ return response()->json($categorie, Response::HTTP_OK); } return response()->json(['message' => 'No category updated'], Response::HTTP_NO_CONTENT); }catch (\Exception $e){ return response()->json(['message' => $e->getMessage()], Response::HTTP_BAD_REQUEST); } } /** * Remove the specified resource from storage. * * @param \App\Categorie $categorie * @return \Illuminate\Http\Response */ public function destroy(Categorie $categorie) { try { $categorie = Categorie::find($id); if ($categorie){ $categorie->delete(); return response()->json(['message' => 'Categorie deleted'], Response::HTTP_OK); } return response()->json(['message' => 'No category'], Response::HTTP_NO_CONTENT); }catch (\Exception $e){ return response()->json(['message' => $e->getMessage()], Response::HTTP_BAD_REQUEST); } $categorie = Categorie::find($id); $categorie->delete(); } }
true
e08149f8aaef000d8ffe87afdd9b4f2c80fa790a
PHP
smartthingsro/emagmarketplace
/Api/VatRepositoryInterface.php
UTF-8
427
2.65625
3
[]
no_license
<?php namespace Zitec\EmagMarketplace\Api; use Zitec\EmagMarketplace\Model\Vat; /** * Interface VatRepositoryInterface * @package Zitec\EmagMarketplace\Api */ interface VatRepositoryInterface { /** * @param array $data * * @return bool */ public function updateData(array $data): bool; /** * @param int $id * @return Vat */ public function getByEmagId(int $id): Vat; }
true
14392c240935e97793cec842a5c9f5ebedf54012
PHP
NiranjanBadgujar/phpmysqlworkshopiitbniranjan
/Day_6-7/Student_login.php
UTF-8
1,550
2.828125
3
[]
no_license
<?php include('connect1.php'); session_start(); if (isset($_SESSION['email']) && $_SESSION['type'] == "student") { header("Location: Student_result.php"); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action="Student_login.php" method="POST"> <input type="text" name="email" placeholder="email"> <br><br> <input type="password" name="password" placeholder="password"> <br><br> <button type="submit">Log In</button> </form> <?php if(isset($_POST['email']) && isset($_POST['password'])) { $email = $_POST['email']; $password = $_POST['password']; $sql = "SELECT * FROM register WHERE email = '$email';"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) == 0) { echo "Student does not exist<br> <a href='register.php'>click here</a> to register"; die(); } while ($row = mysqli_fetch_assoc($result)) { $db_email = $row['email']; $db_passwordenc = $row['password']; } echo "$password"; if (md5($password) != $db_passwordenc) { echo "incorrect password"; } else { $_SESSION['email'] = $email; $_SESSION['type'] = "student"; header("Location: Student_result.php"); } mysqli_close($conn); } ?> </body> </html>
true
27341cd0ef195f50338e03d107928ea53f7be5cd
PHP
tcesarusa/mm-e-commerce
/vendor/omnipay/eway/src/Message/RapidCaptureRequest.php
UTF-8
2,101
2.75
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php /** * eWAY Rapid Capture Request */ namespace Omnipay\Eway\Message; /** * eWAY Rapid Capture Request * * This is a request to capture and process a previously created authorisation. * * Example - note this example assumes that the authorisation has been successful * and that the Transaction ID returned from the authorisation is held in $txn_id. * See RapidDirectAuthorizeRequest for the first part of this example. * * <code> * // Once the transaction has been authorized, we can capture it for final payment. * $transaction = $gateway->capture(array( * 'amount' => '10.00', * 'currency' => 'AUD', * )); * $transaction->setTransactionReference($txn_id); * $response = $transaction->send(); * </code> * * @link https://eway.io/api-v3/#pre-auth * @see RapidDirectAuthorizeRequest */ class RapidCaptureRequest extends AbstractRequest { public function getData() { $this->validate('amount', 'transactionReference'); $data = array(); $data['Payment'] = array(); $data['Payment']['TotalAmount'] = $this->getAmountInteger(); $data['Payment']['InvoiceNumber'] = $this->getTransactionId(); $data['Payment']['InvoiceDescription'] = $this->getDescription(); $data['Payment']['CurrencyCode'] = $this->getCurrency(); $data['Payment']['InvoiceReference'] = $this->getInvoiceReference(); $data['TransactionId'] = $this->getTransactionReference(); return $data; } public function getEndpoint() { return $this->getEndpointBase().'/CapturePayment'; } public function sendData($data) { // This request uses the REST endpoint and requires the JSON content type header $httpResponse = $this->httpClient->post( $this->getEndpoint(), array('content-type' => 'application/json'), json_encode($data) ) ->setAuth($this->getApiKey(), $this->getPassword()) ->send(); return $this->response = new RapidResponse($this, $httpResponse->json()); } }
true
9fb088e84d6eeb10e1391a63ba6b77c7609750c4
PHP
ngitimfoyo/Nyari-AppPHP
/Source/vendor/symfony/process/Tests/NonStopableProcess.php
UTF-8
761
2.984375
3
[ "MIT" ]
permissive
<?php /** * Runs a PHP script that can be stopped only with a SIGKILL (9) signal for 3 seconds. * * @args duration Run this script with a custom duration * * @example `php NonStopableProcess.php 42` will run the script for 42 seconds */ function handleSignal($signal) { switch ($signal) { case SIGTERM : $name = 'SIGTERM'; break; case SIGINT : $name = 'SIGINT'; break; default : $name = $signal . ' (unknown)'; break; } echo "received signal $name\n"; } declare ( ticks = 1 ) ; pcntl_signal ( SIGTERM, 'handleSignal' ); pcntl_signal ( SIGINT, 'handleSignal' ); $duration = isset ( $argv [1] ) ? ( int ) $argv [1] : 3; $start = microtime ( true ); while ( $duration > (microtime ( true ) - $start) ) { usleep ( 1000 ); }
true
96f5c50923a796de09782400b6664607f7e080a6
PHP
postoor/line-notify-sdk
/src/LineNotify/Auth.php
UTF-8
3,208
2.734375
3
[]
no_license
<?php namespace postoor\LineNotify; use GuzzleHttp\Client; use GuzzleHttp\Exception\RequestException; class Auth { const AUTHORIZE_URI = '/oauth/authorize'; const TOKEN_URI = '/oauth/token'; const REVOKE_URI = '/api/revoke'; protected $config = []; public function __construct(array $config) { $this->config = array_merge([ 'clientId' => null, 'clientSecret' => null, 'oauthUri' => 'https://notify-bot.line.me', 'apiUri' => 'https://notify-api.line.me', ], $config); if ($config['clientId'] == null || $config['clientSecret'] == null) { throw new \Exception('clientId/clientSecret Required', 400); } $this->client = new Client(); } public function getAuthorizeUrl(string $callbackUri, string $state = 'none'): string { $params = [ 'response_type' => 'code', 'client_id' => $this->config['clientId'], 'redirect_uri' => $callbackUri, 'scope' => 'notify', 'state' => $state, ]; return $this->config['oauthUri'].Auth::AUTHORIZE_URI.'?'.http_build_query($params); } public function getToken(string $code, string $callbackUri): string { $data = [ 'client_id' => $this->config['clientId'], 'client_secret' => $this->config['clientSecret'], 'grant_type' => 'authorization_code', 'code' => $code, 'redirect_uri' => $callbackUri, ]; $token = ''; try { $res = $this->client->request('POST', $this->config['oauthUri'].Auth::TOKEN_URI, [ 'form_params' => $data, 'headers' => [ 'Content-Type' => 'application/x-www-form-urlencoded', ], ]); if ($res->getStatusCode() != 200) { throw new \Exception("Request Failed: {$res->getBody()}", $res->getResponse()->getStatusCode()); } $data = json_decode((string) $res->getBody(), true); $token = $data['access_token'] ?? ''; } catch (RequestException $error) { throw new \Exception("Request Failed: {$error->getResponse()->getBody()}", $error->getResponse()->getStatusCode()); } return $token; } public function doRevoke(string $token): bool { try { $res = $this->client->request('POST', $this->config['apiUri'].Auth::REVOKE_URI, [ 'headers' => [ 'Content-Type' => 'application/x-www-form-urlencoded', 'Authorization' => "Bearer {$token}", ], ]); if ($res->getStatusCode() != 200) { throw new \Exception("Request Failed: {$res->getBody()}", $res->getResponse()->getStatusCode()); } $data = json_decode((string) $res->getBody(), true); return ($data['status'] ?? '') == 200; } catch (RequestException $error) { throw new \Exception("Request Failed: {$error->getResponse()->getBody()}", $error->getResponse()->getStatusCode()); } } }
true
05ff9b4202d337bf079588e59e7273e84bcd202d
PHP
rra-am1a-2017/blok2-web-crud
/functions/functions.php
UTF-8
434
3.09375
3
[]
no_license
<?php function sanitize($data) { // Het weghalen van alle spaties links en rechts van de string en meerdere spaties in het midden $data = trim($data); // addslashes escaped (onschadelijk maken) een enkele quote', een dubbele quote " en // backslashes \ $data = addslashes($data); // Deze functie zet alle html characters om naar html entities $data = htmlspecialchars($data); return $data; } ?>
true
190c2480d43178bce62cdb668c5e68e468938133
PHP
Chocobann986/umitest
/classes/components/emarket/classes/delivery/Address/iAddressFactory.php
UTF-8
959
2.875
3
[]
no_license
<?php namespace UmiCms\Classes\Components\Emarket\Delivery\Address; /** * Интерфейс фабрики адресов доставки * @package UmiCms\Classes\Components\Emarket\Delivery\Address */ interface iAddressFactory { /** * Создает адрес доставки на основе объекта-источника данных адреса доставки * @param \iUmiObject $object объект-источник данных * @return iAddress */ public static function createByObject(\iUmiObject $object); /** * Создает адрес доставки на основе идентификатора объекта-источника данных адреса доставки * @param int $objectId идентификатор объекта-источника данных * @return iAddress * @throws \expectObjectException */ public static function createByObjectId($objectId); }
true
864afe56d387f33858063132027ec48681476849
PHP
olasesi/obejorlocal
/system/library/nitropackio/core/domain.php
UTF-8
1,896
2.859375
3
[]
no_license
<?php namespace nitropackio\core; use nitropackio\core\exception\Domain as DomainException; class Domain { public static function identify() { $result = null; if (empty($_SERVER['HTTP_HOST'])) { throw new DomainException("Cannot identify current host."); } if (empty($_SERVER['REQUEST_URI'])) { throw new DomainException("Cannot identify current host."); } $url = self::trimLower($_SERVER['HTTP_HOST']) . '/' . self::trimLower($_SERVER['REQUEST_URI']); $settings = Setting::load(); $parsed_url = self::parse($url); $best_match = ''; foreach ($settings as $domain => $config) { if (stripos($parsed_url, $domain) === 0 && strlen($domain) > strlen($best_match)) { $best_match = $domain; } } if ($best_match === '') { return $parsed_url; } else { return $best_match; } } public static function parse($url) { $parsed = parse_url(self::trimLower($url)); $candidate = array(); if (isset($parsed['host'])) { $candidate[] = $parsed['host']; } if (isset($parsed['path'])) { $candidate[] = self::trimPath($parsed['path']); } if (empty($candidate)) { throw new DomainException("Cannot determine the current URL."); } return preg_replace('~^www\.~i', '', implode('/', array_filter($candidate))); } public static function trimLower($text) { return strtolower(trim($text, ' /\\')); } public static function trimPath($path) { $parts = explode('/', $path); $final = array_pop($parts); if ($final != 'index.php') { array_push($parts, $final); } return implode('/', array_filter($parts)); } }
true
d22adcb66af8fa2a43a94ac681474a4931d394a5
PHP
esatapedico/tdd
/tests/CalculatorSubtracaoTest.php
UTF-8
1,504
2.84375
3
[]
no_license
<?php namespace Vox\Treinamento\Tdd\Tests; use Vox\Treinamento\Tdd\Tests\AbstractCalculatorTestCase; class CalculatorSubtracaoTest extends AbstractCalculatorTestCase { public function testSubtracaoInteirosCorreta() { $this->assertEquals($this->calculator->subtrai(1,2), -1); } public function testSubtracaoInteirosIncorreta() { $this->assertNotEquals($this->calculator->subtrai(1,3), 1); } public function testSubtracaoReaisCorreta() { $this->assertEquals($this->calculator->subtrai(1.2,2.3), -1.1); } public function testSubtracaoReaisIncorreta() { $this->assertNotEquals($this->calculator->subtrai(5.3,3.4), 1.4); } public function testSubtracaoNegativosInteirosCorreta() { $this->assertEquals($this->calculator->subtrai(-1,-2), 1); } public function testSubtracaoNegativosInteirosIncorreta() { $this->assertNotEquals($this->calculator->subtrai(-2,-3), 2); } public function testSubtracaoNegativosReaisCorreta() { $this->assertEquals($this->calculator->subtrai(-1.4,-2.5), 1.1); } public function testSubtracaoNegativosReaisIncorreta() { $this->assertNotEquals($this->calculator->subtrai(-3.4,-2.5), -0.95); } /** * @expectedException InvalidArgumentException */ public function testSubtracaoValoresNumericos() { $this->calculator->subtrai('vox', 'tecnologia'); } }
true
5f362fdac555ecad4d92605033e3f9887b608ee5
PHP
bono-cms/Quiz
/Storage/AnswerMapperInterface.php
UTF-8
1,337
2.84375
3
[ "CC-BY-3.0" ]
permissive
<?php /** * This file is part of the Bono CMS * * Copyright (c) No Global State Lab * * For the full copyright and license information, please view * the license file that was distributed with this source code. */ namespace Quiz\Storage; interface AnswerMapperInterface { /** * Checks whether answer is correct * * @param string $questionId * @param string $answerId * @return boolean */ public function getCorrect($questionId, $answerId); /** * Fetch all answers * * @param string $id Question id * @param boolean $sort Whether to use sorting by order attribute or not * @return array */ public function fetchAll($id, $sort); /** * Fetches an answer by its associated id * * @param string $id Answer id * @return array */ public function fetchById($id); /** * Inserts an answer * * @param array $answer * @return boolean */ public function insert(array $answer); /** * Updates an answer * * @param array $answer * @return boolean */ public function update(array $answer); /** * Deletes an answer by its associated id * * @param string $id Answer id * @return boolean */ public function deleteById($id); }
true
b5103534c946cc7134520cccaa6be368eed878c0
PHP
nehulyadav/LaraMail
/forgot.php
UTF-8
2,070
2.578125
3
[]
no_license
<?php //error_reporting(0); if(isset($_POST['rp'])) { $email=$_POST['e']; $fmn=$_POST['fmn']; $newp=$_POST['np']; $conp=$_POST['cp']; if(file_exists("User_Data/$email") && file_exists("User_Data/$email/$fmn")) { if($newp==$conp) { //$fo=fopen("User_Data/$email/"); $op=opendir("User_Data/$email/password/"); $r=readdir("$op"); echo $r; rename("User_Data/$email/$r","User_Data/$email/$newp"); $msg="<font color='green'>Password Successfully Reset</font>"; } else { $msg="<font color='blue' face='cursive'>Confirm Password Does Not Match</font>"; } } else { $msg="<font color='red' face='cursive'>First Mobile Number Does Not Match.......</font>"; } } else { $msg="<font color='red' face='cursive'>Email Id Does Not Exists.......</font>"; } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>forgot password</title> </head> <body> <table border="0"> <caption><h1>Recovering Password.... </h1> </caption> <form method="post" enctype="multipart/form-data"> <tr> <td colspan="2"><?php echo @$msg;?></td> </tr> <tr> <td width="173">Your Email Id</td> <td width="145"><input type="email" placeholder="abc@gmail.com" name="e"></td> </tr> <tr> <td>Your First Phone Number</td> <td><input type="text" placeholder="Enter First Phone Number" name="fmn"></td> </tr> <tr> <td>Your New Password</td> <td><input type="password" placeholder="Enter New Password" name="np"></td> </tr> <tr> <td>Your Confirm Password</td> <td><input type="password" placeholder="Enter Confirm Password" name="cp"></td> </tr> <tr> <td colspan="2" align="center"><input type="submit" value="Reset Password" name="rp"></td> </tr> </form> </table> </body> </html>
true
5e806a50bfd1544155313cf3d1f28a48b697adcc
PHP
inthinks/barbek-restful-api
/migrations/m160904_132618_create_provinsi_table.php
UTF-8
1,364
2.71875
3
[ "BSD-3-Clause" ]
permissive
<?php use yii\db\Migration; use League\Csv\Reader; /** * Handles the creation for table `provinsi`. */ class m160904_132618_create_provinsi_table extends Migration { /** * @inheritdoc */ public function safeUp() { $this->createTable('provinsi', [ 'id' => $this->primaryKey(), 'nama' => $this->string(50), ]); // path tempat file csv berada $provinsi = Yii::getAlias('@app/migrations/provinsi.csv'); // baca file csv menggunakan library league\csv $reader = Reader::createFromPath($provinsi); // insert data provinsi kedalam tabel provinsi foreach ($reader as $index => $row) { $this->insert('provinsi', [ 'id' => (int)$row[0], 'nama' => $row[1], ]); } } /** * @inheritdoc */ public function safeDown() { // path tempat file csv berada $provinsi = Yii::getAlias('@app/migrations/provinsi.csv'); // baca file csv menggunakan library league\csv $reader = Reader::createFromPath($provinsi); // hapus data provinsi dari tabel provinsi foreach ($reader as $index => $row) { $this->delete('provinsi', ['id' => (int)$row[0]]); } $this->dropTable('provinsi'); } }
true
aea84d90d5c275e1cba1981f34d2a26570bdcca3
PHP
dev-softwarehouse/digitalprint
/backend/app/Models/Mongo/MgCart.php
UTF-8
799
2.625
3
[]
no_license
<?php /** * Created by PhpStorm. * User: lenovo * Date: 16.01.19 * Time: 11:44 */ namespace DreamSoft\Models\Mongo; use DreamSoft\Core\MongoModel; use Exception; use MongoCollection; /** * Class MgCart * @package DreamSoft\Models\Mongo */ class MgCart extends MongoModel { /** * @var MongoCollection */ private $collection; /** * MgCart constructor. */ public function __construct() { parent::__construct(); try { $this->collection = $this->db->selectCollection('Cart'); } catch (Exception $e) { $this->debug('Collection Cart problem!', $e->getMessage()); } } /** * @return MongoCollection */ public function getAdapter() { return $this->collection; } }
true
30f5f21e9f59ef94f4a0bcc6c97d657d39b55625
PHP
adsr/mkcstubs
/mkcstubs
UTF-8
8,681
2.625
3
[]
no_license
#!/usr/bin/env php <?php $m = new Mkcstub(); $m->run(); /** * A tool for creating and maintaing C function stubs given an authoritative * set of header files */ class Mkcstub { const FUNCTION_REGEX_FMT = '@^([A-Za-z0-9_]+) ([A-Za-z0-9]+)_([A-Za-z0-9_]+)\(([A-Za-z0-9_\*, ]+)\)%s@m'; const DIVIDER = '// ============================================================================'; private $function_regex_prot; private $function_regex_impl; private $help; private $quiet; private $makeBackups; private $hFiles; private $numUpdatedFiles; /** Run */ function run() { $rc = 0; $this->parseArgs(); if ($this->help) { $this->showHelp(); } else { $this->makeCStubs(); } } /** Main func */ private function makeCStubs() { $hFiles = $this->hFiles ? $this->hFiles : glob('*.h'); $this->log(sprintf("Found %d header files", count($hFiles))); foreach ($hFiles as $hFile) { $this->log("{$hFile}:"); $namespaceProtos = $this->getNamespaceProtos($hFile); $this->log(sprintf(" Found %d namespaces", count($namespaceProtos))); foreach ($namespaceProtos as $namespace => $protos) { $protosMap = []; foreach ($protos as $proto) { $protosMap[$proto['name']] = $proto; } $this->log(sprintf(" Ensuring %d functions in %s namespace", count($protos), $namespace)); $this->ensureStubs($hFile, $namespace, $protosMap); } } $this->log(sprintf("Updated %d source files", $this->numUpdatedFiles)); } /** Ensure stubs exist */ private function ensureStubs($hFile, $namespace, $protosMap) { $cFile = "{$namespace}.c"; if (!file_exists($cFile)) { $this->createCFile($hFile, $cFile, $namespace, $protosMap); } else { $this->updateCFile($hFile, $cFile, $namespace, $protosMap); } } /** Create a C file */ private function createCFile($hFile, $cFile, $namespace, $protosMap) { $cFuncs = $this->getUpdatedCFuncs([], $namespace, $protosMap); $hFileShort = basename($hFile); $this->writeCFile($cFile, "#include \"{$hFileShort}\"", self::DIVIDER, $cFuncs); } /** Update a C file */ private function updateCFile($hFile, $cFile, $namespace, $protosMap) { list($cFuncs, $sourceBefore, $sourceAfter) = $this->extractCFuncs($cFile); $cFuncs = $this->getUpdatedCFuncs($cFuncs, $namespace, $protosMap); $this->writeCFile($cFile, $sourceBefore, $sourceAfter, $cFuncs); } /** Write or overwrite a C file */ private function writeCFile($cFile, $sourceBefore, $sourceAfter, $cFuncs) { $content = trim($sourceBefore) . "\n\n"; foreach ($cFuncs as $cFunc) { $content .= "/** {$cFunc['comment']} */\n" . rtrim($cFunc['first'], '; {') . " {\n" . ($cFunc['body'] ? $cFunc['body'] . "\n" : '') . "}\n\n"; } $content .= trim($sourceAfter); $content = trim($content) . "\n"; if (file_exists($cFile)) { if (md5($content) == md5_file($cFile)) { return; } else if ($this->makeBackups) { copy($cFile, "{$cFile}.bak"); } } $this->numUpdatedFiles += 1; file_put_contents($cFile, $content); } /** Integrates protosMap into cFuncs */ private function getUpdatedCFuncs($cFuncs, $namespace, $protosMap) { foreach ($protosMap as $name => $proto) { if (!isset($cFuncs[$name])) { $cFuncs[$name] = [ 'comment' => "TODO {$name}", 'first' => $proto['line'], 'body' => '' ]; } else { $cFuncs[$name]['first'] = $proto['line']; if (!isset($cFuncs[$name]['comment'])) { $cFuncs[$name]['comment'] = "TODO {$name}"; } } } return $this->getSortedCFuncs($cFuncs, $protosMap); } /** Sort C functions in the order of protosMap, unknown funcs last */ private function getSortedCFuncs($cFuncs, $protosMap) { $sortedCFuncs = []; foreach ($protosMap as $name => $proto) { if (isset($cFuncs[$name])) { $sortedCFuncs[$name] = $cFuncs[$name]; } } foreach ($cFuncs as $name => $cFunc) { if (!isset($sortedCFuncs[$name])) { $sortedCFuncs[$name] = $cFunc; } } return $sortedCFuncs; } /** Extract C functions from $cFile */ private function extractCFuncs($cFile) { $cFuncs = []; $cLines = explode("\n", file_get_contents($cFile)); $sourceBefore = null; $sourceAfter = ''; $i = 0; $l = count($cLines); $lastFuncLine = $l - 1; while ($i < $l) { $cLine = $cLines[$i]; if ($cLine == self::DIVIDER) { $lastFuncLine = $i - 1; break; } if (preg_match($this->function_regex_impl, $cLine, $m)) { $name = $m[2] . '_' . $m[3]; $cFunc = [ 'comment' => "TODO {$name}", 'first' => $m[0], 'body' => null ]; $fi = $i; if ($i - 1 > 0 && substr($cLines[$i - 1], 0, 2) == '/*') { $cFunc['comment'] = preg_replace('@(/\*+\s*|\s*\*+/)@', '', $cLines[$i - 1]); $fi = $i - 1; } if ($sourceBefore === null) { $sourceBefore = implode("\n", array_slice($cLines, 0, $fi - 1)); } for ($j = $i + 1; $j < $l; $j++) { if ($cLines[$j] == '}') { $cFunc['body'] = implode("\n", array_slice($cLines, $i + 1, ($j - 1) - $i)); break; } } if ($cFunc['body'] === null) { break; } $cFuncs[$name] = $cFunc; $i = $j + 1; } else { $i += 1; } } $sourceAfter .= implode("\n", array_slice($cLines, $lastFuncLine)); return [$cFuncs, $sourceBefore, $sourceAfter]; } /** Extract prototypes from $hFile */ private function getNamespaceProtos($hFile) { $protos = []; if (!is_readable($hFile) || !is_file($hFile)) { return []; } $hFileSource = file_get_contents($hFile); if (preg_match_all($this->function_regex_prot, $hFileSource, $m) > 0) { foreach ($m[0] as $i => $line) { $namespace = $m[2][$i]; if (!isset($protos[$namespace])) { $protos[$namespace] = []; } $protos[$namespace][] = [ 'line' => $line, 'type' => $m[1][$i], 'name' => $namespace . '_' . $m[3][$i], 'args' => $m[4][$i] ]; } } return $protos; } /** Parse command line args */ private function parseArgs() { $opt = getopt('hqB'); $this->help = isset($opt['h']); $this->quiet = isset($opt['q']); $this->makeBackups = !isset($opt['B']); $this->hFiles = []; $fileArgs = $_SERVER['argv']; array_shift($fileArgs); foreach (array_reverse($fileArgs) as $fileArg) { if (is_readable($fileArg) && is_file($fileArg)) { $this->hFiles[] = $fileArg; } else { break; } } } /** Show help */ private function showHelp() { echo "Usage: php {$_SERVER['PHP_SELF']} -hqB HFILE...\n\n" . "Makes stubs from prototypes in HFILEs or glob('*.h') if not specified.\n\n" . "Options:\n" . " -h show help\n" . " -q quiet mode\n" . " -B do not make bak files\n"; } /** Output log line */ private function log($s) { if (!$this->quiet) { echo "{$s}\n"; } } /** Ctor */ function __construct() { $this->function_regex_prot = sprintf(self::FUNCTION_REGEX_FMT, ';'); $this->function_regex_impl = sprintf(self::FUNCTION_REGEX_FMT, ' {'); } }
true
f4a23ed24ade63be004dc3fdfa81b21c74537e7b
PHP
ijsepro/System-Rest-House-Managment-DEV15
/BackEnd/application/controllers/mealcatagory.php
UTF-8
780
2.546875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php /** * Created by IntelliJ IDEA. * User: USER * Date: 5/15/2018 * Time: 3:24 PM */ header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods:GET,POST'); header('Access-Control-Allow-Headers, Content-Type'); class Mealcatagory extends CI_Controller{ public function __construct() { parent::_construct(); $this->load->model('mealcatagory_model'); } public function getMealCata($mealcatagoryId = ''){ $data = $this->mealcatagory_model->getMealCata($mealcatagoryId); print_r($data); $this->output->enable_profiler(); } public function insert(){ $result = $this->mealcatagory_model->insert([ 'mealcatagoryId' => 'mealcatagoryName' ]); print_r($result); } public function update(){ } public function delete(){ } }
true
321366c19f153b838c066e64c6f13e7d64046e15
PHP
ThunderID/SHOP-API
/app/Models/Traits/HasBillAmountTrait.php
UTF-8
435
2.578125
3
[]
no_license
<?php namespace App\Models\Traits; use App\Models\Scopes\BillAmountScope; /** * Apply scope to get bill of sales transaction * * @author cmooy */ trait HasBillAmountTrait { /** * Boot the Has Amount scope for a model to get amount of transaction hasn't been paid. * * @return void */ public static function bootHasBillAmountTrait() { static::addGlobalScope(new BillAmountScope); } }
true
e4e04cd8fbbee657e1ead066d9c5c6d724cc1c7b
PHP
mastuyink/traviora
/frontend/models/JenisDestinasi.php
UTF-8
1,976
2.515625
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\models; use Yii; /** * This is the model class for table "v_jenis_destinasi". * * @property integer $id * @property integer $id_destinasi * @property string $gbr_thumbnail * @property string $judul_content * @property string $content * @property integer $id_author * @property string $create_at * @property string $last_update * @property integer $id_jenis_destinasi */ class JenisDestinasi extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'v_jenis_destinasi'; } /** * @inheritdoc */ public function rules() { return [ [['id', 'id_destinasi', 'id_author', 'id_jenis_destinasi'], 'integer'], [['id_destinasi', 'judul_content', 'content', 'id_author', 'id_jenis_destinasi'], 'required'], [['judul_content', 'content'], 'string'], [['create_at', 'last_update'], 'safe'], [['gbr_thumbnail'], 'string', 'max' => 255], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => Yii::t('app', 'ID'), 'id_destinasi' => Yii::t('app', 'Id Destinasi'), 'gbr_thumbnail' => Yii::t('app', 'Gbr Thumbnail'), 'judul_content' => Yii::t('app', 'Judul Content'), 'content' => Yii::t('app', 'Content'), 'id_author' => Yii::t('app', 'Id Author'), 'create_at' => Yii::t('app', 'Create At'), 'last_update' => Yii::t('app', 'Last Update'), 'id_jenis_destinasi' => Yii::t('app', 'Id Jenis Destinasi'), ]; } public function getIdAuthor() { return $this->hasOne(User::className(), ['id' => 'id_author']); } /** * @return \yii\db\ActiveQuery */ public function getIdDestinasi() { return $this->hasOne(TDestinasi::className(), ['id' => 'id_destinasi']); } }
true
a0c467be2fd7a84a8fc1c4e20ff338e467431074
PHP
yiisoft/yii
/framework/caching/CDbCache.php
UTF-8
9,719
2.734375
3
[]
permissive
<?php /** * CDbCache class file * * @author Qiang Xue <qiang.xue@gmail.com> * @link https://www.yiiframework.com/ * @copyright 2008-2013 Yii Software LLC * @license https://www.yiiframework.com/license/ */ /** * CDbCache implements a cache application component by storing cached data in a database. * * CDbCache stores cache data in a DB table named {@link cacheTableName}. * If the table does not exist, it will be automatically created. * By setting {@link autoCreateCacheTable} to false, you can also manually create the DB table. * * CDbCache relies on {@link https://www.php.net/manual/en/ref.pdo.php PDO} to access database. * By default, it will use a SQLite3 database under the application runtime directory. * You can also specify {@link connectionID} so that it makes use of * a DB application component to access database. * * See {@link CCache} manual for common cache operations that are supported by CDbCache. * * @property integer $gCProbability The probability (parts per million) that garbage collection (GC) should be performed * when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance. * @property CDbConnection $dbConnection The DB connection instance. * * @author Qiang Xue <qiang.xue@gmail.com> * @package system.caching * @since 1.0 */ class CDbCache extends CCache { /** * @var string the ID of the {@link CDbConnection} application component. If not set, * a SQLite3 database will be automatically created and used. The SQLite database file * is <code>protected/runtime/cache-YiiVersion.db</code>. */ public $connectionID; /** * @var string name of the DB table to store cache content. Defaults to 'YiiCache'. * Note, if {@link autoCreateCacheTable} is false and you want to create the DB table * manually by yourself, you need to make sure the DB table is of the following structure: * <pre> * (id CHAR(128) PRIMARY KEY, expire INTEGER, value BLOB) * </pre> * Note, some DBMS might not support BLOB type. In this case, replace 'BLOB' with a suitable * binary data type (e.g. LONGBLOB in MySQL, BYTEA in PostgreSQL.) * @see autoCreateCacheTable */ public $cacheTableName='YiiCache'; /** * @var boolean whether the cache DB table should be created automatically if it does not exist. Defaults to true. * If you already have the table created, it is recommended you set this property to be false to improve performance. * @see cacheTableName */ public $autoCreateCacheTable=true; /** * @var CDbConnection the DB connection instance */ private $_db; private $_gcProbability=100; private $_gced=false; /** * Initializes this application component. * * This method is required by the {@link IApplicationComponent} interface. * It ensures the existence of the cache DB table. * It also removes expired data items from the cache. */ public function init() { parent::init(); $db=$this->getDbConnection(); $db->setActive(true); if($this->autoCreateCacheTable) { $sql="DELETE FROM {$this->cacheTableName} WHERE expire>0 AND expire<".time(); try { $db->createCommand($sql)->execute(); } catch(Exception $e) { $this->createCacheTable($db,$this->cacheTableName); } } } /** * @return integer the probability (parts per million) that garbage collection (GC) should be performed * when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance. */ public function getGCProbability() { return $this->_gcProbability; } /** * @param integer $value the probability (parts per million) that garbage collection (GC) should be performed * when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance. * This number should be between 0 and 1000000. A value 0 meaning no GC will be performed at all. */ public function setGCProbability($value) { $value=(int)$value; if($value<0) $value=0; if($value>1000000) $value=1000000; $this->_gcProbability=$value; } /** * Creates the cache DB table. * @param CDbConnection $db the database connection * @param string $tableName the name of the table to be created */ protected function createCacheTable($db,$tableName) { $driver=$db->getDriverName(); if($driver==='mysql') $blob='LONGBLOB'; elseif($driver==='pgsql') $blob='BYTEA'; else $blob='BLOB'; $sql=<<<EOD CREATE TABLE $tableName ( id CHAR(128) PRIMARY KEY, expire INTEGER, value $blob ) EOD; $db->createCommand($sql)->execute(); } /** * @return CDbConnection the DB connection instance * @throws CException if {@link connectionID} does not point to a valid application component. */ public function getDbConnection() { if($this->_db!==null) return $this->_db; elseif(($id=$this->connectionID)!==null) { if(($this->_db=Yii::app()->getComponent($id)) instanceof CDbConnection) return $this->_db; else throw new CException(Yii::t('yii','CDbCache.connectionID "{id}" is invalid. Please make sure it refers to the ID of a CDbConnection application component.', array('{id}'=>$id))); } else { $dbFile=Yii::app()->getRuntimePath().DIRECTORY_SEPARATOR.'cache-'.Yii::getVersion().'.db'; return $this->_db=new CDbConnection('sqlite:'.$dbFile); } } /** * Sets the DB connection used by the cache component. * @param CDbConnection $value the DB connection instance * @since 1.1.5 */ public function setDbConnection($value) { $this->_db=$value; } /** * Retrieves a value from cache with a specified key. * This is the implementation of the method declared in the parent class. * @param string $key a unique key identifying the cached value * @return string|boolean the value stored in cache, false if the value is not in the cache or expired. */ protected function getValue($key) { $time=time(); $sql="SELECT value FROM {$this->cacheTableName} WHERE id='$key' AND (expire=0 OR expire>$time)"; $db=$this->getDbConnection(); if($db->queryCachingDuration>0) { $duration=$db->queryCachingDuration; $db->queryCachingDuration=0; $result=$db->createCommand($sql)->queryScalar(); $db->queryCachingDuration=$duration; return $result; } else return $db->createCommand($sql)->queryScalar(); } /** * Retrieves multiple values from cache with the specified keys. * @param array $keys a list of keys identifying the cached values * @return array a list of cached values indexed by the keys */ protected function getValues($keys) { if(empty($keys)) return array(); $ids=implode("','",$keys); $time=time(); $sql="SELECT id, value FROM {$this->cacheTableName} WHERE id IN ('$ids') AND (expire=0 OR expire>$time)"; $db=$this->getDbConnection(); if($db->queryCachingDuration>0) { $duration=$db->queryCachingDuration; $db->queryCachingDuration=0; $rows=$db->createCommand($sql)->queryAll(); $db->queryCachingDuration=$duration; } else $rows=$db->createCommand($sql)->queryAll(); $results=array(); foreach($keys as $key) $results[$key]=false; foreach($rows as $row) $results[$row['id']]=$row['value']; return $results; } /** * Stores a value identified by a key in cache. * This is the implementation of the method declared in the parent class. * * @param string $key the key identifying the value to be cached * @param string $value the value to be cached * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire. * @return boolean true if the value is successfully stored into cache, false otherwise */ protected function setValue($key,$value,$expire) { $this->deleteValue($key); return $this->addValue($key,$value,$expire); } /** * Stores a value identified by a key into cache if the cache does not contain this key. * This is the implementation of the method declared in the parent class. * * @param string $key the key identifying the value to be cached * @param string $value the value to be cached * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire. * @return boolean true if the value is successfully stored into cache, false otherwise */ protected function addValue($key,$value,$expire) { if(!$this->_gced && mt_rand(0,1000000)<$this->_gcProbability) { $this->gc(); $this->_gced=true; } if($expire>0) $expire+=time(); else $expire=0; $sql="INSERT INTO {$this->cacheTableName} (id,expire,value) VALUES ('$key',$expire,:value)"; try { $command=$this->getDbConnection()->createCommand($sql); $command->bindValue(':value',$value,PDO::PARAM_LOB); $command->execute(); return true; } catch(Exception $e) { return false; } } /** * Deletes a value with the specified key from cache * This is the implementation of the method declared in the parent class. * @param string $key the key of the value to be deleted * @return boolean if no error happens during deletion */ protected function deleteValue($key) { $sql="DELETE FROM {$this->cacheTableName} WHERE id='$key'"; $this->getDbConnection()->createCommand($sql)->execute(); return true; } /** * Removes the expired data values. */ protected function gc() { $this->getDbConnection()->createCommand("DELETE FROM {$this->cacheTableName} WHERE expire>0 AND expire<".time())->execute(); } /** * Deletes all values from cache. * This is the implementation of the method declared in the parent class. * @return boolean whether the flush operation was successful. * @since 1.1.5 */ protected function flushValues() { $this->getDbConnection()->createCommand("DELETE FROM {$this->cacheTableName}")->execute(); return true; } }
true
85f84de696f522fd46138d2a3c15833b042e1ac8
PHP
tkcmuzrepo/muz_repo
/htdocs/classes/form_base/selectbox.php
UTF-8
2,634
2.796875
3
[]
no_license
<?php require_once(CLASS_DIR."form.php"); # 通常TEXT 郵便番号 電話番号 をカバーできる class SelectBox extends Form{ function __construct($form_id,$field_id){ $this->formType='select'; parent::__construct($form_id,$field_id); } # ■Styleを設定 # @author Kiyosawa # @date public function setStyleAttr($style=''){ $style_format=$this->attrFormatStyle; $form=$this->_getForm(); $form=str_replace($this->attrStyle,sprintf($style_format,$style),$form); $this->form=$form; } # ■data属性 # @author Kiyosawa # @date public function setData($data=''){ $data_format=$this->attrFormatData; $form=$this->_getForm(); $form=str_replace($this->attrData,sprintf($data_format,$data),$form); $this->form=$form; } # ■初期値の設定 # ■設定した値を保持しておいて置換できる様にする # ■box_numの値によって状況は変わる public function setOption($values=array(),$selected_index=''){ $value_change_code='#value#'; $selected_change_code="#selected#"; $option_string=''; $option_format="<option value=\"{$value_change_code}\" {$selected_change_code}>{$value_change_code}</option>"; foreach($values as $k=>$v){ $_option=str_replace($value_change_code,$v,$option_format); if($k==$selected_index){ $_option=str_replace("#selected#",'selected',$_option); $option_string.=$_option; continue; } $_option=str_replace($selected_change_code,'',$_option); $option_string.=$_option; } $this->form=str_replace($this->attrOption,$option_string,$this->form); } # ■クラスの設定 # @author Kiyosawa # @date public function setClass($className=''){ if(empty($className)) return; $class_format=$this->attrFormatClass; $form=$this->_getForm(); $form=str_replace($this->attrClass,sprintf($class_format,$className),$form); $this->form=$form; } # ■フォームの取得 public function getForm($formType=''){ if(!empty($type)){ $this->formType=$formType; } # フィールドindex if(!isset($this->formCountStacks[$this->form_id][$this->field_id]))$this->formCountStacks[$this->form_id][$this->field_id]=0; $this->formCountStacks[$this->form_id][$this->field_id]++; # name $attr_name_value=$this->_makeName($this->form_id,$this->field_id); $this->_setName($attr_name_value); # id $attr_id_value=$this->_makeID($this->form_id,$this->field_id); $this->_setID($attr_id_value); # type $this->_setTypeAttr(); $form=$this->_getForm(); $form=$this->stripCodes($form); $this->_clean(); return $form; } } ?>
true
81e3f998751ce1afb042a15233146f478b2be989
PHP
mhas97/TennisLadder-Backend
/ChallengeRequest.php
UTF-8
16,238
3.3125
3
[]
no_license
<?php /** * Class ChallengeRequest * * Handles database queries corresponding to challenge related requests. Allows the user to create challenges, * modify their status (accept, decline, cancel) and finally post a result. */ class ChallengeRequest { /* The connection object. */ private $connection; /** * Obtains a mysqli connection object via the Connection class. */ function __construct() { require_once dirname(__FILE__) . "/Connection.php"; $tennisDatabase = new Connection(); $this->connection = $tennisDatabase->connect(); } /** * @param $time String provided in UNIX time (seconds) makes for easier conversion for DB storage. * Create an entry in the challenge table containing challenge metadata. * @return bool Success status. */ function createChallenge($clubName, $date, $time): bool { /* Format time for database storage */ $date = intval($date); date_default_timezone_set("Europe/London"); $mysqlDate = date("Y-m-d", $date); /* Prepare and execute statement. */ $statementChallenge = $this->connection->prepare ( "INSERT INTO challenge (clubid, date, time) VALUES ((SELECT clubid from club WHERE name = ?), ?, ?)" ); $statementChallenge->bind_param("sss", $clubName, $mysqlDate, $time); if ($statementChallenge->execute()) { return true; } return false; } /** * Sets the accepted status for a given challenge ID to true. */ function acceptChallenge($challengeID): bool { $statementAcceptChallenge = $this->connection->prepare ( "UPDATE challenge SET accepted = 1 WHERE challengeid = ?" ); $statementAcceptChallenge->bind_param("i", $challengeID); if ($statementAcceptChallenge->execute()) { return true; } return false; } /** * Shares functionality for both cancelling and declining a challenge. Deletes the challenge * with the associated ID from both the challenge and player_challenge tables. */ function cancelChallenge($challengeID): bool { /* Player challenge statement. */ $statementPlayerChallenge = $this->connection->prepare ( "DELETE FROM player_challenge WHERE challengeid = ?" ); $statementPlayerChallenge->bind_param("i", $challengeID); /* Challenge statement. */ $statementChallenge = $this->connection->prepare ( "DELETE FROM challenge WHERE challengeid = ?" ); /* Execute statements. */ $statementChallenge->bind_param("i", $challengeID); if (!$statementPlayerChallenge->execute()) { return false; } if (!$statementChallenge->execute()) { return false; } return true; } /** * Upon creation of a challenge, returns the newly auto-generated challenge ID. This is further used as * a reference in the player_challenge table as part of a compound key. The limitation of this function * is that it returns the latest entry, which will run into concurrency issues if the app gets busy. */ function getChallengeID(): string { /* Prepare and execute statement. */ $statementGetID = $this->connection->prepare ( "SELECT challengeid FROM challenge ORDER BY challengeid DESC LIMIT 1" ); $statementGetID->bind_result($challengeID); $statementGetID->execute(); $statementGetID->fetch(); $statementGetID->close(); $challengeID = strval($challengeID); // Returned in string format as it is fed back as a parameter. return $challengeID; } /** * @param int $challengeID The autogenerated challenge ID. * Use the autogenerated challenge ID to create player_challenge entries for both players. * @return bool Error status. */ function createPlayerChallenge($challengeID, $playerID, $opponentID): bool { $challengeID = intval($challengeID); /* Prepare and execute the user entry, where 1 indicates that they initiated the challenge from their client. */ $playerID = intval($playerID); $statementUser = $this->connection->prepare ( "INSERT INTO player_challenge (challengeid, playerid, didinitiate) VALUES (?, ?, 1)" ); $statementUser->bind_param("ii", $challengeID, $playerID); if (!$statementUser->execute()) { return false; } $statementUser->close(); /* Prepare and execute the opponent entry, 0 indicates that they are recieving the challenge. */ $opponentID = intval($opponentID); $statementOpponent = $this->connection->prepare ( "INSERT INTO player_challenge (challengeid, playerid, didinitiate) VALUES (?, ?, 0)" ); $statementOpponent->bind_param("ii", $challengeID, $opponentID); if (!$statementOpponent->execute()) { return false; } $statementOpponent->close(); /* Both statements executed successfully. */ return true; } /** * Obtain all challenges for a user, preceded by the depreciated getChallengesData() method. * * * First obtains a list of challenge ID's and initiation status' from the * player_challenge table, and inserts these into an array of keypair values. Using the challenge ID's, * query for challenge metadata as well as opponent data. As we iterate, append data from the initial array * (used to identify challenge ID's), and the fetched data to the array for return. This results in final * array being correctly formatted for JSON encoding. */ function getChallenges($playerID): array { /* Construct a list of challenge ID's an initiation status'. -1 indicates that a result has not been posted and the match not yet played. */ $statementGetIDList = $this->connection->prepare ( "SELECT challengeid, didinitiate FROM player_challenge WHERE playerid = ? AND didwin = -1" ); /* Prepare and execute statement. */ $playerID = intval($playerID); $statementGetIDList->bind_param("i", $playerID); $statementGetIDList->execute(); $statementGetIDList->bind_result($challengeID, $didInitiate); $challengeList = array(); while ($statementGetIDList->fetch()) { $locatedChallenge = array(); $locatedChallenge["challengeid"] = $challengeID; $locatedChallenge["didinitiate"] = $didInitiate; array_push($challengeList, $locatedChallenge); } $statementGetIDList->close(); /* For each identified challenge, fetch relevant data. */ $challenges = array(); // The final challenges array to be returned. foreach ($challengeList as $c) { /* Statement to fetch opponent data, != playerID refers to the opponent. */ $statementGetOpponent = $this->connection->prepare ( "SELECT playerid, fname, lname, elo, winstreak, hotstreak, matchesplayed, wins, losses, highestelo, clubchamp FROM player WHERE playerid = (SELECT playerid FROM player_challenge WHERE challengeid = ? AND playerid != ?)" ); /* Statement to fetch challenge metadata. */ $statementGetChallengeData = $this->connection->prepare ( "SELECT date, time, (SELECT name FROM club WHERE challenge.clubid = club.clubid ), accepted FROM challenge WHERE challengeid = ?" ); /* Prepare and execute the opponent data statement. */ $statementGetOpponent->bind_param("ii", $c["challengeid"], $playerID); $statementGetOpponent->execute(); $statementGetOpponent->bind_result($opponentID, $fname, $lname, $elo, $winStreak, $hotStreak, $matchesPlayed, $numWins, $numLosses, $highestElo, $clubChamp); $statementGetOpponent->fetch(); $statementGetOpponent->close(); /* Prepare and execute the challenge data statement. */ $statementGetChallengeData->bind_param("i", $c["challengeid"]); $statementGetChallengeData->execute(); $statementGetChallengeData->bind_result($date, $time, $location, $accepted); $statementGetChallengeData->fetch(); $statementGetChallengeData->close(); $challenge = array(); // Array to hold a single challenge. /* Append fetched data to the challenges array. */ $challenge["challengeid"] = $c["challengeid"]; $challenge["didinitiate"] = $c["didinitiate"]; $challenge["opponentid"] = $opponentID; $challenge["fname"] = $fname; $challenge["lname"] = $lname; $challenge["elo"] = $elo; $challenge["winstreak"] = $winStreak; $challenge["hotstreak"] = $hotStreak; $challenge["matchesplayed"] = $matchesPlayed; $challenge["wins"] = $numWins; $challenge["losses"] = $numLosses; $challenge["highestelo"] = $highestElo; $challenge["clubchamp"] = $clubChamp; $challenge["date"] = $date; $challenge["time"] = $time; $challenge["location"] = $location; $challenge["accepted"] = $accepted; $challenge["achieved"] = (new PlayerRequest)->getUserAchievements($opponentID); // Fetch user achievement data. array_push($challenges, $challenge); } return $challenges; } /** * Updates the database with fields relating to a reported result. */ function postResult($challengeID, $winnerID, $loserID, $score, $winnerElo, $loserElo, $newHighestElo, $hotStreak) { $challengeID = intval($challengeID); $winnerID = intval($winnerID); $loserID = intval($loserID); $winnerElo = intval($winnerElo); $loserElo = intval($loserElo); $newHighestElo = intval($newHighestElo); $hotStreak = intval($hotStreak); /* Identify the current highest rated player at the winners club and check if the user has overtaken them. If they have, unset the club champion status for the current holder. */ $currentClubMax = $this->getClubMaxElo($winnerID); if ($winnerElo >= $currentClubMax) { $clubChampion = 1; $this->removeChampionStatus($currentClubMax); } else { $clubChampion = 0; } /* Check if the loser has been dethroned (lost their champion status). */ $this->checkDethroned($loserID, $loserElo); /* Update the score in the challenges table. */ $statementUpdateScore = $this->connection->prepare ( "UPDATE challenge SET score = ? WHERE challengeid = ?" ); $statementUpdateScore->bind_param("si", $score, $challengeID); if (!$statementUpdateScore->execute()) { return false; } $statementUpdateScore->close(); /* Update the winner in the player_challenges table. */ $statementUpdateWinner = $this->connection->prepare ( "UPDATE player_challenge SET didwin = 1 WHERE challengeid = ? AND playerid = ?" ); $statementUpdateWinner->bind_param("ii", $challengeID, $winnerID); if (!$statementUpdateWinner->execute()) { return false; } $statementUpdateWinner->close(); /* Update the loser in the player_challenges table. */ $statementUpdateLoser = $this->connection->prepare ( "UPDATE player_challenge SET didwin = 0 WHERE challengeid = ? AND playerid = ?" ); $statementUpdateLoser->bind_param("ii", $challengeID, $loserID); if (!$statementUpdateLoser->execute()) { return false; } $statementUpdateLoser->close(); /* Update the player data for the winner. */ $statementWinnerPlayer = $this->connection->prepare ( "UPDATE player SET elo = ?, winstreak = winstreak + 1, hotstreak = ?, matchesplayed = matchesplayed + 1, wins = wins + 1, highestelo = ?, clubchamp = ? WHERE playerid = ?" ); $statementWinnerPlayer->bind_param("iiiii", $winnerElo, $hotStreak, $newHighestElo, $clubChampion, $winnerID); if (!$statementWinnerPlayer->execute()) { return false; } $statementWinnerPlayer->close(); /* Update the player data for the loser. */ $statementLoserPlayer = $this->connection->prepare ( "UPDATE player SET elo = ?, winstreak = 0, hotstreak = 0, matchesplayed = matchesplayed + 1, losses = losses + 1 WHERE playerid = ?" ); $statementLoserPlayer->bind_param("ii", $loserElo, $loserID); if (!$statementLoserPlayer->execute()) { return false; } $statementLoserPlayer->close(); /* Statement executed successfully. */ return true; } /** * Identify the current highest Elo at a given users club. */ function getClubMaxElo($playerID) { /* Fetch every players Elo from the users club. */ $statementGetElos = $this->connection->prepare ( "SELECT playerid, elo FROM player WHERE clubid = (SELECT clubid FROM player WHERE playerid = ?)" ); $statementGetElos->bind_param("i", $playerID); $statementGetElos->execute(); $statementGetElos->bind_result($userID, $elo); $elos = array(); /* Don't append the users elo. */ while ($statementGetElos->fetch()) { if ($userID != $playerID) { array_push($elos, $elo); } } $statementGetElos->close(); return max($elos); // Return the highest value. } /** * Unset the club champion status of the current club champion. */ function removeChampionStatus($elo) { $statementRemoveChampion = $this->connection->prepare ( "UPDATE player SET clubchamp = 0 WHERE elo = ?" ); $statementRemoveChampion->bind_param("i", $elo); $statementRemoveChampion->execute(); $statementRemoveChampion->close(); } /** * Check if a losing player has lost their champion status. If so, update the new champion status * in the database. * @param int $loserID The losers ID. * @param int $elo The losers Elo. */ function checkDethroned($loserID, $elo) { /* Check if they are the club champion. */ $statementGetChamp = $this->connection->prepare ( "SELECT clubchamp FROM player WHERE playerid = ?" ); $statementGetChamp->bind_param("i", $loserID); $statementGetChamp->execute(); $statementGetChamp->bind_result($clubChamp); $statementGetChamp->fetch(); $statementGetChamp->close(); if ($clubChamp == 1) { $currentClubMax = $this->getClubMaxElo($loserID); /* If there is now a player at the club with a higher rating, remove clubchamp status. */ if ($currentClubMax >= $elo) { $statementDethrone = $this->connection->prepare ( "UPDATE player SET clubchamp = 0 WHERE playerid = ?" ); $statementDethrone->bind_param("i", $loserID); $statementDethrone->execute(); $statementDethrone->close(); /* Crown the new club champion. */ $statementThrone = $this->connection->prepare ( "UPDATE player SET clubchamp = 1 WHERE elo = ?" ); $statementThrone->bind_param("i", $currentClubMax); $statementThrone->execute(); $statementThrone->close(); } } } }
true
e7bb2fab96f27327f1a5d8e450913b4f98aef9b1
PHP
libreforce/zend-glib
/src/DocBlock/AbstractDocBlock.php
UTF-8
767
2.59375
3
[]
no_license
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\GLib\DocBlock; use Zend\GLib\AbstractGenerator; abstract class AbstractDocBlock extends AbstractGenerator { public function format($text, $length=80, $decor=' * ') { $output = str_replace (PHP_EOL, ' ', $text); $output = wordwrap($output, $length, PHP_EOL); $lines = explode(PHP_EOL, $output); $glue = PHP_EOL . $decor; $output = $decor . implode($glue, $lines); return $output; } }
true
c5d70b2b2016232ed886defb472c709e393df8e9
PHP
josAlba/packlink
/src/Model/PostalCodeModel.php
UTF-8
2,388
2.609375
3
[ "Apache-2.0" ]
permissive
<?php namespace packlink\Model; use JMS\Serializer\Annotation\Type; use Symfony\Component\Serializer\Annotation\SerializedName; class PostalCodeModel { /** * @var string * @Type("string") * @SerializedName("id") */ private $id; /** * @var string * @Type("string") * @SerializedName("zipcode") */ private $zipcode; /** * @var string * @Type("string") * @SerializedName("zipcodeCity") */ private $zipcodeCity; /** * @var string * @Type("string") * @SerializedName("latitude") */ private $latitude; /** * @var string * @Type("string") * @SerializedName("longitude") */ private $longitude; /** * @var int * @Type("int") * @SerializedName("postalZoneId") */ private $postalZoneId; /** * @var PostalZoneModel * @Type("packlink\Model\PostalZoneModel") * @SerializedName("postalZone") */ private $postalZone; public function getPostalZone(): PostalZoneModel { return $this->postalZone; } public function setPostalZone(PostalZoneModel $postalZone): void { $this->postalZone = $postalZone; } public function getId(): string { return $this->id; } public function setId(string $id): void { $this->id = $id; } public function getZipcode(): string { return $this->zipcode; } public function setZipcode(string $zipcode): void { $this->zipcode = $zipcode; } public function getZipcodeCity(): string { return $this->zipcodeCity; } public function setZipcodeCity(string $zipcodeCity): void { $this->zipcodeCity = $zipcodeCity; } public function getLatitude(): string { return $this->latitude; } public function setLatitude(string $latitude): void { $this->latitude = $latitude; } public function getLongitude(): string { return $this->longitude; } public function setLongitude(string $longitude): void { $this->longitude = $longitude; } public function getPostalZoneId(): int { return $this->postalZoneId; } public function setPostalZoneId(int $postalZoneId): void { $this->postalZoneId = $postalZoneId; } }
true
a2d92953723d929f4180df579fd14ff76f75429c
PHP
daoyazi/cos-php-sdk
/samples/Common.php
UTF-8
2,498
2.6875
3
[ "MIT" ]
permissive
<?php if (is_file(__DIR__ . '/../autoload.php')) { require_once __DIR__ . '/../autoload.php'; } if (is_file(__DIR__ . '/../vendor/autoload.php')) { require_once __DIR__ . '/../vendor/autoload.php'; } require_once __DIR__ . '/Config.php'; use COS\CosClient; use COS\Core\CosException; /** * 断言回调函数,抛出异常 */ function assert_callcack() { throw new Exception("assert error"); } // Set our assert options assert_options(ASSERT_WARNING, true); assert_options(ASSERT_CALLBACK, 'assert_callcack'); /** * Class Common * * 示例程序【Samples/*.php】 的Common类,用于获取CosClient实例和其他公用方法 */ class Common { /** * 根据Config配置,得到一个CosClient实例 * * @return CosClient 一个CosClient实例 */ public static function getCosClient() { $config = new Config(); try { $cosClient = new CosClient($config->COS_ACCESS_ID, $config->COS_ACCESS_KEY, $config->COS_ENDPOINT); } catch (CosException $e) { printf(__FUNCTION__ . "creating CosClient instance: FAILED\n"); printf($e->getMessage() . "\n"); assert(0); } return $cosClient; } public static function getBucketName() { $config = new Config(); return $config->COS_TEST_BUCKET; } /** * 工具方法,创建一个存储空间,如果发生异常直接exit */ public static function createBucket() { $cosClient = self::getCosClient(); if (is_null($cosClient)) exit(1); $bucket = self::getBucketName(); $acl = CosClient::COS_ACL_TYPE_PUBLIC_READ; try { $cosClient->createBucket($bucket, $acl); } catch (CosException $e) { $message = $e->getMessage(); if (\COS\Core\CosUtil::startsWith($message, 'http status: 403')) { echo "Please Check your AccessKeyId and AccessKeySecret" . "\n"; exit(0); } elseif (strpos($message, "BucketAlreadyOwnedByYou") !== false) { print("BucketAlreadyOwnedByYou\n"); return; } printf(__FUNCTION__ . ": FAILED\n"); printf($e->getMessage() . "\n"); assert(0); } print(__FUNCTION__ . ": OK" . "\n"); } public static function println($message) { if (!empty($message)) { echo strval($message) . "\n"; } } }
true
01b948230ff58a6382538b218ea679f461063cac
PHP
nidhinvaishnavam/Tasks
/app/Http/Controllers/ProjectTaskController.php
UTF-8
2,469
2.71875
3
[]
no_license
<?php namespace App\Http\Controllers; use App\Task; use App\Beverage; use Illuminate\Http\Request; class ProjectTaskController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Beverage $project) { // Task::create([ // 'beverage_id'=>$project->id, // 'description'=>request('description')]); // return back();// //old method //new method $attributes=request()->validate(['description'=>'required']); $project->addTask($attributes); return back(); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Task $task) { // if(request->has('completed')){ // $task->complete(); // } // else{ // $task->incomplete(); // } //this is one method // request()->has('completed')? $task->complete():$task->incomplete(); //this is another method of function calling $method=request()->has('completed')?'complete':'incomplete'; $task->$method(); return back(); //this is third method } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } public function use(Request $request) { dd($request->nidhin); } public function useMe() { dd(1); } }
true
72cab79e44e0d68064acf024721e7958273c71ef
PHP
ExaByt3s/yueyue_repo
/mobile_app/protocol_methods.func.php
GB18030
4,905
2.65625
3
[]
no_license
<?php /** * APIӿ * * @author willike <chenwb@yueus.com> * @since 2015/10/12 9:56 */ if (!function_exists('interface_content_replace_pics')) { /** * 滻 ͼеͼƬ * * @param string $contents * @param int $size ߴ * @return string */ function interface_content_replace_pics($contents, $size = 640) { $size = intval($size); if ($size < 0 || empty($contents)) { return $contents; } $match = array(); preg_match_all('/http[s]?:\/\/[^"]+/', $contents, $match); if (empty($match)) { return $contents; } foreach ($match[0] as $value) { if (strpos($value, '.poco.cn') === FALSE && strpos($value, '.yueus.com') === FALSE) { continue; } $ext = pathinfo($value, PATHINFO_EXTENSION); if (($offset = strpos($ext, '?')) > 0) { $ext = substr($ext, 0, $offset); } $ext = strtolower($ext); if (!in_array($ext, array('jpg', 'jpeg', 'gif', 'png'))) { // ͼƬļ continue; } // ߴ滻 $new = yueyue_resize_act_img_url($value, $size); $contents = str_replace($value, $new, $contents); } return $contents; } } if (!function_exists('interface_html_decode')) { /** * htmlʵ ת * * @param string $str * @return string */ function interface_html_decode($str) { $reg = array( '&lt;', '&gt;', '&quot;', '&nbsp;', '&#160;', '&#032', '&#124;', '&#036;', '&#33;', '&#39;', '&#092;', '&#60;', '&#62;', ); $rpl = array( '<', '>', '"', ' ', ' ', ' ', '|', '$', '!', '\'', '\\', '<', '>', ); $str = str_replace($reg, $rpl, $str); return trim($str); } } if (!function_exists('interface_ubb_encode')) { /** * html ת ubb ʽ * * @param string $str * @return string */ function interface_ubb_encode($str) { if (empty($str)) { return FALSE; } $reg = array( '/\<a[^>]+href="mailto:(\S+)"[^>]*\>(.*?)<\/a\>/i', // Email '/\<a[^>]+href=\"([^\"]+)\"[^>]*\>(.*?)<\/a\>/i', '/\<img[^>]+src=\"([^\"]+)\"[^>]*\>/i', '/\<div[^>]+align=\"([^\"]+)\"[^>]*\>(.*?)<\/div\>/i', '/\<([\/]?)u\>/i', '/\<([\/]?)em\>/i', '/\<([\/]?)strong\>/i', '/\<([\/]?)b[^(a|o|>|r)]*\>/i', '/\<([\/]?)i\>/i', '/&amp;/i', '/&lt;/i', '/&gt;/i', '/&nbsp;/i', '/\s+/', '/&#160;/', // '/\<p[^>]*\>/i', '/\<br[^>]*\>/i', '/\<[^>]*?\>/i', '/\&#\d+;/', // ); $rpl = array( '[email=$1]$2[/email]', '[url=$1]$2[/url]', '[img]$1[/img]', '[align=$1]$2[/align]', '[$1u]', '[$1I]', '[$1b]', '[$1b]', '[$1i]', '&', '<', '>', ' ', ' ', ' ', "\r\n", "\r\n", '', '', ); $str = preg_replace($reg, $rpl, $str); return trim($str); } } if (!function_exists('interface_grab_content_images')) { /** * ȡ еͼƬ * * @param string $contents * @param int $size ޸ͼƬߴ * @param boolean $check_domain ͼƬ֤ * @return array */ function interface_grab_content_images($contents, $size = 0, $check_domain = true) { $match = array(); preg_match_all('/http[s]?:\/\/[^"]+/', $contents, $match); if (empty($match)) { return $contents; } $size = intval($size); $check_domain == ($check_domain === false) ? false : true; $images = array(); foreach ($match[0] as $value) { if ($check_domain && strpos($value, '.poco.cn') === FALSE && strpos($value, '.yueus.com') === FALSE) { continue; } $ext = pathinfo($value, PATHINFO_EXTENSION); if (($offset = strpos($ext, '?')) > 0) { $ext = substr($ext, 0, $offset); } if (!in_array(strtolower($ext), array('jpg', 'jpeg', 'gif', 'png'))) { // ͼƬļ continue; } // ߴ滻 if ($size > 0) { $value = yueyue_resize_act_img_url($value, $size); } $images[] = $value; } return $images; } }
true
b3ccb8fb6558f62634385f46dad9622cd723e364
PHP
oscarotero/letrag
/www/includes/comun/include_erros.php
UTF-8
1,114
3.109375
3
[]
no_license
<?php defined('OK') or die(); /* CONTROL DE ERROS Almacena todos os erros que haxa nas distintas clases v.1.0 */ class Erros { var $erros = array(); var $arquivo; //Engade un novo erro function erro ($texto) { $rexistro = debug_backtrace(); $rexistro[1]['erro'] = $texto; $rexistro[1]['data'] = date('Y/m/d H:i:s'); array_push($this->erros, $rexistro[1]); } //Imprimir todos os erros function imprimir () { foreach ($this->erros as $clave => $valor) { print('<p>'.$valor['erro']."</p> \n"); } } //Especifica un arquivo de texto para gardar os erros function arquivo ($arquivo) { $this->arquivo = $arquivo; } //Garda os erros nun arquivo de texto function gardar () { if ($this->erros) { foreach ($this->erros as $clave => $valor) { $texto .= '<p>'.$valor['erro']."</p> \n"; } if (is_file($this->arquivo)) { $abrir = fopen($this->arquivo,'a+'); } else { $abrir = fopen($this->arquivo,'w'); } flock($abrir, LOCK_EX); fwrite($abrir, addslashes($texto)); flock($abrir, LOCK_UN); fclose($abrir); } } } $erros = new Erros; ?>
true
0704a9fda64edac49b52f20f0ad0b098bfd65146
PHP
BetsyMcPhail/CDash
/tests/test_localheader.php
UTF-8
2,896
2.5625
3
[]
no_license
<?php // // After including cdash_test_case.php, subsequent require_once calls are // relative to the top of the CDash source tree // require_once dirname(__FILE__) . '/cdash_test_case.php'; require_once 'include/common.php'; require_once 'include/pdo.php'; class OverrideHeaderTestCase extends KWWebTestCase { public function __construct() { parent::__construct(); $this->ConfigFile = dirname(__FILE__) . '/../config/config.local.php'; } public function testEnableConfigSetting() { $contents = file_get_contents($this->ConfigFile); $handle = fopen($this->ConfigFile, 'w'); $lines = explode("\n", $contents); foreach ($lines as $line) { if (strpos($line, 'CDASH_USE_LOCAL_DIRECTORY') !== false) { fwrite($handle, "\$CDASH_USE_LOCAL_DIRECTORY = '1';\n"); } elseif ($line != '') { fwrite($handle, "$line\n"); } } fclose($handle); } public function testOverrideHeader() { global $CDASH_ROOT_DIR; // Create a local header & footer. $dir_name = "$CDASH_ROOT_DIR/public/local/views"; if (!file_exists($dir_name)) { mkdir($dir_name); } touch("$CDASH_ROOT_DIR/public/local/views/header.html"); touch("$CDASH_ROOT_DIR/public/local/views/footer.html"); // Verify that these are used. $this->get($this->url . '/api/v1/index.php?project=InsightExample'); $content = $this->getBrowser()->getContent(); $jsonobj = json_decode($content, true); if ($jsonobj['header'] !== 'local/views/header.html') { $this->fail('Expected local/views/header.html, found ' . $jsonobj['header']); $this->cleanup(); return 1; } if ($jsonobj['footer'] !== 'local/views/footer.html') { $this->fail('Expected local/views/footer.html, found ' . $jsonobj['footer']); $this->cleanup(); return 1; } $this->cleanup(); $this->pass('Passed'); return 0; } public function testRestoreConfigSetting() { $contents = file_get_contents($this->ConfigFile); $handle = fopen($this->ConfigFile, 'w'); $lines = explode("\n", $contents); foreach ($lines as $line) { if (strpos($line, 'CDASH_USE_LOCAL_DIRECTORY') !== false) { fwrite($handle, "\$CDASH_USE_LOCAL_DIRECTORY = '0';\n"); } elseif ($line != '') { fwrite($handle, "$line\n"); } } fclose($handle); } private function cleanup() { global $CDASH_ROOT_DIR; // Delete the local files that we created. unlink("$CDASH_ROOT_DIR/public/local/views/header.html"); unlink("$CDASH_ROOT_DIR/public/local/views/footer.html"); } }
true
f5be01c552d74cbcfb41db48f3cedff3d4d88c41
PHP
Genotroid/Yii2Blog
/console/migrations/m200323_145059_add_admin_and_roles.php
UTF-8
1,790
2.53125
3
[]
permissive
<?php use yii\db\Migration; /** * Class m200323_145059_add_admin_and_roles */ class m200323_145059_add_admin_and_roles extends Migration { /** * {@inheritdoc} */ public function safeUp() { //Роль для автора, может добавлять и редактировать статьи $this->insert('auth_item', [ 'name' => 'author', 'type' => 1, 'created_at' => time(), 'updated_at' => time() ]); //Роль для админа, может все $this->insert('auth_item', [ 'name' => 'admin', 'type' => 1, 'created_at' => time(), 'updated_at' => time() ]); //Добавление пользователя с доступами administrator/administrator, необходим для тестирования $this->insert('user', [ 'id' => 1, 'username' => 'administrator', 'email' => 'admin@admin.com', 'password_hash' => '$2y$10$5wDxUa2kDgTWDyJYVQrEKOFthUlAjR/ffxJ6o8trG1VTNuT.21BWG', 'auth_key' => 'KctHxMNHqXe-am9kRK8eLGMlpvb6BLfn', 'confirmed_at' => time(), 'created_at' => time(), 'updated_at' => time() ]); //Связываем пользователя administrator и роль admin $this->insert('auth_assignment', [ 'item_name' => 'admin', 'user_id' => 1, 'created_at' => time() ]); } /** * {@inheritdoc} */ public function safeDown() { $this->delete('auth_item', [ 'name' => 'author' ]); $this->delete('auth_item', [ 'name' => 'admin' ]); $this->delete('user', [ 'id' => 1 ]); } }
true
cbc0f824939e8528c2b5e99aa1faf055abff1fb8
PHP
phpgears/event
/src/AbstractEmptyEvent.php
UTF-8
2,668
2.859375
3
[ "MIT" ]
permissive
<?php /* * event (https://github.com/phpgears/event). * Event handling. * * @license MIT * @link https://github.com/phpgears/event * @author Julián Gutiérrez <juliangut@gmail.com> */ declare(strict_types=1); namespace Gears\Event; use Gears\Event\Exception\EventException; use Gears\Event\Time\SystemTimeProvider; use Gears\Event\Time\TimeProvider; /** * Abstract empty immutable event. */ abstract class AbstractEmptyEvent implements Event { use EventBehaviour; /** * AbstractEmptyEvent constructor. * * @param \DateTimeImmutable $createdAt */ private function __construct(\DateTimeImmutable $createdAt) { $this->assertImmutable(); $this->createdAt = $createdAt->setTimezone(new \DateTimeZone('UTC')); } /** * {@inheritdoc} */ public function getEventType(): string { return static::class; } /** * Instantiate new event. * * @param TimeProvider $timeProvider * * @return mixed|self */ final protected static function occurred(?TimeProvider $timeProvider = null) { $timeProvider = $timeProvider ?? new SystemTimeProvider(); return new static($timeProvider->getCurrentTime()); } /** * {@inheritdoc} * * @return mixed|self * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public static function reconstitute(array $payload, \DateTimeImmutable $createdAt, array $attributes) { $event = new static($createdAt); if (isset($attributes['metadata'])) { $event->addMetadata($attributes['metadata']); } return $event; } /** * @return array<string, mixed> */ final public function __serialize(): array { throw new EventException(\sprintf('Event "%s" cannot be serialized.', static::class)); } /** * @param array<string, mixed> $data * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ final public function __unserialize(array $data): void { throw new EventException(\sprintf('Event "%s" cannot be unserialized.', static::class)); } /** * @return string[] */ final public function __sleep(): array { throw new EventException(\sprintf('Event "%s" cannot be serialized.', static::class)); } final public function __wakeup(): void { throw new EventException(\sprintf('Event "%s" cannot be unserialized.', static::class)); } /** * {@inheritdoc} * * @return string[] */ final protected function getAllowedInterfaces(): array { return [Event::class]; } }
true
b451cd59a4d1abcf16339af71d9e91f4af13f3f2
PHP
AndrewTachilin/Paysera-test
/tests/Unit/Services/Wallet/MathOperationsTest.php
UTF-8
1,379
2.890625
3
[]
no_license
<?php declare(strict_types=1); namespace Tests\Unit\Services\Wallet; use App\Services\Wallet\MathOperations; use Tests\TestCase; class MathOperationsTest extends TestCase { private MathOperations $mathOperations; public function setUp(): void { parent::setUp(); $this->mathOperations = new MathOperations(); } public function testCalculateCommissionReturnCommission(): void { $fromAmount = '1000'; $percent = '10'; $result = $this->mathOperations->calculateCommission($fromAmount, $percent, 4); $this->assertEquals(100, $result); } public function testCalculateCommissionReturnCommissionWithFloat(): void { $fromAmount = '10'; $percent = '0.1'; $result = $this->mathOperations->calculateCommission($fromAmount, $percent, 4); $this->assertEquals('0.0100', $result); } public function testConvertCurrencyReturnInt(): void { $currency = '10.00'; $rate = '5'; $result = $this->mathOperations->convertCurrency($currency, $rate); $this->assertEquals(50, $result); } public function testRoundToThousandthsWithBelowFiveValueReturnHigherValue(): void { $number = '10.123'; $result = $this->mathOperations->roundToThousandths($number); $this->assertEquals(10, $result); } }
true
b21b3eda09408fc3ccf79145386c0c94607db864
PHP
marneicardoso/Agenda-PHP-MVC
/controller/contatoController.php
UTF-8
1,963
3.234375
3
[]
no_license
<?php // Sempre devemos verificar se um objeto // ou variável NÃO é null, antes de utilizá-los if (isset($_POST['btnCadastrarContato'])) { cadastrar(); } elseif (isset($_POST['editar'])) { editar(); } elseif (isset($_POST['excluir'])) { excluir(); } elseif (isset($_POST['btnBuscarContato'])) { buscar(); } else { header('Location: ../view/home.php'); } // PSR - function e class a abertura do bloco é embaixo function cadastrar() { // Inclui os arquivos (Model) require_once "../model/Contato.php"; require_once "../model/ContatoService.php"; // Guarda os dados informados no formulário //$nome = $_POST['nome']; //$fone = $_POST['fone']; //$email = $_POST['email']; // Cria o objeto das classes Contato e ContatoService $contato = new Contato(); $service = new ContatoService(); // Preenche o objeto com os dados informados $contato->nome = $_POST['nome']; $contato->fone = $_POST['fone']; $contato->email = $_POST['email']; $service->cadastrarContato($contato); } function editar() { } function excluir() { } function buscar() { // Inclui o arquivo (Model) require_once "../model/ContatoService.php"; // Cria o objeto da classe ContatoService $service = new ContatoService(); $resultado = $service->buscarContato($_POST['campo'], $_POST['tipo']); if ($resultado->num_rows > 0) { ?> <table style="border: solid 1px"> <?php while ($row = mysqli_fetch_assoc($resultado)) { ?> <tr> <td style="border: solid 1px"><?= $row['id'] ?></td> <td style="border: solid 1px"><?= $row['nome'] ?></td> <td style="border: solid 1px"><?= $row['email'] ?></td> <td style="border: solid 1px"><?= $row['senha'] ?></td> <tr> <?php } ?> </table> <?php } }
true
b77bb8178d788566e26da9415c137765489e4d60
PHP
ChrisStyles99/php-library-app
/class/bookClass.php
UTF-8
1,254
2.90625
3
[]
no_license
<?php include('dbClass.php'); class Book extends DB { public function getBooks() { $sql = 'SELECT * FROM books'; $stmt = $this->connect()->prepare($sql); $stmt->execute(); $books = $stmt->fetchAll(); return $books; } public function getProfileBooks($user_id) { $sql = 'SELECT * FROM books WHERE user_id = ?'; $stmt = $this->connect()->prepare($sql); $stmt->execute(array($user_id)); $books = $stmt->fetchAll(); return $books; } public function getSingleBook($id) { $sql = 'SELECT * FROM books where id = ?'; $stmt = $this->connect()->prepare($sql); $stmt->execute(array($id)); $book = $stmt->fetch(); return $book; } public function reserveBook($id, $user_id) { $sql = 'UPDATE books SET available = 0, user_id = ? WHERE id = ?'; $stmt = $this->connect()->prepare($sql); $stmt->execute(array($user_id, $id)); return "You lended the book!"; } public function returnBook($id) { $sql = 'UPDATE books SET available = 1, user_id = NULL WHERE id = ?'; $stmt = $this->connect()->prepare($sql); $stmt->execute(array($id)); return "You successfully returned the book!"; } }
true
c59ac083378c09891323f68d99dc6f7dcfc077a5
PHP
noxeternal/vgi-jsonrpc
/public/api/styles.php
UTF-8
564
2.890625
3
[]
no_license
<?php header("Content-type: text/css; charset: UTF-8"); require_once('../../lib/init.php'); $sql = "SELECT * FROM style ORDER BY styleName"; $result = $db->query($sql); function formatClassName ($s) { return str_replace(' ', '_', $s); } function formatStyle ($s) { $split = explode(';', $s); $style = []; for($i=0; $i<count($split)-1;$i++) { $style[] = ' '.$split[$i]; } $style = implode(";\n", $style); return $style; } foreach($result as $row) echo '.',formatClassName($row['styleName'])," {\n",formatStyle($row['styleText']),";\n}\n";
true
7a6452a23015a07cb88995da41f134a876e8ebe2
PHP
Jean-BaptisteL/PHP
/partie3/exo6/index.php
UTF-8
282
3.140625
3
[]
no_license
<?php $number = 20; ?> <!DOCTYPE html> <html lang="fr" dir="ltr"> <head> <meta charset="utf-8"> <title>Exercice 6</title> </head> <body> <?php for ($number = 20; $number >= 0; $number--) { ?> <p>C'est presque bon</p> <?php } ?> </body> </html>
true
e0c9abbc3bbb316a4f9d7f965ce99e60c0b4de55
PHP
Deeptirajput59/Functions-and-Control-Structures
/ConditionalScript.php
UTF-8
576
3.0625
3
[]
no_license
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>ConditionalScript</title> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> </head> <body> <p> <?php $IntVariable = 75; if($IntVariable > 100) { $Result = '$IntVariable is greater than 100</br>'; } else { $Result = '$IntVariable is less than 100'; } echo "<font color = 'Red'><b><i><p>$Result</p></i></b></font>"; ?> </p> </body> </html>
true
c228f08b91726ba7b21693314efb000b4323343f
PHP
Yasaminm/ajax_cities
/insertCity.php
UTF-8
1,464
2.71875
3
[]
no_license
<?php //sleep(10); //echo 1; require_once './config.php'; require_once './classes/DbClass.php'; require_once './classes/FilterForm.php'; require_once './classes/DbClassExt.php'; require_once './data.php'; try { //DB connection: $db = new DbClassExt('mysql:host=' . HOST . ';dbname=' . DB , USER, PASSWORD); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $exc) { echo $exc->getCode(); } $f = new FilterForm(); $f->setFilter('country', FILTER_SANITIZE_STRING, 'iso3'); $f->setFilter('city', FILTER_SANITIZE_STRING); $f->setFilter('province', FILTER_SANITIZE_STRING); $f->setFilter('lat', FILTER_VALIDATE_FLOAT); $f->setFilter('lng', FILTER_VALIDATE_FLOAT); $f->setFilter('pop', FILTER_VALIDATE_FLOAT); $data = $f->filter(INPUT_POST); $db->setTable('tb_cities'); $db->setColumns('iso2, country'); $db->setStatement('DISTINCT'); $where = sprintf("iso3='%s' AND province='%s'",$data['iso3'], $data['province']); $db->setWhere($where); $countryData = $db->getData(); if (count($countryData) !== 1) { echo -1; exit(); } $data['country'] = $countryData[0]['country']; $data['iso2'] = $countryData[0]['iso2']; //var_dump($countryData); //var_dump($data); if(count($data) >= 5){ if($db->insert($data) > 0){ echo 1; }else { echo -1; } }else { echo -1; }
true
d9e15bb7b6b645f34a7586c93d9e7bdd1ae601fc
PHP
Stolz/DockerLumen
/lumen/app/Models/Route.php
UTF-8
4,953
3.421875
3
[ "MIT" ]
permissive
<?php namespace App\Models; class Route extends Model { /** * Possible status of the route. * * @const string */ const STATUS_UNPROCESSED = 'pending'; const STATUS_PROCESSING = 'in progress'; const STATUS_SUCCESSFUL = 'success'; const STATUS_FAILED = 'failure'; /** * Token that identifies the route. * * @var string */ protected $token; /** * Current status of the route. * * @var string */ protected $status = self::STATUS_UNPROCESSED; /** * List of locations (latitude, longitude) of the route. * First item on the list is the start location. * * @var array */ protected $path = []; /** * Total route distance (in meters) after following the shortest driving path. * * @var int */ protected $totalDistance; /** * Total route time (in seconds) after following the shortest driving path. * * @var int */ protected $totalTime; /** * Last calculation error. * * @var string */ protected $error; /** * Set the token of the route. * * @param string $token * * @return self */ public function setToken(string $token): self { // Set token $this->token = $token; // Allow method chaining return $this; } /** * Set the status of the route. * * @param string $status * * @return self * * @throws \InvalidArgumentException */ public function setStatus(string $status): self { // Normalize status name $status = strtolower($status); // Validate status $validStatus = [ static::STATUS_UNPROCESSED, static::STATUS_PROCESSING, static::STATUS_SUCCESSFUL, static::STATUS_FAILED, ]; if (! in_array($status, $validStatus, true)) { throw new \InvalidArgumentException('Invalid status'); } // Set status $this->status = $status; // Allow method chaining return $this; } /** * Set the path of the route. * * @param array $path * * @return self * * @throws \InvalidArgumentException */ public function setPath(array $path): self { // Validate path if (count($path) < 2) { throw new \InvalidArgumentException('Invalid path'); } // Set path $this->path = $path; // Allow method chaining return $this; } /** * Set the total distance of the route. * * @param int $distance * * @return self */ public function setTotalDistance(int $distance): self { // Set distance $this->totalDistance = $distance; // Allow method chaining return $this; } /** * Set the total time of the route. * * @param int $time * * @return self */ public function setTotalTime(int $time): self { // Set distance $this->totalTime = $time; // Allow method chaining return $this; } /** * Set the last error of the route. * * @param string|null $error * * @return self */ public function setError($error): self { // Set error $this->error = $error; // Allow method chaining return $this; } /** * Get the token of the route. * * @return string|null */ public function getToken() { return $this->token; } /** * Get the status of the route. * * @return string */ public function getStatus(): string { return $this->status; } /** * Get the path of the route. * * @return array */ public function getPath(): array { return $this->path; } /** * Get the total distance of the route. * * @return int|null */ public function getTotalDistance() { return $this->totalDistance; } /** * Get the total time of the route. * * @return int|null */ public function getTotalTime() { return $this->totalTime; } /** * Get the last calculation error. * * @return string|null */ public function getError() { return $this->error; } /** * Convert the route to its array representation. * * @return array */ public function toArray(): array { return [ 'token' => $this->getToken(), 'status' => $this->getStatus(), 'path' => $this->getPath(), 'total_distance' => $this->getTotalDistance(), 'total_time' => $this->getTotalTime(), 'error' => $this->getError(), ]; } }
true
d5d278729d7737d9ce90882094744b305510aa80
PHP
NickKalar/database_project
/helpers.php
UTF-8
8,402
2.734375
3
[]
no_license
<?php // //CONNECT_TO_DATABASE/////////////////////////////////// $server = 'localhost'; $user = 'nkalar'; $password = 'edwinblue'; $database = 'nkalar'; $db = new mysqli($server, $user, $password, $database); if($db->connect_error) { exit("Bad Connection\n"); } else { // DEVELOPMENT // echo "We're connected<br>"; } function isActive() { if(isset($_SESSION['active']) ){ return($_SESSION['active']); } return(false); } function sanitize($var) { return(htmlentities(strip_tags(trim($var)), ENT_QUOTES)); } function add($sql) { global $db; if($db->query($sql) === TRUE) echo "<strong>Added</strong>"; else echo "error"; } function remove($sql) { global $db; if($db->query($sql) === TRUE) echo "<strong>Removed</strong>"; else echo "error"; } function getLastId($id, $table ) { global $db; $query = "SELECT MAX($id) FROM $table"; $result2 = mysqli_query($db, $query); while($row2 = mysqli_fetch_array($result2)) { $id = $row2[0]; } return $id+1; } function ddMenu($type) { global $db; switch($type) { case "status": $query = "SELECT * FROM Status"; $result2 = mysqli_query($db, $query); $dropdown = ""; echo "Select Status: "; echo "<select name = 'Status'>"; echo "<option value='0" . "'>" . "</option>"; while($row2 = mysqli_fetch_array($result2)) { // $dropdown .= "<div class='custom-select'>"; $dropdown = $dropdown."<option value='" . $row2[0] . "'>" . $row2[1] . "</option>"; } echo $dropdown; echo "</select><br><br>"; break; case "payload": $query = "SELECT * FROM Payload NATURAL JOIN Trailer ORDER BY LoadID"; $result2 = mysqli_query($db, $query); $dropdown = ""; echo "Select Payload: "; echo "<select name = 'Payload'>"; while($row2 = mysqli_fetch_array($result2)) { $dropdown = $dropdown."<option value='" . $row2[1] . "'>". $row2[2] . " ". $row2[3] . ", " . $row2[4] ."</option>"; } echo $dropdown; echo "</select>"; break; case "position": $query = "SELECT * FROM Position"; $result2 = mysqli_query($db, $query); $dropdown = ""; echo "Select Position: "; echo "<select name = 'PositionID'>"; while($row2 = mysqli_fetch_array($result2)) { $dropdown = $dropdown."<option value='$row2[0]'> $row2[1]</option>"; } echo $dropdown; echo "</select>"; break; case "supervisor": $query = "SELECT EmployeeID,Fname, Lname FROM Employee WHERE PositionID = 5"; $result2 = mysqli_query($db, $query); $dropdown = ""; echo "Select Supervisor: "; echo "<select name = 'SupervisorID'>"; while($row2 = mysqli_fetch_array($result2)) { $dropdown = $dropdown."<option value='$row2[0]'> $row2[1]" . " " . $row2[2] . "</option>"; } echo $dropdown; echo "</select>"; break; case "customer": $query = "SELECT * FROM Customer"; $result2 = mysqli_query($db, $query); $dropdown = ""; echo "Select Customer: "; echo "<select name = 'CustomerID'>"; echo "<option value='0" . "'>" . "</option>"; while($row2 = mysqli_fetch_array($result2)) { // $dropdown .= "<div class='custom-select'>"; $dropdown = $dropdown."<option value='" . $row2[0] . "'>" . $row2[1] . "</option>"; } echo $dropdown; echo "</select> "; // echo "<button onclick= \"location.href='customer.php'\" type=\"button\"> // Create Customer</button>"; break; case "destination": $dropdown = ""; $query = "SELECT * FROM Address"; $result2 = mysqli_query($db, $query); echo "Destination Address: "; echo "<select name = 'Destination'>"; while($row2 = mysqli_fetch_array($result2)) { $dropdown = $dropdown."<option value='" . $row2[0] . "'>" . $row2[1] ." ". $row2[2] . " ". $row2[3] . ", " . $row2[4] ."</option>"; } echo $dropdown; echo "</select> "; echo "<button onclick= \"location.href='address.php'\" type=\"button\">Create Address</button>"; break; case "pickup": $dropdown = ""; $query = "SELECT * FROM Address"; $result2 = mysqli_query($db, $query); echo "Pickup Address: "; echo "<select name = 'Pickup'>"; while($row2 = mysqli_fetch_array($result2)) { $dropdown = $dropdown."<option value='" . $row2[0] . "'>" . $row2[1] ." ". $row2[2] . " ". $row2[3] . ", " . $row2[4] ."</option>"; } echo $dropdown; echo "</select> "; echo "<button onclick= \"location.href='address.php'\" type=\"button\">Create Address</button>"; break; case "truck": $dropdown = ""; $query = "SELECT * FROM Truck NATURAL JOIN Trailer NATURAL JOIN Employee ORDER BY TruckID"; $result2 = mysqli_query($db, $query); echo "Select Truck: "; echo "<select name = 'TruckID'>"; while($row2 = mysqli_fetch_array($result2)) { $dropdown = $dropdown."<option value='" . $row2[2] . "'>" . $row2[3] ." ". $row2[4] . " ". $row2[8] . " ". $row2[9] . " " . $row2[7] ."</option>"; } echo $dropdown; echo "</select> "; echo "<button onclick= \"location.href='truck.php'\" type=\"button\">Create Truck</button>"; break; case "trailer": $query = "SELECT * FROM Trailer"; $result2 = mysqli_query($db, $query); $dropdown = ""; echo "Select Trailer: "; echo "<select name = 'TrailerID'>"; while($row2 = mysqli_fetch_array($result2)) { $dropdown = $dropdown."<option value='" . $row2[0] . "'>" . $row2[1] . "</option>"; } echo $dropdown; echo "</select>"; break; case "address": $dropdown = ""; $query = "SELECT * FROM Address"; $result2 = mysqli_query($db, $query); echo "Address: "; echo "<select name = 'AddressID'>"; while($row2 = mysqli_fetch_array($result2)) { $dropdown = $dropdown."<option value='" . $row2[0] . "'>" . $row2[1] ." ". $row2[2] . " ". $row2[3] . ", " . $row2[4] ."</option>"; } echo $dropdown; echo "</select> "; echo "<button onclick= \"location.href='address.php'\" type=\"button\">Create Address</button>"; break; case "employee": $query = "SELECT * FROM Employee"; $result2 = mysqli_query($db, $query); $dropdown = ""; echo "Select Employee: "; echo "<select name = 'EmployeeID'>"; while($row2 = mysqli_fetch_array($result2)) { $dropdown = $dropdown."<option value='" . $row2[0] . "'>" . $row2[1] ." ". $row2[2] . "</option>"; } echo $dropdown; echo "</select> "; echo "<button onclick= \"location.href='employee.php'\" type=\"button\"> Create Employee</button>"; break; } } //GLOBAL_VAR $db//////////////////////////////////////// ?>
true
f5c43ac9e6a952910ed7b5843598984da4cb4756
PHP
james9909/PracticeCTF
/ccse-ctf-2016/The-Future_100/solution.php
UTF-8
270
2.984375
3
[]
no_license
<?php $first = 391220580; $time = 1477459467; while (true) { mt_srand(($time - 42) ^ 42); $rand0 = mt_rand(); if ($rand0 === $first) { $rand1 = mt_rand(); $rand2 = mt_rand(); print $rand2; break; } $time += 1; } ?>
true
281d50e80cd7cfe7e63e8543cbf9581330d64803
PHP
ivanfadh/jgtc_epl
/app/SuitEvent/Models/Kecamatan.php
UTF-8
3,981
2.578125
3
[]
no_license
<?php namespace App\SuitEvent\Models; use RichanFongdasen\EloquentBlameable\BlameableTrait; use Suitcore\Models\SuitModel; /* |-------------------------------------------------------------------------- | all_kecamatan Table Structure |-------------------------------------------------------------------------- | * id INT(10) NOT NULL | * kabkota_id INT(10) UNSIGNED | * code INT(10) UNSIGNED NOT NULL | * shipment_area_code VARCHAR(16) NULL | * name VARCHAR(50) NOT NULL | * created_at TIMESTAMP | * updated_at TIMESTAMP */ class Kecamatan extends SuitModel { use BlameableTrait; // MODEL DEFINITION protected $primaryKey = 'id'; public $table = 'kecamatans'; protected static $bufferAttributeSettings = null; public $fillable = [ 'code', 'shipment_area_code', 'name', 'kabkota_id' ]; public $rules = [ 'code' => 'required', 'name' => 'required', 'kabkota_id' => 'required' ]; // RELATIONSHIP /** * Get the city of the kecamatan. * @return \App\SuitEvent\Models\City|null */ public function city() { return $this->belongsTo(City::class, 'kabkota_id'); } /** * Get kelurahans of the kecamatan. * @return \Illuminate\Database\Eloquent\Collection|static[] */ public function kelurahans() { return $this->hasMany(Kelurahan::class); } public function getLabel() { return 'Kecamatan'; } public function getFormattedValue() { return $this->name; } public function getOptions() { return self::all(); } public function getDefaultOrderColumn() { return 'name'; } public function getDefaultOrderColumnDirection() { return 'asc'; } public function getAttributeSettings() { // default attribute settings of generic model, override for furher use return [ 'id' => [ 'type' => self::TYPE_NUMERIC, 'visible' => true, 'formdisplay' => false, 'required' => true, 'relation' => null, 'label' => 'ID' ], 'kabkota_id' => [ 'type' => self::TYPE_NUMERIC, 'visible' => true, 'formdisplay' => true, 'required' => true, 'relation' => 'city', 'label' => 'Kab / Kota', 'options' => (new City)->all()->pluck('name', 'id'), ], 'name' => [ 'type' => self::TYPE_TEXT, 'visible' => true, 'formdisplay' => true, 'required' => true, 'relation' => null, 'label' => 'Kecamatan Name' ], 'code' => [ 'type' => self::TYPE_TEXT, 'visible' => true, 'formdisplay' => true, 'required' => true, 'relation' => null, 'label' => 'ID Kecamatan' ], 'shipment_area_code' => [ 'type' => self::TYPE_TEXT, 'visible' => true, 'formdisplay' => true, 'required' => false, 'relation' => null, 'label' => 'Shipment Area Code' ], 'created_at' => [ 'type' => self::TYPE_DATETIME, 'visible' => true, 'formdisplay' => false, 'required' => false, 'relation' => null, 'label' => 'Created At' ], 'updated_at' => [ 'type' => self::TYPE_DATETIME, 'visible' => true, 'formdisplay' => false, 'required' => false, 'relation' => null, 'label' => 'Updated At' ] ]; } }
true
1fb4d568e505c0bcde059a5b49570131e54bc7d2
PHP
Ocramius/PSR7Csrf
/test/PSR7CsrfTest/Exception/InvalidRequestParameterNameExceptionTest.php
UTF-8
893
2.59375
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace PSR7CsrfTest\Exception; use InvalidArgumentException; use PHPUnit\Framework\TestCase; use PSR7Csrf\Exception\ExceptionInterface; use PSR7Csrf\Exception\InvalidRequestParameterNameException; /** * @covers \PSR7Csrf\Exception\InvalidRequestParameterNameException */ final class InvalidRequestParameterNameExceptionTest extends TestCase { public function testFromEmptyRequestParameterName() { $exception = InvalidRequestParameterNameException::fromEmptyRequestParameterName(); self::assertInstanceOf(InvalidRequestParameterNameException::class, $exception); self::assertInstanceOf(InvalidArgumentException::class, $exception); self::assertInstanceOf(ExceptionInterface::class, $exception); self::assertSame('The given request parameter must be a non-empty string', $exception->getMessage()); } }
true
f761ae0b9d0397cb319296cd51576604c334e552
PHP
chenke91/MyForms
/validator.php
UTF-8
2,181
3.1875
3
[]
no_license
<?php abstract class Validator { protected $msg; public function __construct($args) { $this->msg = isset($args[0]) ? $args[0]:null; } abstract function run($form, $field); } class Required extends Validator { public function run($form, $field) { if (empty($field->data)) { $msg = $this->msg == null ? $field->name.' is required!':$this->msg; $field->error = $msg; return false; } return true; } } class Email extends Validator { public function run($form, $field) { $pattern = '/^.+@[^.].*\.[a-z]{2,10}$/'; if (!preg_match($pattern, $field->data)) { $msg = $this->msg == null ? $field->name.' require a email!':$this->msg; $field->error = $msg; return false; } return true; } } class EqualTo extends Validator { public function __construct($args) { $this->equal = isset($args[0]) ? $args[0]:null; $this->msg = isset($args[1]) ? $args[1]:null; if (!$this->equal) { throw new Exception("EqualTo validator need a equal field"); } } public function run($form, $field) { $equal = $this->equal; if ($field->data != $form->$equal->data) { $msg = $this->msg == null ? $field->name.' not equal to '.$form->$equal->data.'!':$this->msg; $field->error = $msg; return false; } return true; } } class Length extends Validator { public function __construct($args) { $this->lt = isset($args[0]) ? $args[0]:null; $this->gt = isset($args[1]) ? $args[1]:null; $this->msg = isset($args[2]) ? $args[2]:null; if (!$this->lt || !$this->gt) { throw new Exception("require begin & end number"); } } public function run($form, $field) { if (count($field->data) < $this->lt || count($field->data) > $this->gt) { $msg = $this->msg == null ? $field->name.' should be between '.$this->lt.' and '. $this->gt .'!':$this->msg; $field->error = $msg; return false; } return true; } }
true
52141b6bd9890410387bcde3092bb7d4c2023da7
PHP
leemour/Parcels
/src/LocaleLocales.php
UTF-8
415
2.84375
3
[]
no_license
<?php /** * Контент страницы * */ namespace Parcels; class LocaleLocales { public $uri = ''; public $class = ''; public function __construct($name, $active) { //не добавляем раздел 'ru' в URI if ($name != 'ru') $this->uri = '/' . $name; if ($active) { $this->class = 'active'; } } }
true
e6c1b5078ed285a8082ef608272d4a71dd394ba7
PHP
SergeyVityazev/resumePHP
/InheritanceAndIntrfeys/index.php
UTF-8
3,012
3.125
3
[]
no_license
<?php abstract class Product { private $weight; private $type; private $color; private $price; private $namemarket='MyMarket'; abstract public function Discount(); public function Comment(){ echo "<br>"; echo "<br>"; return 'Name - '.$this->namemarket; } public function Delivery($weight){ if ($weight>10){ return $this->Delivery=300; } else { return $this->Delivery=250; } } } interface iCars { public function Mileage(); public function State(); } interface iPEn{ public function Year(); } interface iDuck{ public function State(); } interface iTV{ public function Type(); } class Cars extends Product implements iCars { private $price; private $weight; private $brand; public function CarsMethod($price,$weight,$brand){ $this->price=$price; $this->weight=$weight; $this->brand=$brand; echo $this->market = parent::Comment(); echo "<br>"; echo $this->delivery = parent::Delivery($weight); echo "<br>"; echo $brand; } public function Discount() { // TODO: Implement Discount() method. } public function Mileage() { return 10000; // TODO: Implement Mileage() method. } public function State() { return "Germany"; // TODO: Implement Mileage() method. } } class Pen extends Product implements iPen { private $price; private $color; public function PenMethod($price,$color){ $this->price=$price; $this->color=$color; echo "<br>"; echo $this->market = parent::Comment(); } public function Discount() { // TODO: Implement Discount() method. } public function Year() { return "2018"; } } class Duck extends Product implements iDuck { private $price; private $state; public function DuckMethod($price,$state){ echo "<br>"; echo $this->price=$price; echo "<br>"; echo $this->state=$state; echo "<br>"; echo $this->market = parent::Comment(); } public function Discount() { // TODO: Implement Discount() method. } public function State() { return "USA"; } } class TV extends Product implements iTV { private $price; private $color; public function TVMethod($price,$color){ $this->price=$price; $this->color=$color; echo "<br>"; echo $this->market = parent::Comment(); } public function Discount() { // TODO: Implement Discount() method. } public function Type() { return "Samsung"; } } $BMV = new Cars; $BMV->CarsMethod(1000,5,"BMV"); $Audi = new Cars; $Audi->CarsMethod(2000,25,"Audi"); $Samsung=new TV; $Samsung->TVMethod(500,"white"); $Duck=new Duck; $Duck->DuckMethod(100,"grey"); $Pen=new Pen; $Pen->PenMethod(200,"red");
true
6568d03b4ecf7fa9476b3ea639bf9943035aa6fd
PHP
OUTRAGElib/psr7-file-stream
/lib/FileInterface.php
UTF-8
1,033
3.203125
3
[ "MIT" ]
permissive
<?php /** * Value object representing a file uploaded through an HTTP request. * * Instances of this interface are considered immutable; all methods that * might change state MUST be implemented such that they retain the internal * state of the current instance and return an instance that contains the * changed state. */ namespace OUTRAGElib\FileStream; use \Exception; use \Psr\Http\Message\StreamInterface as PsrStreamInterface; use \Psr\Http\Message\UploadedFileInterface as PsrUploadedFileInterface; interface FileInterface extends PsrUploadedFileInterface { /** * Set the stream which this uploaded file refers to. */ public function setStream(PsrStreamInterface $stream); /** * What is the error, as reported by PHP's upload functionality? */ public function setError($errno); /** * Set the filename of the upload in question */ public function setClientFilename($filename); /** * Set the MIME type of the upload in question */ public function setClientMediaType($media_type); }
true
8855a9227b636d1b7340b2163d15d48c5dec2177
PHP
wearesho-team/wearesho-notifications-repository-message-delivery
/tests/PushTest.php
UTF-8
1,688
2.5625
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace Wearesho\Notifications\MessageDelivery\Tests; use Wearesho\Notifications; use Wearesho\Delivery; use PHPUnit\Framework\TestCase; /** * Class PushTest * @package Wearesho\Notifications\MessageDelivery\Tests */ class PushTest extends TestCase { public function testNoRecipint(): void { $repository = new class implements Notifications\MessageDelivery\RecipientRepositoryInterface { public function find(int $id): ?string { return null; } }; $service = new Delivery\ServiceMock(); $push = new Notifications\MessageDelivery\Push($service, $repository); $push->push(new Notifications\Notification(1, 'Hello World!')); $this->assertCount(0, $service->getRepository()->getHistory()); } public function testSent(): void { $repository = new class implements Notifications\MessageDelivery\RecipientRepositoryInterface { public function find(int $id): ?string { return 'recipient'; } }; $service = new Delivery\ServiceMock(); $push = new Notifications\MessageDelivery\Push($service, $repository); $push->push(new Notifications\Notification(1, 'Hello {name}!', ['name' => 'World'])); /** @var Delivery\MessageInterface[] $history */ $history = $service->getRepository()->getHistory(); $this->assertCount(1, $history); $message = $history[0]; $this->assertEquals('Hello World!', $message->getText()); $this->assertEquals('recipient', $message->getRecipient()); } }
true
478a6210231a7fcf83d4ef19c7dd18cb49755419
PHP
Nydareld/ProjetVoxel
/src/ProjetVoxel/EconomyBundle/Entity/BankAccount.php
UTF-8
1,650
2.53125
3
[]
no_license
<?php namespace ProjetVoxel\EconomyBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * bankAccount * * @ORM\Table() * @ORM\Entity */ class BankAccount { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var boolean * * @ORM\Column(name="main", type="boolean") */ private $main = false; /** * @var string * * @ORM\Column(name="name", type="string", length=255) */ private $name; /** * @var integer * * @ORM\Column(name="amount", type="integer") */ private $amount; /** * @ORM\ManyToOne(targetEntity="BankId", inversedBy="bankAccount") */ private $owner; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set amount * * @param integer $amount * * @return bankAccount */ public function setAmount($amount) { $this->amount = $amount; return $this; } /** * Get amount * * @return integer */ public function getAmount() { return $this->amount; } public function getOwner(){ return $this->owner; } public function setOwner($owner){ $this->owner = $owner; } public function getName(){ return $this->name; } public function setName($name){ $this->name = $name; } public function isMain(){ return $this->main; } public function setMain($main){ $this->main = $main; } }
true
fa9f2111d5a6e5718816e25951355de1be53b948
PHP
emtiazzahid/php-ndjson
/test/ParserTest.php
UTF-8
785
2.65625
3
[ "MIT" ]
permissive
<?php namespace EmtiazZahid\Ndjson\Test; use PHPUnit\Framework\TestCase; use EmtiazZahid\Ndjson\Parser; class ParserTest extends TestCase { protected $file = 'test_sample.ndjson'; public function testDecode() { $base_path = dirname(__FILE__); $decode = Parser::decode($base_path . '/' . $this->file); $this->assertIsArray($decode); $this->assertCount(3, $decode); } public function testEncode() { $array = [ ['foo' => 'bar'], ['hello' => 'world'] ]; $encode = Parser::encode($array); $this->assertIsString($encode); $this->assertStringContainsString('{"foo":"bar"}', $encode); $this->assertStringContainsString('{"hello":"world"}', $encode); } }
true
771150a3eb4182ba0a1ba929f5e2852812c3866f
PHP
DylanBaine/teamup
/app/Notifications/Markup/MailMarkup.php
UTF-8
364
2.59375
3
[]
no_license
<?php namespace App\Notifications\Markup; use Illuminate\Notifications\Messages\MailMessage; abstract class MailMarkup { public abstract function from(); public function markup($type){ return call_user_func([$this, $type.'Markup']); } protected function mailMessage(){ return (new MailMessage)->from($this->from()); } }
true
e4fe61b0bee6461246dd6f08267c966aa684f40a
PHP
jamesk14022/Spotify-Widget
/sw_db.php
UTF-8
1,440
2.625
3
[]
no_license
<?php //pull latest auth and refresh tokens from the db - if they don't exist - //return false function sw_get_latest_tokens(){ global $wpdb; $table_name = $wpdb->prefix . 'sw_creds'; $row = $wpdb->get_row("SELECT * FROM $table_name ORDER BY id DESC LIMIT 1"); if(!isset($row)){ return false; }else{ return $row; } } //add newest refresh and auth token to table and delete the last entry function sw_insert_auth_row($auth_token, $refresh_token){ global $wpdb; $table_name = $wpdb->prefix . 'sw_creds'; //first delete any existing tokens sw_clear_tokens(); //insert new auth and request token $wpdb->insert($table_name, array('id' => '', 'auth_token' => $auth_token, 'refresh_token' => $refresh_token)); } //function to create table that the current auth and refresh tokens will be stored in function sw_create_table(){ global $wpdb; $table_name = $wpdb->prefix . 'sw_creds'; $charset_collate = $wpdb->get_charset_collate(); //crete table query $sql = "CREATE TABLE $table_name ( id mediumint(9) NOT NULL PRIMARY KEY AUTO_INCREMENT, auth_token text NOT NULL, refresh_token text NOT NULL ) $charset_collate;"; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); } //clears table of all previous tokens function sw_clear_tokens(){ global $wpdb; $table_name = $wpdb->prefix . 'sw_creds'; $wpdb->query("TRUNCATE $table_name"); } ?>
true
fd7cf33b79a9e22334095cf6f47b1f1c3c00fcb8
PHP
duocircle/remoteauth-php-sdk
/src/HttpClient.php
UTF-8
6,100
2.703125
3
[]
no_license
<?php namespace RemoteAuthPhp; use GuzzleHttp\Client as GuzzleClient; use GuzzleHttp\Exception\ClientException; use Psr\SimpleCache\CacheInterface; use Carbon\Carbon; class HttpClient { /** @var array */ private $options; /** @var GuzzleClient */ private $http; /** @var CacheInterface */ private $cache; /** @var bool */ private $attemptingRefresh = false; /** * Creates a new RemoteAuthPhp Client. * * @param array $options */ public function __construct( array $options = [], ?CacheInterface $cache = null, ?GuzzleClient $http = null ) { $this->options = $options; $this->cache = $cache; if (is_null($http)) { $http = new GuzzleClient(); } $this->http = $http; } /** * Performs a synchronous GET request to the given URL. * * Returns the response * * @param string $url * @param RemoteAuthUser $user * @return array */ public function get(string $url, RemoteAuthUser $user, ?bool $ignoreCache = false) { return $this->request('GET', $url, $user, null, $ignoreCache); } /** * Performs a synchronous POST request to the given URL. * * Returns the response * * @param string $url * @param RemoteAuthUser $user * @param array $payload * @return array */ public function post(string $url, RemoteAuthUser $user, ?array $payload = []) { return $this->request('POST', $url, $user, $payload); } /** * Performs a synchronous PUT request to the given URL. * * Returns the response * * @param string $url * @param RemoteAuthUser $user * @param array $payload * @return array */ public function put(string $url, RemoteAuthUser $user, ?array $payload = []) { return $this->request('PUT', $url, $user, $payload); } /** * Performs a synchronous DELETE request to the given URL. * * Returns the response * * @param string $url * @param RemoteAuthUser $user * @param array $payload * @return array */ public function delete(string $url, RemoteAuthUser $user, ?array $payload = []) { return $this->request('DELETE', $url, $user, $payload); } /** * Makes a HTTP request. * * Adds Authentication header for authenticating the user. * * @param string $method * @param string $url * @param RemoteAuthUser $user * @param array $payload * @return array */ public function request(string $method, string $url, RemoteAuthUser $user, ?array $payload = [], ?bool $ignoreCache = false) { try { $cacheKey = $this->getCacheKey($user, $method, $url, $payload); $isCacheAvailable = strtoupper($method) === 'GET' && !is_null($this->cache); if ($isCacheAvailable && !$ignoreCache && $this->cache->has($cacheKey)) { return $this->cache->get($cacheKey); } $response = $this->http->request($method, $url, [ 'headers' => [ 'Accept' => 'application/json', 'Authorization' => 'Bearer ' . $user->accessToken() ], 'json' => !empty($payload) ? $payload : null ]); } catch (ClientException $e) { if ($e->getCode() === 401 && !$this->attemptingRefresh) { // Request is unauthorized, use refresh token to get a new access token $this->attemptingRefresh = true; $response = $this->post( $this->options['baseUrl'] . '/oauth/token', $user, [ 'grant_type' => 'refresh_token', 'refresh_token' => $user->refreshToken(), 'client_id' => $this->options['clientId'], 'client_secret' => $this->options['clientSecret'], 'scope' => $this->options['scope'] ] ); if (isset($response['error'])) { throw new \Exception($response['message']); } $user->handleTokenRefresh( $response['id'], $response['access_token'], $response['refresh_token'], $response['expires_in'], $response['user']['email_verified_at'] ); $this->attemptingRefresh = false; return $this->request($method, $url, $user, $payload); } $errorMessage = 'An unknown error occurred.'; if ($e && $e->getResponse()) { $errorMessage = (string)$e->getResponse()->getBody(); } return [ 'error' => true, 'message' => $errorMessage ]; } $responseBody = null; if ($response) { $responseBody = (string)$response->getBody(); } $result = json_decode($responseBody, true); if ($isCacheAvailable) { $this->cache->set($cacheKey, $result, Carbon::now()->addHour(1)); } return $result; } /** * Helper function to generate the URL to call. * * @param string $url * @return string */ public function url(string $url) { return $this->options['baseUrl'] . '/api/v1/' . $url; } /** * Builds the cache key for caching GET requests. * * @param RemoteAuthUser $user * @param string $method * @param string $url * @param array $payload * @return string */ public function getCacheKey(RemoteAuthUser $user, string $method, string $url, ?array $payload = []) { return md5($user->remoteAuthUserId() . '-' . $method . '-' . $url . '-' . json_encode($payload)); } }
true
50b90311c1c2ac9f74e6e7297c104718447c2e37
PHP
leifos-gmbh/4_2_lm_overlay
/Services/Form/classes/class.ilNestedListInputGUI.php
UTF-8
2,752
2.734375
3
[]
no_license
<?php /* Copyright (c) 1998-2010 ILIAS open source, Extended GPL, see docs/LICENSE */ include_once 'Services/UIComponent/Toolbar/interfaces/interface.ilToolbarItem.php'; /** * This class represents a (nested) list of checkboxes (could be extended for radio items, too) * * @author Alex Killing <alex.killing@gmx.de> * @version $Id$ * @ingroup ServicesForm */ class ilNestedListInputGUI extends ilFormPropertyGUI { protected $value = "1"; protected $checked; protected $list_nodes = array(); /** * Constructor * * @param string $a_title Title * @param string $a_postvar Post Variable */ function __construct($a_title = "", $a_postvar = "") { parent::__construct($a_title, $a_postvar); $this->setType("nested_list"); include_once("./Services/UIComponent/NestedList/classes/class.ilNestedList.php"); $this->list = new ilNestedList(); } /** * Add list node * * @param */ function addListNode($a_id, $a_text, $a_parent = 0, $a_checked = false, $a_disabled = false, $a_img_src = "", $a_img_alt = "", $a_post_var = "") { $this->list_nodes[$a_id] = array("text" => $a_text, "parent" => $a_parent, "checked" => $a_checked, "disabled" => $a_disabled, "img_src" => $a_img_src, "img_alt" => $a_img_alt, "post_var" => $a_post_var); } /** * Set Value. * * @param string $a_value Value */ function setValue($a_value) { $this->value = $a_value; } /** * Get Value. * * @return string Value */ function getValue() { return $this->value; } /** * Set value by array * * @param object $a_item Item */ function setValueByArray($a_values) { // $this->setChecked($a_values[$this->getPostVar()]); // foreach($this->getSubItems() as $item) // { // $item->setValueByArray($a_values); // } } /** * Check input, strip slashes etc. set alert, if input is not ok. * * @return boolean Input ok, true/false */ function checkInput() { global $lng; return true; } /** * Render item */ function render() { foreach ($this->list_nodes as $id => $n) { if ($n["post_var"] == "") { $post_var = $this->getPostVar()."[]"; $value = $id; } else { $post_var = $n["post_var"]; $value = $id; } $item_html = ilUtil::formCheckbox($n["checked"], $post_var, $value, $n["disabled"]); if ($n["img_src"] != "") { $item_html.= ilUtil::img($n["img_src"], $n["img_alt"])." "; } $item_html.= $n["text"]; $this->list->addListNode($item_html, $id, $n["parent"]); } return $this->list->getHTML(); } /** * Insert property html * * @return int Size */ function insert(&$a_tpl) { $html = $this->render(); $a_tpl->setCurrentBlock("prop_generic"); $a_tpl->setVariable("PROP_GENERIC", $html); $a_tpl->parseCurrentBlock(); } }
true
c9be834b0945c99c3571c832428de9dfb0bcc2b8
PHP
Qaweeds/Homework
/04-08/OCP/Format/WithDateFormat.php
UTF-8
181
2.75
3
[]
no_license
<?php namespace Format; use Interfaces\ILogFormat; class WithDateFormat implements ILogFormat { public function getFormat() { return date('Y-m-d H:i:s '); } }
true
bb8afae8bb7e49c662745b91dca63acf3f33e6b1
PHP
liangf/www
/ZBACKUP/tomatoink/add_rabchicken.php
UTF-8
2,110
2.515625
3
[]
no_license
<?php header('Access-Control-Allow-Origin: http://www.tomatoink.com'); header('Access-Control-Allow-Methods: POST, GET, OPTIONS'); require_once 'database.php'; $username = "DBCOMPANDSAVE"; $password = "CAS123cas!"; $hostname = "DBCOMPANDSAVE.db.11475010.hostedresource.com"; $databasename = "DBCOMPANDSAVE"; $db = new Mysql($hostname, $username, $password, $databasename); $db->connect(); if( $_POST["initial"] ) { // get the rabbit counts $sql = "SELECT rab_count FROM easter_rabchicken WHERE id=0"; $result = $db->query($sql); $array = $db->myArray($result); echo $array[0]; // seaperate by "," echo ","; // get the chicken counts $sql = "SELECT chi_count FROM easter_rabchicken WHERE id=0"; $result = $db->query($sql); $array = $db->myArray($result); echo $array[0]; //echo "this is initial."; } if( $_POST["rabbit"] ) { // get the rabbit counts $sql = "SELECT rab_count FROM easter_rabchicken WHERE id=0"; $result = $db->query($sql); $array = $db->myArray($result); echo $array[0]; // seaperate by "," echo ","; // get the chicken counts $sql = "SELECT chi_count FROM easter_rabchicken WHERE id=0"; $result = $db->query($sql); $array = $db->myArray($result); echo $array[0]; //$name = $_POST["rabbit"]; //echo $name; $sql2 = "UPDATE easter_rabchicken SET rab_count=rab_count+1 WHERE id=0"; $db->query($sql2); } if( $_POST["chicken"] ) { // get the rabbit counts $sql = "SELECT rab_count FROM easter_rabchicken WHERE id=0"; $result = $db->query($sql); $array = $db->myArray($result); echo $array[0]; // seaperate by "," echo ","; // get the chicken counts $sql = "SELECT chi_count FROM easter_rabchicken WHERE id=0"; $result = $db->query($sql); $array = $db->myArray($result); echo $array[0]; //$name = $_POST["chicken"]; //echo $name; $sql = "UPDATE easter_rabchicken SET chi_count=chi_count+1 WHERE id=0"; $db->query($sql); } $db->dbClose(); ?>
true
da5976a76483539b503030a6f927a454f0f3384c
PHP
builderprofessional/clients
/src/Clients/TurnKeyBundle/Controller/GalleryController.php
UTF-8
1,413
2.6875
3
[]
no_license
<?php /** * This controller publishes an API that will pull the right images to display in a turn-key gallery. * * @copyright 2016 Third Engine Software */ namespace Clients\TurnKeyBundle\Controller; use ThirdEngine\PropelSOABundle\Http\PropelSOASuccessResponse; use ThirdEngine\PropelSOABundle\Controller\ServiceController; use Symfony\Component\HttpFoundation\Request; /** * @route /turnkey/gallery */ class GalleryController extends ServiceController { /** * @Route("/gallery/{key}") * @Method({"GET"}) * * @param Request $request * @param string $key */ public function imagesAction(Request $request, $key) { $photos = []; for ($i = 1; $i <= 7; ++$i) { $photos[] = [ 'category' => 'Exteriors', 'fileName' => 'ext' . $i . '.jpg', ]; } for ($i = 1; $i <= 7; ++$i) { $photos[] = [ 'category' => 'Exteriors', 'fileName' => 'int' . $i . '.jpg', ]; } for ($i = 1; $i <= 7; ++$i) { $photos[] = [ 'category' => 'Exteriors', 'fileName' => 'ext' . $i . '.jpg', ]; } for ($i = 1; $i <= 7; ++$i) { $photos[] = [ 'category' => 'Exteriors', 'fileName' => 'int' . $i . '.jpg', ]; } $response = [ 'key' => $key, 'images' => $photos, ]; return new PropelSOASuccessResponse($response, 200); } }
true
2b1d8bfaf9434fe1027eb205621f9fbca6d32f46
PHP
ASUPortal/ASUPortalPHP
/_core/_framework/CUtilNumberToWords.class.php
UTF-8
5,001
2.734375
3
[]
no_license
<?php /** * Created by JetBrains PhpStorm. * User: Aleksandr Barmin * Date: 12.10.14 * Time: 20:38 * * URL: http://mydesignstudio.ru/ * mailto: abarmin@mydesignstudio.ru * twitter: @alexbarmin */ class CUtilNumberToWords { private static $def = array ( 'forms' => array(2, 0, 1, 1, 1, 2, 2, 2, 2, 2), 'words' => array( 0 => array('секунда', 'секунды', 'секунд'), 1 => array('минута', 'минуты', 'минут'), 2 => array('час', 'часа', 'часов'), 3 => array('день', 'дня', 'дней'), 4 => array('месяц', 'месяца', 'месяцев'), 5 => array('год', 'года', 'лет'), 'r' => array('рубль', 'рубля', 'рублей'), 'k' => array('копейка', 'копейки', 'копеек'), ), 'rank' => array( 0 => array('штука', 'штуки', 'штук'), 1 => array('тысяча', 'тысячи', 'тысяч'), 2 => array('миллион', 'миллиона', 'миллионов'), 3 => array('миллиард', 'миллиарда', 'миллиардов'), ), 'nums' => array( '0' => array( '', 'десять', '', ''), '1' => array( 'один', 'одиннадцать', '', 'сто'), '2' => array( 'два', 'двенадцать', 'двадцать', 'двести'), '1f' => array( 'одна', '', '', ''), '2f' => array( 'две', '', '', ''), '3' => array( 'три', 'тринадцать', 'тридцать', 'триста'), '4' => array( 'четыре', 'четырнадцать', 'сорок', 'четыреста'), '5' => array( 'пять', 'пятнадцать', 'пятьдесят', 'пятьсот'), '6' => array( 'шесть', 'шестнадцать', 'шестьдесят', 'шестьсот'), '7' => array( 'семь', 'семнадцать', 'семьдесят', 'семьсот'), '8' => array( 'восемь', 'восемнадцать', 'восемьдесят', 'восемьсот'), '9' => array( 'девять', 'девятнадцать', 'девяносто', 'девятьсот') ) ); public static function get($str) { $def =& self::$def; $res = array(); $group = preg_split("/\D+/", $str); if (count($group) < 3) //деньги { $res[] = self::get_one($group[0], $def['words']['r']); $def['rank'][0] = $def['words']['k']; $res[] = self::num2word($group[1]); } else //время - дата { $group = array_reverse($group); foreach ($group as $key => $value) { if (trim($value)) { $def['rank'][0] = $def['words'][$key]; $res[] = self::num2word($value, 0); } } $res = array_reverse($res); } return implode(' ', $res); } public static function get_one($num, $words = array()) { if (count($words)) self::$def['rank'][0] = $words; $str = number_format($num, 0, '', ','); $r = explode(',', $str); $r = array_reverse($r); $word = array(); foreach($r as $key => $value) { $word[] = self::num2word($value, $key); } $word = array_reverse($word); return implode(' ', $word); } private static function num2word($str, $key = null) { if (intval(trim($str)) === 0 && $key !== 0) return ''; $def = self::$def; $nums = $def['nums']; $forms = $def['forms']; $rank = $def['rank']; $dig = str_split(sprintf('%02d', $str)); $dig = array_reverse($dig); //если нет ключа, вернуть цифры с правильной plural-формой (можно использовать для копеек) if (!isset($key)) return $str . ' ' . ((1 == $dig[1]) ? $rank[0][2] : $rank[0][$forms[$dig[0]]]); //если кончился запас "миллионов", вернуть цифры if (!isset($rank[$key])) return $str; $rank = $rank[$key]; $f = (preg_match("/[ая]$/", $rank[0]) && ($dig[0] == 1 || $dig[0] == 2)) ? 'f' : ''; if (1 == $dig[1]) { $num_word = $nums[$dig[0]][1]; $word = $rank[2]; } else { $num_word = $nums[$dig[1]][2] . ' ' . $nums[$dig[0] . $f][0]; $word = $rank[$forms[$dig[0]]]; } $sotni = (isset($dig[2])) ? $nums[$dig[2]][3] . ' ' : ''; if (!trim($num_word)) $num_word = '0'; //это для секунд (рубли сюда не доходят) return $sotni . $num_word . ' ' . $word; } }
true
289f58df0c9d321041a69cc19b6c17db52183668
PHP
Yosh244/toisute
/goodAjax.php
UTF-8
2,279
2.53125
3
[]
no_license
<?php require_once __DIR__ . '/../app/config/database.php'; require_once __DIR__ . '/../app/functions/review.php'; session_start(); if(!empty($_SESSION['user_id'])) { $user_id = (int)$_SESSION['user_id']; } // いいねボタンが押されたときの処理(追加・削除→全いいね数表示) // ログインユーザーのいいね情報を取得 if(!empty($_POST['postId'])){ $review_id = (int)$_POST['postId']; $sql1 = "SELECT count(*) as cnt FROM good WHERE review_id = ? AND good_user_id = ? LIMIT 1"; $stmt1 = $mysqli->prepare($sql1); $stmt1->bind_param('ii', $review_id, $user_id); $stmt1->execute(); $resultSet1 = $stmt1->get_result(); $user_good_row = $resultSet1->fetch_all(); // レコードが1件でもある場合 if ($user_good_row[0][0] > 0){ // レコードを削除する→<span>内に全いいね数を表示する $sql2 = "DELETE FROM good WHERE review_id=? AND good_user_id=?"; $stmt2 = $mysqli->prepare($sql2); $stmt2->bind_param('ii', $review_id, $user_id); $stmt2->execute(); $stmt2->close(); good_number($review_id, $mysqli); } else { //レコードがない場合 // レコードを挿入する→<span>内に全いいね数を表示する $sql = "INSERT INTO good (review_id, good_user_id, create_date) VALUES (?, ?, NOW())"; $stmt = $mysqli->prepare($sql); $stmt->bind_param('ii', $review_id, $user_id); $stmt->execute(); $stmt->close(); good_number($review_id, $mysqli); } } // back to script.js // $good_check_res = $stmt1->fetch(); // $stmt1->close(); // // レコードが1件でもある場合 // if ($good_check_res == true){ // // レコードを削除する // $sql2 = "DELETE FROM good WHERE review_id=? AND good_user_id=?"; // $stmt2 = $mysqli->prepare($sql2); // $stmt2->bind_param('ii', $review_id, $user_id); // $stmt2->execute(); // $stmt2->close(); // } else { // // レコードを挿入する // $sql = "INSERT INTO good (review_id, good_user_id, create_date) VALUES (?, ?, NOW())"; // $stmt = $mysqli->prepare($sql); // $stmt->bind_param('ii', $review_id, $user_id); // $stmt->execute(); // $stmt->close(); // if(!$stmt) { // echo 'エラーが発生しました。'; // } // } // }
true
ac23331da15b16c30c509e89fe77c3c0f0f11c53
PHP
Greg0ryj/OSF-Kiosk
/Kiosk Server/PHP Scripts/encoder.php
UTF-8
804
3.0625
3
[ "Apache-2.0" ]
permissive
<?php function jsEscape($str) { $output = ''; $str = str_split($str); for($i=0;$i<count($str);$i++) { $chrNum = ord($str[$i]); $chr = $str[$i]; if($chrNum === 226) { if(isset($str[$i+1]) && ord($str[$i+1]) === 128) { if(isset($str[$i+2]) && ord($str[$i+2]) === 168) { $output .= '\u2028'; $i += 2; continue; } if(isset($str[$i+2]) && ord($str[$i+2]) === 169) { $output .= '\u2029'; $i += 2; continue; } } } switch($chr) { case "'": case '"': case "\n"; case "\r"; case "&"; case "\\"; case "<": case ">": $output .= sprintf("\\u%04x", $chrNum); break; default: $output .= $str[$i]; break; } } return $output; } ?>
true
696ab19ab344c6f60ad9ab22e51043a6d7a18d48
PHP
rositatisor/gradebook
/src/Entity/Lecture.php
UTF-8
2,343
2.734375
3
[]
no_license
<?php namespace App\Entity; use App\Repository\LectureRepository; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; /** * @ORM\Entity(repositoryClass=LectureRepository::class) */ class Lecture { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=64) * @Assert\NotBlank(message="Name should not be blank.") * @Assert\Length( * min = 2, * max = 64, * minMessage = "Name must be at least {{ limit }} characters long.", * maxMessage = "Name cannot be longer than {{ limit }} characters." * ) */ private $name; /** * @ORM\Column(type="text") * @Assert\NotBlank(message="Description should not be blank.") */ private $description; /** * @ORM\OneToMany(targetEntity=Grade::class, mappedBy="lecture") */ private $grades; public function __construct() { $this->grades = new ArrayCollection(); } public function getId(): ?int { return $this->id; } public function getName(): ?string { return $this->name; } public function setName(string $name): self { $this->name = $name; return $this; } public function getDescription(): ?string { return $this->description; } public function setDescription(string $description): self { $this->description = $description; return $this; } /** * @return Collection|Grade[] */ public function getGrades(): Collection { return $this->grades; } public function addGrade(Grade $grade): self { if (!$this->grades->contains($grade)) { $this->grades[] = $grade; $grade->setLecture($this); } return $this; } public function removeGrade(Grade $grade): self { if ($this->grades->removeElement($grade)) { // set the owning side to null (unless already changed) if ($grade->getLecture() === $this) { $grade->setLecture(null); } } return $this; } }
true
627f7c4d45c355f657403dcf44807ce835ffb039
PHP
prybudko/Contact_Book
/update/Update.php
UTF-8
1,065
2.6875
3
[]
no_license
<?php require_once '../classes/DBConnect.php'; error_reporting(0); class Update { public function updateInformation(){ $db = new DBConnect(); $db->connectToDataBase(); $data_json = json_decode($_POST['json'],true); $name = mysqli_real_escape_string($db->mysqli, $data_json['name']); $birthday = mysqli_real_escape_string($db->mysqli, $data_json['birthday']); $phone = mysqli_real_escape_string($db->mysqli, $data_json['phone']); $email = mysqli_real_escape_string($db->mysqli, $data_json['email']); $id = (int)mysqli_real_escape_string($db->mysqli, $data_json['id']); $query = "update ContactTable set name = '$name', birthday = '$birthday', phone = '$phone', email = '$email' where id = '$id'"; $result = mysqli_query($db->mysqli, $query) or die('not done'); mysqli_close($db->mysqli); $json = json_encode($data_json); echo $json; } } $update = new Update(); $update->updateInformation();
true
881c7614b150e0dacf45ec3d6b4a7054a77411d5
PHP
Lemurro/api-core
/src/Helpers/DataChangeLog.php
UTF-8
1,504
2.796875
3
[ "MIT" ]
permissive
<?php namespace Lemurro\Api\Core\Helpers; use Lemurro\Api\Core\Abstracts\Action; /** * Добавление записи в лог действий */ class DataChangeLog extends Action { /** * @var string */ public const ACTION_INSERT = 'insert'; /** * @var string */ public const ACTION_UPDATE = 'update'; /** * @var string */ public const ACTION_DELETE = 'delete'; /** * Добавление записи в лог действий * * @param string $table_name Имя таблицы * @param string $action_name Название действия ('insert'|'update'|'delete') * @param integer $record_id ИД записи * @param array $data Массив данных * * @return boolean */ public function insert($table_name, $action_name, $record_id, $data = []) { if (isset($this->dic['user']['user_id'])) { $user_id = $this->dic['user']['user_id']; } else { $user_id = 0; } $cnt = $this->dbal->insert('data_change_logs', [ 'user_id' => $user_id, 'table_name' => $table_name, 'action_name' => $action_name, 'record_id' => $record_id, 'data' => json_encode($data, JSON_UNESCAPED_UNICODE), 'created_at' => $this->dic['datetimenow'], ]); if ($cnt !== 1) { return false; } return true; } }
true
af93650cb94886fc5b9ca9303653e8f4a9d0f6f6
PHP
confile/Malware-Sample
/CnC.Pony/panel/includes/Smarty-3.1.15/libs/plugins/modifier.items.php
WINDOWS-1251
400
2.578125
3
[]
no_license
<?php function smarty_modifier_items($value = 0) { $reminder = $value % 10; if ($value === null || $reminder == 0 || $value == 0 || ($reminder >= 5 && $reminder <= 9) ) return ''; if ($reminder == 1) return ''; if ($reminder == 2 || $reminder == 3 || $reminder == 4) return ''; return ''; } ?>
true
f1460a98555e47ac3ea6f677d691561abf892482
PHP
kimhyonseong/phptest
/php/test3.php
UTF-8
3,797
3.84375
4
[]
no_license
<?php /** * Created by PhpStorm. * User: KimHyonSeong * Date: 2018-10-29 * Time: 오후 4:32 */ $object = new User; print_r($object); echo "<br>"; $object -> name = "Joe"; $object -> password = "ypass"; print_r($object); echo "<br>"; $object -> save_user(); class User { public $name, $password; function save_user() { echo "Save User code goes here"."<br>"; } } $object1 = new User1(); $object1 -> name = "Alice"; $object2 = clone $object1; $object2 -> name = "Amy"; echo "object1 name = " . $object1 -> name . "<br>"; echo "object2 name = " . $object2 -> name . "<br>"; class User1 { public $name; } class User2 //생성자 { public function User2($param1,$param2) { //??;; $username = "Guest"; } } class User3 { function __destruct() { //소멸자 코드...? } } class User4 { public $name, $password; function get_password() { return $this -> password; } } $object4 = new User4(); $object4 -> password = "secret"; echo $object4 -> get_password()."<br>"; class User5 { static function pwd_string() { echo "Please enter your password"."<br>"; } } User5::pwd_string(); class Translate { const ENGLISH = 0; const SPANISH = 1; const FRENCH = 2; const GERMAN = 3; static function lookup() { echo self::SPANISH; } } Translate::lookup(); echo "<br>"; class Example { var $name = "Michel"; public $age = 23; protected $usercount; private function admin() { } } class Test { static $static_property = "I'm static"; function get_sp() { return self::$static_property; } } $temp = new Test(); echo "Test A: " . Test::$static_property . "<br>"; echo "Test B: " . $temp->get_sp() . "<br>"; //echo "Test C: " . $temp->static_property . "<br`>" class User_ { public $name, $password; function save_user() { echo "Save User code goes here"; } } class Subscriber extends User_ { public $phone , $email; function display() { echo "Name: " . $this->name . "<br>"; echo "Pass: " . $this->password . "<br>"; echo "Phone: " . $this->phone . "<br>"; echo "E-mail: " . $this->email . "<br>"; } } $ob = new Subscriber(); $ob->name = "Fred"; $ob->password = "pword"; $ob->phone = "012 3456 7890"; $ob->email = "Fred@naver.com"; $ob->display(); class Dad { function test() { echo "[Class Dad] I am your Father<br>"; } } class Son extends Dad { function test() { echo "[Class Son] I am Luke<br>"; } function test2() { parent::test(); } } $obj = new Son; $obj -> test(); $obj -> test2(); class Wildcat { public $fur; function __construct() { $this -> fur = "TRUE"; } } class Triger extends Wildcat { public $stripes; function __construct() { parent::__construct(); $this -> stripes = "TRUE"; } } $ob1 = new Triger(); echo "Trigers have ...<br>"; echo "Fur: " . $ob1->fur . "<br>"; echo "Stripes: " . $ob1->stripes . "<br>"; ?>
true
c09ee882a175d6c946524167151880da36fda44d
PHP
nicolassnider/herramientas
/herramientas_api/Service/FacturaService.php
UTF-8
956
2.6875
3
[ "Apache-2.0" ]
permissive
<?php /** * Created by PhpStorm. * User: nicol * Date: 08/10/2018 * Time: 12:23 AM */ require_once '../Repository/FacturaRepository.php'; class FacturaService { private $repository; public function __construct() { $this->repository = new FacturaRepository(); } public function getAllSorted() { return $this->repository->getAllSorted(); } public function create(Factura $factura) { return $this->repository->create($factura); } public function get($id) { return $this->repository->get($id); } public function getAll() { return $this->repository->getAll(); } public function update(Factura $factura) { $this->repository->update($factura); } public function pagar(int $id) { $this->repository->pagar($id); } public function delete(int $id) { $this->repository->delete($id); } }
true
a908f8dade8b4781a34678672323794a7e3cbb4d
PHP
xtompie/cqa
/app/Core/Util/Serialization/SerializationInterface.php
UTF-8
208
2.640625
3
[ "MIT" ]
permissive
<?php namespace App\Core\Util\Serialization; interface SerializationInterface { public static function fromSerialization(string $serialization): static; public function toSerialization(): string; }
true
4e44cde238f1addb5dab315f4be8bc2081a5b7c8
PHP
Alcatraz1907/academy_Ivan_Dudka
/oop/site/controler.loc/www/page/addproducer/index.php
UTF-8
2,389
2.625
3
[]
no_license
<?php require "../models/Studios.php"; require "../models/Nationalities.php"; ?> <form action="" method="post" name="form1" > <table border="2"> <tr><td>Last name</td> <td><input type="text" ID="lastName" name="last_name" ></td></tr> <tr><td>Name </td> <td><input type="text" id="name" name="name" ></td></tr> <tr><td>Year of birth</td> <td><input type="text" id="YearOfBirth" name="year_of_birth" ></td></tr> <tr><td>Yeat of death</td> <td><input type="text" id="YearOfFDeath" name="year_of_death" ></td></tr> <tr><td>Національність</td> <td> <select name="nationality_id"> <?php $nationalities = new Nationalities(); $result = $nationalities->outputNationalities(); for($i = 0;$i < count($result);$i++){ echo '<option value="'.$result[$i]->getId().'">'.$result[$i]->getNationality().'</option>'; } ?> </select> </td></tr> <tr><td colspan="2" align="center"><input name="add" type="submit" value="Додати" > </td> </table> </form> <script type="text/javascript"> $(document).ready(function(){ $("#lastName").mask("aaaaaaaaaaaaaaaaaaaa"); $("#name").mask("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); $("#YearOfBirth").mask("9999"); $("#YearOfFDeath").mask("9999"); }); </script> <?php if (($_POST['last_name']!=NULL)&&($_POST['name']!=NULL)&&($_POST['year_of_birth']!=NULL)&&($_POST['year_of_death']!=NULL || $_POST['year_of_death']==NULL ) &&($_POST['nationality_id']!=NULL)) { $year_of_birth = $_POST['year_of_birth']; if($_POST['year_of_death'] =="") { $year_of_death = NULL; }else{ $year_of_death = $_POST['year_of_death']; } $array_studio = array('id'=>NULL ,'last_name'=>$_POST['last_name'] ,'name'=>$_POST['name'] ,'year_of_birth'=>$_POST['year_of_birth'] ,'year_of_death'=>$year_of_death ,'nationality_id'=>$_POST['nationality_id']); $studio = new Studios(); $studio->addStudios($array_studio); } ?>
true
eaa481a8e179e3ecf18ecf79e2ff3ae06b71ad02
PHP
StereoFlo/simple-mvc
/src/Core/Request/ServerBag.php
UTF-8
745
2.734375
3
[ "MIT" ]
permissive
<?php namespace Core\Request; use App\Utils; /** * Class ServerBag * @package Core\Request */ class ServerBag extends Bag { /** * @return string */ public function getMethod(): string { return \strtolower(Utils::getProperty($this->stack, 'REQUEST_METHOD', '')); } /** * @return array */ public function getHeaders(): array { $headers = []; foreach ($this->stack as $key => $value) { if (substr($key, 0, 5) <> 'HTTP_') { continue; } $header = \str_replace(' ', '-', \ucwords(\str_replace('_', ' ', \strtolower(\substr($key, 5))))); $headers[$header] = $value; } return $headers; } }
true
1e18b6aa7cd6eae4b637d7808cf8b6d4d6c337b1
PHP
SuperPignouf/ProjAParcels
/ConsolePHP/seeOrders.php
UTF-8
2,375
2.828125
3
[]
no_license
<?php if(!isset($_SESSION)) session_start(); ?> <!DOCTYPE html> <html> <head> <?php include("head.php"); ?> </head> <body> <header> <!--En-tête--> <h1>Nos Ordres de Transport</h1> </header> <section> <!--Zone centrale--> Pour chaque colis nous affichons de gauche à droite: l'id de l'ordre, l'id du client émetteur, l'id du client récepteur, la monnaie et le prix du service. Les colis concernés par l'ordre sont disponibles grâce à un clic sur l'id de l'ordre. <?php //------------------------------------------------ // Connection avec la base de données. //------------------------------------------------ try{ $bdd = new PDO('mysql:host=localhost;dbname=parcels', 'root', '', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)); } catch(Exception $e){ die('Error : ' .$e -> getMessage()); echo 'Something went wrong...'; } $bdd->exec("SET CHARACTER SET utf8"); $response = $bdd->query('SELECT * FROM orders WHERE CURRENT_TIMESTAMP < to_date ORDER BY order_id '); // on sélectionne les ordres de transport valides pour affichage. ?> <table border="1" style="width:300px"><tr> <th>order_id</th> <th>sender_id</th> <th>receiver_id</th> <th>billing_currency</th> <th>billing_value</th> </tr> <?php while ($data = $response -> fetch()){ ?> <tr> <td><a href= <?php echo '"seeParcels.php?order='.($data['order_id']).'"';?>> <strong><?php echo $data['order_id']; ?></strong></a></td> <td><a href= <?php echo '"seeClient.php?id='.($data['sender_id']).'"';?>> <strong><?php echo $data['sender_id']; ?></strong></a></td> <td><a href= <?php echo '"seeClient.php?id='.($data['receiver_id']).'"';?>> <strong><?php echo $data['receiver_id']; ?></strong></a></td> <td><?php echo $data['billing_currency']; ?></td> <td><?php echo $data['billing_value']; ?></td> </tr> <?php } $response->closeCursor(); // Termine le traitement de la requête ?> </section> <nav> <!--Menu--> <?php include ("menu.php"); ?> </nav> <footer> <!--Footer--> <?php include ("footer.php"); ?> </footer> </body> </html>
true
1a8a4b5a0b2160264d6a2e34d6a9a6d2907923b7
PHP
joshuaruesweg/de.voolia.news
/files/lib/system/attachment/NewsAttachmentObjectType.class.php
UTF-8
1,594
2.703125
3
[]
no_license
<?php namespace news\system\attachment; use news\data\news\News; use wcf\system\attachment\AbstractAttachmentObjectType; use wcf\system\WCF; use wcf\util\ArrayUtil; /** * Attachment object type implementation for news entries. * * @author Florian Frantzen * @copyright 2013 voolia.de * @license Creative Commons CC-BY-ND <http://creativecommons.org/licenses/by-nd/3.0/deed.de> * @package de.voolia.news */ class NewsAttachmentObjectType extends AbstractAttachmentObjectType { /** * @see \wcf\system\attachment\IAttachmentObjectType::getAllowedExtensions() */ public function getAllowedExtensions() { return ArrayUtil::trim(explode("\n", WCF::getSession()->getPermission('user.news.allowedAttachmentExtensions'))); } /** * @see \wcf\system\attachment\IAttachmentObjectType::getMaxCount() */ public function getMaxCount() { return WCF::getSession()->getPermission('user.news.maxAttachmentCount'); } /** * @see \wcf\system\attachment\IAttachmentObjectType::canDownload() */ public function canDownload($objectID) { if ($objectID) { $news = new News($objectID); if ($news->canRead()) return true; } return false; } /** * @see \wcf\system\attachment\IAttachmentObjectType::canUpload() */ public function canUpload($objectID, $parentObjectID = 0) { return WCF::getSession()->getPermission('user.news.canUploadAttachment'); } /** * @see \wcf\system\attachment\IAttachmentObjectType::canDelete() */ public function canDelete($objectID) { if ($objectID) { $news = new News($objectID); return $news->isEditable(); } return false; } }
true
5e2d301f6222f52359fe26418bed4d7670ca121c
PHP
dwfriends/dokuwiki-plugin-gitlivesync
/conf/settings.class.php
UTF-8
14,827
2.703125
3
[]
no_license
<?php /** * Fieldset to Display a Section for each Repository */ class setting_fieldset2 extends setting_fieldset { function prompt(&$plugin) { return $this->_text; } } /** * gitlivesync_newrepo setting class for adding a new Repository to Configuration */ class setting_gitlivesync_newrepo extends setting_string { function html(&$plugin, $echo=false) { $res = parent::html($plugin,$echo); $res[1] .= '<br><button type="submit" name="submit">Add Repository</button>'; return $res; } public function _out_key($pretty=false,$url=false) { if ($pretty) { return "";//str_replace(CM_KEYMARKER,"»",$this->_key); } else { $key = $this->_local; if (substr($this->_local,0,4)!="git:") { $this->_local = "git:".$this->_local; } else { $key= substr($key,4); } return str_replace("_nEwRePo",''.$key,str_replace(CM_KEYMARKER,"']['",$this->_key.CM_KEYMARKER."gitMap")); } } } /** * A text-only view setting class to view/display repository status */ class setting_gitlivesync_textonly extends setting_gitlivesync { function html(&$plugin, $echo=false) { $disable = ''; $key = htmlspecialchars($this->_key); //$value = htmlspecialchars($this->_input); $value = $this->_input; $label = '<label>'.$this->prompt($plugin).'</label>'; $input = $value; return array($label,$input); } } /** * gitlivesync string setting class which impelents Git-Repository Functions and handels Repository delete */ class setting_gitlivesync extends setting_string { var $_reponame = ''; /** * Returns the configured Git-Directory for the plugin */ function getGitDir() { global $conf; $gitdir = $conf['plugin']['gitlivesync']['gitdir']; if (!isset($gitdir) || $gitdir === false || $gitdir === "") { $gitdir = $conf['savedir']."/git/"; } return DOKU_INC.$gitdir; } /** * Returns an initialized Git-Object for the repository specified by the _reponame var of this setting class */ function initializeGitObject() { $repodir = $this->getGitDir().$this->_reponame; if (!is_dir($repodir)) { mkdir($repodir,0770,true); } if (is_dir($repodir)) { $repo = new GitRepo($repodir, true, false); if (!($repo->is_repo_present())) { $repo->run('init'); } return $repo; } return false; } /** * Handels to set the defaultConfiguration to new Repositories */ public function initialize($default, $local, $protected) { parent::initialize($default,$local,$protected); if (!isset($local) && isset($this->_mydefault)) { $this->_local = $this->_mydefault; } } /** * Handles deleteRepository by deleting the Setting from the configuration file save output (return "") */ function out($var, $fmt='php') { if(isset($_REQUEST['gitlivesync_deleteRepo'])) { if ($_REQUEST['gitlivesync_deleteRepo']==$this->_reponame) { return ''; } } return parent::out($var,$fmt); } } /** * Setting class onoff with own default value and repository delete handle. */ class setting_gitlivesync_onoff extends setting_onoff { var $_reponame = ''; public function initialize($default, $local, $protected) { parent::initialize($default,$local,$protected); if (!isset($local) && isset($this->_mydefault)) { $this->_local = $this->_mydefault; } } function out($var, $fmt='php') { if(isset($_REQUEST['gitlivesync_deleteRepo'])) { if ($_REQUEST['gitlivesync_deleteRepo']==$this->_reponame) { return ''; } } return parent::out($var,$fmt); } } /** * Setting class numeric with own default value and repository delete handle. */ class setting_gitlivesync_numeric extends setting_numeric { var $_reponame = ''; public function initialize($default, $local, $protected) { parent::initialize($default,$local,$protected); if (!isset($local) && isset($this->_mydefault)) { $this->_local = $this->_mydefault; } } function out($var, $fmt='php') { if(isset($_REQUEST['gitlivesync_deleteRepo'])) { if ($_REQUEST['gitlivesync_deleteRepo']==$this->_reponame) { return ''; } } return parent::out($var,$fmt); } } /** * Setting class to delete an gitlivesync-repository */ class setting_gitlivesync_delrepo extends setting_gitlivesync { //See: http://php.net/manual/de/function.rmdir.php#110489 private function _delTree($dir, $del=false) { $files = array_diff(scandir($dir), array('.','..')); foreach ($files as $file) { (is_dir("$dir/$file")) ? $this->_delTree("$dir/$file",true) : @unlink("$dir/$file"); } if ($del) { return @rmdir($dir); } else { return; } } function initialize($default,$local,$protected) { global $conf; //ToDo; if (isset($_REQUEST['gitlivesync_deleteRepo'])) { if ($_REQUEST['gitlivesync_deleteRepo']==$this->_reponame) { if (checkSecurityToken()) { //ToDo: Handle Delete Repo $repodir = $this->getGitDir().$this->_reponame; $keyfile = $this->getGitDir()."key/".$this->_reponame.".rsa"; $file = $this->getGitDir().$this->_reponame.".force"; $lastpull_file = $this->getGitDir().$this->_reponame.".lastpull"; $this->_delTree($repodir,true); @unlink($keyfile.".pub"); @unlink($keyfile); @unlink($file."pull"); @unlink($file."import"); @unlink($lastpull_file); //ToDo: $this->_delTree(map); bzw ist eine löschung im zugehörigen config-objekt sinnvoll (wikiMap). $this->_delTree($conf['datadir'].str_replace(":","/",$conf['plugin']['gitlivesync']['repositories'][$this->_reponame]['wikiMap'])); $this->_delTree($conf['mediadir'].str_replace(":","/",$conf['plugin']['gitlivesync']['repositories'][$this->_reponame]['wikiMap'])); } } } } function html(&$plugin, $echo = false) { global $ID; //global $conf; $key = htmlspecialchars($this->_key); $label = '<label for="config___'.$key.'">'.$this->prompt($plugin).'</label>'; $input = '<div class="input"><input id="config___'.$key.'" name="config['.$key.']" type="checkbox" class="checkbox" value="1"/> '; $input .= '<button type="submit" name="gitlivesync_deleteRepo" value="'.$this->_reponame.'" onclick="if (document.getElementById(\'config___'.$key.'\').checked) { return confirm(\'delete Repo.\'); } else { return false; }">Delete Repository</button>'; //$input .= "Wiki-Path:".$conf['mediadir'].str_replace(":","/",$conf['plugin']['gitlivesync']['repositories'][$this->_reponame]['wikiMap'])."bla:".$conf['datadir']; return array($label,$input); } } /** * Setting class to display the creation time of an existing key for the repository and allows to generate a (new) one and offers the corresponding private key for donload */ class setting_gitlivesync_sshkey extends setting_gitlivesync_textonly { //see: http://stackoverflow.com/questions/6648337/generate-ssh-keypair-form-php private function _sshEncodePublicKey($privKey) { $keyInfo = openssl_pkey_get_details($privKey); $buffer = pack("N", 7) . "ssh-rsa" . $this->_sshEncodeBuffer($keyInfo['rsa']['e']) . $this->_sshEncodeBuffer($keyInfo['rsa']['n']); return "ssh-rsa " . base64_encode($buffer); } private function _sshEncodeBuffer($buffer) { $len = strlen($buffer); if (ord($buffer[0]) & 0x80) { $len++; $buffer = "\x00" . $buffer; } return pack("Na*", $len, $buffer); } function initialize($default,$local,$protected) { global $ID; if ($this->_reponame != "") { if (!file_exists($this->getGitDir()."key/")) mkdir($this->getGitDir()."key/",0777,true); $keyfile = $this->getGitDir()."key/".$this->_reponame.".rsa"; if (isset($_REQUEST['gitlivesync_generateKey'])) { if ($_REQUEST['gitlivesync_generateKey']==$this->_reponame) { if (checkSecurityToken()) { $rsaKey = openssl_pkey_new(array( 'private_key_bits' => 1024, 'private_key_type' => OPENSSL_KEYTYPE_RSA)); $privKey = openssl_pkey_get_private($rsaKey); openssl_pkey_export($privKey, $pem); //Private Key $pubKey = $this->_sshEncodePublicKey($rsaKey); //Public Key $umask = umask(0066); @unlink($keyfile); file_put_contents($keyfile, $pem); //save private key into file @unlink($keyfile.'.rsa.pub'); file_put_contents($keyfile.'.pub', $pubKey); //save public key into file } } } $keyfile .=".pub"; if(file_exists($keyfile)) { $this->_input = "Key generated on: ".@date("d.m.Y H:m:s",@filemtime($keyfile)); $this->_input .= "<br>[ <a href=\"".script()."?id=$ID&do=admin&page=config&gitlivesync_generateKey=$this->_reponame&sectok=".getSecurityToken()."\" onclick=\"return confirm('Are you sure to generate a new Key? The old one will be deleted.')\">Generate NEW Key</a> |"; $this->_input .= " <a download=\"".$this->_reponame.".rsa.pub\" href=\"data:application/octet-stream;charset=utf-8;base64,".base64_encode(file_get_contents($keyfile))."\">Download Public Key</a> ]"; } else { $this->_input = "No Key generated for this Repository"; $this->_input .= "<br>[ <a href=\"".script()."?id=$ID&do=admin&page=config&gitlivesync_generateKey=$this->_reponame&sectok=".getSecurityToken()."\">Generate Key</a> ]"; } } } } /** * Setting class to display the gitlivesync-lastpull of an repositora and allows to force an pull/import */ class setting_gitlivesync_lastpull extends setting_gitlivesync_textonly { public function setRepositoryForcePull($force_import=false) { $file = $this->getGitDir().$this->_reponame.".force"; touch($this->getGitDir()."forcepull"); touch($file."pull"); if ($force_import) { touch($file."import"); } } function initialize($default,$local,$protected) { global $conf; global $ID; if ($this->_reponame != "") { $lastpull_file = $this->getGitDir().$this->_reponame.".lastpull"; $lastpull_time = 0; if (file_exists($lastpull_file)) { $lastpull_time = file_get_contents($lastpull_file); } if ($lastpull_time != 0) { $this->_input = date("d.m.Y H:m:s",$lastpull_time)."<br>[ "; } else { $this->_input = "No Pull for this Repository.<br>[ "; } $this->_input .= "<a href=\"".script()."?id=$ID&do=admin&page=config&gitlivesync_importpull=$this->_reponame&sectok=".getSecurityToken()."\">Pull and Import Changes</a> | "; //} $this->_input .= "<a href=\"".script()."?id=$ID&do=admin&page=config&gitlivesync_pull=$this->_reponame&sectok=".getSecurityToken()."\">Pull</a> ]"; if (isset($_REQUEST['gitlivesync_pull'])) { if ($_REQUEST['gitlivesync_pull']==$this->_reponame) { if (checkSecurityToken()) { $this->setRepositoryForcePull(); $this->_input .= "<br> Pull forced for next Page load."; } } } if (isset($_REQUEST['gitlivesync_importpull'])) { if ($_REQUEST['gitlivesync_importpull']==$this->_reponame) { if (checkSecurityToken()) { $this->setRepositoryForcePull(true); $this->_input .= "<br> Pull and Import forced for next Page load."; } } } } else { $this->_input="No Repository given."; } } } /** * Setting class to display the actual revision of an git repository */ class setting_gitlivesync_repoinfo_revision extends setting_gitlivesync_textonly { function initialize($default,$local,$protected) { $repo = $this->initializeGitObject(); if ($repo!==false) { try { $this->_input = trim($repo->run("rev-list -1 HEAD")); } catch (Exception $e) { } } else { $this->_input=""; } } } /** * Setting class to read/set the (origin) remote of an git repository */ class setting_gitlivesync_repoinfo_remote extends setting_gitlivesync { var $_repo = ''; private function _getRemote() { if ($this->_repo!==false) { try { $remote = trim($this->_repo->run("remote show")); if ($remote!=="") { $remote = trim($this->_repo->run("config --get remote.".$remote.".url")); } return $remote; } catch (Exception $e) { } } else { return ""; } } function initialize($default,$local,$protected) { $this->_repo = $this->initializeGitObject(); $this->_local = $this->_getRemote(); } public function out($var, $fmt='php') { if ($fmt=='php') { if ($this->_local!="") { $newremote = $this->_local; if ($this->_getRemote() == "") { //Add new remote //die("Set new remote $newremote"); $this->_repo->run("remote add origin $newremote"); } elseif($this->_getRemote()!=$newremote) { //Change Remote $remote = trim($this->_repo->run("remote show")); $this->_repo->run("config remote.".$remote.".url ".$newremote); } } } return ''; } } /** * Setting class to display the active brach of an git repository */ class setting_gitlivesync_repoinfo_branch extends setting_gitlivesync_textonly { function initialize($default,$local,$protected) { $repo = $this->initializeGitObject(); if ($repo!==false) { $this->_input = trim($repo->active_branch()); } else { $this->_input=""; } } }
true
4aece201b33a0227c2accbc8fa76657abc9ab520
PHP
firassleibi/firassleibi
/ghm/post.php
UTF-8
1,639
2.546875
3
[]
no_license
<?php $error=false; if(!isset($_POST['name'])||!isset($_POST['email'])||!isset($_POST['text_area'])||!isset($_POST['radio_selected'])||!isset($_POST['check_boxs'])){ $error=true; } else{ include("include/db.php"); //Backend Validation $name = $_POST["name"]; $email = $_POST["email"]; $text_area = $_POST["text_area"]; $radio_selected = $_POST["radio_selected"]; $check_boxs = $_POST["check_boxs"]; if (!preg_match("/^[a-zA-Z]*$/",$name)) { $error = true; } if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $error = true; } if(count(explode(' ' , $check_boxs))!=3){ $error = true; } if(strlen($text_area)<200||strlen($text_area)>400){ $error = true; } if(!$error){ $ok=mysqli_query($con,"insert into queries set name='$name', email='$email', text_area='$text_area',radio_selected='$radio_selected',check_boxs='$check_boxs'"); if($ok){ // Send Mail $to = "me@kotovs.com"; $subject = "Form Submission"; $txt = "name: ".htmlspecialchars($name, ENT_QUOTES, 'UTF-8')."\n"; $txt .= "email: ".htmlspecialchars($email, ENT_QUOTES, 'UTF-8')."\n"; $txt .= "text area: ".htmlspecialchars($text_area, ENT_QUOTES, 'UTF-8')."\n"; $txt .= "radio_selected: ".htmlspecialchars($radio_selected, ENT_QUOTES, 'UTF-8')."\n"; $txt .= "check_boxs: ".htmlspecialchars($check_boxs, ENT_QUOTES, 'UTF-8')."\n"; $headers = "From: webmaster@firassleibi.com"; $sent=mail($to,$subject,$txt,$headers); if($sent) echo "Form Submitted"; } else{ $error = true; } } } if($error){ echo $error; } ?>
true
f917772907e4f2e85cce4a2dc7555a95936ef85a
PHP
Sirgalas/parserYiiRss
/repositories/admin/NewsRepository.php
UTF-8
956
2.640625
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\repositories\admin; use app\entities\News; use app\entities\NewsCategory; use yii\helpers\ArrayHelper; class NewsRepository { public function get($id):News { if(!$news=News::findOne($id)) throw new \RuntimeException('Ссылка не найдена'); return $news; } public function save(News $news):News { if(!$news->save()) throw new \RuntimeException(print_r($news->errors,1)); return $news; } public function remove(News $news):void { $news->delete(); } public function newQuery($id) { $newQuery = News::find()->where(['is_active'=>News::ACTIVE]); if ($id !== null && isset($categories[$id])) { $id = ArrayHelper::getColumn(NewsCategory::find()->where(['category_id'=>$id])->all(),'new_id'); $newQuery->andWhere(['in','id', $id]); } return $newQuery; } }
true
8fe89026ba7068e7c72596398442e00c3ce69fdd
PHP
cosnicsTHLU/cosnics
/src/Chamilo/Core/User/Storage/Repository/UserRepository.php
UTF-8
5,882
2.609375
3
[ "MIT" ]
permissive
<?php namespace Chamilo\Core\User\Storage\Repository; use Chamilo\Core\User\Storage\DataClass\User; use Chamilo\Core\User\Storage\DataClass\UserSetting; use Chamilo\Core\User\Storage\DataManager; use Chamilo\Core\User\Storage\Repository\Interfaces\UserRepositoryInterface; use Chamilo\Libraries\Storage\DataClass\DataClass; use Chamilo\Libraries\Storage\Parameters\DataClassRetrieveParameters; use Chamilo\Libraries\Storage\Query\Condition\AndCondition; use Chamilo\Libraries\Storage\Query\Condition\ComparisonCondition; use Chamilo\Libraries\Storage\Query\Condition\Condition; use Chamilo\Libraries\Storage\Parameters\DataClassRetrievesParameters; use Chamilo\Libraries\Storage\Query\Condition\EqualityCondition; use Chamilo\Libraries\Storage\Query\Variable\PropertyConditionVariable; use Chamilo\Libraries\Storage\Query\Variable\StaticConditionVariable; /** * The repository wrapper for the user data manager * * @package user * @author Sven Vanpoucke - Hogeschool Gent */ class UserRepository implements UserRepositoryInterface { /** * Finds a user by a given id * * @param int $id * * @return \Chamilo\Core\User\Storage\DataClass\User */ public function findUserById($id) { return DataManager::retrieve_by_id(User::class_name(), $id); } /** * Finds a user by a list of parameters * * @param Condition $condition * @param int $count * @param int $offset * @param OrderBy[] $order_by * * @return User[] */ public function findUsers(Condition $condition, $count = null, $offset = null, $order_by = array()) { $parameters = new DataClassRetrievesParameters($condition, $count, $offset, $order_by); return DataManager::retrieves(User::class_name(), $parameters)->as_array(); } /** * Finds a user by a given email * * @param string $email * * @return User; */ public function findUserByEmail($email) { $condition = new ComparisonCondition( new PropertyConditionVariable(User::class_name(), User::PROPERTY_EMAIL), ComparisonCondition::EQUAL, new StaticConditionVariable($email)); $users = $this->findUsers($condition); return $users[0]; } /** * Finds a user by a given username * * @param string $username * * @return \Chamilo\Core\User\Storage\DataClass\User */ public function findUserByUsername($username) { return \Chamilo\Core\User\Storage\DataManager::retrieve_user_by_username($username); } /** * * @return User[] */ public function findActiveStudents() { return $this->findActiveUsersByStatus(User::STATUS_STUDENT); } /** * * @return User[] */ public function findActiveTeachers() { return $this->findActiveUsersByStatus(User::STATUS_TEACHER); } /** * * @param $status * @return User[] */ protected function findActiveUsersByStatus($status) { $conditions = array(); $conditions[] = new ComparisonCondition( new PropertyConditionVariable(User::class_name(), User::PROPERTY_STATUS), ComparisonCondition::EQUAL, new StaticConditionVariable($status)); $conditions[] = new ComparisonCondition( new PropertyConditionVariable(User::class_name(), User::PROPERTY_ACTIVE), ComparisonCondition::EQUAL, new StaticConditionVariable(1)); $parameters = new DataClassRetrievesParameters(new AndCondition($conditions)); /** * * @var User[] $users */ $users = DataManager::retrieves(User::class_name(), $parameters)->as_array(); return $users; } public function create(DataClass $dataClass) { return $dataClass->create(); } public function update(DataClass $dataClass) { return $dataClass->update(); } public function delete(DataClass $dataClass) { return $dataClass->delete(); } public function getUserSettingForSettingAndUser($context, $variable, User $user) { $setting = \Chamilo\Configuration\Storage\DataManager::retrieve_setting_from_variable_name( $variable, $context ); $conditions = array(); $conditions[] = new EqualityCondition( new PropertyConditionVariable(UserSetting::class_name(), UserSetting::PROPERTY_USER_ID), new StaticConditionVariable($user->getId()) ); $conditions[] = new EqualityCondition( new PropertyConditionVariable(UserSetting::class_name(), UserSetting::PROPERTY_SETTING_ID), new StaticConditionVariable($setting->getId()) ); $condition = new AndCondition($conditions); return \Chamilo\Core\User\Storage\DataManager::retrieve( UserSetting::class_name(), new DataClassRetrieveParameters($condition) ); } public function createUserSettingForSettingAndUser($context, $variable, User $user, $value = null) { $userSetting = $this->getUserSettingForSettingAndUser($context, $variable, $user); if(!$userSetting instanceof UserSetting) { $setting = \Chamilo\Configuration\Storage\DataManager::retrieve_setting_from_variable_name( $variable, $context ); $userSetting = new UserSetting(); $userSetting->set_setting_id($setting->getId()); $userSetting->set_user_id($user->getId()); $userSetting->set_value($value); return $this->create($userSetting); } else { $userSetting->set_value($value); return $this->update($userSetting); } } }
true
ae0ccab67c6f345008807e425e50f70710d04716
PHP
Th3Mouk/coding-standard-php
/YoudotAdditional/Sniffs/Classes/PsalmImmutableSniff.php
UTF-8
3,644
2.796875
3
[]
no_license
<?php declare(strict_types=1); namespace YoudotAdditional\Sniffs\Classes; use PHP_CodeSniffer\Files\File; use PHP_CodeSniffer\Sniffs\Sniff; use SlevomatCodingStandard\Helpers\AnnotationHelper; use SlevomatCodingStandard\Helpers\DocCommentHelper; use SlevomatCodingStandard\Helpers\TokenHelper; /** * @psalm-immutable */ class PsalmImmutableSniff implements Sniff { /** * Returns an array of tokens this test wants to listen for. * * @return array<int|string> */ public function register(): array { return [T_CLASS, T_INTERFACE]; } /** * Processes this test, when one of its tokens is encountered. * * @param File $phpcs_file The file being scanned. * @param int $stack_ptr The position of the current token * in the stack passed in $tokens. * * @return void */ public function process(File $phpcs_file, $stack_ptr) { $tokens = $phpcs_file->getTokens(); $first_token_of_line = TokenHelper::findFirstTokenOnLine($phpcs_file, $stack_ptr); if (!DocCommentHelper::hasDocComment($phpcs_file, $stack_ptr)) { $phpcs_file->addFixableError( 'The class has no PhpDoc block, and must have one with @psalm-immutable tag', $stack_ptr, 'MissingTag' ); $phpcs_file->fixer->addContent( $first_token_of_line - 1, "/**\n * @psalm-immutable\n */\n" ); return; } $annotations = AnnotationHelper::getAnnotationsByName($phpcs_file, $stack_ptr, '@psalm-immutable'); if (!empty($annotations)) { return; } $doc_block_start_pointer = TokenHelper::findPrevious( $phpcs_file, T_DOC_COMMENT_OPEN_TAG, $first_token_of_line ); $phpcs_file->addFixableError( 'The PhpDoc block of the class does not contains @psalm-immutable tag', $doc_block_start_pointer, 'MissingTag' ); // Single line comment must be exploded in multiple if ($tokens[$stack_ptr]['line'] - 1 === $tokens[$doc_block_start_pointer]['line']) { $phpcs_file->fixer->beginChangeset(); $phpcs_file->fixer->addContent($doc_block_start_pointer, "\n * @psalm-immutable\n *\n *"); $phpdoc_content_pointer = TokenHelper::findNext( $phpcs_file, [T_DOC_COMMENT_STRING, T_DOC_COMMENT_TAG], $doc_block_start_pointer, $stack_ptr ); if ($tokens[$phpdoc_content_pointer]['code'] === T_DOC_COMMENT_STRING) { $content = trim($tokens[$phpdoc_content_pointer]['content']); $phpcs_file->fixer->replaceToken($phpdoc_content_pointer, "$content\n "); $phpcs_file->fixer->endChangeset(); return; } if ($tokens[$phpdoc_content_pointer + 2]['code'] === T_DOC_COMMENT_STRING) { $content = trim($tokens[$phpdoc_content_pointer + 2]['content']); $phpcs_file->fixer->replaceToken($phpdoc_content_pointer + 2, "$content\n "); $phpcs_file->fixer->endChangeset(); return; } $phpcs_file->fixer->addNewline($phpdoc_content_pointer); $phpcs_file->fixer->endChangeset(); return; } $phpcs_file->fixer->addContent($doc_block_start_pointer, "\n * @psalm-immutable\n *"); $phpcs_file->fixer->endChangeset(); return; } }
true
0473759015b526d3c768b22d828430e6949c2d1f
PHP
Jamaludin-Sanur/reserved-backend
/database/seeders/UserTableSeeder.php
UTF-8
742
2.875
3
[ "MIT" ]
permissive
<?php namespace Database\Seeders; use Illuminate\Database\Seeder; use App\Models\User; class UserTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // Let's truncate our existing records to start from scratch. User::truncate(); $faker = \Faker\Factory::create(); // And now, let's create a few articles in our database: for ($i = 0; $i < 50; $i++) { User::create([ 'name' => $faker->name, 'email' => $faker->email, 'password' => 'password', 'urlImage' => $faker->imageUrl($width = 300, $height = 300) ]); } } }
true
da569b88e9310f901bb5b8a510c4a2c9e3edbf93
PHP
Anisasundarti/aplikasi_skripsi
/app/Models/LokasiKejahatan.php
UTF-8
1,796
2.625
3
[ "MIT" ]
permissive
<?php namespace App\Models; use Eloquent as Model; use Illuminate\Database\Eloquent\SoftDeletes; /** * Class LokasiKejahatan * @package App\Models * @version February 24, 2021, 10:57 am UTC * * @property integer $id_jenis_kejahatan * @property string $alamat * @property string $gambar * @property string $deskripsi * @property string $tahun_kejadian * @property string $kelurahan * @property string $kecamatan * @property string $potensi_kerawanan * @property string $koordinat */ class LokasiKejahatan extends Model { use SoftDeletes; public $table = 'lokasi_kejahatans'; protected $dates = ['deleted_at']; public $fillable = [ 'id_jenis_kejahatan', 'alamat', 'deskripsi', 'tahun_id', 'kelurahan_id' ]; /** * The attributes that should be casted to native types. * * @var array */ protected $casts = [ 'id' => 'integer', 'id_jenis_kejahatan' => 'integer', 'alamat' => 'string', 'deskripsi'=> 'string', 'tahun_id' => 'integer', 'kelurahan_id' => 'integer', ]; /** * Validation rules * * @var array */ public static $rules = [ 'id_jenis_kejahatan' => 'required', 'alamat' => 'required', 'deskripsi' => 'required', 'tahun_id' => 'required', 'kelurahan_id' => 'required', ]; public function JenisKejahatan(){ return $this->belongsTo('App\Models\JenisKejahatan','id_jenis_kejahatan','id'); } public function Tahun(){ return $this->belongsTo('App\Models\Tahun','tahun_id','id'); } public function Kelurahan(){ return $this->belongsTo('App\Models\Kelurahan','kelurahan_id','id'); } }
true
158f4d84c041d7684999e412fbb096bc18f6a710
PHP
JojoLgenius/Projet_Dev_Web
/Webetu/ConnexionGestion/enregistrer.php
UTF-8
2,110
2.84375
3
[]
no_license
<?php session_start(); ?> <!DOCTYPE html> <html lang="fr"> <head> <meta charset="utf-8"> <title>Enregistrement</title> <link rel="stylesheet" type="text/css" href="StylePartieConnexion.css"> </head> <body> <center> <?php /* recupere le nom l'id et le mdp envoyés par le formulaire de modifier.php */ if (isset($_POST['nom'],$_POST['passe'],$_POST['id'])) { /*initialisation des nouvelles variables pour la requete de modification */ $classe = 'membre'; $id = $_POST['id']; $nom = htmlspecialchars($_POST['nom']); $passe = password_hash($_POST['passe'], PASSWORD_DEFAULT); /* connexion pdo */ include('connex.inc.php'); $pdo = connexion('bdd_membre'); try { /*preparation de la requete de modification */ $stmt = $pdo->prepare('UPDATE membres SET classe=:classe,nom=:nom,passe=:passe WHERE id=:id'); $stmt->bindParam(':id', $id); $stmt->bindParam(':nom', $nom); $stmt->bindParam(':classe', $classe); $stmt->bindParam(':passe', $passe); /*utilisateur modifié*/ $stmt->execute(); /*on regarde si ca a marché*/ if ($stmt->rowCount() == 1) { echo '<p>Modification effectuée</h1> <br> <a href="../Accueil.php">Revenir accueil</a>'; } else { echo '<p>Erreur</h1> <br> <a href="../Accueil.php">Revenir accueil</a>' ; } /* Si il y a une erreur dans les requetes sql ou PDO on affiche l'erreur pour le debugging*/ } catch(PDOException $e) { echo '<h1>Problème PDO</h1> <br> <a href="../Accueil.php">Revenir accueil</a>'; echo $e->getMessage(); } $stmt->closeCursor(); $pdo = null; } else { echo '<h1>Mauvais paramètres</h1> <br> <a href="../Accueil.php">Revenir accueil</a>'; }?> </center> <meta http-equiv="refresh" content="1; url=../Accueil.php" /> </body> </html>
true
933bebf0d3a406bf43a54d72d2edfb531398f0c0
PHP
rjilimarwa/a-sample--PHPUnit
/src/AppBundle/Entity/Serialiser.php
UTF-8
1,408
2.578125
3
[]
no_license
<?php namespace AppBundle\Entity; namespace JMS\Serialiser; use Metadata\MetadataFactoryInterface; use JMS\Serializer\Construction\ObjectConstructorInterface; use PhpCollection\MapInterface; use JMS\Serializer\EventDispatcher\EventDispatcherInterface; use JMS\Serializer\Handler\HandlerRegistryInterface; use JMS\Serializer\TypeParser; use JMS\Serializer\Expression\ExpressionEvaluatorInterface; /** * Class Serialiser * @package JMS\Serialiser */ class Serialiser { /** * Serialiser constructor. * @param MetadataFactoryInterface $factory * @param HandlerRegistryInterface $handlerRegistry * @param ObjectConstructorInterface $objectConstructor * @param MapInterface $serializationVisitors * @param MapInterface $deserializationVisitors * @param EventDispatcherInterface|null $dispatcher * @param TypeParser|null $typeParser * @param ExpressionEvaluatorInterface|null $expressionEvaluator */ public function __construct( MetadataFactoryInterface $factory, HandlerRegistryInterface $handlerRegistry, ObjectConstructorInterface $objectConstructor, MapInterface $serializationVisitors, MapInterface $deserializationVisitors, EventDispatcherInterface $dispatcher = null, TypeParser $typeParser = null, ExpressionEvaluatorInterface $expressionEvaluator = null ) { } }
true
8c4dc5269a3f4e8b65697ce5c41b8aa8004391e9
PHP
pitch7900/BlindTest
/app/Authentication/Authentication.php
UTF-8
18,969
2.78125
3
[ "Apache-2.0" ]
permissive
<?php declare(strict_types=1); namespace App\Authentication; use App\Database\User; use Carbon\Carbon; use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; /** * @author: Pierre Christensen * Manage authentication */ class Authentication { /** * IsAuthentified * * @return bool */ public static function IsAuthentified(): bool { if (isset($_SESSION['userid'])) { return true; } else { return false; } } /** * setUserID : Set database user id for current session * * @param mixed $userid * @return void */ private static function setUserID($userid) { $_SESSION["userid"] = $userid; } /** * getUserId : Return database user id * * @return int */ public static function getUserId(): int { return $_SESSION["userid"]; } /** * getUserEmail : Return user email addresse * * @return string */ public static function getUserEmail(): string { $user = User::find(Authentication::getUserId()); return $user->email; } /** * getUserNickName : return user nickname * * @return string */ public static function getUserNickName(): string { return User::find(Authentication::getUserId())->nickname; } /** * checkPassword : Check password for a given email address * * @param mixed $email * @param mixed $password * @return bool */ public static function checkPassword(string $email, string $password): bool { $email = strtolower($email); $user = User::where([ ['email', '=', $email] ])->first(); if (is_null($user)) { unset($_SESSION["userid"]); return false; } if (password_verify($password, $user->password)) { Authentication::setUserID($user->id); return true; } return false; } public static function setOriginalRequestedPage(string $page) { if (strcmp('/user/signout', $page) == 0) { $_SESSION['OriginalRequestedPage'] = '/'; } else { $_SESSION['OriginalRequestedPage'] = $page; } } public static function getOriginalRequestedPage(): string { if (isset($_SESSION['OriginalRequestedPage'])) { return $_SESSION['OriginalRequestedPage']; } else { return ""; } } /** * signout user and remove all $_SESSION entries * * @return void */ public static function signout() { unset($_SESSION['norobot']); unset($_SESSION["userid"]); } /** * sendValidationEmail : Send a validation email with link to validate email * * @param mixed $email * @param mixed $v4uuid * @return void */ public static function sendValidationEmail(string $email, string $v4uuid) { $mail = new PHPMailer(true); try { //Server settings // $mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output $mail->isSMTP(); // Send using SMTP $mail->Host = $_ENV['SMTP_SERVER']; // Set the SMTP server to send through if (strcmp($_ENV['SMTP_USEAUTH'], "true") == 0) { $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = $_ENV['SMTP_USERNAME']; // SMTP username $mail->Password = $_ENV['SMTP_PASSSWORD']; // SMTP password } if (strcmp($_ENV['SMTP_USESSL'], "true") == 0) { $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged } $mail->Port = $_ENV['SMTP_PORT']; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above //Recipients $mail->setFrom($_ENV['SMTP_MAILFROM'], 'Blindtest mailer daemon'); $mail->addAddress($email); // Add a recipient $mail->addReplyTo($_ENV['SMTP_MAILFROM'], 'Blindtest mailer daemon'); // Content $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'Mail validation for Blindtest'; $mail->Body = "<p>Hello,</p>" . "\r\n" . "<p>Please find below an URL to validate your email." . "</p>\r\n" . "<p>This link is valid for 15 minutes." . "</p>\r\n" . '<p><a href="' . $_ENV['PUBLIC_HOST'] . '/auth/checkmail/' . $v4uuid . '" >Validate my email address</a></p>'; $mail->AltBody = "Hello," . "\r\n" . "Please find below an URL to validate your email." . "\r\n" . "This link is valid for 15 minutes." . "\r\n" . $_ENV['PUBLIC_HOST'] . "/auth/checkmail/" . $v4uuid; $mail->send(); } catch (Exception $e) { die("Message could not be sent. Mailer Error: {$mail->ErrorInfo}"); } } /** * sendAdminsitratorEmail : Send to the admin an information email for a new account creation * * @param mixed $email * @return void */ public static function sendAdminsitratorEmail(string $email) { $mail = new PHPMailer(true); try { //Server settings // $mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output $mail->isSMTP(); // Send using SMTP $mail->Host = $_ENV['SMTP_SERVER']; // Set the SMTP server to send through if (strcmp($_ENV['SMTP_USEAUTH'], "true") == 0) { $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = $_ENV['SMTP_USERNAME']; // SMTP username $mail->Password = $_ENV['SMTP_PASSSWORD']; // SMTP password } if (strcmp($_ENV['SMTP_USESSL'], "true") == 0) { $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged } $mail->Port = $_ENV['SMTP_PORT']; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above //Recipients $mail->setFrom($_ENV['SMTP_MAILFROM'], 'Blindtest mailer daemon'); $mail->addAddress($_ENV['REGISTRATION_ADMIN_EMAIL']); // Add a recipient $mail->addReplyTo($_ENV['SMTP_MAILFROM'], 'Blindtest mailer daemon'); // Content $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'New account creation for Blindtest'; $mail->Body = "<p>Hello,</p>" . "\r\n" . "<p>A new account has been created for $email." . "</p>\r\n"; $mail->AltBody = "Hello," . "\r\n" . "A new account has been created for $email." . "\r\n"; $mail->send(); } catch (Exception $e) { die("Message could not be sent. Mailer Error: {$mail->ErrorInfo}"); } } /** * CurrentUserID * * @return int */ public static function CurrentUserID(): int { if (isset($_SESSION['userid'])) { return intval($_SESSION['userid']); } else { return -1; } } /** * sendValidationEmail : Send a validation email with link to validate email * * @param mixed $email * @param mixed $v4uuid * @return void */ public static function sendValidatorEmail(string $email, string $v4uuid) { $mail = new PHPMailer(true); try { //Server settings // $mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output $mail->isSMTP(); // Send using SMTP $mail->Host = $_ENV['SMTP_SERVER']; // Set the SMTP server to send through if (strcmp($_ENV['SMTP_USEAUTH'], "true") == 0) { $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = $_ENV['SMTP_USERNAME']; // SMTP username $mail->Password = $_ENV['SMTP_PASSSWORD']; // SMTP password } if (strcmp($_ENV['SMTP_USESSL'], "true") == 0) { $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged } $mail->Port = $_ENV['SMTP_PORT']; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above //Recipients $mail->setFrom($_ENV['SMTP_MAILFROM'], 'Blindtest mailer daemon'); $mail->addAddress($_ENV['REGISTRATION_ADMIN_EMAIL']); // Add a recipient $mail->addReplyTo($_ENV['SMTP_MAILFROM'], 'Blindtest mailer daemon'); // Content $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'Mail validation for Blindtest'; $mail->Body = "<p>Hello,</p>" . "\r\n" . "<p>Please find below an URL to validate the email for user $email." . "</p>\r\n" . '<p><a href="' . $_ENV['PUBLIC_HOST'] . '/auth/validate/' . $v4uuid . '" >Validate this user email address</a></p>'; $mail->AltBody = "Hello," . "\r\n" . "Please find below an URL to validate the email for user $email." . "\r\n" . $_ENV['PUBLIC_HOST'] . "/auth/validate/" . $v4uuid; $mail->send(); } catch (Exception $e) { die("Message could not be sent. Mailer Error: {$mail->ErrorInfo}"); } } /** * addUser : Add a user and Send an email link to validate the email address as valid * * @param mixed $email * @param mixed $encryptedpassword * @return bool */ public static function addUser(string $email, string $encryptedpassword, string $nickname): bool { $email = strtolower($email); $user = User::where([ ['email', 'like', $email] ])->first(); if (is_null($user)) { $v4uuid_user = UUID::v4(); $v4uuid_validator = UUID::v4(); //current timestamp +15 minutes $timestamp = Carbon::createFromTimestamp(time() + 15 * 60); User::updateOrCreate([ 'email' => $email, 'password' => $encryptedpassword, 'nickname' => $nickname, 'emailchecklink' => $v4uuid_user, 'emailchecklinktimeout' => $timestamp, //curent time + 15 minutes 'emailchecked' => false, 'resetpasswordlink' => null, 'resetpasswordlinktimeout' => null, 'approvaleuuid' => $v4uuid_validator, 'adminapproved' => false, 'darktheme' => true ]); if (strcmp($_ENV['REGISTRATION_REQUIRE_APPROVAL'], "true") == 0) { Authentication::sendValidatorEmail($email, $v4uuid_validator); } else { $user = User::where([ ['email', '=', $email] ])->first(); $user->adminapproved = true; Authentication::sendAdminsitratorEmail($email); Authentication::sendValidationEmail($email, $v4uuid_user); } } return true; } /** * validateEmail : check the email is valid (Answer of the addUser email) * * @param mixed $uuid * @return bool */ public static function validateEmail(string $uuid): bool { $user = User::where([ ['emailchecklink', 'like', $uuid] ])->first(); if (!is_null($user)) { $time = $user->emailchecklinktimeout; $validationtime = Carbon::createFromFormat(Carbon::DEFAULT_TO_STRING_FORMAT, $time); $currenttime = Carbon::createFromTimestamp(time()); if ($validationtime->gte($currenttime)) { //Mail is checked, we can trust this user $user->emailchecked = true; $user->save(); Authentication::setUserID($user->id); return true; } else { $user->emailchecked = false; $user->save(); unset($_SESSION["userid"]); return false; } } return false; } /** * setNickname : change nickname for current user's session * * @param mixed $nickname * @return void */ public static function setNickname(string $nickname) { $user = User::find(Authentication::getUserId()); $user->nickname = $nickname; $user->save(); } /** * return current user name * @return string */ public static function CurrentUserName() { return User::getUserName(Authentication::CurrentUserID()); } /** * resetPassword : set a new password for the uuid passed * * @param mixed $uuid * @param mixed $encryptedpassword * @return void */ public static function resetPassword(string $uuid, string $encryptedpassword): void { if (Authentication::checkUUIDpasswordreset($uuid)) { $user = User::where([ ['resetpasswordlink', 'like', $uuid] ])->first(); //reset the password $user->password = $encryptedpassword; //Set the reset link to now, for avoiding attacks $user->resetpasswordlinktimeout = Carbon::createFromTimestamp(time()); $user->save(); } } /** * changePassword * * @param mixed $newencryptedpasssword * @return void */ public static function changePassword(string $newencryptedpasssword) { User::find(Authentication::getUserId())->password = $newencryptedpasssword; } /** * checkUUIDpasswordreest : check if UUID is valid * * @param mixed $uuid * @return bool */ public static function checkUUIDpasswordreset(string $uuid): bool { $user = User::where([ ['resetpasswordlink', 'like', $uuid] ])->first(); if (!is_null($user)) { $time = $user->resetpasswordlinktimeout; $validationtime = Carbon::createFromFormat(Carbon::DEFAULT_TO_STRING_FORMAT, $time); $currenttime = Carbon::createFromTimestamp(time()); if ($validationtime->gte($currenttime)) { return true; } } return false; } /** * sendResetPasswordLink : Create a UUID for password reset with 15 min validity and send the email with reset link * * @param mixed $email * @return bool */ public static function sendResetPasswordLink(string $email): bool { $email = strtolower($email); $user = User::where([ ['email', 'like', $email] ])->first(); if (!is_null($user)) { $v4uuid = UUID::v4(); //current timestamp +15 minutes $timestamp = Carbon::createFromTimestamp(time() + 15 * 60); $user->resetpasswordlink = $v4uuid; $user->resetpasswordlinktimeout = $timestamp; $user->save(); $mail = new PHPMailer(true); try { //Server settings // $mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output $mail->isSMTP(); // Send using SMTP $mail->Host = $_ENV['SMTP_SERVER']; // Set the SMTP server to send through if (strcmp($_ENV['SMTP_USEAUTH'], "true") == 0) { $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = $_ENV['SMTP_USERNAME']; // SMTP username $mail->Password = $_ENV['SMTP_PASSSWORD']; // SMTP password } if (strcmp($_ENV['SMTP_USESSL'], "true") == 0) { $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged } $mail->Port = $_ENV['SMTP_PORT']; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above //Recipients $mail->setFrom($_ENV['SMTP_MAILFROM'], 'Blindtest mailer daemon'); $mail->addAddress($email); // Add a recipient $mail->addReplyTo($_ENV['SMTP_MAILFROM'], 'Blindtest mailer daemon'); // Content $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'Password reset for Blindtest'; $mail->Body = "<p>Hello,</p>" . "\r\n" . "<p>Please find below an URL to reset your password." . "</p>\r\n" . "<p>This link is valid for 15 minutes." . "</p>\r\n" . '<p><a href="' . $_ENV['PUBLIC_HOST'] . '/auth/resetpassword/' . $v4uuid . '" >Validate my email address</a>' . "</p>\r\n" . "<br>" . "\r\n" . "<p>Note : If you're not at the origin of this password reset, simply ignore this email</p>" . "\r\n"; $mail->AltBody = "Hello," . "\r\n" . "Please find below an URL to reset your password." . "\r\n" . "This link is valid for 15 minutes." . "\r\n" . $_ENV['PUBLIC_HOST'] . "/auth/resetpassword/" . $v4uuid . "\r\n" . "\r\n" . "Note : If you're not at the origin of this password reset, simply ignore this email" . "\r\n";; $mail->send(); } catch (Exception $e) { die("Message could not be sent. Mailer Error: {$mail->ErrorInfo}"); } } return true; } }
true
1c2f31319ba42b603ff5d9b4ed92a9bc3cb94dee
PHP
Markcial/fs-wrapper
/src/Socket.php
UTF-8
484
2.828125
3
[ "MIT" ]
permissive
<?php namespace Fs; use Fs\Socket\Client; use Fs\Socket\Server; class Socket extends File { /** @var Server|Client|null */ protected $socket; /** * @return Client|null */ public function client() { $this->socket = new Client($this->path); return $this->socket; } /** * @return Server|null */ public function server() { $this->socket = new Server($this->path); return $this->socket; } }
true
73b455c369927b7b644c45c47ec294582bf6dcdf
PHP
yeka/Stringy
/src/Stringy/Stringy.php
UTF-8
23,068
3.59375
4
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php namespace Stringy; class Stringy { /** * Converts the first character of the supplied string to upper case. * * @param string $str String to modify * @param string $encoding The character encoding * @return string String with the first character being upper case */ public static function upperCaseFirst($str, $encoding = null) { $encoding = $encoding ?: mb_internal_encoding(); $first = mb_substr($str, 0, 1, $encoding); $rest = mb_substr($str, 1, mb_strlen($str, $encoding) - 1, $encoding); return mb_strtoupper($first, $encoding) . $rest; } /** * Converts the first character of the supplied string to lower case. * * @param string $str String to modify * @param string $encoding The character encoding * @return string String with the first character being lower case */ public static function lowerCaseFirst($str, $encoding = null) { $encoding = $encoding ?: mb_internal_encoding(); $first = mb_substr($str, 0, 1, $encoding); $rest = mb_substr($str, 1, mb_strlen($str, $encoding) - 1, $encoding); return mb_strtolower($first, $encoding) . $rest; } /** * Returns a camelCase version of a supplied string. Trims surrounding * spaces, capitalizes letters following digits, spaces, dashes and * underscores, and removes spaces, dashes, underscores. * * @param string $str String to convert to camelCase * @param string $encoding The character encoding * @return string String in camelCase */ public static function camelize($str, $encoding = null) { $encoding = $encoding ?: mb_internal_encoding(); $camelCase = preg_replace_callback( '/[-_\s]+(.)?/u', function ($matches) use (&$encoding) { return $matches[1] ? mb_strtoupper($matches[1], $encoding) : ""; }, self::lowerCaseFirst(trim($str), $encoding) ); $camelCase = preg_replace_callback( '/[\d]+(.)?/u', function ($matches) use (&$encoding) { return mb_strtoupper($matches[0], $encoding); }, $camelCase ); return $camelCase; } /** * Returns an UpperCamelCase version of a supplied string. Trims surrounding * spaces, capitalizes letters following digits, spaces, dashes and * underscores, and removes spaces, dashes, underscores. * * @param string $str String to convert to UpperCamelCase * @param string $encoding The character encoding * @return string String in UpperCamelCase */ public static function upperCamelize($str, $encoding = null) { $encoding = $encoding ?: mb_internal_encoding(); $camelCase = self::camelize($str, $encoding); return self::upperCaseFirst($camelCase, $encoding); } /** * Returns a lowercase and trimmed string seperated by dashes. Dashes are * inserted before uppercase characters (with the exception of the first * character of the string), and in place of spaces as well as underscores. * * @param string $str String to convert * @param string $encoding The character encoding * @return string Dasherized string */ public static function dasherize($str, $encoding = null) { $encoding = $encoding ?: mb_internal_encoding(); mb_regex_encoding($encoding); $dasherized = mb_ereg_replace('\B([A-Z])', '-\1', trim($str)); $dasherized = mb_ereg_replace('[-_\s]+', '-', $dasherized); return mb_strtolower($dasherized, $encoding); } /** * Returns a lowercase and trimmed string seperated by underscores. * Underscores are inserted before uppercase characters (with the exception * of the first character of the string), and in place of spaces as well as * dashes. * * @param string $str String to convert * @param string $encoding The character encoding * @return string Underscored string */ public static function underscored($str, $encoding = null) { $encoding = $encoding ?: mb_internal_encoding(); mb_regex_encoding($encoding); $underscored = mb_ereg_replace('\B([A-Z])', '_\1', trim($str)); $underscored = mb_ereg_replace('[-_\s]+', '_', $underscored); return mb_strtolower($underscored, $encoding); } /** * Returns a case swapped version of a string. * * @param string $str String to swap case * @param string $encoding The character encoding * @return string String with each character's case swapped */ public static function swapCase($str, $encoding = null) { $encoding = $encoding ?: mb_internal_encoding(); $swapped = preg_replace_callback( '/[\S]/u', function ($match) use (&$encoding) { if ($match[0] == mb_strtoupper($match[0], $encoding)) return mb_strtolower($match[0], $encoding); else return mb_strtoupper($match[0], $encoding); }, $str ); return $swapped; } /** * Capitalizes the first letter of each word in a string, after trimming. * Ignores the case of other letters, allowing for the use of acronyms. * Also accepts an array, $ignore, allowing you to list words not to be * capitalized. * * @param string $str String to titleize * @param string $encoding The character encoding * @param array $ignore An array of words not to capitalize * @return string Titleized string */ public static function titleize($str, $ignore = null, $encoding = null) { $encoding = $encoding ?: mb_internal_encoding(); $titleized = preg_replace_callback( '/([\S]+)/u', function ($match) use (&$encoding, &$ignore) { if ($ignore && in_array($match[0], $ignore)) return $match[0]; return Stringy::upperCaseFirst($match[0], $encoding); }, trim($str) ); return $titleized; } /** * Capitalizes the first word of a string, replaces underscores with spaces, * and strips '_id'. * * @param string $str String to humanize * @param string $encoding The character encoding * @return string A humanized string */ public static function humanize($str, $encoding = null) { $humanized = str_replace('_id', '', $str); $humanized = str_replace('_', ' ', $humanized); return self::upperCaseFirst(trim($humanized), $encoding); } /** * Replaces smart quotes, ellipsis characters, and dashes from Windows-1252 * (and commonly used in Word documents) with their ASCII equivalents. * * @param string $str String to remove special chars * @param string $encoding The character encoding * @return string String with those characters removed */ public static function tidy($str) { $tidied = preg_replace('/\x{2026}/u', '...', $str); $tidied = preg_replace('/[\x{201C}\x{201D}]/u', '"', $tidied); $tidied = preg_replace('/[\x{2018}\x{2019}]/u', "'", $tidied); $tidied = preg_replace('/[\x{2013}\x{2014}]/u', '-', $tidied); return $tidied; } /** * Trims the string and replaces consecutive whitespace characters with a * single space. * * @param string $str The string to cleanup whitespace * @return string The trimmed string with condensed whitespace */ public static function clean($str) { return preg_replace('/\s+/u', ' ', trim($str)); } /** * Converts some non-ASCII characters to their closest ASCII counterparts. * * @param string $str A string with non-ASCII characters * @return string The string after the replacements */ public static function standardize($str) { $charsArray = array( 'a' => array('à', 'á', 'â', 'ã', 'ă', 'ä', 'å', 'ą'), 'c' => array('ć', 'č', 'ç'), 'd' => array('ď', 'đ'), 'e' => array('è', 'é', 'ê', 'ě', 'ë', 'ę'), 'g' => array('ğ'), 'i' => array('ì', 'í', 'ï', 'î'), 'l' => array('ĺ', 'ł'), 'n' => array('ń', 'ñ', 'ň'), 'o' => array('ò', 'ó', 'ô', 'õ', 'ö', 'ø'), 'r' => array('ř', 'ŕ'), 's' => array('š', 'š', 'ş'), 't' => array('ť', 'ţ'), 'u' => array('ü', 'ù', 'ú', 'û', 'µ', 'ů'), 'y' => array('ý', 'ÿ'), 'z' => array('ź', 'ž', 'ż'), 'A' => array('À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Ă', 'Ą'), 'C' => array('Ć', 'Č', 'Ç'), 'D' => array('Ď', 'Ð'), 'E' => array('È', 'É', 'Ê', 'Ë', 'Ě', 'Ę'), 'G' => array('Ğ'), 'I' => array('Ì', 'Í', 'Ï', 'Î'), 'L' => array('Ĺ', 'Ł'), 'N' => array('Ń', 'Ñ', 'Ň'), 'O' => array('Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø'), 'R' => array('Ř', 'Ŕ'), 'S' => array('Š', 'Ş', 'Ś'), 'T' => array('Ť', 'Ţ'), 'U' => array('Ü', 'Ù', 'Ú', 'Û', 'Ů'), 'Y' => array('Ý', 'Ÿ'), 'Z' => array('Ź', 'Ž', 'Ż') ); foreach ($charsArray as $key => $value) { $str = str_replace($value, $key, $str); } return $str; } /** * Pads a string to a given length with another string. If length is less * than or equal to the length of $str, then no padding takes places. The * default string used for padding is a space, and the default type (one of * 'left', 'right', 'both') is 'right'. * * @param string $str String to pad * @param int $length Desired string length after padding * @param string $padStr String used to pad, defaults to space * @param string $padType One of 'left', 'right', 'both' * @param string $encoding The character encoding * @return string The padded string * @throws InvalidArgumentException If $padType isn't one of 'right', * 'left' or 'both' */ public static function pad($str, $length, $padStr = ' ', $padType = 'right', $encoding = null) { $encoding = $encoding ?: mb_internal_encoding(); if (!in_array($padType, array('left', 'right', 'both'))) { throw new InvalidArgumentException('Pad expects the fourth ' . "argument to be one of 'left', 'right' or 'both'"); } $strLength = mb_strlen($str, $encoding); $padStrLength = mb_strlen($padStr, $encoding); if ($length <= $strLength || $padStrLength <= 0) return $str; // Number of times to repeat the padStr if left or right $times = ceil(($length - $strLength) / $padStrLength); $paddedStr = ''; if ($padType == 'left') { // Repeat the pad, cut it, and prepend $leftPad = str_repeat($padStr, $times); $leftPad = mb_substr($leftPad, 0, $length - $strLength, $encoding); $paddedStr = $leftPad . $str; } elseif ($padType == 'right') { // Append the repeated pad and get a substring of the given length $paddedStr = $str . str_repeat($padStr, $times); $paddedStr = mb_substr($paddedStr, 0, $length, $encoding); } else { // Number of times to repeat the padStr on both sides $paddingSize = ($length - $strLength) / 2; $times = ceil($paddingSize / $padStrLength); // Favour right padding over left, as with str_pad() $rightPad = str_repeat($padStr, $times); $rightPad = mb_substr($rightPad, 0, ceil($paddingSize), $encoding); $leftPad = str_repeat($padStr, $times); $leftPad = mb_substr($leftPad, 0, floor($paddingSize), $encoding); $paddedStr = $leftPad . $str . $rightPad; } return $paddedStr; } /** * Returns a new string of a given length such that the beginning of the * string is padded. Alias for pad($str, $length, $padStr, 'left', $encoding) * * @param string $str String to pad * @param int $length Desired string length after padding * @param string $padStr String used to pad, defaults to space * @param string $encoding The character encoding * @return string The padded string */ public static function padLeft($str, $length, $padStr = ' ', $encoding = null) { return self::pad($str, $length, $padStr, 'left', $encoding); } /** * Returns a new string of a given length such that the end of the string is * padded. Alias for pad($str, $length, $padStr, 'right', $encoding) * * @param string $str String to pad * @param int $length Desired string length after padding * @param string $padStr String used to pad, defaults to space * @param string $encoding The character encoding * @return string The padded string */ public static function padRight($str, $length, $padStr = ' ', $encoding = null) { return self::pad($str, $length, $padStr, 'right', $encoding); } /** * Returns a new string of a given length such that both sides of the string * string are padded. Alias for pad($str, $length, $padStr, 'both', $encoding) * * @param string $str String to pad * @param int $length Desired string length after padding * @param string $padStr String used to pad, defaults to space * @param string $encoding The character encoding * @return string The padded string */ public static function padBoth($str, $length, $padStr = ' ', $encoding = null) { return self::pad($str, $length, $padStr, 'both', $encoding); } /** * Returns true if the string $str begins with $substring, false otherwise. * By default, the comparison is case-sensitive, but can be made insensitive * by setting $caseSensitive to false. * * @param string $str String to check the start of * @param string $substring The substring to look for * @param bool $caseSensitive Whether or not to enfore case-sensitivity * @param string $encoding The character encoding * @return bool Whether or not $str starts with $substring */ public static function startsWith($str, $substring, $caseSensitive = true, $encoding = null) { $encoding = $encoding ?: mb_internal_encoding(); $substringLength = mb_strlen($substring, $encoding); $startOfStr = mb_substr($str, 0, $substringLength, $encoding); if (!$caseSensitive) { $substring = mb_strtolower($substring, $encoding); $startOfStr = mb_strtolower($startOfStr, $encoding); } return $substring === $startOfStr; } /** * Returns true if the string $str ends with $substring, false otherwise. * By default, the comparison is case-sensitive, but can be made insensitive * by setting $caseSensitive to false. * * @param string $str String to check the end of * @param string $substring The substring to look for * @param bool $caseSensitive Whether or not to enfore case-sensitivity * @param string $encoding The character encoding * @return bool Whether or not $str ends with $substring */ public static function endsWith($str, $substring, $caseSensitive = true, $encoding = null) { $encoding = $encoding ?: mb_internal_encoding(); $substringLength = mb_strlen($substring, $encoding); $strLength = mb_strlen($str, $encoding); $endOfStr = mb_substr($str, $strLength - $substringLength, $substringLength, $encoding); if (!$caseSensitive) { $substring = mb_strtolower($substring, $encoding); $endOfStr = mb_strtolower($endOfStr, $encoding); } return $substring === $endOfStr; } /** * Converts each tab in a string to some number of spaces, as defined by * $tabLength. By default, each tab is converted to 4 consecutive spaces. * * @param string $str String to convert tabs to spaces * @param int $tabLength Number of spaces to replace each tab with * @return string String with tabs switched to spaces */ public static function toSpaces($str, $tabLength = 4) { $spaces = str_repeat(' ', $tabLength); return str_replace("\t", $spaces, $str); } /** * Converts each occurence of some consecutive number of spaces, as defined * by $tabLength, to a tab. By default, each 4 consecutive spaces are * converted to a tab. * * @param string $str String to convert spaces to tabs * @param int $tabLength Number of spaces to replace with a tab * @return string String with spaces switched to tabs */ public static function toTabs($str, $tabLength = 4) { $spaces = str_repeat(' ', $tabLength); return str_replace($spaces, "\t", $str); } /** * Converts the supplied text into an URL slug. This includes replacing * non-ASCII characters with their closest ASCII equivalents, removing * non-alphanumeric and non-ASCII characters, and replacing whitespace with * dashes. The string is also converted to lowercase. * * @param string $str Text to transform into an URL slug * @return string The corresponding URL slug */ public static function slugify($str) { $str = preg_replace('/[^a-zA-Z\d -]/u', '', self::standardize($str)); $str = self::clean($str); return str_replace(' ', '-', strtolower($str)); } /** * Returns true if $haystack contains $needle, false otherwise. * * @param string $haystack String being checked * @param string $needle Substring to look for * @param string $encoding The character encoding * @return bool Whether or not $haystack contains $needle */ public static function contains($haystack, $needle, $encoding = null) { $encoding = $encoding ?: mb_internal_encoding(); if (mb_strpos($haystack, $needle, 0, $encoding) !== false) return true; return false; } /** * Surrounds a string with the given substring. * * @param string $str The string to surround * @param string $substring The substring to add to both sides * @return string The string with the substring prepended and appended */ public static function surround($str, $substring) { return implode('', array($substring, $str, $substring)); } /** * Inserts $substring into $str at the $index provided. * * @param string $str String to insert into * @param string $substring String to be inserted * @param int $index The index at which to insert the substring * @param string $encoding The character encoding * @return string The resulting string after the insertion */ public static function insert($str, $substring, $index, $encoding = null) { $encoding = $encoding ?: mb_internal_encoding(); if ($index > mb_strlen($str, $encoding)) return $str; $start = mb_substr($str, 0, $index, $encoding); $end = mb_substr($str, $index, mb_strlen($str, $encoding), $encoding); return $start . $substring . $end; } /** * Truncates the string to a given length, while ensuring that it does not * chop words. If $substring is provided, and truncating occurs, the string * is further truncated so that the substring may be appended without * exceeding the desired length. * * @param string $str String to truncate * @param int $length Desired length of the truncated string * @param string $substring The substring to append if it can fit * @param string $encoding The character encoding * @return string The resulting string after truncating */ public static function truncate($str, $length, $substring = '', $encoding = null) { $encoding = $encoding ?: mb_internal_encoding(); if ($length >= mb_strlen($str, $encoding)) return $str; // Need to further trim the string so we can append the substring $substringLength = mb_strlen($substring, $encoding); $length = $length - $substringLength; $truncated = mb_substr($str, 0, $length, $encoding); // If the last word was truncated if (mb_strpos($str, ' ', $length - 1, $encoding) != $length) { // Find pos of the last occurence of a space, and get everything up until $lastPos = mb_strrpos($truncated, ' ', 0, $encoding); $truncated = mb_substr($truncated, 0, $lastPos, $encoding); } return $truncated . $substring; } /** * Reverses a string. A multibyte version of strrev. * * @param string $str String to reverse * @param string $encoding The character encoding * @return string The reversed string */ public static function reverse($str, $encoding = null) { $encoding = $encoding ?: mb_internal_encoding(); $strLength = mb_strlen($str, $encoding); $reversed = ''; // Loop from last index of string to first for ($i = $strLength - 1; $i >= 0; $i--) { $reversed .= mb_substr($str, $i, 1, $encoding); } return $reversed; } /** * A multibyte str_shuffle function. It randomizes the order of characters * in a string. * * @param string $str String to shuffle * @param string $encoding The character encoding * @return string The shuffled string */ public static function shuffle($str, $encoding = null) { $encoding = $encoding ?: mb_internal_encoding(); $indexes = range(0, mb_strlen($str, $encoding) - 1); shuffle($indexes); $shuffledStr = ''; foreach ($indexes as $i) { $shuffledStr .= mb_substr($str, $i, 1, $encoding); } return $shuffledStr; } } ?>
true
64e61858381b87b9734c3eaedf1c621a268b3cdc
PHP
xiaochong0302/cphalcon
/tests/unit/Assets/Filters/Jsmin/FilterCest.php
UTF-8
4,182
2.5625
3
[ "BSD-3-Clause" ]
permissive
<?php /** * This file is part of the Phalcon Framework. * * (c) Phalcon Team <team@phalcon.io> * * For the full copyright and license information, please view the LICENSE.txt * file that was distributed with this source code. */ declare(strict_types=1); namespace Phalcon\Test\Unit\Assets\Filters\Jsmin; use Phalcon\Assets\Filters\Jsmin; use UnitTester; class FilterCest { /** * Tests Phalcon\Assets\Filters\Jsmin :: filter() * * @author Phalcon Team <team@phalcon.io> * @since 2016-01-24 */ public function assetsFiltersJsminFilter(UnitTester $I) { $I->wantToTest('Assets\Filters\Jsmin - filter()'); $I->skipTest('Need Phalcon implementation'); $jsmin = new Jsmin(); $actual = $jsmin->filter('{}}'); $I->assertEquals( "\n" . '{}}', $actual ); } /** * Tests Phalcon\Assets\Filters\Jsmin :: filter() - spaces * * @author Phalcon Team <team@phalcon.io> * @since 2016-01-24 */ public function assetsFiltersJsminFilterSpaces(UnitTester $I) { $I->wantToTest('Assets\Filters\Jsmin - filter() - spaces'); $I->skipTest('Need Phalcon implementation'); $jsmin = new Jsmin(); $actual = $jsmin->filter( 'if ( a == b ) { document . writeln("hello") ; }' ); $I->assertEquals( "\n" . 'if(a==b){document.writeln("hello");}', $actual ); } /** * Tests Phalcon\Assets\Filters\Jsmin :: filter() - tabs * * @author Phalcon Team <team@phalcon.io> * @since 2016-01-24 */ public function assetsFiltersJsminFilterTabs(UnitTester $I) { $I->wantToTest('Assets\Filters\Jsmin - filter() - tabs'); $I->skipTest('Need Phalcon implementation'); $jsmin = new Jsmin(); $actual = $jsmin->filter( "\n" . "if ( a == b ) { document . writeln('\t') ; }" ); $I->assertEquals( "\n" . "if(a==b){document.writeln('\t');}", $actual ); } /** * Tests Phalcon\Assets\Filters\Jsmin :: filter() - tabs comment * * @author Phalcon Team <team@phalcon.io> * @since 2016-01-24 */ public function assetsFiltersJsminFilterTabsComment(UnitTester $I) { $I->wantToTest('Assets\Filters\Jsmin - filter() - tabs comment'); $I->skipTest('Need Phalcon implementation'); $jsmin = new Jsmin(); $actual = $jsmin->filter( "/** this is a comment */ if ( a == b ) { document . writeln('\t') ; /** this is a comment */ }" ); $I->assertEquals( "\nif(a==b){document.writeln('\t');}", $actual ); } /** * Tests Phalcon\Assets\Filters\Jsmin :: filter() - tabs newlines * * @author Phalcon Team <team@phalcon.io> * @since 2016-01-24 */ public function assetsFiltersJsminFilterTabsCommentNewlines(UnitTester $I) { $I->wantToTest('Assets\Filters\Jsmin - filter() - tabs newlines'); $I->skipTest('Need Phalcon implementation'); $jsmin = new Jsmin(); $expected = "\n" . 'a=100;'; $actual = $jsmin->filter("\t\ta\t\r\n= \n \r\n100;\t"); $I->assertEquals($expected, $actual); } /** * Tests Phalcon\Assets\Filters\Jsmin :: filter() - empty * * @author Phalcon Team <team@phalcon.io> * @since 2016-01-24 */ public function assetsFiltersJsminFilterEmpty(UnitTester $I) { $I->wantToTest('Assets\Filters\Jsmin - filter() - empty'); $I->skipTest('Need Phalcon implementation'); $jsmin = new Jsmin(); $I->assertIsEmpty( $jsmin->filter('') ); } /** * Tests Phalcon\Assets\Filters\Jsmin :: filter() - comment * * @author Phalcon Team <team@phalcon.io> * @since 2016-01-24 */ public function assetsFiltersJsminFilterComment(UnitTester $I) { $I->wantToTest('Assets\Filters\Jsmin - filter() - comment'); $I->skipTest('Need Phalcon implementation'); $jsmin = new Jsmin(); $I->assertIsEmpty( $jsmin->filter('/** this is a comment */') ); } }
true
165fd0fc6d3df52de92ad3743e669303d6148df5
PHP
iqbalbaharum/rivilTool
/api/v1/Models/Oauth.class.php
UTF-8
839
2.84375
3
[]
no_license
<?php require('Models/ApiKey'); class Oauth extends API { protected $User; /*** * * @param $request * Authorization : Bearer <APIKey> */ public function __construct($request, $origin) { parent::__construct($request); $APIKey = Models/ApiKey(); if (!array_key_exists('apiKey', $this->request)) { throw new Exception('No API Key provided'); } else if (!$APIKey->verifyKey($this->request['apiKey'], $origin)) { throw new Exception('Invalid API Key'); } } /** * Example of an Endpoint */ protected function authenticate($args) { if ($this->method == 'POST') { // Validate username & password // Create user token // Store token // pass token } else { return "Only accepts GET requests"; } } } ?>
true
f96d9d214416111f90ec77366c985ec140e0de05
PHP
herbrich/Jenni-CMS
/setupx.php
UTF-8
3,104
2.515625
3
[]
no_license
<?php $table = "rootLevel_Sites"; $rootTable = ' CREATE TABLE IF NOT EXISTS `' . $table . '` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `Title` varchar(94) DEFAULT NULL, `Content` text, `Parrent` int(11) DEFAULT NULL, PRIMARY KEY (`ID`) ) ENGINE=InnoDB DEFAULT CHARSET=big5 AUTO_INCREMENT=12 ;'; function CreateDataBase() { } function CreateConfigFille($dbServer,$dbName,$dbUser,$dbPassword) { $configFille = ' <?php /** This is the Configuration PHP Fille. **/ /**Database Relevanted Stuf**/ $server = "%server%"; //The MySQL-Server that running the database; $database = "%database%"; //The Database; $user = "%user%"; //The Username to access the MySQL Server; $password = "%password%"; //The Password to autenthicate you user on the MySQL Server; $table = "%table%"; //The table the sotres the Sites; /**Jenni-CMS relevanted config Stuff**/ $installed=%installed%; //has value true or false, if flase the install screen is unlooct otherwise the install screen is open ?> '; $myConfig = str_replace("%server%",$dbServer,str_replace("%database%",$dbName,str_replace("%user%",$dbUser,str_replace("%password%",$dbPassword,str_replace("%table%","Jenni-CMS",str_replace("%installed%","true",$configFille)))))); $xConfig = fopen("jh_conf.php","w"); fwrite($xConfig,$myConfig); } //Comment out for Debug! CreateConfigFille("server","Jenni-CMS","user","password"); ?> <div id="content"> <div id="innerContent"> <h2>Jenni-CMS Installation</h2> <p>Das ist die Instalations-Seite des Jenni-CMS, hier werden iniziale Einstellungen vorgenommen wie Datenbank und sonstige umbedingt benötigten einstellungen.</p> <hr style="color:#FF0000;"/> <form method="post"> <table> <tr> <td>Installations Art</td> <td> <ul> <li><input type="radio" name="setupMode" value="install">Neu Installieren</input></li> <li><input type="radio" name="setupMode" value="join">Mit Existierender Datenbank Verbinden</input></li> </ul> </td> </tr> <tr> <td><p>MySQL Server</p></td> <td><input type="text" name="dbServer"/></td> </tr> <tr> <td><p>MySQL Datenbank Name</p></td> <td><input type="text" name="dbName"/></td> </tr> <tr> <td><p>MySQL Benutzername</p></td> <td><input type="text" name="dbUser"/></td> </tr> <tr> <td><p>MySQL Password</p></td> <td><input type="password" name="dbPassword"/></td> </tr> </table> <input type="submit" value="Speichern"/> </form> </div> </div> <?php $dbServer = $_POST["dbServer"]; $dbName = $_POST["dbName"]; $dbUser = $_POST["dbUser"]; $dbPassword = $_POST["dbPassword"]; $setupMode = $_POST["setupMode"]; function JoinDB() { try { CreateConfigFille($dbServer,$dbName,$dbUser,$dbPassword); } catch($e0) { echo("Beim Beiträten der Datenbank Domäne ist ein Fehler aufgetreten!"); } } function CreateDB() { } if($setupMode != NULL) { switch($setupMode) { switch "join": JoinDB(); break; switch "install": CreateDB(); break; } } ?>
true
77e0ef3be544c36d3784f2a28da8eccd53bde962
PHP
LucasVSCS/bees-plants-api
/app/Interfaces/BeeInterface.php
UTF-8
198
2.53125
3
[]
no_license
<?php namespace App\Interfaces; use App\Http\Requests\Api\CreateBeeRequest; interface BeeInterface { public function getAllBees(); public function storeBee(CreateBeeRequest $request); }
true
1e0193207101520f77ce4ca84c555abe15fc1384
PHP
parsica-php/parsica
/src/sideEffects.php
UTF-8
1,217
2.828125
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); /** * This file is part of the Parsica library. * * Copyright (c) 2020 Mathias Verraes <mathias@verraes.net> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Parsica\Parsica; /** * If the parser is successful, call the $receiver function with the output of the parser. The resulting parser * behaves identical to the original one. This combinator is useful for expressing side effects during the parsing * process. It can be hooked into existing event publishing libraries by using $receiver as an adapter for those. Other * use cases are logging, caching, performing an action whenever a value is matched in a long running input stream, ... * * @template T * @psalm-param Parser<T> $parser * @psalm-param callable(T): void $receiver * @psalm-return Parser<T> * @api */ function emit(Parser $parser, callable $receiver): Parser { return Parser::make("emit", static function (Stream $input) use ($receiver, $parser): ParseResult { $result = $parser->run($input); if ($result->isSuccess()) { $receiver($result->output()); } return $result; }); }
true
457919a6df158a00a322252a3ad3e4cff6bf5e1e
PHP
tgozo19/laravel-codegen
/src/Console/Commands/Migrations/Traits/MethodsTrait.php
UTF-8
2,435
2.609375
3
[ "MIT" ]
permissive
<?php namespace Tgozo\LaravelCodegen\Console\Commands\Migrations\Traits; trait MethodsTrait { public function getStubName($migrationName) { return $this->stub_names[$this->checkStart($migrationName)]; } public function getFieldNamesString($fields): string { if (empty($fields)) return "''"; if (count($fields) === 1) return "'{$fields[0]['name']}'"; return "[" . join(',', array_map(function ($field){ return "'{$field['name']}'"; }, $fields)) . "]"; } public function get_migration_description(mixed $migrationType, $fields, string $tableName, $migrationName): mixed { if (empty($fields)) return $migrationName; if ($migrationType === "add_column") { $column = $fields[0]['name']; return "add_column_{$column}_to_{$tableName}_table"; } if ($migrationType === "add_columns") { $columns = join('-', array_map(function ($field) { return "{$field['name']}"; }, $fields)); return "add_columns_{$columns}_to_{$tableName}_table"; } return $migrationName; } public function createMigration($migrationName, $fields, $migrationType = "create"): string { $tableName = $this->getTableName($migrationName); $stubName = $this->getStubName($migrationName); $codegen_path = $this->codegen_path("stubs/migration.{$stubName}.stub"); $stub = file_get_contents($codegen_path); $stub = str_replace('{{ tableName }}', $tableName, $stub); $fieldsString = $this->getFieldsString($fields); $stub = str_replace('{{ fields }}', $fieldsString, $stub); if ($migrationType === "add_column"){ $dropFieldsString = $this->getFieldNamesString($fields); $stub = str_replace('{{ dropFields }}', $dropFieldsString, $stub); } if ($migrationType === "add_columns"){ $dropFieldsString = $this->getFieldNamesString($fields); $stub = str_replace('{{ dropFields }}', $dropFieldsString, $stub); } $file_name = $this->get_migration_description($migrationType, $fields, $tableName, $migrationName); $migrationFile = database_path('migrations') . '/' . date('Y_m_d_His') . '_' . $file_name . '.php'; file_put_contents($migrationFile, $stub); return $migrationFile; } }
true
62a8bf946f53f2ffd96ab83757425491c89bae6d
PHP
ICanBoogie/HTTP
/lib/FileOptions.php
UTF-8
744
2.546875
3
[ "BSD-3-Clause" ]
permissive
<?php /* * This file is part of the ICanBoogie package. * * (c) Olivier Laviale <olivier.laviale@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace ICanBoogie\HTTP; /** * Options to create {@link File} instances. */ interface FileOptions { /** * Name of the file. */ const OPTION_NAME = 'name'; /** * MIME type of the file. */ const OPTION_TYPE = 'type'; /** * Size of the file. */ const OPTION_SIZE = 'size'; /** * Temporary filename. */ const OPTION_TMP_NAME = 'tmp_name'; /** * Error code, one of `UPLOAD_ERR_*`. */ const OPTION_ERROR = 'error'; /** * Pathname of the file. */ const OPTION_PATHNAME = 'pathname'; }
true
1581c4dffb924b748998a5cccfabe2668433add3
PHP
guillaumemonet/Rad
/src/Rad/Build/DatabaseBuilder/Elements/BaseElementTrait.php
UTF-8
1,892
2.765625
3
[ "MIT" ]
permissive
<?php /** * @license http://www.opensource.org/licenses/mit-license.php MIT (see the LICENSE file) * @author Guillaume Monet * @link https://github.com/guillaumemonet/Rad * @package Rad */ namespace Rad\Build\DatabaseBuilder\Elements; /** * Description of BaseElementTrait * * @author guillaume */ trait BaseElementTrait { public function getPrimaryColumns($type) { $ret = []; foreach ($this->columns as $col_name => $col) { if ($col->key == "PRI") { $ret[] = $col->getAsVar($type); } } return $ret; } public function getAutoIncPrimaryColumns($type) { $ret = []; foreach ($this->columns as $col_name => $col) { if ($col->key == "PRI" && $col->auto > 0) { $ret[] = $col->getAsVar($type); } } return $ret; } public function getNotPrimaryColumns($type, $ignoreSpecial = false) { $ret = []; foreach ($this->columns as $col_name => $col) { if ($col->key !== "PRI" && (!$ignoreSpecial || !in_array($col_name, array("password", "token")))) { $ret[] = $col->getAsVar($type); } } return $ret; } public function getNotAutoIncColumns($type) { $ret = []; foreach ($this->columns as $col_name => $col) { if ($col->auto == 0) { $ret[] = $col->getAsVar($type); } } return $ret; } public function getColumns($type, $ignoreSpecial = false) { $ret = []; foreach ($this->columns as $col_name => $col) { if (!$ignoreSpecial || (!in_array($col_name, array("password", "token")))) { $ret[] = $col->getAsVar($type); } } return $ret; } }
true
a322f16fc5e3f946b8585f9d1ed93d9d23d8f9b3
PHP
posiyans/pim
/app/Modules/User/Classes/CreateUserTwoFactorCodeClass.php
UTF-8
579
2.515625
3
[]
no_license
<?php namespace App\Modules\User\Classes; use App\Models\User; use App\Modules\Telegram\Classes\TelegramDeleteLoginCodeMessage; class CreateUserTwoFactorCodeClass { private $user; public function __construct(User $user) { $this->user = $user; } public function run() { $code = rand(100000, 999999); $opt = $this->user->options; $opt['two_code'] = $code; $this->user->options = $opt; $this->user->save(); (new TelegramDeleteLoginCodeMessage($this->user))->run(); return $code; } }
true
8dfd017cdd1f2223b418776922ea345227bd7595
PHP
dotienduc/MVC
/app/model/TimeServing.php
UTF-8
608
2.65625
3
[]
no_license
<?php namespace App\model; use \InvalidArgumentException; use App\core\Model; class TimeServing extends Model { public $id_timeserving; public $weeksday; public $work_time; public function __construct( $row = [] ) { if($row != []) { $this->id_timeserving = $row['id_timeserving']; $this->weeksday = $row['weeksday']; $this->work_time = $row['work_time']; } parent::__construct(); } public function calendars() { return $this->hasMany('App\model\Calendar', ['id_timeserving' => $this->id_timeserving]); } public function entityTable() { return "timeserving"; } }
true
8cd620a33d20fba89254e49bd46d7d9209b5c18c
PHP
poojakarthik/my-work
/html/ui/classes/Validation.php
UTF-8
17,723
3.40625
3
[]
no_license
<?php //----------------------------------------------------------------------------// // Validation //----------------------------------------------------------------------------// /** * Validation * * The Validation class * * The Validation class - encapsulates all validation rules * It can also handle validation against a regex * Each validation rule that isn't a regex will have a method defined in this class. * * @package ui_app * @class Validation */ class Validation { //------------------------------------------------------------------------// // instance //------------------------------------------------------------------------// /** * instance() * * Returns a singleton instance of this class * * Returns a singleton instance of this class * * @return __CLASS__ * * @method */ public static function instance() { static $instance; if (!isset($instance)) { $instance = new self(); } return $instance; } //------------------------------------------------------------------------// // RegexValidate //------------------------------------------------------------------------// /** * RegexValidate() * * Validates a value using a regular expression as the validation rule * * Validates a value using a regular expression as the validation rule * * @param string $strValidationRule the validation rule as a regex * @param mix $mixValue the value to validate * * @return bool * * @method */ static function RegexValidate($strValidationRule, $mixValue) { //echo "entered"; // return false if not a valid regex /* if ((substr($strValidationRule, 0, 1) != '/') || (!strrpos($strValidationRule, '/') > 0)) { return FALSE; } */ // try to match with a regex if (preg_match($strValidationRule, $mixValue)) { return TRUE; } return FALSE; } //------------------------------------------------------------------------// // IsValidABN //------------------------------------------------------------------------// /** * IsValidABN() * * Checks if a value is a valid ABN Number * * Checks if a value is a valid ABN Number * * @param mix $strValue the value to validate * * @return bool * * @method */ static function IsValidABN($strValue) { // 1. If the length is 0, it is invalid if (strlen($strValue) == 0) { return FALSE; } // 2. Check that the item has only Numbers and Spaces // The ereg function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. // if (ereg("/[^\d\s]/g", $strValue) != FALSE) if(!preg_match("/^[\d\s]+$/", $strValue)) { return FALSE; } // The ereg function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. // $strABN_without_spaces = ereg_replace(" ","", $strValue); $strABN_without_spaces = preg_replace("/\s/","", $strValue); // 3. Check there are 11 integers if ((strlen($strABN_without_spaces) > 11) || (strlen($strABN_without_spaces) < 11)) { return FALSE; } // 4. ABN Calculation // http://www.ato.gov.au/businesses/content.asp?doc=/content/13187.htm&pc=001/003/021/002/001&mnu=610&mfp=001/003&st=&cy=1 // 1. Subtract 1 from the first (left) digit to give a new eleven digit number // 2. Multiply each of the digits in this new number by its weighting factor // 3. Sum the resulting 11 products // 4. Divide the total by 89, noting the remainder // 5. If the remainder is zero the number is valid $arrWeights = Array(10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19); // 1. Subtract 1 from the first (left) digit to give a new eleven digit number $intFirstDigitABN = substr($strABN_without_spaces, 0, 1) - 1; $intNewABN =$intFirstDigitABN .= substr($strABN_without_spaces, 1); // 2. Multiply each of the digits in this new number by its weighting factor // 3. Sum the resulting 11 products $intNumberSum = 0; for ($i = 0; $i < 11; $i ++) { $intNumberSum += substr($intNewABN,$i,1) * $arrWeights[$i]; } // 4. Divide the total by 89, noting the remainder // 5. If the remainder is zero the number is valid if ($intNumberSum % 89 != 0) { return FALSE; } else { return TRUE; } } //------------------------------------------------------------------------// // IsValidACN //------------------------------------------------------------------------// /** * IsValidACN() * * Checks if a value is a valid ACN Number * * Checks if a value is a valid ACN Number * * @param mix $strValue the value to validate * * @return bool * * @method */ public static function isValidACN($strValue) { $arrWeights = array(8, 7, 6, 5, 4, 3, 2, 1, 0); // Strip non-numbers from the acn $strValue = preg_replace('/[^0-9]/', '', $strValue); // Check acn is 9 chars long if(strlen($strValue) != 9) { return false; } // Sum the products $intSum = 0; foreach(str_split($strValue) as $intKey=>$intDigit) { $intSum += $intDigit * $arrWeights[$intKey]; } // Get the remainder $intRemainder = $intSum % 10; // Get remainder compliment $intComplement = (string)(10 - $intRemainder); // If complement is 10, set to 0 if($intComplement === "10") { $intComplement = "0"; } return ($strValue[8] === $intComplement); } //------------------------------------------------------------------------// // IsValidPostcode //------------------------------------------------------------------------// /** * IsValidPostcode() * * Checks if a value is a valid Australian Postcode * * Checks if a value is a valid Australian Postcode * * @param mix $mixValue postcode to validate * * @return bool * @method */ static function IsValidPostcode($mixValue) { return preg_match("/^\d{4}$/", $mixValue); } //------------------------------------------------------------------------// // IsValidPhoneNumber //------------------------------------------------------------------------// /** * IsValidPhoneNumber() * * Check the format of a phone number * * Check the format of a phone number * * @param str $strNumber The phone number to check * * @return bool * * @function */ static function IsValidPhoneNumber ($strNumber) { return preg_match ("/^\+?[\d\s]{10,}$/", $strNumber); } //------------------------------------------------------------------------// // IsValidInteger //------------------------------------------------------------------------// /** * IsValidInteger() * * Checks if a value is a valid integer * * Checks if a value is a valid integer * * @param mix $mixValue the value to validate * * @return bool * * @method */ static function IsValidInteger($mixValue) { if ((string)(int)$mixValue == (string)$mixValue) { return TRUE; } return FALSE; } //------------------------------------------------------------------------// // Integer //------------------------------------------------------------------------// /** * Integer() * * Checks if a value is a valid integer * * Checks if a value is a valid integer * * @param mix $mixValue the value to validate * * @return bool * * @method * * @deprecated - use Validation::IsValidInteger - hadrian - 12/03/2008 */ static function Integer($mixValue) { return self::IsValidInteger($mixValue); } //------------------------------------------------------------------------// // UnsignedInteger //------------------------------------------------------------------------// /** * UnsignedInteger() * * Checks if a value is a valid unsigned integer * * Checks if a value is a valid unsigned integer * * @param mix $mixValue the value to validate * * @return bool * * @method */ static function UnsignedInteger($mixValue) { if ((int)$mixValue > -1 && (string)(int)$mixValue == (string)$mixValue) { return TRUE; } return FALSE; } //------------------------------------------------------------------------// // NonZeroInteger //------------------------------------------------------------------------// /** * UnsignedInteger() * * Checks if a value is a valid non-zero integer * * Checks if a value is a valid non-zero integer * * @param mix $mixValue the value to validate * * @return bool * * @method */ static function NonZeroInteger($mixValue) { if ((int)$mixValue != 0 && (string)(int)$mixValue == (string)$mixValue) { return TRUE; } return FALSE; } //------------------------------------------------------------------------// // UnsignedNonZeroInteger //------------------------------------------------------------------------// /** * UnsignedNonZeroInteger() * * Checks if a value is a valid unsigned non-zero integer * * Checks if a value is a valid unsigned non-zero integer * * @param mix $mixValue the value to validate * * @return bool * * @method */ static function UnsignedNonZeroInteger($mixValue) { if ((int)$mixValue > 0 && (string)(int)$mixValue == (string)$mixValue) { return TRUE; } return FALSE; } //------------------------------------------------------------------------// // UnsignedFloat //------------------------------------------------------------------------// /** * UnsignedFloat() * * Checks if a value is a valid unsigned float * * Checks if a value is a valid unsigned float * * @param mix $mixValue the value to validate * * @return bool * * @method */ static function UnsignedFloat($mixValue) { if ((float)$mixValue >= 0 && (string)(float)$mixValue == (string)$mixValue) { return TRUE; } return FALSE; } //------------------------------------------------------------------------// // ShortDate //------------------------------------------------------------------------// /** * ShortDate() * * Checks if a value is in a valid date format * * Checks if a value is in a valid date format * * @param mix $mixDateAndTime the value to validate * * @return bool * * @method */ static function ShortDate($mixDate) { if ($mixDate == "00/00/0000") { return TRUE; } else { $bolValidDateFormat = self::RegexValidate('^(0[1-9]|[12][0-9]|3[01])[/](0[1-9]|1[012])[/](19|20)[0-9]{2}$^' , $mixDate); if (!$bolValidDateFormat) { return FALSE; } // The Date is in the correct format, but now check that it is a proper date // IE check that it isn't the 31st of February $arrParts = explode("/", $mixDate); return checkdate((int)$arrParts[1], (int)$arrParts[0], (int)$arrParts[2]); } } //------------------------------------------------------------------------// // Time //------------------------------------------------------------------------// /** * Time() * * Checks if a value is in a valid time format (HH:MM:SS) * * Checks if a value is in a valid time format (HH:MM:SS) * * @param string $strTime the value to validate * * @return bool * @method */ static function Time($strTime) { return self::RegexValidate('^(0[0-9]|[1][0-9]|2[0-3])(:(0[0-9]|[1-5][0-9])){2}$^' , $strTime); } //------------------------------------------------------------------------// // IsValidDate //------------------------------------------------------------------------// /** * IsValidDate() * * Check the validity of a short date * * Check the validity of a short date, which should be in the format yyyy-mm-dd * * @param str $strShortDate The date to check * * @return bool * * @function */ static function IsValidDate($strShortDate) { $dateParts = array(); $ok = preg_match ("/^(?:(\d\d\d\d)\-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01]))$/", $strShortDate, $dateParts); if (!$ok) { return FALSE; } return checkdate((int)$dateParts[2], (int)$dateParts[3], (int)$dateParts[1]); } //------------------------------------------------------------------------// // IsValidDateInPast //------------------------------------------------------------------------// /** * IsValidDateInPast() * * Checks if a value is in valid date in the past * * Checks if a value is in valid date in the past * * @param str $strShortDate the date to validate * * @return bool * * @method */ static function IsValidDateInPast($strShortDate) { $dateParts = array(); $ok = preg_match ("/^(?:(\d\d\d\d)\-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01]))$/", $strShortDate, $dateParts); if (!$ok) { return FALSE; } $year = (int)$dateParts[1]; $month = (int)$dateParts[2]; $day = (int)$dateParts[3]; $ok = checkdate($month, $day, $year); if (!$ok) { return FALSE; } $yearNow = (int)date("Y"); $monthNow = (int)date("m"); $dayNow = (int)date("d"); if ($year > $yearNow || ($year == $yearNow && ($month > $monthNow || ($month == $monthNow && $day > $dayNow)))) { return FALSE; } return TRUE; } //------------------------------------------------------------------------// // DateAndTime //------------------------------------------------------------------------// /** * DateAndTime() * * Checks if a value is in a valid date and time format * * Checks if a value is in a valid date and time format * * @param mix $mixDateAndTime the value to validate * * @return bool * * @method */ static function DateAndTime($mixDateAndTime) { // TODO! Joel Test against all variations of the MySql datetime data type return TRUE; } //------------------------------------------------------------------------// // IsMoneyValue //------------------------------------------------------------------------// /** * IsMoneyValue() * * Checks if a value is in a valid monetary format and is not NULL * * Checks if a value is in a valid monetary format and is not NULL * The valid format is a float that can start with a '$' char * * @param mix $mixValue value to validate * * @return bool * * @method */ static function IsMoneyValue($mixValue) { // remove whitespace and the $ if they are present $mixValue = trim($mixValue); $mixValue = ltrim($mixValue, "$"); //check that the value is a float list($fltValue, $strAppendedText) = sscanf($mixValue, "%f%s"); if ($strAppendedText) { // there was some text after the float return FALSE; } return (is_numeric($fltValue)); } //------------------------------------------------------------------------// // IsNotNull //------------------------------------------------------------------------// /** * IsNotNull() * * Returns TRUE if the value is not NULL * * Returns TRUE if the value is not NULL * This will return TRUE if $mixValue == 0 * * * @param mix $mixValue value to validate * * @return bool * * @method */ static function IsNotNull($mixValue) { // take care of the special case where $mixValue == 0 if (is_numeric($mixValue)) { // if the value is a number then it can't be NULL return TRUE; } return (bool)($mixValue != NULL); } //------------------------------------------------------------------------// // IsNotEmptyString //------------------------------------------------------------------------// /** * IsNotEmptyString() * * Returns TRUE if the value is not an empty string and is not just whitespace * * Returns TRUE if the value is not an empty string and is not just whitespace * * * @param mix $mixValue value to validate * * @return bool * * @method */ static function IsNotEmptyString($mixValue) { $mixValue = trim($mixValue); return (strlen($mixValue) > 0)? TRUE : FALSE; } //------------------------------------------------------------------------// // IsAlphaString //------------------------------------------------------------------------// /** * IsAlphaString() * * Returns TRUE if the value is comprises of only alpha characters (A-Z and a-z) * * Returns TRUE if the value is comprises of only alpha characters (A-Z and a-z) * * @param mix $mixValue value to validate * * @return bool * * @method */ static function IsAlphaString($mixValue) { return self::RegexValidate('/^[A-Za-z]+$/', $mixValue); } //------------------------------------------------------------------------// // IsValidEmail //------------------------------------------------------------------------// /** * IsValidEmail() * * Returns TRUE if the value has all the components of a valid email * address i.e. minimum length the '@' symbol and atleast one period '.' * * Returns FALSE if the value has some components of a valid email * address missing * * Uses RegexValidate and custom regex validation to check email address * * * @param mix $mixValue value to validate * * @return bool * * @method */ static function IsValidEmail($mixValue) { return self::RegexValidate('^([[:alnum:]]([-_.]?[[:alnum:]])*)@([[:alnum:]]([.]?[-[:alnum:]])*[[:alnum:]])\.([[:alpha:]]){2,25}$^', $mixValue); } //------------------------------------------------------------------------// // IsValidFNN //------------------------------------------------------------------------// /** * IsValidFNN() * * Returns TRUE if the value is a valid FNN * * Returns TRUE if the value is a valid FNN * Wrapper for the function IsValidFNN found in framework/functions.php * * @param mix $mixValue value to validate * * @return bool * * @method */ static function IsValidFNN($mixValue) { return IsValidFNN($mixValue); } } ?>
true
efdc82b710b2eb1ca6f3dd9bb4ace6c63295730f
PHP
Farrien/sanity.net
/server/Superior/Tool/ImageResource.php
UTF-8
364
3.03125
3
[]
no_license
<?php namespace Superior\Tool; class ImageResource { public $path; public $dir; public $name; public $mimetype; public function __construct(string $path, string $name, string $dir, string $mimetype) { $this->path = $path; $this->dir = $dir; $this->name = $name; $this->mimetype = $mimetype; } public function get() { return $this->path; } }
true
0235b996f2ffa5ca65db4763aaf768ed81ec19d0
PHP
boekkooi/tactician-amqp
/src/Publisher/Publisher.php
UTF-8
442
2.5625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
<?php namespace Boekkooi\Tactician\AMQP\Publisher; use Boekkooi\Tactician\AMQP\Message; use Boekkooi\Tactician\AMQP\Exception\FailedToPublishException; interface Publisher { /** * Publish a message to a AMQP exchange. * * @param Message $message * * @throws FailedToPublishException * * @return mixed Should be void but is mixed to support RPC */ public function publish(Message $message); }
true
9890e9d4802f7a6782044b4bdeae0ca58d8fae31
PHP
gooddream-hub/PurePHP
/logic/db.class.php
UTF-8
728
2.765625
3
[]
no_license
<?php class DB extends MySQLi { private static $instance = null; // private static $_host = "localhost"; // private static $_uname = "mjtren5_user2"; // private static $_pass = "XLgf;E0uWz_#"; // private static $_database = "mjtren5_mjtrends"; private static $_host = "localhost"; private static $_uname = "root"; private static $_pass = ""; private static $_database = "mjtren5_mjtrends"; private function __construct($host, $user, $password, $database){ parent::__construct($host, $user, $password, $database); } public static function getInstance(){ if (self::$instance == null){ self::$instance = new self(self::$_host, self::$_uname, self::$_pass, self::$_database); } return self::$instance; } }
true
a7d9139617402748d10393bf9f02168931dad94f
PHP
mvtenorio/mico
/app/Mico/Repositories/Interfaces/TagRepositoryInterface.php
UTF-8
235
2.578125
3
[ "MIT" ]
permissive
<?php namespace Mico\Repositories\Interfaces; use Mico\Models\Tag; interface TagRepositoryInterface extends BaseRepositoryInterface { public function getTagById($id); public function save(Tag $tag); public function destroy($id); }
true
2a5722262836ae1f08f2ee22aa1a1568c6db1e29
PHP
azhang57/sinkd
/main/create.php
UTF-8
891
3.1875
3
[]
no_license
<?php /* //=================================================================================================== // File: create.js // Description: This file is used to create a new folder in the server. //=================================================================================================== */ $path = $_POST['userdir'] . "/"; $name = $_POST['name']; $status = 0; $i = 1; $new_path = $path . $name; // if the folder already exists in the server, rename it. if (file_exists($new_path)) { // keep renaming the folder with an iterator, until it is unique. while (file_exists($new_path)) { $new_name = pathinfo($path . $name, PATHINFO_FILENAME); $new_path = $path . $new_name . '_' . $i; $i++; } $status = 1; // means the folder was renamed with iterator } // create the directory in the server. mkdir($new_path); // return the status echo $status; ?>
true
89d73c4b8ab60f981dc9471199a202bee527f552
PHP
TangoToCoding/my-homepage
/BD_2018/Anmelde-Formular/index.php
ISO-8859-1
8,816
2.859375
3
[]
no_license
<?php // GammaGroup Kontaktscript // All rights by Moosa (Klaus Mooser) // Support gibts hier: (http://www.Neandertaler.net) (Moosa@web.de) // Version 2.7. // E-Mail Adresse des Empfngers (Im Normalfall Ihre eigene) einfach zwischen den beiden "" einfgen. $adresse = "IhrName@IhreDomain.de"; // Soll als Absenderadresse Ihre eigene oder die des Kontaktaufnehmenden benutzt werden? // Bei manchen Providern ist es zwingend notwendig, dass die eigene benutzt wird // 0 = eigene 1 = Besucher $absender = "1"; // Hier kann definiert werden, nach wievielen Zeichen ein automatischer Zeilenumbruch eingefgt werden soll, // wenn sie $umbruch = "no" eingeben, wird kein automatischer Zeilenumbruch eingefgt. $umbruch = "70"; //bestimmen der Hintergrundfarbe: $bgcolor = "#F3F4F5"; //bestimmen der Textfarbe: $textcolor = "#000000"; //bestimmen der Textfarbe der Fehler: $fehlercolor = "#FF3300"; // Hier knnen Sie definieren, was ber dem Kontaktformular stehen soll: $head = "Hier Ihre berschrift<br>Version 2.7."; // Bei manchen Webhoster ist es notwendig, dass noch ein zustzlicher Parameter bergeben wird, der Ihre E-Mail-Adresse // enthlt. // Bei den meisten Hostern ist dies nicht notwendig, dann mssen Sie zwischen die beiden "" nichts einfgen // aber z.B. bei Hosteurope ist die Angabe zwingend und dann mssen sie hier eine Ihrem Webpack zugehrige und // eingerichtete E-Mail-Adresse eintragen, z.B. in dieser Form: $add = "info@ihre_webpack_domain.tld" // NOCHMAL: Setzen Sie hier nur was ein, wenn Sie wissen das es notwendig ist!!! $add = ""; // Ab hier sollten Sie nur noch etwas ndern, wenn sie wissen was sie tun, // bzw. wenn sie noch mehr am Design ndern wollen. //hier wird die Lnge der verschiedenen Eingaben ermittelt $lengthm = strlen($_POST["send"]["mail"]); $lengtha = strlen($_POST["send"]["autor"]); $lengthb = strlen($_POST["send"]["betreff"]); $lengthn = strlen($_POST["send"]["nachricht"]); // der Zhler wird auf null gesetzt $i = "0"; // Je nachdem welche Adresse als Absender benutzt werden soll, wird die Variable beschrieben: if ($absender == "0") { $from = $adresse ; } else { $from = $_POST["send"]["mail"] ; } //Nun berprfen wir die Eingaben auf alle mglichen Fehler (Es muss berall was eingegeben werden, // die Eintrge drfen eine bestimmte Lnge nicht berschreiten und die E-Mail-Adresse muss ein @ enthalten) // Ausserdem darf im Namensfeld kein @ Zeichen enthalten sein und in der Adresse nicht mehr als eins. // Das ist notwendig, damit im vierten Parameter keine CC oder BCC Adressen bergeben werden knnen. // Und zu guter Letzt werden die Sonderzeichen fr die HTML-Ausgabe codiert und die Backslashes aus der Mail entfernt if(isset($_POST["send"]) && is_array($_POST["send"])) { if(empty($_POST["send"]["autor"])) { $fautor = "Sie mssen einen Namen eingeben!<br>"; } else { $fautor = "Name ok!<br>"; $i++; } if(empty($_POST["send"]["betreff"])) { $fbetreff = "Sie mssen einen Betreff eingeben!<br>"; } else { $fbetreff = "Betreff ok!<br>"; $i++; } if(empty($_POST["send"]["mail"])) { $fmail = "Sie mssen Ihre E-Mail-Adresse eingeben!<br>"; } else { $fmail = "Adresse ok!<br>"; $i++; } if(empty($_POST["send"]["nachricht"])) { $fnachricht = "Sie mssen eine Nachricht eingeben!<br>"; } else { $fnachricht = "Nachricht ok!<br>"; $i++; } if ($lengthm > "50") { $flmail = "Ihre eingegebene E-Mail-Adresse ist zu lang!<br>"; $fmail = ""; } else { $i++; } if ($lengtha > "30") { $flautor = "Ihr eingegebener Name ist zu lang!<br>"; $fautor = ""; } else { $i++; } if ($lengthb > "150") { $flbetreff = "Ihr eingegebener Betreff ist zu lang!<br>"; $fbetreff = ""; } else { $i++; } if ($lengthn > "60000") { $flnachricht = "Ihre eingegebene Nachricht darf nicht mehr<br> als 60000 Zeichen haben! Sie hat: ".$lengthn."<br>"; $fnachricht = ""; } else { $i++; } if (!strpos($_POST["send"]["mail"], "@") == "false" or substr_count($_POST["send"]["mail"], "@") > 1) { $fgmail = "Ihre angegebene E-Mail Adresse ist nicht gltig!<br>"; $fmail = ""; } else { $i++; } if (substr_count($_POST["send"]["autor"], "@") >= 1) { $fgautor = "Aus Sicherheitsgrnden darf das Namensfeld kein @ Zeichen enthalten!<br>"; $fautor = ""; } else { $i++; } $str = ":\/,\""; if (strcspn($_POST["send"]["mail"], $str) < $lengthm) { $fgmail = "Ihre angegebene E-Mail Adresse ist nicht gltig!<br>"; $fmail = "" ; } else { $i++ ; } if (get_magic_quotes_gpc() == "1") { $_POST["send"]["autor"] = stripslashes($_POST["send"]["autor"]); $_POST["send"]["betreff"] = stripslashes($_POST["send"]["betreff"]); $_POST["send"]["mail"] = stripslashes($_POST["send"]["mail"]); $_POST["send"]["nachricht"] = stripslashes($_POST["send"]["nachricht"]); } $sautor = htmlspecialchars($_POST["send"]["autor"]); $sbetreff = htmlspecialchars($_POST["send"]["betreff"]); $smail = htmlspecialchars($_POST["send"]["mail"]); $snachricht = htmlspecialchars($_POST["send"]["nachricht"]); } //Wenn alles korrekt eingegeben wurde, wird die Mail nun erst formatiert und dann verschickt if(isset($_POST["send"]) && is_array($_POST["send"])) { if ($i == "11") { $autor = $_POST["send"]["autor"]; if ($umbruch == "no") { $texto = $_POST["send"]["nachricht"] ; } else { $texto = wordwrap( $_POST["send"]["nachricht"], $umbruch ); } $_POST["text"] = $_POST["send"]["autor"]." mit der Mail Adresse: ".$_POST["send"]["mail"]." hat ihnen folgende Nachricht gesendet: \n \n $texto"; $fautor = "<h2>Ihre Mail wurde versendet!</h2>"; $fbetreff = ""; $fmail = ""; $fnachricht = ""; // Und ab dafr... je nachdem mit oder ohne additional_parameters if(empty($add)) { $addp = ""; if (@mail($adresse, $_POST['send']['betreff'], $_POST['text'], "From: \"$autor\" <$from>")) { $fautor = "<h2>Ihre Mail wurde versendet!</h2>"; unset($sautor); unset($sbetreff); unset($smail); unset($snachricht); } else { $fautor = "<h2>Fehler! Mail konnte nicht gesendet werden</h2>"; } } else { if (@mail($adresse, $_POST['send']['betreff'], $_POST['text'], "From: \"$autor\" <$from>", "-f $add")) { $fautor = "<h2>Ihre Mail wurde versendet!</h2>"; unset($sautor); unset($sbetreff); unset($smail); unset($snachricht); } else { $fautor = "<h2>Fehler! Mail konnte nicht gesendet werden</h2>"; } } } } // Hier kommt nun das eigentliche Formular in HTML + CSS ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <style type="text/css"><!-- body { font-family:Verdana,sans-serif; font-size:12px; color:<?php echo $textcolor ; ?>; background-color:<?php echo $bgcolor ; ?>; text-align:center; } a:link, a:visited, a:active { text-decoration:underline; font-weight:bold; color:#000000; font-size:10px; } a:hover { color:#8B0000; } h1 { font-size:18px; margin-top:30px; } h2 { font-size:18px; } .formular { margin:0px auto; width:480px; border:1px solid #000000; text-align:left; } .fehler { color:<?php echo $fehlercolor ; ?>; text-align:left; } .box { margin-top:10px; } .um { margin-left:105px; } .bez { float:left; text-align:left; width:9.5em; line-height:25px; } input { margin-top:5px; } .nachricht { clear:both; text-align:center; } .copy { font-size:10px; position:relative;top:30px; } //--></style> <title></title> <meta name='author' content='Klaus Mooser'> <meta http-equiv='Content-Type' content='text/html; charset=ISO-8859-1'> </head> <body> <h1><?php echo $head ; ?></h1> <form class="formular" action="<?php echo $PHP_SELF;?>" method="post" target="_self"> <div class="fehler"><?php echo $fautor ; echo $fbetreff ; echo $fmail ; echo $fnachricht ; echo $flautor ; echo $flbetreff ; echo $flnachricht ; echo $flmail ; echo $fgmail ; echo $fgautor ;?></div> <div class="box"> <div class="um"> <div class="bez"><label for="autor">Ihr Name:</label></div> <div><input name='send[autor]' type='text' id="autor" size='20' value="<?php echo $sautor ; ?>"></div> </div> <div class="um"> <div class="bez"><label for="betreff">Betreff:</label></div> <div><input name='send[betreff]' type='text' id="betreff" size='20' value="<?php echo $sbetreff ; ?>"></div> </div> <div class="um"> <div class="bez"><label for="mail">E-Mail Adresse:</label></div> <div><input name='send[mail]' type='text' id="mail" size='20' value="<?php echo $smail ; ?>"></div> </div> </div> <div class="nachricht"> <br><label for="nachricht">Ihre Nachricht:</label><br><textarea name='send[nachricht]' id="nachricht" rows='10' cols='40'><?php echo $snachricht ;?></textarea><br> <input type='submit' value='Absenden'><p></p> </div> </form> <div class="copy"> &copy; by <a href='http://www.Neandertaler.net'>www.Neandertaler.net</a> 2005 <br> </div> <p></p> </body> </html>
true
9085ca00fcba94c33b74ebec89add6b375db5b70
PHP
berlianafd/simple_api
/CekIdUser.php
UTF-8
1,193
2.5625
3
[]
no_license
<?php require_once 'include/DB_Functions.php'; $db = new DB_Functions(); // json response array $response = array("error" => FALSE); // check for post data if (isset($_POST["nohp"]) && isset($_POST['name'])) { $nohp = $_POST['nohp']; // get the user poin $user = $db->getUserId($nohp); if ($user != false) { // use is found $response["error"] = FALSE; $response["user"]["id"] = $user["id"]; $response["user"]["nama"] = $user["name"]; $response["user"]["nohp"] = $user["nohp"]; $path = $user["image_path"]; $basec = base64_encode(file_get_contents("$path")); $response["user"]["image_path"] = $basec; $response["user"]["image_name"] = $user["image_name"]; echo json_encode($response); } else { // user is not found with the credentials $response["error"] = TRUE; $response["error_msg"] = "Akun tidak ditemukan!"; echo json_encode($response); } } else { // required field is missing $response["success"] = 0; $response["message"] = "Required field(s) is missing"; // echoing JSON response echo json_encode($response); } ?>
true