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
7e731e8cdf0ccd576e088ea0eb1e0696abe4d5e9
PHP
PHP-CS-Fixer/PHP-CS-Fixer
/src/Fixer/FunctionNotation/RegularCallableCallFixer.php
UTF-8
9,160
2.671875
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Fixer\FunctionNotation; use PhpCsFixer\AbstractFixer; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> */ final class RegularCallableCallFixer extends AbstractFixer { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Callables must be called without using `call_user_func*` when possible.', [ new CodeSample( '<?php call_user_func("var_dump", 1, 2); call_user_func("Bar\Baz::d", 1, 2); call_user_func_array($callback, [1, 2]); ' ), new CodeSample( '<?php call_user_func(function ($a, $b) { var_dump($a, $b); }, 1, 2); call_user_func(static function ($a, $b) { var_dump($a, $b); }, 1, 2); ' ), ], null, 'Risky when the `call_user_func` or `call_user_func_array` function is overridden or when are used in constructions that should be avoided, like `call_user_func_array(\'foo\', [\'bar\' => \'baz\'])` or `call_user_func($foo, $foo = \'bar\')`.' ); } /** * {@inheritdoc} * * Must run before NativeFunctionInvocationFixer. * Must run after NoBinaryStringFixer, NoUselessConcatOperatorFixer. */ public function getPriority(): int { return 2; } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(T_STRING); } public function isRisky(): bool { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $functionsAnalyzer = new FunctionsAnalyzer(); $argumentsAnalyzer = new ArgumentsAnalyzer(); for ($index = $tokens->count() - 1; $index > 0; --$index) { if (!$tokens[$index]->equalsAny([[T_STRING, 'call_user_func'], [T_STRING, 'call_user_func_array']], false)) { continue; } if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { continue; // redeclare/override } $openParenthesis = $tokens->getNextMeaningfulToken($index); $closeParenthesis = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesis); $arguments = $argumentsAnalyzer->getArguments($tokens, $openParenthesis, $closeParenthesis); if (1 > \count($arguments)) { return; // no arguments! } $this->processCall($tokens, $index, $arguments); } } /** * @param array<int, int> $arguments */ private function processCall(Tokens $tokens, int $index, array $arguments): void { $firstArgIndex = $tokens->getNextMeaningfulToken( $tokens->getNextMeaningfulToken($index) ); /** @var Token $firstArgToken */ $firstArgToken = $tokens[$firstArgIndex]; if ($firstArgToken->isGivenKind(T_CONSTANT_ENCAPSED_STRING)) { $afterFirstArgIndex = $tokens->getNextMeaningfulToken($firstArgIndex); if (!$tokens[$afterFirstArgIndex]->equalsAny([',', ')'])) { return; // first argument is an expression like `call_user_func("foo"."bar", ...)`, not supported! } $firstArgTokenContent = $firstArgToken->getContent(); if (!$this->isValidFunctionInvoke($firstArgTokenContent)) { return; } $newCallTokens = Tokens::fromCode('<?php '.substr(str_replace('\\\\', '\\', $firstArgToken->getContent()), 1, -1).'();'); $newCallTokensSize = $newCallTokens->count(); $newCallTokens->clearAt(0); $newCallTokens->clearRange($newCallTokensSize - 3, $newCallTokensSize - 1); $newCallTokens->clearEmptyTokens(); $this->replaceCallUserFuncWithCallback($tokens, $index, $newCallTokens, $firstArgIndex, $firstArgIndex); } elseif ( $firstArgToken->isGivenKind(T_FUNCTION) || ( $firstArgToken->isGivenKind(T_STATIC) && $tokens[$tokens->getNextMeaningfulToken($firstArgIndex)]->isGivenKind(T_FUNCTION) ) ) { $firstArgEndIndex = $tokens->findBlockEnd( Tokens::BLOCK_TYPE_CURLY_BRACE, $tokens->getNextTokenOfKind($firstArgIndex, ['{']) ); $newCallTokens = $this->getTokensSubcollection($tokens, $firstArgIndex, $firstArgEndIndex); $newCallTokens->insertAt($newCallTokens->count(), new Token(')')); $newCallTokens->insertAt(0, new Token('(')); $this->replaceCallUserFuncWithCallback($tokens, $index, $newCallTokens, $firstArgIndex, $firstArgEndIndex); } elseif ($firstArgToken->isGivenKind(T_VARIABLE)) { $firstArgEndIndex = reset($arguments); // check if the same variable is used multiple times and if so do not fix foreach ($arguments as $argumentStart => $argumentEnd) { if ($firstArgEndIndex === $argumentEnd) { continue; } for ($i = $argumentStart; $i <= $argumentEnd; ++$i) { if ($tokens[$i]->equals($firstArgToken)) { return; } } } // check if complex statement and if so wrap the call in () if on PHP 7 or up, else do not fix $newCallTokens = $this->getTokensSubcollection($tokens, $firstArgIndex, $firstArgEndIndex); $complex = false; for ($newCallIndex = \count($newCallTokens) - 1; $newCallIndex >= 0; --$newCallIndex) { if ($newCallTokens[$newCallIndex]->isGivenKind([T_WHITESPACE, T_COMMENT, T_DOC_COMMENT, T_VARIABLE])) { continue; } $blockType = Tokens::detectBlockType($newCallTokens[$newCallIndex]); if (null !== $blockType && (Tokens::BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE === $blockType['type'] || Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE === $blockType['type'])) { $newCallIndex = $newCallTokens->findBlockStart($blockType['type'], $newCallIndex); continue; } $complex = true; break; } if ($complex) { $newCallTokens->insertAt($newCallTokens->count(), new Token(')')); $newCallTokens->insertAt(0, new Token('(')); } $this->replaceCallUserFuncWithCallback($tokens, $index, $newCallTokens, $firstArgIndex, $firstArgEndIndex); } } private function replaceCallUserFuncWithCallback(Tokens $tokens, int $callIndex, Tokens $newCallTokens, int $firstArgStartIndex, int $firstArgEndIndex): void { $tokens->clearRange($firstArgStartIndex, $firstArgEndIndex); $afterFirstArgIndex = $tokens->getNextMeaningfulToken($firstArgEndIndex); $afterFirstArgToken = $tokens[$afterFirstArgIndex]; if ($afterFirstArgToken->equals(',')) { $useEllipsis = $tokens[$callIndex]->equals([T_STRING, 'call_user_func_array'], false); if ($useEllipsis) { $secondArgIndex = $tokens->getNextMeaningfulToken($afterFirstArgIndex); $tokens->insertAt($secondArgIndex, new Token([T_ELLIPSIS, '...'])); } $tokens->clearAt($afterFirstArgIndex); $tokens->removeTrailingWhitespace($afterFirstArgIndex); } $tokens->overrideRange($callIndex, $callIndex, $newCallTokens); $prevIndex = $tokens->getPrevMeaningfulToken($callIndex); if ($tokens[$prevIndex]->isGivenKind(T_NS_SEPARATOR)) { $tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex); } } private function getTokensSubcollection(Tokens $tokens, int $indexStart, int $indexEnd): Tokens { $size = $indexEnd - $indexStart + 1; $subCollection = new Tokens($size); for ($i = 0; $i < $size; ++$i) { /** @var Token $toClone */ $toClone = $tokens[$i + $indexStart]; $subCollection[$i] = clone $toClone; } return $subCollection; } private function isValidFunctionInvoke(string $name): bool { if (\strlen($name) < 3 || 'b' === $name[0] || 'B' === $name[0]) { return false; } $name = substr($name, 1, -1); if ($name !== trim($name)) { return false; } return true; } }
true
de5552c91a98c4f58b616e4637070b8041ffff82
PHP
kapilg12/lmk
/app/Office.php
UTF-8
1,330
2.515625
3
[ "MIT" ]
permissive
<?php namespace App; use App\Scope\ActiveScope; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Builder; use Baum; use Auth; class Office extends Baum\Node { protected $table = 'offices'; // 'parent_id' column name protected $parentColumn = 'parent_id'; // 'lft' column name protected $leftColumn = 'lft'; // 'rgt' column name protected $rightColumn = 'rgt'; // 'depth' column name protected $depthColumn = 'depth'; // guard attributes from mass-assignment protected $guarded = array('id', 'parent_id', 'lft', 'rgt', 'depth'); /** * The "booting" method of the model. * * @return void */ /*protected static function boot() { parent::boot(); static::addGlobalScope(new ActiveScope); }*/ protected static function boot() { parent::boot(); static::addGlobalScope('active', function(Builder $builder) { $builder->where('is_active', 1); //$builder->whereIn('id', Auth::user()->options['allowedOffices']); }); } public function states() { return $this->belongsTo('App\State','state_id'); } public function scopeAllowedoffices($query){ return $query->whereIn('id', Auth::user()->options['allowedOffices']); } }
true
fad689483c31f15893308660eae301f511e198ee
PHP
Targoniy/PHP-with-MySQL-Essential-Training
/includes/session.php
UTF-8
905
2.65625
3
[]
no_license
<?php session_start(); function message() { if (isset($_SESSION["message"])) { $output = "<div class=\"message\">"; $output .= htmlentities($_SESSION["message"]); $output .= "</div>"; $_SESSION["message"] = null; return $output; } } function errors() { if (isset($_SESSION["errors"])) { $errors = $_SESSION["errors"]; $_SESSION["errors"] = null; return $errors; } } function subject_pages() { if (isset($_SESSION["pages"])) { $pages = $_SESSION["pages"]; $_SESSION["pages"] = null; return $pages; } } function current_subject_id() { if (isset($_SESSION["current_subject_id"])) { $current_subject_id = $_SESSION["current_subject_id"]; $_SESSION["current_subject_id"] = null; return $current_subject_id; } }
true
80b36a023b093ac66d68ddf17b3f64974fe56ca7
PHP
diegoromero93/elaniin-test
/app/Models/Product.php
UTF-8
1,061
2.765625
3
[]
no_license
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Product extends Model { use HasFactory; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'sku', 'name', 'qty', 'amount', 'description', 'image' ]; public static $creation_rules = array( 'sku' => 'required|string|between:8,14|unique:products', 'name' => 'required|string|between:2,100', 'qty' => 'required|numeric|min:0|not_in:0', 'amount' => 'required|numeric|min:0|not_in:0', 'description' => 'required|min:5', 'image' => 'required|image:jpeg,png,jpg,gif,svg|max:2048' ); public static $update_rules = array( 'name' => 'string|between:2,100', 'qty' => 'numeric|min:0|not_in:0', 'amount' => 'numeric|min:0|not_in:0', 'description' => 'min:5', 'image' => 'image:jpeg,png,jpg,gif,svg|max:2048' ); }
true
1321127dfc62eb9d0fb2d9bec7ff56fb3f5b5e13
PHP
vadzzim/commission-task
/src/Model/Operation.php
UTF-8
484
3.03125
3
[]
no_license
<?php declare(strict_types=1); namespace App\Model; class Operation { public string $date; public string $type; public string $amount; public string $currency; public string $rate; public function __construct(string $date, string $type, string $amount, string $currency, string $rate) { $this->date = $date; $this->type = $type; $this->amount = $amount; $this->currency = $currency; $this->rate = $rate; } }
true
f6b06225b30925146afe3db0c34862f3f49c14d7
PHP
rmm429/reading
/php/config.php
UTF-8
2,818
2.71875
3
[]
no_license
<?php $datetimeUTC = gmdate("Y-m-d H:i:s"); if(isset($_REQUEST)) { error_reporting(E_ALL && ~E_NOTICE && E_COMPILE_ERROR); /* ***UNCOMMENT AND SET SRC WHEN TESTING*** $breach_log_file = 'HIDDEN'; $$blocked_file = 'HIDDEN'; $error_log_file = 'HIDDEN'; */ $ip = $_SERVER["REMOTE_ADDR"]; $script_filename = $_SERVER["SCRIPT_FILENAME"]; $requestType = $_SERVER['REQUEST_METHOD']; $ip_log = array(); $breach_log = file($breach_log_file); foreach($breach_log as $line_num => $line) { //26 junk characters, IP begins on character 27 $ip_end = strpos($line, ' ', 26); $ip_cur = substr($line, 26, $ip_end - 26); array_push($ip_log, $ip_cur); } $ip_dups = array_count_values($ip_log); //Create an array of blocked IP Addresses $blocked = array(); foreach ($ip_dups as $i => $d) { if ($d >= 3) { array_push($blocked, $i); } } //Erase the old backup file unlink($blocked_file); //Store each blocked IP Address in a backup file foreach ($blocked as $b) { file_put_contents($blocked_file, $b . PHP_EOL, FILE_APPEND); } //If this file was accessed by a blocked IP Address if ( in_array($ip, $blocked) ) { //Log access information in the breach log $access = "[$datetimeUTC UTC] $ip BLOCKED IP - config.php $script_filename"; file_put_contents($breach_log_file, $access . PHP_EOL, FILE_APPEND); //Exit the program with an access denied message die("ACCESS DENIED! You are permanently banned from accessing any resources on this domain!"); } //If this file was not called by an AJAX request if ($requestType != "POST") { //Log access information in the file breach.log $access = "[$datetimeUTC UTC] $ip - config.php DIRECT $script_filename"; file_put_contents($breach_log_file, $access . PHP_EOL, FILE_APPEND); //Exit the program with an access denied message die("ACCESS DENIED! You are not permitted to access this page! Your IP Address has been logged. Further attempts to access this page will result in a permanent ban from accessing any resources on this domain."); } return [ 'blocked' => $blocked, 'database' => [ /* ***UNCOMMENT AND SET SRC WHEN TESTING*** 'servername' => 'HIDDEN', 'username' => 'HIDDEN', 'password' => 'HIDDEN', 'dbname' => 'HIDDEN', 'options' => [] */ ] ]; error_reporting(E_ALL && ~E_NOTICE); } else { error_log("[$datetimeUTC UTC] Indirect request made\n", 3, $error_log_file); die("ACCESS DENIED! Indirect request made."); } ?>
true
fac3f061ec08bcf47d0cfe88854d120967a3a697
PHP
brainmangv/omnipay-pagseguro
/src/Message/TransactionSearchResponse.php
UTF-8
1,518
2.6875
3
[ "MIT" ]
permissive
<?php namespace Omnipay\PagSeguro\Message; use Omnipay\Common\Message\AbstractResponse; use Omnipay\Common\Message\RequestInterface; class TransactionSearchResponse extends AbstractResponse { public function __construct(RequestInterface $request, $data) { parent::__construct($request, $data); $transactions = array(); if ($this->isSuccessful()) { if ($this->getData()['resultsInThisPage'] == 1) { $transactions[] = $this->xml2array($this->getData()['transactions']['transaction']); } else if ($this->getData()['resultsInThisPage'] > 0) { foreach ($this->getData()['transactions']['transaction'] as $transaction) { $transactions[] = $this->xml2array($transaction); } } } $this->data['transactions'] = $transactions; } public function getTransactions() { return $this->data['transactions']; } public function isSuccessful() { return isset($this->data['error']) ? false : true; } protected function xml2array($xml) { $arr = []; foreach ($xml as $element) { $tag = $element->getName(); $e = get_object_vars($element); if (!empty($e)) { $arr[$tag] = $element instanceof SimpleXMLElement ? xml2array($element) : $e; continue; } $arr[$tag] = trim($element); } return $arr; } }
true
46184cdfba265a735dedc1adc438c4357684ad97
PHP
bxav/service_handler
/src/Bxav/Bundle/ServiceHandlerBundle/Service/SoapServiceManagerService.php
UTF-8
766
2.671875
3
[ "MIT" ]
permissive
<?php namespace Bxav\Bundle\ServiceHandlerBundle\Service; use Bxav\Bundle\ServiceHandlerBundle\Model\ServiceProviderChain; class SoapServiceManagerService { protected $serviceChain; public function __construct(ServiceProviderChain $serviceChain) { $this->serviceChain = $serviceChain; } /** * get all services * * @return string $services */ public function getSoapServices() { $ser = []; foreach ($this->serviceChain->getServiceProviders() as $serviceP) { $obj = new \stdClass(); $obj->wsdl = $serviceP->getWsdlUrl(); $obj->location = $serviceP->getUrlLocation(); $ser[] = $obj; } return json_encode($ser); } }
true
d253e49371b05eaeb04fccbc07acc9d556077fec
PHP
buiphong/sanglocsosinh
/Library/Rewrite.php
UTF-8
7,579
2.765625
3
[]
no_license
<?php /** * Rewrite url * @author buiphong * */ class Rewrite { /** * Router hiện tại * @var Router */ protected $_router; /** * Router trong file rewrite */ protected $_routers; protected $fileName = 'Rewrite.php'; public $file = 'rewrite.xml'; /** * request uri */ protected $_requestUri; /** * Mảng tham số */ protected $_args; /** * Khởi tạo rewrite * @param unknown_type $router */ public function __construct($router) { $this->_router = $router; //Lấy cấu hình rewrite, các tham số cơ bản: request uri //Kiểm tra file rewrite if (!is_file($this->fileName)) throw new Exception('Không tìm thấy tệp tin cấu hình rewrite: ' . $this->fileName . ' trong hệ thống'); else { $this->getRouters(); $uri = $_SERVER['REQUEST_URI']; $basePath = explode(DIRECTORY_SEPARATOR, ROOT_PATH); $uri = explode('/', $uri); $uri = array_slice($uri, count($basePath), count($uri) - count($basePath)); $this->_requestUri = implode('/', $uri); } } /** * Xử lý phân tích rewrite */ public function processing() { //Request hệ thống $uri = new Uri(); $arrUri = $uri->parseRequestUri(); $request = implode('/', $arrUri['request']); foreach ($this->_routers as $regex => $router) { if ($regex) { //So sánh request và router if ($this->compareRouter($regex, $request)) { if (!empty($router['alias'])) $this->_router->alias = $router['alias']; else $this->_router->alias = 'Portal'; if (!empty($router['module'])) $this->_router->module = $router['module']; else $this->_router->module = 'index'; if (!empty($router['controller'])) $this->_router->controller = $router['controller']; else $this->_router->controller = 'Index'; if (!empty($router['action'])) $this->_router->action = $router['action']; else $this->_router->controller = 'index'; $this->_router->args = $this->parseParams($router['url']); return true; } } } return false; } /** * Lấy đường dẫn đã rewrite */ public function getUrl() { $t = count($this->_router->args); foreach ($this->_routers as $regex => $router) { if(MULTI_LANGUAGE && !empty($router['langcode']) && $router['langcode'] != $_SESSION['langcode']) continue; if ($this->_router->module) { if (!isset($router['module']) || $router['module'] != $this->_router->module) continue; } if ($this->_router->controller) { if (!isset($router['controller']) || $router['controller'] != $this->_router->controller ) continue; } else continue; if ($this->_router->action) { if (!isset($router['action']) || $router['action'] != $this->_router->action ) continue; } else continue; //Link được định nghĩa trong rewrite $url = $router['url']; //Kiểm tra args if ($t != $router['totalParams']) continue; else { //Kiểm tra các tham số có tương ứng hay không $v = true; $aks = array_keys($router['args']); foreach ($this->_router->args as $k => $e) { if (!in_array($k, $aks)) { $v = false; } } if (!$v) { continue; } } //Replace các tham số thành các giá trị tương ứng foreach ($this->_router->args as $n => $v) { if(!is_array($v)) $url = str_replace("{" . $n . "}", $v, $url); } require_once 'Url.php'; return Url::getApplicationUrl() . '/' . $url; } return null; } /** * so sánh request hiện tại và router */ private function compareRouter($router_preg, $request) { $router_preg = trim($router_preg); $request = trim($request); $out = array(); $x = preg_match("/^$router_preg/i", $request, $out); for ($i = 1; $i < sizeof($out); $i++) { $this->_args[] = $out[$i]; } return $x; } /** * Phân tích url lấy tham số truyền vào */ private function parseParams($url_rewrite) { $total = array(); $out = array(); $prg = '/\{(\w+)\}/'; while (preg_match($prg, $url_rewrite, $out)) { $total[] = $out[1]; $url_rewrite = str_replace($out[1], "", $url_rewrite); } $args = array(); $m = count($total); for ($i = 0; $i < $m; $i++) { if (isset($this->_args[$i])) $args[$total[$i]] = $this->_args[$i]; else $args[$total[$i]] = null; } $this->_args = $args; return $this->_args; } /** * Load danh sách router được cấu hình trong rewrite */ private function getRouters() { //Kiểm tra xem đã có trong runtime hay không if(!file_exists(Url::getAppDir() . RUNTIME_DIR . DIRECTORY_SEPARATOR . 'Routers.php') || DEBUG) { //Load default rewrite $arr = include(ROOT_PATH . DIRECTORY_SEPARATOR . 'Public' . DIRECTORY_SEPARATOR . $this->fileName); foreach ($arr as $k => $v) { //Count total params $v['args'] = $this->parseParams($v['url']); $v['totalParams'] = count($v['args']); $this->_routers[$k] = $v; } //Xử lý cho file rewrite các module $subdirs = PTDirectory::getSubDirectories( APPLICATION_PATH . DIRECTORY_SEPARATOR . 'Modules'); $arr2 = PTDirectory::getSubDirectories(APPLICATION_PATH . DIRECTORY_SEPARATOR . 'Portal'); $subdirs = array_merge($subdirs, $arr2); $tmpArr = array(); $i = 1; foreach ($subdirs as $fname => $fpath) { if(file_exists($fpath . DIRECTORY_SEPARATOR . 'Config' . DIRECTORY_SEPARATOR . $this->fileName)) { $a = include($fpath . DIRECTORY_SEPARATOR . 'Config' . DIRECTORY_SEPARATOR . $this->fileName); $tmpArr[$a['priority'] . $i] = $a['items']; $i++; } } //order $tmpArr krsort($tmpArr); //Load menu's rewrite if($tmpArr) { foreach($tmpArr as $items) foreach($items as $k => $v) { //Count total params $v['args'] = $this->parseParams($v['url']); $v['totalParams'] = count($v['args']); $this->_routers[$k] = $v; } } //Save to file if(!DEBUG) file_put_contents(Url::getAppDir() . RUNTIME_DIR . DIRECTORY_SEPARATOR . 'Routers.php', '<?php $routers = ' . var_export($this->_routers,true) . '; ?>'); } else { require Url::getAppDir() . RUNTIME_DIR . DIRECTORY_SEPARATOR . 'Routers.php'; $this->_routers = $routers; } return true; } }
true
7866f7510083d8a64d5a076cd7e7ea70b37d4a35
PHP
saidreamx/Alumni-Network
/backend/upload.php
UTF-8
1,725
2.71875
3
[]
no_license
<?php $target_dir = "uploads/"; $time=number_format(round(microtime(true) * 1000),0,'.',''); $target_file = $target_dir . $time .".". pathinfo($_FILES["image"]["name"],PATHINFO_EXTENSION); $target_file_output=$time .".". pathinfo($_FILES["image"]["name"],PATHINFO_EXTENSION); $sid=$_POST["s_id"]; echo $sid; $uploadOk = 1; echo "QWERTYYYYY"; // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error echo "VALUE OF UPLOADOK "; echo $uploadOk; if ($uploadOk == 0) { echo "{\"Message\":\"Sorry, there was an error uploading your file.\"}"; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) { echo "added successfully"; require_once('dbConnect.php'); echo $sid; $abc = "SELECT sid from photograph where sid = '$sid'"; $get_sid = mysqli_query($con, $abc); // echo $get_sid; echo "SIZE OF NUM "; echo mysqli_num_rows($get_sid); if(mysqli_num_rows($get_sid) == 1) { $fin_q = "UPDATE photograph SET photo = '$target_file_output' where sid = '$sid'"; $if_exe = mysqli_query($con,$fin_q); } if(mysqli_num_rows($get_sid) == 0) { echo " NEW ENTRY "; $fin_q = "INSERT INTO photograph VALUES ('$sid','$target_file_output')"; $if_exe = mysqli_query($con,$fin_q); } if(! $if_exe ) { echo "die out"; die('Could not update data: ' . mysqli_error($con)); } mysqli_close($con); } else { echo "{\"Message\":\"Sorry, there was an error uploading your file.\"}"; } } ?>
true
54d0a2c893a4c7df342e5f5c06085e854fb1d07e
PHP
amphp/sync
/src/SemaphoreMutex.php
UTF-8
827
2.75
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
<?php declare(strict_types=1); namespace Amp\Sync; use Amp\ForbidCloning; use Amp\ForbidSerialization; final class SemaphoreMutex implements Mutex { use ForbidCloning; use ForbidSerialization; private bool $locked = false; /** * @param Semaphore $semaphore A semaphore with a single lock. */ public function __construct( private readonly Semaphore $semaphore ) { } /** {@inheritdoc} */ public function acquire(): Lock { $lock = $this->semaphore->acquire(); if ($this->locked) { throw new \Error("Cannot use a semaphore with more than a single lock"); } $this->locked = true; return new Lock(function () use ($lock): void { $this->locked = false; $lock->release(); }); } }
true
5091ee4aefbe324f0414eb83596c9f250d7f28e8
PHP
yii2-vn/payment
/src/BaseMerchant.php
UTF-8
2,182
2.78125
3
[ "BSD-3-Clause" ]
permissive
<?php /** * @link https://github.com/yii2-vn/payment * @copyright Copyright (c) 2017 Yii2VN * @license [New BSD License](http://www.opensource.org/licenses/bsd-license.php) */ namespace yii2vn\payment; use yii\base\Component; use yii\base\NotSupportedException; /** * Class BaseMerchant * * @property BasePaymentGateway|PaymentGatewayInterface $paymentGateway * * @author Vuong Minh <vuongxuongminh@gmail.com> * @since 1.0 */ abstract class BaseMerchant extends Component implements MerchantInterface { /** * BaseMerchant constructor. * @param BasePaymentGateway $paymentGateway * @param array $config */ public function __construct(BasePaymentGateway $paymentGateway, array $config = []) { $this->_paymentGateway = $paymentGateway; parent::__construct($config); } /** * @var BasePaymentGateway|PaymentGatewayInterface */ private $_paymentGateway; /** * @return BasePaymentGateway|PaymentGatewayInterface */ public function getPaymentGateway(): PaymentGatewayInterface { return $this->_paymentGateway; } /** * @inheritdoc * @throws NotSupportedException */ public function signature(string $data, string $type = null): string { if ($dataSignature = $this->initDataSignature($data, $type)) { return $dataSignature->generate(); } else { throw new NotSupportedException("Signature data with type: '$type' is not supported!"); } } /** * @inheritdoc * @throws NotSupportedException */ public function validateSignature(string $data, string $expectSignature, string $type = null): bool { if ($dataSignature = $this->initDataSignature($data, $type)) { return $dataSignature->validate($expectSignature); } else { throw new NotSupportedException("Validate signature with type: '$type' is not supported!"); } } /** * @param string $data * @param string $type * @return null|DataSignature */ abstract protected function initDataSignature(string $data, string $type): ?\yii2vn\payment\DataSignature; }
true
8567d2649dd973c3c007db4f1039d6aeffc87fc4
PHP
icrewsystemsofficial/covid19resources
/app/Models/Mission.php
UTF-8
3,661
2.59375
3
[]
no_license
<?php namespace App\Models; use Exception; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Factories\HasFactory; use App\Models\User; class Mission extends Model { use HasFactory; public const ASSIGNED = '0'; public const INPROGRESS = '1'; public const DELAYED = '2'; public const COMPLETED = '3'; public const MISSION_TWEET = '0'; public const MISSION_RESOURCE = '1'; public function missionType($type = '') { if($type == '') { $type = $this->type; } $response = array(); $response['type'] = $type; switch($type) { case 0: $response['name'] = 'Tweet Verification'; $response['color'] = 'primary'; $response['gradient'] = 'bg-primary-gradient'; $response['icon'] = 'fab fa-twitter'; break; case 1: $response['name'] = 'Resource Verification'; $response['color'] = 'success'; $response['gradient'] = 'bg-success-gradient'; $response['icon'] = 'fas fa-info-circle'; break; default: throw new Exception('Unknown Mission type provided'); break; } $response = (object) $response; return $response; } protected $fillable = [ 'volunteer_id', 'uuid', 'description', 'slot_start', 'slot_end', 'count', 'data', 'completed', 'type', 'total', ]; public static function getAllTweetStatus() { $status = array(); $status[] = self::ASSIGNED; $status[] = self::INPROGRESS; $status[] = self::DELAYED; $status[] = self::COMPLETED; return $status; } public function getStatus($status = '') { if($status == '') { $status = $this->status; } $response = array(); $response['id'] = $status; switch($status) { case 0: $response['name'] = 'Assigned'; $response['color'] = 'warning'; $response['gradient'] = 'bg-warning-gradient'; $response['icon'] = 'circle-notch'; break; case 1: $response['name'] = 'In Progress'; $response['color'] = 'primary'; $response['gradient'] = 'bg-primary-gradient'; $response['icon'] = 'sync fa-spin'; break; case 2: $response['name'] = 'Delayed'; $response['color'] = 'danger'; $response['gradient'] = 'bg-danger-gradient'; $response['icon'] = 'exclamation-triangle'; break; case 3: $response['name'] = 'Completed'; $response['color'] = 'success'; $response['gradient'] = 'bg-success-gradient'; $response['icon'] = 'check'; break; default: throw new Exception('Unknown Mission status ID type provided'); break; } $response = (object) $response; return $response; } public function dataArray() { return json_decode($this->data); } public function getVolunteer() { return $this->hasOne(User::class, 'id', 'volunteer_id'); } public static function getAssignedMissions($id = '') { if($id == '') { $id = $this->volunteer_id; } return Mission::where('volunteer_id', $id)->get(); } }
true
554b5b746b7dd0b4aa52b419922d5e0deae0e5bb
PHP
kennitromero/php-learning
/design-patterns/src/AbstractFactory/ExampleTemplates/ConcreteElements/PHP/PHPTemplateRenderer.php
UTF-8
735
3.203125
3
[]
no_license
<?php namespace DesignPatterns\AbstractFactory\ExampleTemplate\ConcreteElements\PHP; use DesignPatterns\AbstractFactory\ExampleTemplate\AbstractElements\TemplateRenderer; /** * Class PHPTemplateRenderer * @package DesignPatterns\AbstractFactory\ExampleTemplate\ConcreteElements\PHP */ class PHPTemplateRenderer implements TemplateRenderer { /** * @param string $templateString * @param array $arguments * @return string */ public function render(string $templateString, array $arguments = []): string { extract($arguments); ob_start(); eval(' ?>' . $templateString . '<?php '); $result = ob_get_contents(); ob_end_clean(); return $result; } }
true
4b805b318ebd7f6b0a2380ff469282319673b712
PHP
WaseemCake/qb
/tests/intrinsic-sin.phpt
UTF-8
740
3.078125
3
[]
no_license
--TEST-- Sine test --FILE-- <?php /** * A test function * * @engine qb * @param float64 $[ab] * @param float32 $[cd] * @param int32 $i * * @return void * */ function test_function($a, $b, $c, $d, $i) { echo sin($a), "\n"; echo sin($b), "\n"; echo sin($c), "\n"; echo sin($d), "\n"; echo sin($i), "\n"; } qb_compile(); $a = M_PI / 4; $b = M_PI / 2; $c = 3; $d = 2; $i = 1; echo sin($a), "\n"; echo sin($b), "\n"; echo sin($c), "\n"; echo sin($d), "\n"; echo sin($i), "\n"; echo "---\n"; test_function($a, $b, $c, $d, $i); ?> --EXPECT-- 0.70710678118655 1 0.14112000805987 0.90929742682568 0.8414709848079 --- 0.70710678118655 1 0.14112 0.9092974 0.8414709848079
true
469831568b30eca4f6e9e4df79343126fc3ae8a0
PHP
JanBlatter/ICT-133_JBR
/Site/view/register.php
UTF-8
787
2.59375
3
[]
no_license
<?php /** * ICT-133_JBR - register.php * User: Jan.BLATTER * Date: 20.01.2020 */ // tampon de flux stocké en mémoire ob_start();//ouvre la mémoire tampon $titre="Rent A Snow - Accueil" ?> <form class="form" method="POST" action="index.php?action=register"> <br> <h1> Création d'un compte </h1> <b>Username:</b><br> <input type="email" name="username" value="" placeholder="username" required> <br> <b>Password:</b><br> <input type="password" name="password" value="" placeholder="password" required> <br> <br> <input type="submit" value="submit"> </form> <?php $content = ob_get_clean(); //efface la mémoire tampon dans la variable $content require "gabarit.php"; //Appele le fichier. gabarit.php est requis pour que ça marche.
true
46b7977083aceb63f0a0aee7ba9cfa5b3c4e1cb2
PHP
nickspaargaren/php-git-leren
/index.php
UTF-8
1,159
2.734375
3
[]
no_license
<?php // Algemene variabelen $pagina = "php, écht mooi"; $base = "//".$_SERVER['HTTP_HOST']."/"; // {BASISDIR}, soort van. // Database gegevens $db_hostname = 'localhost'; $db_database = 'test'; $db_userid = 'root'; $db_password = 'root'; // Connectie met database maken $mysqli = new mysqli($db_hostname, $db_userid, $db_password, $db_database); // Gebruiker gegevens ophalen (In dit geval gebruiker #1, Marit) $gebruikerQuery = $mysqli->query('SELECT id, naam FROM gebruikers WHERE id=1'); $gebruiker = $gebruikerQuery->fetch_assoc(); // Stel er is hierboven voor Marit (gebruiker #1) gekozen if($gebruiker['id'] == 1){ $background = 'style="background-color: pink;"'; } elseif ($gebruiker['id'] == 2) { $background = 'style="background-color: paars;"'; } ?> <html> <head> <title><?php echo $pagina; ?></title> <link rel="stylesheet" href="<?php echo $base; ?>style.css"> </head> <body <?php echo $background; ?>> <?php echo '<h1 class="titel">Hallo, '.$gebruiker['naam'].' <span>(#'.$gebruiker['id']. ')</span></h1><p>Dankzij Nick kan ik nu weer verder, YES!</p>'; ?> </body> </html>
true
eb8dc3d5abb9ba3aad9672158eff25a2b327b126
PHP
kunx-edu/Interview-record
/frontend/models/Interview.php
UTF-8
3,048
2.71875
3
[ "BSD-3-Clause" ]
permissive
<?php namespace frontend\models; use common\helper\Helper; use Yii; /** * This is the model class for table "interview". * * @property integer $id * @property integer $class_id * @property string $company_name * @property string $company_address * @property string $salary * @property integer $company_type * @property integer $interview_time * @property string $interview_info * @property integer $student_id * @property integer $is_written_examination * @property string $sound_recording_file * @property double $grade * @property integer $is_delete */ class Interview extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'interview'; } /** * @inheritdoc */ public function rules() { return [ ['company_name','required','message'=>'公司名称不能为空'], ['company_address','required','message'=>'公司地址不能为空'], ['occupation','required','message'=>'面试职位不能为空'], ['class_id','required','message'=>'班级不能为空'], ['company_type','required','message'=>'公司类型不能为空'], ['interview_time','required','message'=>'面试时间不能为空'], ['interview_info','required','message'=>'面试记录不能为空'], ['is_written_examination','required','message'=>'是否有笔试不能为空'], ['grade','required','message'=>'面试评分不能为空'], ['salary','required','message'=>'要求薪水不能为空'], // [['company_name'], 'required'], // [['company_type', 'interview_time', 'student_id', 'is_written_examination', 'is_delete'], 'integer'], // [['interview_info'], 'string'], // [['grade'], 'number'], // [['company_name'], 'string', 'max' => 40], // [['company_address', 'salary', 'sound_recording_file'], 'string', 'max' => 255], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'company_name' => 'Company Name', 'company_address' => 'Company Address', 'salary' => 'Salary', 'company_type' => 'Company Type', 'interview_time' => 'Interview Time', 'interview_info' => 'Interview Info', 'student_id' => 'Student ID', 'is_written_examination' => 'Is Written Examination', 'sound_recording_file' => 'Sound Recording File', 'grade' => 'Grade', 'is_delete' => 'Is Delete', ]; } /** * 添加面试记录的方法. */ public function addInterview($data) { //验证. if ($this->validate()) { //保存面试记录到数据库. $res = Helper::getService('Interview.Interview')->addInterview($data); return $res; } else { return false; } } }
true
2415684b45c8dc2d224202830e7f2913ebe172a7
PHP
crianbra/ProyectoPhp-Grupo8
/admin/ayudante/guardar.php
UTF-8
1,036
2.890625
3
[ "MIT" ]
permissive
<html> <head> </head> <body> <div id="main"> <?php $valor = $_POST["id"]; $valor2 = $_POST["descripcion"]; $valor3 = $_POST["usuario_id"]; $valor3 = $_POST["reconocimiento_id"]; echo 'Hola Usuario con el ID : ' .htmlspecialchars($valor) . '!'; include_once("AyudanteCollector.php"); $AyudanteCollectorObj = new AyudanteCollector(); //$ObjPersona = $PersonaCollectorObj->createPersona($valor); echo "Se ha guardado correctamente </br>"; if (isset($_POST["descripcion"])) { $descripcion =($_POST["descripcion"]); $usuario_id =($_POST["usuario_id"]); $reconocimiento_id =($_POST["reconocimiento_id"]); if ($AyudanteCollectorObj->createAyudante($descripcion, $usuario_id,$reconocimiento_id)) { //var_dump($obj); echo "Se ha guardado correctamente </br>"; header("Location: ../index.php"); exit(); } else { } } else { echo "Hubo un error al intentar crear el usuario."; } ?> <div><a href="index.php">Volver al Inicio</a></div> </div> </body> </html>
true
0618a021f7b993521f812868e76937cf5e748a86
PHP
LauraHegay/564729-yeticave
/add.php
UTF-8
3,343
2.515625
3
[]
no_license
<?php require_once('functions.php'); //подключаем сценарий с функцией-шаблонизатором require_once('init.php'); $errors=[]; if (empty($user_name)) { http_response_code(403); header("Location: /"); exit(); } if ($_SERVER['REQUEST_METHOD']==='POST'){ $lot=$_POST; $required_fields=['lot-name','category','message','lot-rate','lot-step','lot-date']; foreach ($lot as $key => $value){ if ($key==="lot-rate"){ if(!filter_var($value,FILTER_VALIDATE_INT)or $value<0 ){ $errors[$key]='Заполните поле Ставка корректными данными'; } } elseif ($key==="lot-step") { if(!filter_var($value,FILTER_VALIDATE_INT)or $value<0 or is_int($value)){ $errors[$key]='Заполните поле Шаг ставки корректными данными'; } } elseif ($key==="lot-date") { $diff = strtotime($value)-strtotime('today'); if(!check_date_format($value)or($diff <86400)){ $errors[$key]='Заполните поле Дата завершения ставки корректными данными'; } } } if (!empty($_FILES['photo2']['name'])){ $tmp_name=$_FILES['photo2']['tmp_name']; $finfo = finfo_open(FILEINFO_MIME_TYPE); $extension=pathinfo($_FILES['photo2']['name'],PATHINFO_EXTENSION); if($tmp_name!==""){ $file_type=finfo_file($finfo, $tmp_name);} if ($file_type!=="image/png" and $file_type!=="image/jpeg"){ $errors['photo2']='Загрузите картинку в формате jpg, jpeg, png'; } else { $tmp_name=uniqid() .".".$extension; $lot['photo2']='img/'.$tmp_name; } } else { $errors['photo2']='Вы не загрузили файл'; } foreach($required_fields as $key){ if (empty($_POST[$key]) or !(trim($_POST[$key]))) { $errors[$key]='Поле не заполнено'; } } if (count($errors)){ $page_content = include_template('add.php', [ 'categories'=>$cat, 'lot'=>$lot, 'errors' => $errors]); } else { $lot['lot-date'] = date("Y-m-d", strtotime($lot['lot-date'])); move_uploaded_file($_FILES['photo2']['tmp_name'],'img/'.$tmp_name); $sql = 'INSERT INTO lots (date_create, date_end, title, category_id, start_price, step_rate, image_path, description, user_id) VALUES (NOW(), ?, ?, ?, ?, ?,?, ?,?)'; $stmt = db_get_prepare_stmt($con, $sql, [$lot['lot-date'],$lot['lot-name'], $lot['category'], $lot['lot-rate'], $lot['lot-step'], $lot['photo2'],$lot['message'], $user_id]); $res = mysqli_stmt_execute($stmt); $id_lot = mysqli_insert_id($con); header("Location: lot.php?id=$id_lot"); exit(); } } else { $page_content = include_template('add.php', ['categories'=>$cat,'errors' => $errors]); } $layout_content = include_template('layout.php', [ 'title' => 'Yeti - Добавление лота', 'is_auth' => $is_auth, 'user_name' => $user_name, 'content' => $page_content, 'categories' => $cat ]); print($layout_content);
true
9cc0c4a3a89dbda39bbecc00a932d664f664264a
PHP
elhadja/CHU-Bdx
/controller/DelPatController.php
UTF-8
1,258
2.546875
3
[]
no_license
<?php include_once 'model/MatStatisticModel.php'; include_once 'view/Welcome.php'; include_once 'model/DelPatModel.php'; class DelPatController { private $view; public function __construct($bdd){ $this->view = new Welcome($bdd); $model = new MatStatisticModel($bdd); $model->computeForAll(); $this->view->setMatInfos($model->statePoints, $model->nbMatDisp, $model->nbMatTotal, "!"); $model = new DelPatModel($bdd); $ans = $model->delete(); switch($ans){ case 'SUCCESS': $this->view->setMessage("Traitement supprimé", "pagemessage"); break; case 'SUCCESS_PAT': $this->view->setMessage("Traitement et patient supprimés", "pagemessage"); break; case 'ECHEC_PAT': $this->view->setMessage("Traitement supprimé, échec de la suppression du patient", "pagemessage"); break; default: $this->view->setMessage("-- ERROR IN DELETEPAT MODEL --", "pagemessage"); break; } } public function launch(){ $this->view->launch(); } } ?>
true
2d156919490f327a1af2b124c89f837709ea3869
PHP
qlwz/mock
/src/random/helper.php
UTF-8
1,742
3.375
3
[ "MIT" ]
permissive
<?php /** * Mock 一些转换 * * @author 情留メ蚊子 <qlwz@qq.com> * @link http://www.94qing.com */ /** * 把字符串的第一个字母转换为大写。 * * @param string $word * @return string */ function mock_random_capitalize($word = null) { if (!$word) { return $word; } return strtoupper(substr($word, 0, 1)) . substr($word, 1); } /** * 把字符串转换为大写。 * * @param string $str * @return string */ function mock_random_upper($str = null) { if (!$str) { return $str; } return strtoupper($str); } /** * 把字符串转换为小写。 * * @param string $str * @return string */ function mock_random_lower($str = null) { if (!$str) { return $str; } return strtolower($str); } /** * 从数组中随机选取一个元素,并返回。 * * @param array $arr * @param int $min * @param int $max * @return mixed */ function mock_random_pick($arr = null, $min = null, $max = null) { if (!$arr) { return ''; } $num = func_num_args(); if ($num == 1) { return $arr[mt_rand(0, count($arr) - 1)]; } elseif ($num == 2) { $max = $min; } $c = end(mock_random_shuffle($arr, $min, $max)); return $c; } /** * 打乱数组中元素的顺序,并返回。 * * @param array $arr * @param int $min * @param int $max * @return array */ function mock_random_shuffle($arr = null, $min = null, $max = null) { if (!$arr) { return []; } shuffle($arr); $num = func_num_args(); if ($num == 0 || $num == 1) { return $arr; } elseif ($num == 2) { $max = $min; } return array_slice($arr, 0, mt_rand(intval($min), intval($max))); }
true
6681728b7f4718c06e5f24bbbacf97d6d60d3981
PHP
techichitoltek/zend_istef
/application/modules/backoffice/controllers/PortailurlController.php
UTF-8
715
2.5625
3
[]
no_license
<?php /** * Gestion des url portails * * @category backoffice * @package backoffice_controllers * @copyright RCWEB */ class PortailurlController extends App_Backoffice_Controller { /** * Overrides Zend_Controller_Action::init() * * @access public * @return void */ public function init(){ // init the parent parent::init(); } /** * Index des urls * * @access public * @return void */ public function indexAction(){ $portailUrlModel = new PortailUrl(); $listePortailUrl = $portailUrlModel->getListe(false,false,"portailurl_portail_id ASC"); $this->view->listePortailUrl = $listePortailUrl; } }
true
4ad4885dddd1ff5bc74589befdfa947c4945c99d
PHP
yousafsyed/fyp_fuzzy_keyword
/app/Http/Controllers/UserController.php
UTF-8
647
2.75
3
[ "MIT" ]
permissive
<?php /** * User Controller */ namespace App\Http\Controllers; use App\User; class UserController extends Controller { /** * Confirm email and verify account * @param String $token * @return */ public function confirmEmail($token) { try { User::whereToken($token)->firstOrFail()->confirmEmail(); $status = "status"; $message = 'You are now confirmed. Please login.'; } catch (\Exception $e) { $status = "error"; $message = "Invalid Verification Token"; } return redirect('login')->with($status, $message); } }
true
faf606d7626ddec51a153fe1b53a6ed9dca2b35e
PHP
Detachment-550/det550website
/application/models/Alumni_model.php
UTF-8
621
2.59375
3
[ "MIT" ]
permissive
<?php defined('BASEPATH') OR exit('No direct script access allowed'); use Illuminate\Database\Eloquent\Model; /** * Class Test */ class Alumni_model extends Model { /** * @var string */ protected $table = 'alumni'; /** * @var string */ protected $primaryKey = 'id'; /** * @var bool */ public $incrementing = TRUE; /** * @var string */ protected $keyType = 'int'; /** * @var bool */ public $timestamps = TRUE; }
true
30ab6d35a402eeed8f60b30702b65ebf2a196853
PHP
gonzalobrolyn/gonejofire
/procesos/registro/empresas.php
UTF-8
1,023
2.609375
3
[]
no_license
<?php session_start(); require_once "../../clases/Imagenes.php"; require_once "../../clases/Empresas.php"; $objImg = new imagenes(); $objEmp = new empresas(); $idPersona = $_SESSION['persona']; $fechaMundial = time('Y-m-d H:i:s'); $fechaLocal = $fechaMundial - (7*60*60); $fechaHora = date("Y-m-d H:i:s", $fechaLocal); $archivo = $_FILES['logo']['name']; $rutaAlma = $_FILES['logo']['tmp_name']; $carpeta = '../../imagenes/'; $rutaFinal = $carpeta.$archivo; $datosImg = array( $rutaFinal, $fechaHora, $idPersona); if (move_uploaded_file($rutaAlma, $rutaFinal)) { $idImagen = $objImg->guardaImagen($datosImg); if ($idImagen > 0) { $datosEmp = array( $_POST['ruc'], $_POST['razon'], $_POST['direccion'], $idImagen, $fechaHora, $idPersona); echo $objEmp->guardaEmpresa($datosEmp); } else { echo 0; } } else { echo 0; } ?>
true
e2becde34b557777cee7c2b044f00eb4461f01e7
PHP
nechin/lumen-doctrine-restfull-api
/app/Repositories/Contracts/BaseRepository.php
UTF-8
347
2.625
3
[]
no_license
<?php namespace App\Repositories\Contracts; interface BaseRepository { /** * @param mixed $id * @return object|null */ public function find($id); /** * @return array */ public function findAll(); /** * @param array $data */ public function insertOrUpdateByEmail(array $data): void; }
true
3c525b13bb4f7454a2b28aa7d0ba7e5707121530
PHP
D1ed/spez-gost.ru
/public_html/catalog/model/extension/module/multi_fish_landing.php
UTF-8
589
2.578125
3
[]
no_license
<?php class ModelExtensionModuleMultiFishLanding extends Model { public function getLanding($landing_id) { $data = array(); $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "multi_fish_landing WHERE landing_id = '" . (int)$landing_id . "'"); foreach ($query->rows as $result) { if (!$result['serialized']) { $data[$result['key']] = $result['value']; } else { $data[$result['key']] = json_decode($result['value'], true); } } return $data; } } ?>
true
1cdca9cf452280db7d3e650c052dda304c64b9e8
PHP
ming123jew/sdcms
/doc/Mysqli.php
UTF-8
662
3.015625
3
[]
no_license
<?php /** * Created by PhpStorm. * User: ming123jew * Date: 2018-4-17 * Time: 10:43 */ namespace IMooc; use IMooc\IDatabase; class Mysqli implements IDatabase { protected $conn; function connect($host, $user, $password, $dbname) { // TODO: Implement connect() method. $conn = mysqli_connect($host, $user, $password, $dbname); $this->conn = $conn; } function query($sql) { // TODO: Implement query() method. return mysqli_query($this->conn, $sql); } function close() { // TODO: Implement close() method. mysqli_close($this->conn); } }
true
dbc0c6375d710f775deed85c5adeba6fed1b1dc2
PHP
netzonjoelui/test-backend-app
/tests/NetricTest/Entity/ObjType/NotificationTest.php
UTF-8
4,271
2.59375
3
[]
no_license
<?php /** * Test notification */ namespace NetricTest\Entity\ObjType; use Netric\Entity\EntityInterface; use Netric\EntityLoader; use Netric\Entity\ObjType\UserEntity; use PHPUnit_Framework_TestCase; use Netric\Mail\Transport\InMemory; use Netric\EntityQuery; class NotificationTest extends PHPUnit_Framework_TestCase { /** * Tennant account * * @var \Netric\Account\Account */ private $account = null; /** * Administrative user * * @var \Netric\User */ private $user = null; /** * Test user to notify * * @var User */ private $testUser = null; /** * EntityLoader * * @var EntityLoader */ private $entityLoader = null; /** * List of test entities to cleanup * * @var EntityInterface[] */ private $testEntities = array(); /** * Setup each test */ protected function setUp() { $this->account = \NetricTest\Bootstrap::getAccount(); $this->user = $this->account->getUser(\Netric\Entity\ObjType\UserEntity::USER_SYSTEM); $this->entityLoader = $this->account->getServiceManager()->get("EntityLoader"); // Make sure test user does not exist from previous failed query $index = $this->account->getServiceManager()->get("EntityQuery_Index"); $query = new EntityQuery("user"); $query->where("name")->equals("notificationtest"); $result = $index->executeQuery($query); for ($i = 0; $i < $result->getNum(); $i++) { $this->entityLoader->delete($result->getEntity($i), true); } // Create a test user to assign a task and notification to $this->testUser = $this->entityLoader->create("user"); $this->testUser->setValue("name", "notificationtest"); $this->testUser->setValue("email", "test@netric.com"); $this->entityLoader->save($this->testUser); $this->testEntities[] = $this->testUser; } /** * Cleanup after each test */ protected function tearDown() { // Make sure any test entities created are deleted foreach ($this->testEntities as $entity) { // Second param is a 'hard' delete which actually purges the data $this->entityLoader->delete($entity, true); } } /** * Test dynamic factory of entity */ public function testFactory() { $entity = $this->account->getServiceManager()->get("EntityFactory")->create("notification"); $this->assertInstanceOf("\\Netric\\Entity\\ObjType\\NotificationEntity", $entity); } /** * Test that a email is sent */ public function testSendEmailNotification() { // Set obj_reference to a task $task = $this->entityLoader->create("task"); $task->setValue("name", "A test task"); $this->entityLoader->save($task); $this->testEntities[] = $task; // Create a new notification $notification = $this->entityLoader->create("notification"); $notification->setValue("f_email", true); $notification->setValue("owner_id", $this->testUser->getId()); $notification->setValue("creator_id", $this->user->getId()); $notification->setValue("obj_reference", "task:" . $task->getId(), $task->getName()); // Setup testable transport $transport = new InMemory(); $notification->setMailTransport($transport); // Call onBeforeSave manually $notification->onBeforeSave($this->account->getServiceManager()); $message = $transport->getLastMessage(); // Make sure the message was sent to the owner_id $this->assertEquals( $this->testUser->getValue("email"), $message->getTo()->current()->getEmail() ); // Check that we sent from the creator name $this->assertEquals( $this->user->getName(), $message->getFrom()->current()->getName() ); // Make sure dropbox email is generated for replying to $this->assertContains( $this->account->getName() . "-com-task." . $task->getId(), $message->getFrom()->current()->getEmail() ); } }
true
3bf5558e3fa697a7726afb948ef779a4be63abb4
PHP
VPopchev/phalcon-kanban-board
/app/controllers/UserController.php
UTF-8
2,260
2.6875
3
[]
no_license
<?php use App\Forms\UsersForm; use App\Models\Users; class UserController extends \Phalcon\Mvc\Controller { public function indexAction() { } public function logoutAction() { $sessions = $this->getDI()->getShared('session'); $sessions->remove('user_id'); $sessions->remove('username'); $this->response->redirect(''); } public function loginAction() { $sessions = $this->getDI()->getShared("session"); $form = new UsersForm(); if($this->request->isPost()){ $username = $this->request->getPost('username'); $password = $this->request->getPost('password'); $user = Users::findFirst([ 'conditions' => 'username = ?0', 'bind' => [ 0 => $username, ] ]); if(!$this->security->checkHash($password, $user->password)){ echo 'Invalid Credentials!'; } else { $sessions->set('user_id', $user->id); $sessions->set('username', $user->username); $this->response->redirect(''); } } $this->view->form = $form; } public function registerAction() { $user = new Users(); $form = new UsersForm($user); if($this->request->isPost()){ $form->bind($this->request->getPost(),$user); // Getting Password from the request. $password = $user->password; // Hashing the password and bind it to the new user. $user->password = $this->security->hash($password); $success = $user->save(); // Check for operation success and handling errors. if ($success) { echo 'Thanks you for register in out site!'; $this->response->redirect('user/login'); } else { echo 'Oops, Something Went Wrong'; $messages = $user->getMessages(); foreach ($messages as $message) { echo $message->getMessage(); } } } $this->view->form = $form; $this->view->pick('user/register'); } }
true
a4c390fece4e41800624b0a22e01f5d0b256e35c
PHP
Takahiro928800/task.php
/task_17-21.php
UTF-8
3,398
3.859375
4
[]
no_license
print("#####q17#####".PHP_EOL); <?php class User { protected $name; protected $age; protected $gender; function __construct($user_name,$user_age,$user_gender) { $this->name = $user_name; $this->age = $user_age; $this->gender = $user_gender; } function info() { print("名前:".$this->name.PHP_EOL); print("年齢:".$this->age.PHP_EOL); print("性別:".$this->gender.PHP_EOL); } } $user1 = new User("神里",32,"男"); $user2 = new User("あじー",32,"男"); $user1->info(); print("-------------".PHP_EOL); $user2->info(); echo PHP_EOL; print("#####q18#####".PHP_EOL); class Man { protected $name; protected $age; function __construct($user_name,$user_age) { $this->name = $user_name; $this->age = $user_age; } function introduce () { if($this->age >= 20){ print("こんにちは, ".$this->name."と申します。宜しくお願いいたします。".PHP_EOL); }else{ print("はいさいまいど〜, ".$this->name."です!!!".PHP_EOL); } } } $man1 = new Man("あじー",32); $man2 = new Man("ゆたぼん",10); $man1->introduce(); $man2->introduce(); echo PHP_EOL; print("#####q19#####".PHP_EOL); class Item { public $name; //protected $name; function __construct($book_name){ $this->name = $book_name; } } $book = new Item("ゼロ秒思考"); print($book->name.PHP_EOL); echo PHP_EOL; print("#####q20#####".PHP_EOL); class Human { public $name; public $age; function __construct($user_name,$user_age) { $this->name = $user_name; $this->age = $user_age; } } class Zoo { protected $name; protected $entry_fee; function __construct($zoo_name,$zoo_entry_fee) { $this->name = $zoo_name; $this->entry_fee = $zoo_entry_fee; } function info_entry_fee(Human $human){ if($human->age <= 5){ print($human->name."さんの入場料金は ".$this->entry_fee["infant"]." 円です。".PHP_EOL); }elseif($human->age <= 12){ print($human->name."さんの入場料金は ".$this->entry_fee["children"]." 円です。".PHP_EOL); }elseif($human->age <= 64){ print($human->name."さんの入場料金は ".$this->entry_fee["adult"]." 円です。".PHP_EOL); }elseif($human->age <= 120){ print($human->name."さんの入場料金は ".$this->entry_fee["senior"]." 円です。".PHP_EOL); } } } $zoo = new Zoo("旭山動物園",[ "infant" => 0, "children" => 400, "adult" => 800, "senior" => 500]); $human1 = new Human("たま",3); $human2 = new Human("ゆたぼん",10); $human3 = new Human("あじー",32); $human4 = new Human("ぎん",108); $humans = [ $human1, $human2, $human3, $human4 ]; foreach($humans as $human){ $zoo->info_entry_fee($human); } echo PHP_EOL; print("#####q21#####".PHP_EOL); //Q21. FizzBuzz問題 for($i=1 ; $i <= 30 ; $i++){ if($i % 105 == 0) { echo 'FizzBuzzHoge'. PHP_EOL; }elseif($i %35 == 0) { echo 'BuzzHoge'.PHP_EOL; }elseif($i %21 == 0) { echo 'FizzHoge'.PHP_EOL; }elseif($i %15 == 0) { echo 'FizzBuzz'.PHP_EOL; }elseif($i %7 == 0) { echo 'Hoge'.PHP_EOL; }elseif($i %5 == 0) { echo 'Buzz'.PHP_EOL; }elseif($i %3 == 0) { echo 'Fizz'.PHP_EOL; }else{ echo $i.PHP_EOL; } }
true
96f4f77e6e5d18a3dd597ea81f6d560390fbca38
PHP
dyhb/windsforce
/upload/source/include/DoYouHaoBaby/Base/View/#note/View.class.php
UTF-8
1,235
2.921875
3
[ "BSD-3-Clause" ]
permissive
<?dyhb class View{ /** * Template控件 * * @access private * @var array */ private $_oPar=null; /** * Template控件 * * @access private * @var array */ private $_oTemplate; /** * 是否分享全局Template控件 * * @access private * @static * @var object */ static private $_oShareGlobalTemplate; /** * 模版名字 * * @access private * @var bool */ private $_sTemplate; /** * 模板运行时间 * * @access private * @var int */ private $_nRuntime; /** * 构造函数 * * @access public * @param $oPar 控制器 * @return void */ public function __construct($oPar=null,$sTemplate=null,$oTemplate=null){} /** * 自动定位模板文件 * * @access private * @param string $sTemplateFile 文件名 * @return string */ public function parseTemplateFile($sTemplateFile){} /** * 获取Template控件 * * @access public * @return Template */ public function getTemplate(){} /** * 设置Template控件 * * @access public * @param $oTemplate Template对象 * @return oldValue */ public function setTemplate(Template $oTemplate){} }
true
1788b9bb950861eef050a01e4e912bede24c58a9
PHP
s3inlc/cineast-evaluator
/inc/gamification/Phrases.class.php
UTF-8
755
3
3
[ "MIT" ]
permissive
<?php /** * Created by IntelliJ IDEA. * User: sein * Date: 20.06.17 * Time: 13:27 */ class Phrases { const PHRASES_FILE = "phrases.json"; const PHRASES_START = "startPhrases"; const PHRASES_NORMAL = "phrases"; private $phrases = array(); function __construct() { $this->phrases = json_decode(file_get_contents(dirname(__FILE__) . "/" . Phrases::PHRASES_FILE), true); } public function getStartPhrase() { $size = sizeof($this->phrases[Phrases::PHRASES_START]); return $this->phrases[Phrases::PHRASES_START][mt_rand(0, $size - 1)]; } public function getPhrase() { $size = sizeof($this->phrases[Phrases::PHRASES_NORMAL]); return $this->phrases[Phrases::PHRASES_NORMAL][mt_rand(0, $size - 1)]; } }
true
7812ad0f8060a71cf34eb164a8d074844e6534be
PHP
pablo-maldonado/eventosTemplate
/modals/registro.php
UTF-8
1,928
2.609375
3
[]
no_license
<?php REQUIRE("conexion.php"); header("Content-Type: text/html;charset=utf-8"); $name = $_POST["nombre"]; $surname = $_POST["apellido"]; $email = $_POST["email"]; $empresa = $_POST["empresa"]; $birthdate = $_POST["birthdate"]; $events_id = $_POST["events_id"]; $maxDate = date("Y-m-d", strtotime('-8 year')); $response = array('status'=>false, 'message'=>"nada tipo literal", 'events_id'=>-1); if (empty($name)) { $response['message'] = 'Debes ingresar nombre'; echo json_encode($response); die(); } if (empty($surname)) { $response['message'] = 'Debes ingresar apellido'; echo json_encode($response); die(); } if (empty($email) || (!filter_var($email, FILTER_VALIDATE_EMAIL))) { $response['message'] = 'Debes ingresar un e-mail válido'; echo json_encode($response); die(); } if (empty($birthdate)) { $response['message'] = 'Debes ingresar tu fecha de nacimiento'; echo json_encode($response); die(); } if ($maxDate < $birthdate) { $response['message'] = 'La fecha de nacimiento ingresada no es válida, por favor digitela denuevo'; echo json_encode($response); die(); } $sql = "INSERT INTO user_(user_name, user_surname, user_email, user_company, user_birthdate) VALUES ('$name', '$surname', '$email', '$empresa', STR_TO_DATE('$birthdate', '%Y-%m-%d'))"; $result = mysqli_query($conn, $sql); $sql2= "INSERT INTO user_event(events_id, user_email) VALUES ($events_id, '$email')"; $result2 = mysqli_query($conn, $sql2); if ($result&&$result2) { $response['status'] = true; $response['message'] = "Se ha registrado a $name $surname correctamente."; $response['events_id'] = $events_id; }elseif (!$result && $result2) { $response['status'] = true; $response['message'] = "Se registro a " . $name . ". Muchas gracias"; } elseif (!$result2){ $response['message'] = "Este mail ya está registrado"; } echo json_encode($response); die(); ?>
true
0a04ff52f022672a3eb25ccdb937dd8dd87357aa
PHP
KrystianMroczkowski/Website-project
/login.php
UTF-8
2,269
2.828125
3
[]
no_license
<?php session_start(); if(isset($_POST['login'])) { $OK = true; $login = $_POST['login']; $pasw = $_POST['pasw']; $login = htmlentities($login, ENT_QUOTES, "UTF-8"); require_once "dbconnect.php"; $connection = new mysqli ($host, $db_user, $db_password, $db_name); try { if ($connection->connect_errno != 0) { throw new Exception(mysqli_connect_errno()); } else { if ($result = $connection->query( sprintf("SELECT * FROM registered WHERE login = '%s'", mysqli_real_escape_string($connection,$login)))); { $rows = $result->num_rows; if($rows>0) { $str = $result->fetch_assoc(); if(password_verify($pasw, $str['password'])) { $_SESSION['logged'] = true; header("Location: glowna.php"); } else $_SESSION['e_error'] = "Niepoprawny login lub hasło!"; } $_SESSION['e_error'] = "Niepoprawny login lub hasło!"; } $connection->close(); } } catch (Exception $e) { echo '<span style="color:red;">Błąd serwera!</span>'; echo '<br />Informacja developerska: '.$e; } } ?> <html> <head> <title>Logowanie</title> <style> .error { color:red; margin-top: 10px; margin-bottom: 10px; } </style> <link rel="stylesheet" href="style2.css" type="text/css"/> </head> <body> <div id = "container"> <form method = "post"> <input type = "text" placeholder="Login" onfocus="this.placeholder=''" onblur="this.placeholder='Login'" name = "login"><br><br/> <input type = "password" placeholder="Hasło" onfocus="this.placeholder=''" onblur="this.placeholder='Hasło'" name = "pasw"><br><br/> <input type = "submit" value = "Zaloguj"> <br><br/> <div id = "register"> <a href="db_registration.php">Zarejestruj się!</a><br><br> <a href="glowna.php">Powrót do strony głównej</a> </div> <div id = "error"> <?php if (isset($_SESSION['e_error'])) { echo '<div class ="error">'.$_SESSION['e_error'].'</div>'; unset($_SESSION['e_error']); } ?> </div> </form> </div> </body> </html>
true
3d3f50634c17e13a25d37914aec2f68edef12b33
PHP
crupko93/credit-calculator
/src/helpers.php
UTF-8
3,926
3.234375
3
[]
no_license
<?php namespace Credits; use DateTime; use DateInterval; /** * Считаем дату, на которую приходится следующее погашение * * @param DateTime $initial Начальная дата * @param int $durationType Продолжительность платежного периода * @param int $repaymentNumber Номер платежного периода * @return DateTime * @throws \InvalidArgumentException */ function addDurationToDate(DateTime $initial, int $durationType, int $repaymentNumber): DateTime { if ($repaymentNumber <= 0) { throw new \InvalidArgumentException('Invalid argument repaymentNumber'); } $newDate = clone $initial; if ($durationType === CreditParams::DURATION_WEEK || $durationType === CreditParams::DURATION_TWO_WEEKS || $durationType === CreditParams::DURATION_QUARTER) { $intervalDays = CreditParams::$daysInPaymentPeriod[$durationType]; $days = $intervalDays * $repaymentNumber; $interval = new DateInterval("P{$days}D"); return $newDate->add($interval); } elseif ($durationType === CreditParams::DURATION_MONTH) { // расчет следующей даты платежа при ежемесячных платежах. // в php косяк: если к 29-31 января добавить интервал 1 месяц, то получится март. // эту ситуацию и обрабатывает код ниже $newDate->add(new DateInterval("P{$repaymentNumber}M")); $initialMonthsCount = (int)$initial->format('Y') * 12 + (int)$initial->format('n'); $newMonthsCount = (int)$newDate->format('Y') * 12 + (int)$newDate->format('n'); if ($newMonthsCount - $initialMonthsCount > $repaymentNumber) { $newDate->modify('last day of previous month'); } return $newDate; } throw new \InvalidArgumentException('Invalid argument durationType'); } /** * Получить массив с частичными погашениями кредита между двумя датами, * при этом время не учитывается. Если имеется несколько платежей на одну дату, * то платежи сортируются по времени в порядке его увеличения. * * @param DateTime $currentDate * @param DateTime $previousDate * @return array<UnexpectedPayment> * @throws \InvalidArgumentException */ function getUnexpectedPaymentsBetweenDates(DateTime $currentDate, DateTime $nextDate, array $unexpectedPayments): array { $payments = []; $currDateStr = $currentDate->format('Y-m-d'); $nextDateStr = $nextDate->format('Y-m-d'); foreach ($unexpectedPayments as $unexpectedPayment) { if (!($unexpectedPayment instanceof UnexpectedPayment)) { throw new \InvalidArgumentException('Array shuld contain instances of UnexpectedPayment'); } $paymentDateStr = $unexpectedPayment->getDate()->format('Y-m-d'); if ($paymentDateStr >= $currDateStr && $paymentDateStr < $nextDateStr) { $payments[] = $unexpectedPayment; } } uasort($payments, function($a, $b) { $aTs = (int)$a->getDate()->format('U'); $bTs = (int)$b->getDate()->format('U'); if ($aTs === $bTs) { return 0; } return ($aTs < $bTs) ? -1 : 1; }); return $payments; } /** * Форматируем денежную сумму, выраженную в копейках * в красивый вид, например 1500000(15 тысяч) -> 15 000.00 * * @param int $number Число, которое нуждается форматировании * @return string */ function prettifyNumber(int $number) { return number_format($number / 100, 2, '.', ' '); }
true
10abdc88ae69c2615d47ecee86ac5549b54f231e
PHP
pedrammehrdad/react-with-yii-example
/backend/models/Tracker.php
UTF-8
1,246
2.609375
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\models; use Yii; /** * This is the model class for collection "tracker". * * @property \MongoDB\BSON\ObjectID|string $_id * @property mixed $start_time * @property mixed $end_time * @property mixed $description * @property mixed $duration */ class Tracker extends \yii\mongodb\ActiveRecord { /** * {@inheritdoc} */ public static function collectionName() { return ['tracker', 'tracker']; } /** * {@inheritdoc} */ public function attributes() { return [ '_id', 'start_time', 'end_time', 'description', 'duration', ]; } /** * {@inheritdoc} */ public function rules() { return [ [['start_time', 'end_time', 'description', 'duration'], 'required'], ['end_time', 'default', 'value' => time()], ]; } /** * {@inheritdoc} */ public function attributeLabels() { return [ '_id' => 'ID', 'start_time' => 'Start Time', 'end_time' => 'End Time', 'description' => 'Description', 'duration' => 'Duration', ]; } }
true
974568c1f751a3a7d932598fc51fdf38c195c88f
PHP
bhavisha828/php-day6
/database/databases.php
UTF-8
2,210
2.640625
3
[]
no_license
<?php $connection = mysqli_connect("localhost","root","","tbl_student"); if ($_POST) { $Name = $_POST['txt1']; $Gender = $_POST['txt2']; $Date_of_Birth = $_POST['txt3']; $Email = $_POST['txt4']; $Mobileno = $_POST['txt5']; $Address = $_POST['txt6']; $Area = $_POST['txt7']; $Pincode = $_POST['txt8']; $Bloodgroup = $_POST['txt9']; $Feedback = $_POST['txt10']; $Password = $_POST['txt11']; $q = mysqli_query($connection, "insert_into_std (Name, Gender, Date_of_Birth, Email, Mobileno, Address, Area, Pincode, Bloodgroup, Feedback, Password) values('{$Name}','{$Gender}','{$Date_of_Birth}','{$Email}','{$Mobileno}','{$Address}','{$Area}','{$Pincode}','{$Bloodgroup}','{$Feedback}','{$Password}')") or die(mysqli_error($connection)); if ($q) { echo "<script>alert('record added')</script>"; } } ?> <html> <body> <tr></tr> <form method="post" > <table> <tr> <td>Name : <input type="text" name="txt1"><br/></td></tr> <tr><td>Gender: <select name="txt2"> <option>Male</option> <option>Female</option> </select></td></tr> <tr><td>Date_of_Birth : <input type="date" name="txt3"><br/></td></tr> <tr><td>Email : <input type="email" name="txt4"><br/></td></tr> <tr><td>Mobileno : <input type="number" name="txt5"><br/></td></tr> <tr><td>Address : <input type="textarea" name="txt6"><br/></td></tr> <tr><td>Area : <input list="lang" name="txt7"> <datalist id="lang"> <option value="Demai">demai</option> <option value="Ahemdabad">ahemdabad</option> <option value="Vadodara">vadodara</option> <option value="Surat">surat</option> </datalist> <br/></td></tr> <tr><td>Pincode : <input type="pincode" name="txt8"></td></tr> <tr><td>Bloodgroup : <input type="text" name="txt9"></td></tr> <tr><td>Feedback : <input type="textarea" name="txt10"></td></tr> <tr><td>Password : <input type="password" name="txt11"><br/></td></tr> <tr><td>Submit : <input type="submit"></td></tr> </table> </form> </body></html>
true
e6b32251bde3523aca9b887b912947a4620fef58
PHP
SwithFr/BookStore
/views/editors/index.php
UTF-8
1,606
2.546875
3
[]
no_license
<?php require(D_VIEWS . DS . 'elements' . DS . 'editors-form.php'); use Helpers\Html; ?> <div class="section"> <div class="section__header"> <h2 class="section__title">Selectionnez un editeur</h2> </div> <ul class="filter__list"> <?php for ($i = 'a'; $i <= 'z'; $i++): ?> <li class="filter__item"> <?php if (in_array(ucfirst($i), $data['letters'])): ?> <a href="<?= Html::url('index', 'editor', ['letter' => $i]); ?>" class="dispo-letter<?= ($data['letter'] == $i) ? ' filter--active' : ''; ?>"><?= ucfirst($i); ?></a> <?php else: ?> <?= ucfirst($i); ?> <?php endif; ?> <?php if ($i == 'z') { break; }; ?> </li> <?php endfor; ?> </ul> <?php if (empty($data['editors'])): ?> <h2 class="noResult">Aucun éditeur trouvé !</h2> <?php endif; ?> <ul class="editors__list"> <?php foreach ($data['editors'] as $editor): ?> <li class="section__block editors__list__item"> <img src="<?= $editor->img; ?>"> <h2 class="editor__title"><a href="<?= Html::url('view', 'editor', ['id' => $editor->id]); ?>"><?= $editor->name; ?></a></h2> <span class="editor__infos"><span class="nb"><?= $editor->book_count; ?></span> livres sur ce site</span> <p><?= $editor->history; ?></p> </li> <?php endforeach; ?> </ul> </div>
true
f0d2518a92b6962df21dc3201371d9642b37a09f
PHP
maelzx/sodingv1
/index.php
UTF-8
2,917
3.15625
3
[]
no_license
<?php require('db.php'); $db = new Db; if (isset($_GET['action']) && strtolower($_GET['action']) == "submitadd") { if ($_POST['name'] != '' && $_POST['due_date'] != '') { $db->insert_todo($_POST['name'], $_POST['due_date']); } header('Location: index.php'); } else if (isset($_GET['action']) && strtolower($_GET['action']) == "submitedit") { if ($_POST['name'] != '' && $_POST['due_date'] != '' && $_POST['id'] > 0) { $db->update_todo($_POST['id'], $_POST['name'], $_POST['due_date']); } header('Location: index.php'); } else if (isset($_GET['action']) && strtolower($_GET['action']) == "submitdelete") { if ($_POST['id'] > 0) { $db->delete_todo($_POST['id']); } header('Location: index.php'); } else if (isset($_GET['action']) && strtolower($_GET['action']) == "add") { ?> <form action="?action=submitadd" method="post"> <label for="name">TASK NAME</label><input type="text" id="name" name="name"><br /> <label for="due_date">DUE DATE</label><input type="text" id="due_date" name="due_date"><br /> <button type="submit">ADD</button> </form> <?php } else if (isset($_GET['action']) && strtolower($_GET['action']) == "delete") { $task = $db->get_todo($_GET['id']); ?> <form action="?action=submitdelete" method="post"> <input type="hidden" name="id" value="<?php print $task['id']; ?>" /> <p>Are you sure you want to delete this task?</p> <button type="submit">YES, DELETE!</button> </form> <?php } else if (isset($_GET['action']) && strtolower($_GET['action']) == "edit" && isset($_GET['id']) && $_GET['id'] > 0) { $task = $db->get_todo($_GET['id']); ?> <h4>EDITING TASK NO: <?php print $task['id']; ?></h4> <form action="?action=submitedit" method="post"> <input type="hidden" name="id" value="<?php print $task['id']; ?>" /> <label for="name">TASK NAME</label><input type="text" id="name" name="name" value="<?php print $task['name']; ?>"><br /> <label for="due_date">DUE DATE</label><input type="text" id="due_date" name="due_date" value="<?php print $task['due_date']; ?>"><br /> <button type="submit">EDIT</button> </form> <?php } else { ?> <a href="?action=add">ADD NEW TASK</a> <br /> <br /> <table> <thead> <tr> <th>NAME</th><th>DUE DATE</th><th>ACTION</th> </tr> </thead> <tbody> <?php foreach($db->get_all_todo() as $todo) { print "<tr>"; print_r("<td>" .$todo['name'] ."</td>"); print_r("<td>" .$todo['due_date'] ."</td>"); print_r("<td>[ <a href='?action=edit&id=" .$todo['id'] ."'>EDIT</a> ] [ <a href='?action=delete&id=" .$todo['id'] ."'>DELETE</a> ]</td>"); print "</tr>"; } ?> </tbody> </table> <?php } ?>
true
3485558062058c6e6e2adb7944af13a385994947
PHP
AfrikuS/adventure
/app/Modules/Oil/Persistence/Repositories/OilPumpRepo.php
UTF-8
1,708
2.703125
3
[]
no_license
<?php namespace App\Modules\Oil\Persistence\Repositories; use App\Models\Core\Equipment; use App\Modules\Oil\Domain\Entities\OilPump; use App\Modules\Oil\Persistence\Dao\EquipmentsDao; class OilPumpRepo { /** @var EquipmentsDao */ private $equipmentsDao; public function __construct(EquipmentsDao $equipmentsDao) { $this->equipmentsDao = $equipmentsDao; } public function findBy($hero_id) { $oilPumpData = $this->equipmentsDao->findOilPumpBy($hero_id); $oilPump = new OilPump($oilPumpData); return $oilPump; } public function updateLevel(OilPump $oilPump) { $this->equipmentsDao->updatePump( $oilPump->hero_id, $oilPump->level ); } /* public function getPumpOilDto($hero_id) { $pumpOilModel = $this->findPumpOilByHeroId($hero_id); if (null == $pumpOilModel) { $factory = new HeroEquipmentFactory(); $pumpOilModel = $factory->createEquipment($hero_id); } $pumpOilDto = new PumpOilDto ( $pumpOilModel->pump_level ); return $pumpOilDto; }*/ public function findOilDistillatorByHeroId($hero_id) { $model = Equipment:: select('hero_id', 'oil_distillator_level') ->find($hero_id); return $model; } // public function getOilDistillatorDto($hero_id) // { // $pumpOilModel = $this->findOilDistillatorByHeroId($hero_id); // // $pumpOilDto = new OilDistillatorDto // ( // $pumpOilModel->oil_distillator_level // ); // // return $pumpOilDto; // } }
true
03514ec8c4ced282e6adff183ba86e850c574897
PHP
eriksencosta/silex-docker-example
/src/Example/Command/FixtureLoad.php
UTF-8
2,123
2.734375
3
[ "Apache-2.0" ]
permissive
<?php namespace Example\Command; use Knp\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class FixtureLoad extends Command { protected function configure() { $this ->setName('example:fixtures:load') ->setDescription('Load fixture data into the database.') ->addOption('truncate', null, InputOption::VALUE_NONE, 'Truncate the tables before loading data.'); } protected function execute(InputInterface $input, OutputInterface $output) { $issues = array(); $issues[] = array( 'title' => 'The API returns 200 instead of 201 for POST /issues', 'description' => 'It would be better to return 201 Created. See: '. 'http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html', 'author' => '@foobar', ); $issues[] = array( 'title' => 'The author field is not being validated', 'description' => 'I sent a POST request to /issues without a valid author name and it was accepted.', 'author' => '@foobar', ); $issues[] = array( 'title' => 'Oasis must reunite', 'description' => 'Yeah, for sure. For half a billion pounds or not. See: '. 'http://www.nme.com/news/noel-gallagher/76984', 'author' => '@eriksencosta', ); $app = $this->getSilexApplication(); $connection = $app['db']; if ($input->getOption('truncate')) { $connection->executeQuery('TRUNCATE issues'); $output->writeln('<info>Truncated the table <comment>issues</comment>.'); } foreach ($issues as $issue) { $connection->insert('issues', $issue); $output->writeln( sprintf( '<info>Created issue <comment>%s</comment> on the on the <comment>issues</comment> table.</info>', $issue['title'] ) ); } } }
true
61c6ab6e055eefee97d84d80b920ffe3f2e7ab97
PHP
guidoleen/members_area
/admin_showuser/show-list.php
UTF-8
2,465
2.78125
3
[]
no_license
<?php /* Plugin Name: Members Lijst Centre Plugin URI: http://guidoleen.nl Desciption: ListBuilder Version: 1.0 Author: Guido Leen */ // TODO > show members from location > SELECT FROM WHERE .... // Show the widget function wddp_showfrom_db() { echo wddp_search_form(); echo "<br>De gebruikers die eventueel aan te passen zijn... <BR>"; //// Db connection vanuit WP $dbConn = @new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); if($dbConn->connect_errno) { echo "Helaas geen connectie mogelijk. Probeer het later nog eens...."; exit(); } else { try { $stmt = $dbConn->prepare("SELECT id, username FROM users ORDER BY username LIMIT 5 OFFSET 0"); $stmt->execute(); $stmt->bind_result($Id,$username); $stmt->store_result(); while($stmt->fetch()) { echo "<a href='index.php?usrid=" . $Id . "'>"; echo $username . '</a><br>'; } $stmt->close(); } catch(Exception $e) { echo "er ging iets mis..."; } } //// Connection and show member with ID // id waarde van delete input $Inputval="Id waarde"; // The Post if(isset($_GET['usrid'])) { $id = $_GET['usrid']; try { $stmt = $dbConn->prepare("SELECT u.username, u.lastname, pro.profile_pic FROM users AS u JOIN user_profile AS pro ON pro.user_id=u.id WHERE u.id = $id"); $stmt->execute(); $stmt->bind_result($username, $lastname, $photo); $stmt->store_result(); define('IMAGE_MAP', content_url() . '/osm_uploads/imgusr/'); while($stmt->fetch()) { if($photo == NULL) { $strSet = "<img src='" . IMAGE_MAP . "usr_0.jpg' style='width:100px;border-radius:50%'>"; } else { $strSet = "<img src='" . IMAGE_MAP . $photo . "' style='width:100px;border-radius:50%'>"; } $strSet .= "<br><a href='index.php?usrid=" . $Id . "'>"; $strSet .= "<span class='first b b-posts'>" . $username . '</span></a><br>'; echo $strSet; } // Show in inputfield Delete $Inputval = $id; } catch(Exception $e) { echo "er ging iets mis..."; } } // Calling the Search Function include 'search_users.php'; // Calling the Delete form include 'delete_user.php'; } // Form create search form function wddp_search_form() { $SearchStr = "<form method='post' action='index.php'>"; $SearchStr .= "<input type='text' name='searchuser'>"; $SearchStr .= "<input type='submit' name='userSub' value='Vind member'>"; $SearchStr .= "</form>"; return $SearchStr; }
true
b6663f0780806b0c42a240b045a269043a03dd66
PHP
edufacio/vxml
/src/api/filmpreferences/FilmPreferencesStorage.php
UTF-8
1,313
2.875
3
[]
no_license
<?php class FilmPreferencesStorage extends DbStorage{ const PHONE = 'phone'; const FAVOURITE_DIRECTORS = 'favourite_directors'; const FAVOURITE_ACTORS = 'favourite_actors'; const FAVOURITE_GENRES = 'favourite_genres'; const DISLIKED_DIRECTORS = 'disliked_directors'; const DISLIKED_ACTORS = 'disliked_actors'; const DISLIKED_GENRES = 'disliked_genres'; const CINEMA = 'cinema'; private static $instance; /** * @return FilmPreferencesStorage */ public static function getInstance() { if (self::$instance === NULL) { self::$instance = Injector::get(__CLASS__); } return self::$instance; } /** * @return array with the columns of the table */ protected function getColumnsName() { return array( self::PHONE, self::FAVOURITE_DIRECTORS, self::FAVOURITE_ACTORS, self::FAVOURITE_GENRES, self::DISLIKED_ACTORS, self::DISLIKED_DIRECTORS, self::DISLIKED_GENRES, self::CINEMA, ); } /** * @return String the class in order to encapsualte a row */ protected function getStorageObjectClass() { return 'FilmPreferences'; } /** * @return String */ protected function getTableName() { return 'film_preferences'; } /** * @return array with the primary keys */ protected function getPrimaryKeyColumns() { return array(self::PHONE); } }
true
c9df5bc69fb78fc6d744e91ada6282f733bcb525
PHP
laudesj/banque
/classes/Compte.php
UTF-8
857
3.40625
3
[]
no_license
<?php class Compte { private $numero; private $solde; private $client; function __construct($solde, $client) { $this->numero = uniqid(); $this->solde = $solde; $this->client = $client; } public function crediter($montant) { if($montant > 0) { $this->solde += $montant; return $this; } else { throw new Exception('Le montant doit être supérieur à 0'); } } public function debiter($montant) { if($montant > 0) { $this->solde -= $montant; return $this; } else { throw new Exception('Le montant doit être supérieur à 0'); } } public function getNumero() { return $this->numero; } public function getSolde() { return $this->solde; } // public function addClient($client) { // $this->clients[] = $client; // return $this; // } public function getClient() { return $this->client; } }
true
e67ae30faaa71ce2c4415c59381b78a83843b751
PHP
jadsson/noticias
/Rules/Connection/Connection.php
UTF-8
383
2.953125
3
[]
no_license
<?php class Connection { private static $i; static function Con() { if(!isset(self::$i)) { try { self::$i = new PDO('mysql:dbname=a_news; host=localhost','root', 'root'); } catch (Exception $e) { echo 'Erro : '.$e->getMessage(); exit; } } return self::$i; } }
true
6d206a319bc52fb257ca13bbe800fd752ce71b5e
PHP
TuncayBasak25/AJAX
/multiplication.php
UTF-8
464
3.953125
4
[]
no_license
<?php if (isset($_GET['nombre'])) { // Comme c'est une requete de type GET on vas chercher ça dans $_GET $nombre = $_GET['nombre']; echo "Voici la table de multiplication de " . $nombre; echo "<br>"; echo "<br>"; for ($i = 0; $i < 11; $i++) { echo $nombre . " x " . $i . " = " . $nombre * $i . "<br />"; echo "<br>"; } echo "Tu veut aller encore plus loin ?"; } ?>
true
12acf36b5b208c3842d5f0aabbfd73ed50303a20
PHP
Gemy-Dev/Redbubble-API
/class.redbubble_cache.php
UTF-8
1,032
3.03125
3
[ "MIT" ]
permissive
<?php class RedbubbleCache { protected $cache_path = '/redbubble_cache/'; protected $duration = 172800; // two days public function getPath() { return dirname(__FILE__) . $this->cache_path; } public function getDuration() { return $this->duration; } public function getCacheObject($name) { $file = $this->getPath() . $name . '.cache'; if (file_exists($file) && time() - filemtime($file) < $this->getDuration()) { $file_contents = file_get_contents($file); if (strlen($file_contents) > 0) { return unserialize($file_contents); } else { return false; } } return false; } public function setCacheObject($name, $array) { $file = $this->getPath() . $name . '.cache'; if (is_writable($file)) { file_put_contents($file, serialize($array)); return true; } return false; } }
true
95c3b0621f2dc55b99f3c6f6cd1654cffb9563ca
PHP
tomasfejfar/datetime-strict
/src/DateTime/DateTimeErrorHandler.php
UTF-8
490
2.734375
3
[ "MIT" ]
permissive
<?php namespace TomasFejfar\DateTime; class DateTimeErrorHandler { public function handle($date, array $errors) { $noWarnings = $errors['warning_count'] === 0; $noErrors = $errors['error_count'] === 0; $dateParsingSucceeded = ($date !== false); if ($dateParsingSucceeded && $noWarnings && $noErrors) { return; } throw new InvalidFormatException('Parsing failed', 0, null, $errors['errors'], $errors['warnings']); } }
true
a8950c2f1f977d96d6aaeb05b7d8a5f4d1e3dd61
PHP
pietrop/team21php
/report/myReportsToAssess.php
UTF-8
2,280
2.703125
3
[]
no_license
<?php include "../navbar/navbar.php"; ?> <main> <!--All assessments group needs to make--> <div class="container"> <h1>My Assessments to Make</h1> <?php $query = "SELECT * FROM `groupreportassessment` AS g INNER JOIN reports AS r WHERE g.report_ID = r.reportID AND g.group_ID =".$_SESSION['group'].""; $result = $conn->query($query); while ($row = $result->fetch_array(MYSQLI_ASSOC)){ $reports[] = $row; } $idCounter = 1; foreach($reports as $report){ ?> <!--Assessment <?php echo $report['assessmentID']?>--> <div class="container well"> <div class="row"> <h2 class="col-sm-offset-1">Assessment #<?php echo $report['assessmentID']?></h2> </div> <div class="row"> <h3 class="col-sm-12 text-justify">Abstract</h3> <p class="col-sm-12 text-justify"><?php echo $report['abstract']?></p> </div> <div class="collapse" id="collapse<?php echo $idCounter;?>"> <!--Exapnded text--> <div class="row"> <h3 class="col-sm-12 text-justify">Review One</h3> <p class="col-sm-12 text-justify"><?php echo $report['review1']?></p> </div> <div class="row"> <h3 class="col-sm-12 text-justify">Review Two</h3> <p class="col-sm-12 text-justify"><?php echo $report['review2']?></p> </div> </div> <div class="row"> <div class="col-sm-2"> <a data-toggle="collapse" href="#collapse<?php echo $idCounter;?>" aria-expanded="false" aria-controls="collapse<?php echo $idCounter;?>" class="btn btn-success btn-sm">Expand text</a> </div> <div class="col-sm-2"> <a href="makeAssessment.php?assessmentID=<?php echo $report['assessmentID']?>" class="btn btn-primary btn-sm">Assess</a> </div> </div> </div> <?php $idCounter++; } ?> </div> </main> <?php include "../navbar/footer.php"; ?>
true
695ab51a2493473366bfeaa6882fe76382840055
PHP
david-beglari/php-mvc
/function.php
UTF-8
423
2.734375
3
[]
no_license
<?php /** * @param object $data * @param bool $rule */ function dd($data, $rule = true) { echo '<pre>'; print_r($data); $rule ? exit() : print ('</pre>'); } /** * @param $name * @param $data * @return mixed */ function view($name, $data = []) { extract($data); return require "app/views/{$name}.view.php"; } /** * @param $path */ function redirect($path) { header("Location:/{$path}"); }
true
9997864b6764279630d31ff70e0f00115418a820
PHP
big-picture-medical/openehr-data-structures
/src/Rm/DataTypes/Text/DvCodedText.php
UTF-8
429
2.59375
3
[ "BSD-3-Clause" ]
permissive
<?php namespace BigPictureMedical\OpenEhr\Rm\DataTypes\Text; class DvCodedText extends DvText { public string $_type = 'DV_CODED_TEXT'; public CodePhrase $defining_code; public static function make(string $value, string $codeString, string $terminologyId): self { return new self( value: $value, defining_code: CodePhrase::make($codeString, $terminologyId), ); } }
true
7743fad860b915d053b84b982a5fcf7b4a6714ce
PHP
stevenakida/notification
/app/controllers/SubscriptionsController.php
UTF-8
3,219
2.59375
3
[ "MIT" ]
permissive
<?php use Carbon\Carbon as Cb; class SubscriptionsController extends \BaseController { /** * Display a listing of subscriptions * * @return Response */ public function index() { $clients = Client::with(['services'])->get()->toArray(); return View::make('subscriptions.index', compact('clients')); } /** * Show the form for creating a new subscription * * @return Response */ public function create() { $services = Service::all(['name', 'id'])->toArray(); //fetches name from the array ... $services = array_fetch($services, 'name'); // dd($services); return View::make('subscriptions.create', compact('services')); } /** * Store a newly created subscription in storage. * * @return Response */ public function store() { // $validator = Validator::make($data = Input::all(), Subscription::$rules); // if ($validator->fails()) // { // return Redirect::back()->withErrors($validator)->withInput(); // } // Subscription::create($data); $serviceId = Input::get('service_name'); // $clientName = Client::findOrNew(null,['name' => Input::get('client_name')]); $clientName = Client::firstOrCreate(['name' => Input::get('client_name')]); if($clientName instanceof \Illuminate\Database\Eloquent\Model ){ $clientName->save(); $clientName->services()->sync([intval($serviceId+1) ]); $period = 0; switch(intval(Input::get('period'))){ case 1: $period = Cb::now()->addMonth(); break; case 6: $period = Cb::now()->addMonths(6); break; case 12: $period = Cb::now()->addMonths(12); break; } $clientName->services()->updateExistingPivot(intval($serviceId+1), [ 'expires_at' => $period ]); } return Redirect::route('subscriptions.index'); } /** * Display the specified subscription. * * @param int $id * @return Response */ public function show($id) { // $subscription = Subscription::findOrFail($id); return View::make('subscriptions.show', compact('subscription')); } /** * Show the form for editing the specified subscription. * * @param int $id * @return Response */ public function edit($id) { // $subscription = Subscription::find($id); return View::make('subscriptions.edit', compact('subscription')); } /** * Update the specified subscription in storage. * * @param int $id * @return Response */ public function update($id) { // $subscription = Subscription::findOrFail($id); // $validator = Validator::make($data = Input::all(), Subscription::$rules); // // if ($validator->fails()) // { // return Redirect::back()->withErrors($validator)->withInput(); // } // // $subscription->update($data); return Redirect::route('subscriptions.index'); } /** * Remove the specified subscription from storage. * * @param int $id * @return Response */ public function destroy($id) { // Subscription::destroy($id); return Redirect::route('subscriptions.index'); } }
true
b1b6ef30d67a22a225d77e55fa6d4679040852e2
PHP
roxanerg/projet4
/App/Model/Comments.php
UTF-8
3,610
2.890625
3
[]
no_license
<?php namespace App\Model; use Core; class Comments extends \Core\Model { /** * @fn public function get($episodeId) * * @brief Gets the comment using the given episode identifier * * @author Roxane Riff * @date 25/03/2019 * * @param episodeId The episode Identifier to get. * * @returns A function. */ public function get($episodeId) { $request = $this->db->prepare('SELECT id, auteur, commentaire, DATE_FORMAT(date_commentaire, "%d/%m/%Y %Hh%imin%ss") FROM commentaires WHERE id_episode = ? ORDER BY date_commentaire DESC'); $request->execute(array($episodeId)); $comments = $request->fetchAll(); return $comments; } /** * @fn public function add($episodeId, $auteur, $commentaire) * * @brief Adds a comment * * @author Roxane Riff * @date 25/03/2019 * * @param episodeId Identifier for the linked episode. * @param auteur The author. * @param commentaire The comment. * * @returns A function. */ public function add($episodeId, $auteur, $commentaire) { if (isset($_POST['auteur']) && isset($_POST['commentaire'])) { $request = $this->db->prepare('INSERT INTO commentaires (id_episode, auteur, commentaire, date_commentaire) VALUES (?, ?, ?, NOW())'); $addComm = $request->execute(array($episodeId, $auteur, $commentaire)); return $addComm; } } /** * @fn public function report($id) * * @brief Reports the given comment * * @author Roxane Riff * @date 25/03/2019 * * @param id The comment identifier. * * @returns A function. */ public function report($id) { $request= $this->db->prepare('UPDATE commentaires SET abuse = 1 WHERE id = ?'); $report = $request->execute(array($id)); return $report; } /** * @fn public function moderate() * * @brief Gets the comments to moderate * * @author Roxane Riff * @date 25/03/2019 * * @returns A function. */ public function moderate() { $request= $this->db->prepare('SELECT id, auteur, commentaire, date_commentaire FROM commentaires WHERE abuse = 1'); $request->execute(array()); $moderate = $request->fetchAll(); return $moderate; } /** * @fn public function unreport($id) * * @brief Unreports the given comment * * @author Roxane Riff * @date 25/03/2019 * * @param id The comment identifier. * * @returns A function. */ public function unreport($id) { echo $id; $request= $this->db->prepare('UPDATE commentaires SET abuse = 0 WHERE id = ?'); $unreport = $request->execute(array($id)); return $unreport; } /** * @fn public function all() * * @brief Gets all comments * * @author Roxane Riff * @date 25/03/2019 * * @returns A function. */ public function all() { $request = $this->db->prepare('SELECT * FROM commentaires'); $request->execute(array()); $comments = $request->fetchAll(); return $comments; } /** * @fn public function delete($commentId) * * @brief Deletes the given comment * * @author A * @date 25/03/2019 * * @param commentId The comment Identifier to delete. * * @returns A function. */ public function delete($commentId) { $this->db->exec('DELETE FROM commentaires WHERE id = '.(int) $commentId); } }
true
4e3fc022949eb4b0148cf326e061e1c61b612db1
PHP
TheJohnSub/mouseBrains
/Models/Change.php
UTF-8
2,460
2.890625
3
[]
no_license
<?php class Change { public $ChangeID = 0; public $MapID = 0; public $UserID = 0; public $ChangeDate; public $ChangeType = 0; public $OriginalValue = ''; public $NewValue = ''; public $IsPublicChange = 'TRUE'; public $ChangeLog = ''; function CreateFromQuery($DBRow) { $this->ChangeID = $DBRow[0]; $this->MapID = $DBRow[1]; $this->UserID = $DBRow[2]; $this->ChangeDate = $DBRow[3]; $this->ChangeType = $DBRow[4]; $this->OriginalValue = $DBRow[5]; $this->NewValue = $DBRow[6]; $this->IsPublicChange = $DBRow[7]; $this->ChangeLog = $DBRow[8]; } function CreateCoordinateUpdateChange($oldMapObj, $newMapObj, $CoorType) { $newXYZ = ''; $oldXYZ = ''; if ($CoorType == 'Bregma') { $oldXYZ = '(' . $oldMapObj->BregmaX . ', ' . $oldMapObj->BregmaY . ', ' . $oldMapObj->BregmaZ . ')'; $newXYZ = '(' . $newMapObj->BregmaX . ', ' . $newMapObj->BregmaY . ', ' . $newMapObj->BregmaZ . ')'; } else if ($CoorType == 'Lambda') { $oldXYZ = '(' . $oldMapObj->LambdaX . ', ' . $oldMapObj->LambdaY . ', ' . $oldMapObj->LambdaZ . ')'; $newXYZ = '(' . $newMapObj->LambdaX . ', ' . $newMapObj->LambdaY . ', ' . $newMapObj->LambdaZ . ')'; } else if ($CoorType == 'Midline') { $oldXYZ = '(' . $oldMapObj->MidlineX . ', ' . $oldMapObj->MidlineY . ', ' . $oldMapObj->MidlineZ . ')'; $newXYZ = '(' . $newMapObj->MidlineX . ', ' . $newMapObj->MidlineY . ', ' . $newMapObj->MidlineZ . ')'; } $this->MapID = $newMapObj->MapID; $this->ChangeType = 1; $this->OriginalValue = $CoorType . ': ' . $oldXYZ; $this->NewValue = $CoorType . ': ' . $newXYZ; $this->ChangeDate = date('Y-m-d H:i:s'); $this->ChangeLog = '<b>' . $this->ChangeDate . '</b> ' . $CoorType . ' values were updated. <br/> Old values: ' . $oldXYZ . '. New values: ' . $newXYZ . '. <br/><br/>'; } function ValListStr($db) { $str = "'" . mysqli_real_escape_string($db->Connection, $this->MapID) . "', '" . mysqli_real_escape_string($db->Connection, $this->UserID) . "', '" . mysqli_real_escape_string($db->Connection, $this->ChangeDate) . "', '" . mysqli_real_escape_string($db->Connection, $this->ChangeType) . "', '" . mysqli_real_escape_string($db->Connection, $this->OriginalValue) . "', '" . mysqli_real_escape_string($db->Connection, $this->NewValue) . "', '" . mysqli_real_escape_string($db->Connection, $this->IsPublicChange) . "', '" . mysqli_real_escape_string($db->Connection, $this->ChangeLog) . "'"; return $str; } } ?>
true
5ed75ac2bd25761a7fe45c8b84f2e235f6033d84
PHP
dkelly1127/CS405
/admin/files/php/submit/addProduct.php
UTF-8
1,294
2.75
3
[]
no_license
<?php require_once ("../../../../files/database/db_connect.php"); $product_name = $_POST['name']; $description = $_POST['description']; $quantity = $_POST['quantity']; $category_id = $_POST['category_id']; $price = $_POST['price']; $image = $_POST['image']; $discount = $_POST['discount']; //Sets the image to a default image if one is not uploaded if ($image == "") { $image = "default.jpg"; } //Query to make sure that the name doesn't already exist in the database $checkForDuplicateName = "SELECT product_name FROM product WHERE product_name='$product_name';"; $checkForDuplicateTable = mysqli_query($link, $checkForDuplicateName) or die ("checkForDuplicateName in\nfiles/php/submit/addProduct.php\n\r".mysqli_error($link)); $checkForDuplicateNameRowCount = mysqli_num_rows($checkForDuplicateTable); if ($checkForDuplicateNameRowCount != 0) { echo "Error|Duplicate name"; return; } //Auto increments product_id, the last discount value is always 0 by default. Manager has to put it on sale later $addNewProduct = "INSERT INTO product VALUES (DEFAULT, '$product_name', '$description', '$quantity', '$category_id', '$price', '$image', '$discount');"; mysqli_query($link, $addNewProduct) or die("addNewProduct in\nfiles/php/submit/add.php\n\r".mysqli_error($link)); echo "Success"; ?>
true
428fd25fad7c905aac4871fc76aed1b41fcd6e78
PHP
whoicliu/ooo
/www/Common/Api/SystemApi.class.php
UTF-8
726
2.671875
3
[]
no_license
<?php namespace Common\Api; /** * 系统API */ class SystemApi { /** * 获取插件数量 * * @param array $where 查询条件数组,默认为空 * * @return [type] [description] */ public function getAddonCount($where = array()) { $map = !empty($where) ? $where : array('status' => 1); return M('Addon')->where($map)->count(); } /** * 获取钩子数量 * * @param array $where 查询条件数组,默认为空 * * @return integer 钩子数量 */ public function getHookCount($where = array()) { $map = !empty($where) ? $where : 1; return M('Hook')->where($map)->count(); } }
true
af18e0463a2094db59857bb3326be4037431bc9e
PHP
chitkadia/doodooadmin
/src/Commands/ResetEmailLimitCommand.php
UTF-8
4,219
2.59375
3
[]
no_license
<?php /** * Used to reset Quota of mail account as per user plan */ namespace App\Commands; use \Psr\Http\Message\ServerRequestInterface; use \Psr\Http\Message\ResponseInterface; use \Interop\Container\ContainerInterface; use \App\Components\DateTimeComponent; use \App\Components\SHAppComponent; use \App\Components\LoggerComponent; use \App\Models\AccountSendingMethods; class ResetEmailLimitCommand extends AppCommand { //define constant for reset quota cron execute limt const RESET_QUOTA_PROCESS_LIMIT_TIME = 10; //define constant for document conversion and upload log file const LOG_FILE_QUOTA_RESET_PROCESS = __DIR__ . "/../../logs/reset_quota_process.log"; public function __construct(ContainerInterface $container) { parent::__construct($container); } /** * Reset Quota of mail account * * @param $request (object): Request object * @param $response (object): Response object * @param $args (array): Route parameters */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $args) { $current_time = DateTimeComponent::getDateTime(); $end_time = $current_time + self::RESET_QUOTA_PROCESS_LIMIT_TIME; $num_records_processed = 0; $reminder = (int) $_SERVER["argv"][2]; $modulo = (int) $_SERVER["argv"][3]; LoggerComponent::log("Reset quota process start", self::LOG_FILE_QUOTA_RESET_PROCESS); $model_account_sending_methods = new AccountSendingMethods(); while ($current_time <= $end_time) { $condition = [ "fields" => [ "asm.id", "asm.total_limit", "abm.plan_id" ], "where" => [ ["where" => ["asm.next_reset", "<=", $current_time ]], ["where" => ["asm.status", "<>", SHAppComponent::getValue("app_constant/STATUS_DELETE") ]] ], "join" => [ "account_billing_master" ], "limit" => 1 ]; if ( !empty($modulo) && !is_null($reminder) ) { $condition["where"][] = ["where" => ["asm.id%" . $modulo, "=", $reminder ]]; } try { $row_data = $model_account_sending_methods->fetch($condition); } catch(\Exception $e) { LoggerComponent::log("Database error: " . $e->getMessage(), self::LOG_FILE_QUOTA_RESET_PROCESS); } if (!empty($row_data["id"])) { LoggerComponent::log("Start process of #" .$row_data["id"], self::LOG_FILE_QUOTA_RESET_PROCESS); try { $save = $model_account_sending_methods->setQuota($row_data["plan_id"], $row_data["id"]); if ($save) { LoggerComponent::log("Quota reset of #" . $row_data["id"] . " is successfully", self::LOG_FILE_QUOTA_RESET_PROCESS); } else { LoggerComponent::log("Quota not reset #" . $row_data["id"] . " Error :" . $model_account_sending_methods->getQueryError(), self::LOG_FILE_QUOTA_RESET_PROCESS); } } catch(\Exception $e) { LoggerComponent::log("Database error of #" . $row_data["id"] . " Error :" . $e->getMessage(), self::LOG_FILE_QUOTA_RESET_PROCESS); } LoggerComponent::log("Process Finished for Reset Quota of #". $row_data["id"], self::LOG_FILE_QUOTA_RESET_PROCESS); } else { LoggerComponent::log("Record not found to be processing", self::LOG_FILE_QUOTA_RESET_PROCESS); break; } $current_time = DateTimeComponent::getDateTime(); $num_records_processed++; } LoggerComponent::log("Total ".$num_records_processed." records to be proceed", self::LOG_FILE_QUOTA_RESET_PROCESS); LoggerComponent::log("===================================================", self::LOG_FILE_QUOTA_RESET_PROCESS); } }
true
3ac0d154ea910a891f058baf9cde65bb1bdb3e2c
PHP
wnmribeiro/test
/Insecure File Uploads/example2.php
UTF-8
565
2.96875
3
[]
no_license
// Is it an image? if( ( $uploaded_type == "image/jpeg" || $uploaded_type == "image/png" ) && ( $uploaded_size < 100000 ) ) { // Can we move the file to the upload folder? if( !move_uploaded_file( $_FILES[ 'uploaded' ][ 'tmp_name' ], $target_path ) ) { // No $html .= '<pre>Your image was not uploaded.</pre>'; } else { // Yes! $html .= "<pre>{$target_path} succesfully uploaded!</pre>"; } } else { // Invalid file $html .= '<pre>Your image was not uploaded. We can only accept JPEG or PNG images.</pre>'; } }
true
37ed3927d429a6a7aee1653746ae5ed489414c5c
PHP
bhagoes86/siaro
/application/helpers/coresys_helper.php
UTF-8
5,371
2.578125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); if (! function_exists('get_controller')) { function get_controller($url) { $ctrl_name = str_replace('/arisan/', '', $url); $ctrl_name = explode('/', $ctrl_name); $ctrl_name = $ctrl_name[0]; // controller name //$ctrl_name = str_replace('-', '_', $ctrl_name); // replace '-' with '_'; return $ctrl_name; } } if (! function_exists('active_menu')) { function active_menu($controller) { //$controller = $controller == ''? 'home' : $controller; $CI =& get_instance(); $query = $CI->db->query(" SELECT * FROM menu WHERE controller = '$controller' "); $active_menu = array(); if ($query->num_rows()) { $active_menu = $query->row_array(); } return $active_menu; } } /* | SIDE MENU (not hidden only) | ---------------------------------------------------------------- */ if(! function_exists('side_menu')) { function side_menu($groups, $active) { $CI =& get_instance(); $active = active_menu($active); // -- menu-- echo ' <li class="header">MAIN NAVIGATION</li> '; // -- parent $query_par = $CI->db->query(" SELECT id as id, name as name, controller as controller, function as function, icon as icon FROM authority INNER JOIN menu ON id = menu_id WHERE grup_id = 1 && is_parent = 0 && is_sub = 0 ORDER BY id ASC "); if($query_par->num_rows()) { foreach ($query_par->result() as $row_par) { $id_par = $row_par->id; $name_par = $row_par->name; $controller_par = $row_par->controller; $function_par = $row_par->function; $icon_par = $row_par->icon; $treeview_active_par1 = $id_par == $active['is_parent']? 'active' : ''; $treeview_active_par2 = $id_par == $active['id']? 'active' : ''; $treeview_open_par = $id_par == $active['is_parent']? 'menu-open' : ''; $treeview_display_par = $id_par == $active['is_parent']? 'block' : 'none'; // -- cek parent punya sub tidak $query_cksub = $CI->db->query(" SELECT id as id, name as name, controller as controller, function as function, icon as icon FROM authority INNER JOIN menu ON id = menu_id WHERE grup_id = 1 && is_parent = $id_par && is_sub = 0 ORDER BY id ASC "); if ($query_cksub->num_rows()) { echo ' <li class="treeview '.$treeview_active_par1.'"> '.anchor($controller_par.'/'.$function_par, '<i class="'.$icon_par.'"></i> '.ucwords($name_par).' <i class="fa fa-angle-left pull-right"></i>').' <ul class="treeview-menu '.$treeview_open_par.'" style="display: '.$treeview_display_par.'"> '; foreach($query_cksub->result() as $row_sub) { $id_sub = $row_sub->id; $name_sub = $row_sub->name; $controller_sub = $row_sub->controller; $function_sub = $row_sub->function; $icon_sub = $row_sub->icon; $treeview_active_sub1 = $id_sub == $active['is_sub']? 'active' : ''; $treeview_active_sub2 = $id_sub == $active['id']? 'active' : ''; $treeview_open_sub = $id_sub == $active['is_sub']? 'menu-open' : ''; $treeview_display_sub = $id_sub == $active['is_sub']? 'block' : 'none'; // -- cek sub punya menu tidak $query_ckmn = $CI->db->query(" SELECT id as id, name as name, controller as controller, function as function, icon as icon FROM authority INNER JOIN menu ON id = menu_id WHERE grup_id = 1 && is_parent = $id_par && is_sub = $id_sub ORDER BY id ASC "); if ($query_ckmn->num_rows()) { echo ' <li class="treeview '.$treeview_active_sub1.'"> '.anchor($controller_sub.'/'.$function_sub, '<i class="'.$icon_sub.'"></i> '.ucwords($name_sub).' <i class="fa fa-angle-left pull-right"></i>').' <ul class="treeview-menu '.$treeview_open_sub.'" style="display: '.$treeview_display_par.'"> '; foreach($query_ckmn->result() as $row_mn) { $id_mn = $row_mn->id; $name_mn = $row_mn->name; $controller_mn = $row_mn->controller; $function_mn = $row_mn->function; $icon_mn = $row_mn->icon; $treeview_active_mn = $id_mn == $active['id']? 'active' : ''; echo ' <li class="'.$treeview_active_mn.'"> '.anchor($controller_mn.'/'.$function_mn, '<i class="'.$icon_mn.'"></i> '.ucwords($name_mn)).' </li> '; } // end foreach query_ckmn echo ' </ul> </li> '; } else { echo ' <li class="'.$treeview_active_sub2.'"> '.anchor($controller_sub.'/'.$function_sub, '<i class="'.$icon_sub.'"></i> '.ucwords($name_sub)).' </li> '; } } // end foreach query_cksub echo ' </ul> </li> '; } else { echo ' <li class="'.$treeview_active_par2.'"> '.anchor($controller_par.'/'.$function_par, '<i class="'.$icon_par.'"></i> <span>'.ucwords($name_par)).'</span> </li> '; } } // end foreach query_par } // end query_par (parent) } } /* if (! function_exists('name_function')) { function name_function($var) { $CI =& get_instance(); return $var; } } */
true
a10942b1a7cfd41f3189b6f47c668dafc91f9093
PHP
lunid/mvc
/sys/classes/commerce/ItemPedido.php
UTF-8
6,895
3.015625
3
[]
no_license
<?php namespace sys\classes\commerce; class ItemPedido { private $descricao = ''; private $quantidade = 1; private $precoUnit = 0; private $unidade = 'CX'; private $campanha = ''; private $saveItem = FALSE;//TRUE = grava o registro atual no servidor remoto. private $precoUnitSemFormat; //Preço unitário sem formatação. Ex.: 123,40 ficará 12340, 2345 ficará 234500, 65,3 ficará 6530 /** * Inicializa um objeto com descrição, preço unitário e quantidade. * Ao informar o preço unitário, o padrão usado será o ponto '.' como separador decimal e nenhum separador de milhar. * * @param string $descricao * @param float $precoUnit * @param integer $qtde */ function __construct($descricao,$precoUnit=0,$qtde=1,$unidade='CX',$campanha=''){ $this->setDescricao($descricao); $this->quantidade = (int)$qtde; $this->setUnidade($unidade); $this->setCampanha($campanha); if ($precoUnit > 0) { $this->precoUnitEn($precoUnit); } } /** * Salva o produto atual no servidor remoto. * Este recurso pode ser útil caso queira gerar um novo pedido que inclui o produto atual * a partir do painel de controle. * * @return void */ public function saveItemOn(){ $this->saveItem = true; } public function getSaveItem(){ return $this->saveItem; } function setUnidade($unidade){ if (strlen($unidade) <= 3 && ctype_alpha($unidade)) { $this->unidade = $unidade; } else { throw new \Exception('ItemPedido->setUnidade(): a unidade informada '.$unidade.' não é válida. A unidade deve conter apenas letras e no máximo 3 catacteres.'); } } function getUnidade(){ return $this->unidade; } /** * Informa o nome da campanha relacionada à compra do produto/serviço atual (opcional). * * @param string $campanha String alfanumérica de até 20 caracteres. * @return void */ function setCampanha($campanha){ if (strlen($campanha) > 0) { $this->campanha = $campanha; } } function getCampanha() { return $this->campanha; } /** * Informa a descrição do produto. * @param type $descricao */ function setDescricao($descricao){ if (strlen($descricao) > 0) { $this->descricao = $descricao; } } function getDescricao(){ return $this->descricao; } /** * Informa a quantidade de um produto e qual a sua unidade de medida. * * @param integer $qtde Valor inteiro que indica a quantidade do item. * @param string $unid Unidade de medida do produto. É permitido utilizar no máximo 3 letras para indicar a unidade. * Por exemplo, "CX" para caixa, "PC" para pacote, "UN" * * @throws \Exception */ function setQuantidade($qtde=1,$unidade='CX'){ if (ctype_alpha($unid)) { $this->quantidade = (int)$qtde; $this->setUnidade($unidade); } else { throw new \Exception('A unidade '.$unid.' informada em ItemPedido->setQuantidade() não é válida. O parâmetro unid deve conter apenas letras.'); } } function getQuantidade(){ return $this->quantidade; } /** * Informa o preço unitário do produto no formato 9999.99 (notação inglesa). * * @param float $precoUnit Valor decimal no formato americano (usa ponto como separador decimal) */ function precoUnitEn($precoUnit){ $precoUnit = str_replace(',','',$precoUnit); $this->setPrecoUnit($precoUnit,'.',''); } /** * Informa o preço unitário do produto no formato 9999,99. * * @param float $precoUnit Valor decimal no formato brasileiro (usa vírgula como separador decimal) * @param string $thousandsSep Caractere separador de milhar. */ function precoUnitBr($precoUnit) { $precoUnit = str_replace('.','',$precoUnit); $this->setPrecoUnit($precoUnit,',',''); } /** * Informa o preço unitário do produto. * * @param float $precoUnit Preço como valor decimal * @param string $decPoint Separador decimal usado no $precoUnit informado. * @param string $thousandsSep Separador de milhar usado no $precoUnit informado. * @return void */ private function setPrecoUnit($precoUnit,$decPoint,$thousandsSep){ if (is_numeric($precoUnit)) { $precoUnitSemFormat = $this->convertNumberDec2NumberInt($precoUnit, $decPoint, $thousandsSep); $this->precoUnitSemFormat = $precoUnitSemFormat; $this->precoUnit = number_format($precoUnit,2,'.',''); } else { throw new \Exception('ItemPedido->setPrecoUnit(): O preço unitário informado não é um valor válido.'); } } function getPrecoUnit(){ return $this->precoUnit; } function getPrecoUnitSemFormat(){ return $this->precoUnitSemFormat; } /** * Recebe um valor no formato 9.999,99, ou 9999.99, ou ainda 9999,99, e converte * para um valor inteiro, sem separadores, onde os dois últimos caracteres representam * a parte decimal. * * Exemplos: * 123,543 ficará 12354 (equivale a 123,54) * 1254 ficará 125400 (equivale a 1254,00) * * @param float $valueDec Valor decimal a ser convertido para inteiro * @param string $decPoint Separador decimal usado no $valueDec informado. * @param string $thousandsSep Separador de milhar usado no $valueDec informado. * @return integer */ function convertNumberDec2NumberInt($valueDec,$decPoint,$thousandsSep){ $numberInt = number_format($valueDec, 2, $decPoint, $thousandsSep); $numberInt = str_replace($decPoint,'',$valueDec); $numberInt = str_replace($thousandsSep,'',$valueDec); return $numberInt; } /** * Calcula o subtotal do produto atual multiplicando a quantidade pelo valor unitário. * * @return flaot Retorna o subtotal do produto atual. */ function calcSubtotal(){ $quantidade = (int)$this->quantidade; $precoUnit = $this->precoUnitSemFormat; $subtotal = $precoUnit; if ($quantidade > 1) { $subtotal = $quantidade*$precoUnit; } //Formata a saída com duas casas decimais: $subtotal = number_format($subtotal,2,'.',''); return $subtotal; } function setPrecoPromo($precoDe,$precoPor){ } } ?>
true
e341cb0bdc80e0ad789d3bceea708999422d0414
PHP
Mayowajunior6/fones
/app/Http/Controllers/Admin/ProvincesController.php
UTF-8
3,224
2.609375
3
[]
no_license
<?php /** * Controller for Admin Provinces crud * @file ProvincesController.php * @author Mayowa Ajamu <ajamu-m@webmail.uwinnipeg.ca> * @updated_at 2020-12-5 */ namespace App\Http\Controllers\admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Province; class ProvincesController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $title = "Provinces"; $provinces = Province::all(); return view('admin/provinces/index', compact('title', 'provinces')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $title = 'Add a new province'; return view('admin/provinces/create', compact('title')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $valid = $request->validate([ 'name' => 'bail|required|alpha|max:255' ]); if(Province::create($valid)) { session()->flash('success', 'The province was successfully added.'); } else { session()->flash('error', 'There was a problem adding the province. Please Try again.'); } return redirect('admin/provinces/create'); } /** * 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) { $title = 'Edit province'; $province = Province::find($id); return view('admin/provinces/edit', compact('province', 'title')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $valid = $request->validate([ 'name' => 'bail|required|alpha|string' ]); $province = Province::find($id); if ($province->update($valid)) { session()->flash('success', 'Province was successfully updated.'); } else { session()->flash('error', 'System error when updating province record'); } return redirect('/admin/provinces'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $province = Province::find($id); $province->taxation()->delete(); if ($province->delete()) { session()->flash('success', 'The province was successfully deleted.'); } else { session()->flash('error', 'System error when deleting province record'); } return redirect('/admin/provinces'); } }
true
cf950b33235c66e109753c83292cd2b5bdab4f49
PHP
threadshare/yii2-alipay
/AlipayApi.php
UTF-8
2,741
2.515625
3
[]
no_license
<?php namespace leyestd\alipay; use leyestd\alipay\Aliconfig; use leyestd\alipay\lib\AlipaySubmit; use leyestd\alipay\lib\AlipayCore; /** * @abstract 支付宝订单管理 * @author lenovo * */ class AlipayApi extends AlipaySubmit { public $alipay_config = []; public function __construct(){ $this->alipay_config=(new Aliconfig)->getAliconfig(); parent::__construct($this->alipay_config); } /** * 关闭待支付的订单 * @param string $out_trade_no 商户订单号 * @param string $trade_no 支付宝交易号 * @return string T | F //T成功|F失败 */ public function closeOrder($out_trade_no, $trade_no = ''){ $ret = 'F'; //构造要请求的参数数组,无需改动 $parameter = array("service" => "close_trade", "partner" => trim($this->alipay_config['partner']), "trade_no" => $trade_no, "out_order_no" => $out_trade_no, "_input_charset" => trim(strtolower($this->alipay_config['input_charset'])) ); //建立请求 $html_text = $this->buildRequestHttp($parameter); //解析XML //注意:该功能PHP5环境及以上支持,需开通curl、SSL等PHP配置环境。建议本地调试时使用PHP开发软件 $doc = new \DOMDocument(); $doc->loadXML($html_text); //解析XML if(!empty($doc->getElementsByTagName("alipay")->item(0)->nodeValue)) { $ret = $doc->getElementsByTagName("alipay")->item(0)->nodeValue; } if($ret != 'T' && $ret != 'F') { $ret = 'F'; } return $ret; } /** * 查询订单 * @param string $out_trade_no 订单号 * @param string $trade_no 支付宝交易流水号 * @return \leyestd\alipay\lib\要请求的参数数组 */ public function selectOrder($out_trade_no,$trade_no='') { //构造要请求的参数数组,无需改动 $parameter = array("service" => "single_trade_query", "partner" => trim($this->alipay_config['partner']), "trade_no" => $trade_no, "out_trade_no" => $out_trade_no, "_input_charset" => trim(strtolower($this->alipay_config['input_charset'])) ); $veryfy_url = 'https://mapi.alipay.com/gateway.do?service=single_trade_query&'; $veryfy_url.= $this->buildRequestParaToString($parameter); $responseTxt = AlipayCore::getHttpResponseGET($veryfy_url, $this->alipay_config['cacert']); return simplexml_load_string($responseTxt); } }
true
5f173393304e1e2a160522ddbfac5128e90d7474
PHP
WPTEbilkent/WPTE
/database/migrations/2015_12_18_120032_create_tutorials_table.php
UTF-8
1,136
2.65625
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTutorialsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('tutorials', function (Blueprint $table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->integer('user_id')->unsigned()->index(); $table->string('title',150); $table->LongText('content',30000); $table->string('tags', 15); $table->integer('rate'); $table->date('date'); //constraints for table $table->foreign('user_id') ->references('id') ->on('users') ->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('tutorials', function (Blueprint $table) { $table->dropForeign('tutorials_user_id_foreign'); }); Schema::drop('tutorials'); } }
true
033e43f14bbd6c51990e21ec5556eef90a9b772e
PHP
ecomsh/webstore
/common/models/Curl.php
UTF-8
8,125
2.71875
3
[ "BSD-3-Clause" ]
permissive
<?php /** * This is the base curl class */ namespace common\models; use Yii; use yii\web\BadRequestHttpException; /** * Curl Class for curl rest apis * Normally you should new a Curl entity and call function * exapmle: * $this->_curl = Curl::getInstance(); * $data = $this->get(); * * * * @author Henry <hezonglin@cn.ibm.com> * @copyright (c) 2015, IBM CDL Commerce * * */ class Curl { /** * put method */ const METHOD_PUT = 'PUT'; /** * delete method */ const METHOD_DELETE = 'DELETE'; /** * post method */ const METHOD_POST = 'POST'; /** * get method */ const METHOD_GET = 'GET'; /** * set the header text * @var string */ public $header = []; /** * set to debug model * @var boolen */ public $debug = YII_DEBUG; public $debugInfo; /** * set the longest waiting time of curl * @var int */ public $timeout = 15; /** * set the waiting time before connect to the server * @var int */ public $connectTimeout = 15; /** * set the default language * @var string */ public $lan; public $gzip = true; private static $_instance; public function __construct() { } //创建__clone方法防止对象被复制克隆 public function __clone() { trigger_error('Clone is not allow!', E_USER_ERROR); } public static function getInstance() { if (self::$_instance === null) { self::$_instance = new self(); } return self::$_instance; } /** * * @param array $urls [key1=>url1,key2=>url2,key3=>url3] * @param array $params [$params1,$params2,$params3] * @param type $method get only * @return array */ public function multiFetch($urls = array(), $params = [[]], $method = self::METHOD_GET) { $json = json_encode(['header' => $this->header, 'url' => $urls, 'params' => $params, 'method' => $method]); Yii::beginProfile('multi fetch profile:' . $json); $queue = curl_multi_init(); $map = array(); $this->method = $method; $i = 0; foreach ($urls as $key => $url) { $this->method = strtoupper($method); if (isset($params[$i])) { $url = $this->_setParams($url, $params[$i], $method); } $this->pathKey = is_string($key) ? $key : $url; $ch = curl_init($url); $options = $this->_setOptions(); curl_setopt_array($ch, $options); curl_multi_add_handle($queue, $ch); $map[(string) $ch] = $this->pathKey; $i++; } $rs = array(); $active = null; do { while (($code = curl_multi_exec($queue, $active)) == CURLM_CALL_MULTI_PERFORM); // a request was just completed -- find out which one while ($code == CURLM_OK && $done = curl_multi_info_read($queue)) { // get the info and content returned on the request $info = curl_getinfo($done['handle']); $error = curl_error($done['handle']); $response = curl_multi_getcontent($done['handle']); $rs[$map[(string) $done['handle']]] = compact('error', 'response'); $rs[$map[(string) $done['handle']]]['http_code'] = $info['http_code']; if ($this->debug) { $rs[$map[(string) $done['handle']]]['info'] = $info; $rs[$map[(string) $done['handle']]]['curl_info'] = $error; //unset($rs[$map[(string) $done['handle']]]['error']); } else { $this->debugInfo = $rs; } // remove the curl handle that just completed curl_multi_remove_handle($queue, $done['handle']); curl_close($done['handle']); } // Block for data in / output; error handling is done by curl_multi_exec if ($active > 0) { curl_multi_select($queue, $this->connectTimeout); } } while ($active); curl_multi_close($queue); Yii::endProfile('multi fetch profile:' . $json); return $rs; } public function fetch($url, $params = [], $method = self::METHOD_GET) { $json = json_encode(['header' => $this->header, 'url' => $url, 'time' => microtime(),'params' => $params, 'method' => $method]); // if (YII_DEBUG) // { // Yii::info('curl header is' . $json); // } Yii::beginProfile('single fetch profile:' . $json); $starttime = explode(' ',microtime()); if (is_array($url)) { $key = key($url); $this->pathKey = is_string($key) ? $key : $url[$key]; $url = $url[$key]; } else { $this->pathKey = $url ? $url : ''; } $this->method = strtoupper($method); if (isset($params)) { $url = $this->_setParams($url, $params, $method); } $this->_dataString = $params ? json_encode($params) : ''; $options = $this->_setOptions(); $ch = curl_init($url); curl_setopt_array($ch, $options); $response = curl_exec($ch); $error = curl_error($ch); $info = curl_getinfo($ch); $rs = array(); $rs[$this->pathKey] = compact('error', 'response'); $rs[$this->pathKey]['http_code'] = $info['http_code']; if ($this->debug) { $rs[$this->pathKey]['info'] = $info; $rs[$this->pathKey]['curl_error'] = $error; } curl_close($ch); // if (YII_DEBUG) // { // Yii::info($rs, 'Curl'); // } $endtime = explode(' ',microtime()); $thistime = round($endtime[0]+$endtime[1]-($starttime[0]+$starttime[1]),6); Yii::info('cost_time: '.$thistime); //$json = json_encode(['header' => $this->header, 'url' => $url, 'cost_time' => $thistime,'params' => $params, 'method' => $method]); Yii::endProfile('single fetch profile:' . $json); return $rs; } private function _setParams($url, $params, $method) { $query = $this->_buildQuery($params); if ($method === self::METHOD_GET && $query) { $url .= preg_match('/\?/i', $url) ? '&' . $query : '?' . $query; } return $url; } private function _setOptions() { $options = [ CURLOPT_HTTP_VERSION => 'CURL_HTTP_VERSION_1_1', CURLOPT_HTTPHEADER => $this->header, CURLOPT_CONNECTTIMEOUT => $this->connectTimeout, CURLOPT_TIMEOUT => $this->timeout, CURLOPT_CUSTOMREQUEST => $this->method, CURLOPT_HEADER => false, CURLOPT_RETURNTRANSFER => true, // CURLOPT_USERAGENT => "", ]; if ($this->method == self::METHOD_POST || $this->method == self::METHOD_PUT) { $options[CURLOPT_POSTFIELDS] = $this->_dataString; $options[CURLOPT_HTTPHEADER] = array_merge($this->header, ['Content-Type: application/json', 'Content-Length: ' . strlen($this->_dataString)]); } if ($this->gzip) { $options[CURLOPT_ENCODING] = 'gzip'; } return $options; } /** * 把数组生成http请求需要的参数。 * @param array $params * @return string */ private function _buildQuery($params) { $args = http_build_query($params); // remove the php special encoding of parameters // see http://www.php.net/manual/en/function.http-build-query.php#78603 //return preg_replace('/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '=', $args); return $args; } }
true
e54cd4d9171a3430c099058ee879a25b5ce9df50
PHP
renattomartins/photo-viewer
/src/Widgets/PhotoGallery/GalleryPhoto.php
UTF-8
2,711
2.96875
3
[]
no_license
<?php namespace Widgets\PhotoGallery; use Widgets\Widget; use Models\PhotoRecord; /** * Classe GalleryPhoto. * * Essa classe é a representação principal da foto, onde além da imagem em si, * são renderizados marcações HTML que estruturam e posicionam a imagem dentro * galeria. Essa classe tem a responsabilidade única de renderizar essa * reprensentação de acordo com o estado do domínio. * * @author Renato Martins <renatto.martins@gmail.com> */ class GalleryPhoto extends Widget { /** * Método construtor. * * @param $photo PhotoRecord Objeto PhotoRecord que será renderizado * @param $total int Total de fotos da galeria */ public function __construct(PhotoRecord $photo = null, $total) { // Preenche a saída $this->output = '<div class="gallery-photo-area">'; // Se NÃO existe um PhotoRecord e o total de fotos da galeria é igual 0 if (!isset($photo) && $total == 0) { $this->output .= '<div class="gallery-placeholder">'; $this->output .= '<span class="gallery-placeholder-msg">'; $this->output .= 'Você ainda não possui nenhuma foto cadastrada.'; $this->output .= '</span>'; $this->output .= '</div>'; // Se NÃO existe um PhotoRecord e o total de fotos da galeria for maior que 0 } elseif (!isset($photo) && $total > 0) { $this->output .= '<div class="gallery-placeholder">'; $this->output .= '<span class="gallery-placeholder-msg">'; $this->output .= '<strong class="gallery-placeholder-msg-strong">'; $this->output .= 'A foto que você está tentando acessar, não existe!'; $this->output .= '</strong> Tente voltar à '; $this->output .= '<a href="index.php?class=PhotosControl&action=view"'. ' class="gallery-placeholder-link">página inicial</a> '; $this->output .= 'e começar novamente.'; $this->output .= '</span>'; $this->output .= '</div>'; // Se existe um PhotoRecord } elseif (isset($photo)) { $this->output .= '<img src="'. PhotoRecord::PHOTOS_DIRECTORY.$photo->getName(). '" class="gallery-photo">'; $this->output .= '<form class="gallery-form-delete js-form-delete" method="post"'. ' action="index.php?class=PhotosControl&action=delete&id='.$photo->getId().'">'; $this->output .= '<input type="submit" class="gallery-form-delete-submit" value="Excluir foto">'; $this->output .= '</form>'; } $this->output .= '</div>'; } }
true
dc8bf3207a140c2ec534047ecf694ad0d2996f93
PHP
TYPO3-extensions/fal_webdav
/Classes/Utility/EncryptionUtility.php
UTF-8
6,273
2.8125
3
[]
no_license
<?php namespace TYPO3\FalWebdav\Utility; /** * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use TYPO3\CMS\Core\Utility; /** * Utility methods for encrypting/decrypting data. Currently only supports Blowfish encryption in CBC mode, * * NOTE: This is just a working draft - the methods should be refined and moved to the TYPO3 core. * * @author Andreas Wolf <dev@a-w.io> */ class EncryptionUtility { protected static $encryptionMethod = MCRYPT_BLOWFISH; protected static $encryptionMode = MCRYPT_MODE_CBC; /** * @var \TYPO3\CMS\Core\Log\Logger */ protected static $logger; public static function getEncryptionMethod() { return self::$encryptionMethod; } public static function getEncryptionMode() { return self::$encryptionMode; } /** * Returns TRUE if the mcrypt extension is available. * * @return bool */ public static function isMcryptAvailable() { return extension_loaded('mcrypt'); } /** * @return \TYPO3\CMS\Core\Log\Logger */ protected static function getLogger() { if (self::$logger === null) { /** @var $logManager \TYPO3\CMS\Core\Log\LogManager */ $logManager = Utility\GeneralUtility::makeInstance('TYPO3\CMS\Core\Log\LogManager'); self::$logger = $logManager->getLogger(__CLASS__); } return self::$logger; } /** * Returns an initialization vector suitable for the chosen encryption method. * * @param string $encryptionMethod * @param string $encryptionMode * @return string */ protected static function getInitializationVector($encryptionMethod = null, $encryptionMode = null) { if (!$encryptionMethod) { $encryptionMethod = self::$encryptionMethod; } if (!$encryptionMode) { $encryptionMode = self::$encryptionMode; } $iv_size = mcrypt_get_iv_size($encryptionMethod, $encryptionMode); $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); return $iv; } /** * Creates and returns a resource pointer for the encryption method. This is required for e.g. retrieving an * encryption key. * * @param string $encryptionMethod * @param string $encryptionMode * @return resource */ protected static function createEncryptionContext($encryptionMethod = null, $encryptionMode = null) { if (!$encryptionMethod) { $encryptionMethod = self::$encryptionMethod; } if (!$encryptionMode) { $encryptionMode = self::$encryptionMode; } $td = mcrypt_module_open($encryptionMethod, '', $encryptionMode, ''); return $td; } /** * @param $td * @return string */ protected static function getEncryptionKey($td) { $ks = mcrypt_enc_get_key_size($td); $key = substr(md5($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']), 0, $ks); return $key; } /** * Encrypts a password. The algorithm used and - if necessary - the initialization vector are stored within the * password string. The encrypted password itself is stored base64 encoded to make it possible to store this * password in an XML structure. * * @param $value * @return string * @see decryptPassword() */ public static function encryptPassword($value) { if ($value == '') { return ''; } if (!self::isMcryptAvailable()) { self::getLogger()->error('Encryption utility is not available. See reports module for more information.'); return ''; } $td = self::createEncryptionContext(); $iv = self::getInitializationVector(); $key = self::getEncryptionKey($td); mcrypt_generic_init($td, $key, $iv); $encryptedPassword = mcrypt_generic($td, $value); mcrypt_generic_deinit($td); $encryptedText = sprintf('$%s$%s$%s$%s', self::$encryptionMethod, self::$encryptionMode, base64_encode($iv), base64_encode($encryptedPassword) ); // close the module opened for encrypting mcrypt_module_close($td); return $encryptedText; } /** * Decrypts a password. The necessary initialization vector is extracted from the password. * * @param string $encryptedPassword * @return string * @see encryptPassword() */ public static function decryptPassword($encryptedPassword) { if ($encryptedPassword == '') { return ''; } if (!self::isMcryptAvailable()) { self::getLogger()->error('Encryption utility is not available. See reports module for more information.'); return ''; } if (substr_count($encryptedPassword, '$') > 0) { $passwordParts = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode('$', $encryptedPassword, true); // Base64 decoding the password is done below $encryptedPassword = $passwordParts[3]; $encryptionMethod = $passwordParts[0]; $mode = $passwordParts[1]; $td = self::createEncryptionContext($encryptionMethod, $mode); $iv = base64_decode($passwordParts[2]); } else { $td = self::createEncryptionContext(self::$encryptionMethod, self::$encryptionMode); $iv = self::getInitializationVector(); } $key = self::getEncryptionKey($td); mcrypt_generic_init($td, $key, $iv); $decryptedPassword = trim(mdecrypt_generic($td, base64_decode($encryptedPassword))); mcrypt_generic_deinit($td); // close the module opened for decrypting mcrypt_module_close($td); return $decryptedPassword; } }
true
6c42ee91d0f9ae6fa05a6992ba6b1173e4fb636e
PHP
ThanhTrieu/laravel1808e
/app/Models/Brands.php
UTF-8
693
2.515625
3
[ "MIT" ]
permissive
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Brands extends Model { // chi dinh file model nay lam viec voi bang du lieu nao protected $table = 'brands'; // tao phuong thuc de lien ket quan he voi model khac public function products() { // y dinh : phuong thuc se lien ket quan he one - to - many voi bang product return $this->hasMany('App\Models\Products'); } public function testOneToMany() { return Brands::find(1)->products; } public function getAllDataBrands() { $data = Brands::all(); if($data){ $data = $data->toArray(); } return $data; } }
true
d7294e6422906ff0ce6773c5159308eacf931c12
PHP
gopalindians/base
/src/base/php/router/URI.php
UTF-8
2,180
3.359375
3
[ "MIT" ]
permissive
<?php namespace base; /** * Class to work with RESTful URIs. * * @author Marvin Blum */ class URI{ const DELIMETER = '/'; const PARAM_DELIMETER = '/:'; const PARAM_OPTIONAL = '?'; private $route = array(); private $params = array(); private $optionalParams = array(); function __construct($route = null){ if($route){ $this->parse($route); } } private function parseRoute($route){ $parts = explode(self::DELIMETER, $route); foreach($parts AS $value){ if(!empty($value)){ $this->route[] = $value; } } } private function parseParams($route){ $get = explode(self::PARAM_DELIMETER, $route); foreach($get AS $value){ if(!empty($value)){ $value = str_replace('/', '', $value); if(substr($value, -1) == self::PARAM_OPTIONAL){ $this->optionalParams[] = $value; } else{ $this->params[] = $value; } } } } private function parse($route){ $len = strlen($route); $end = strpos($route, self::PARAM_DELIMETER); if($end === FALSE){ $end = strlen($route); } $this->parseRoute(substr($route, 0, $end)); if($end != $len){ $this->parseParams(substr($route, $end, $len)); } } function equals(URI $uri, $compareParams = false){ if(!$compareParams){ $a = $this->route; $b = $uri->getRouteParts(); } else{ $a = $this->getFullRouteParts(); $b = $uri->getFullRouteParts(); } if(count($a) != count($b)){ return false; } foreach($a AS $key => $value){ if($value != $b[$key]){ return false; } } return true; } function getFullRouteParts(){ return array_merge($this->route, $this->getParams()); } function getFullRoute(){ return $this->getRoute().self::DELIMETER.$this->getRouteParams(); } function getRoute(){ return self::DELIMETER.implode(self::DELIMETER, $this->route); } function getRouteParts(){ return $this->route; } function getRouteParams(){ return implode(self::DELIMETER, $this->getParams()); } function getParams(){ return array_merge($this->params, $this->optionalParams); } function getRequiredParams(){ return $this->params; } function getOptionalParams(){ return $this->optionalParams; } } ?>
true
629459a43d3fb355450b722e06060187a19036f5
PHP
itkg/core
/src/Itkg/Core/Cache/Adapter/Memcached.php
UTF-8
3,150
2.703125
3
[ "MIT" ]
permissive
<?php namespace Itkg\Core\Cache\Adapter; use Itkg\Core\Cache\AdapterAbstract; use Itkg\Core\Cache\AdapterInterface; use Itkg\Core\CacheableInterface; /** * Memcached cache adapter */ class Memcached extends AdapterAbstract implements AdapterInterface { /** * Memcached connection instance * @var \Memcached */ protected $connection; /** * Default options * @var array */ protected $defaultOptions = array( \Memcached::OPT_COMPRESSION => true, \Memcached::OPT_LIBKETAMA_COMPATIBLE => true, \Memcached::OPT_CONNECT_TIMEOUT => 500, \Memcached::OPT_SERVER_FAILURE_LIMIT => 3, ); /** * Constructor * * @param array $config */ public function __construct(array $config) { parent::__construct($config); $this->setConnection(new \Memcached); } /** * Set connection * * @param \Memcached $memcached * * @return $this * */ public function setConnection(\Memcached $memcached) { $this->connection = $memcached; if (!count($this->connection->getServerList())) { $this->configureServers(); } $this->setOptions(); return $this; } /** * Configure servers * * @return void * * @throws \InvalidArgumentException */ public function configureServers() { if (!array_key_exists('server', $this->config)) { throw new \InvalidArgumentException('Configuration key "server" must be set'); } $servers = $this->config['server']; // Single server if (array_key_exists('host', $servers)) { $servers = array($servers); } $this->connection->addServers($servers); } /** * Configure options * * @return void */ protected function setOptions() { $options = $this->defaultOptions; if (array_key_exists('options', $this->config)) { $options = array_merge($options, $this->config['options']); } $this->connection->setOptions($options); } /** * Get value from cache * Must return false when cache is expired or invalid * * @param CacheableInterface $item * * @return mixed */ public function get(CacheableInterface $item) { return $this->connection->get($item->getHashKey()); } /** * Set a value into the cache * * @param CacheableInterface $item * * @return void */ public function set(CacheableInterface $item) { $this->connection->set($item->getHashKey(), $item->getDataForCache(), $item->getTtl()); } /** * Remove a value from cache * * @param CacheableInterface $item * * @return void */ public function remove(CacheableInterface $item) { $this->connection->delete($item->getHashKey()); } /** * Remove all cache * * @return void */ public function removeAll() { $this->connection->flush(); } }
true
e9cc7e18ec5dcfa0f04a9be63f8d1f87a3465ac8
PHP
alexcaussades/ShadeArmy
/assets/class/players.php
UTF-8
3,339
2.859375
3
[]
no_license
<?php namespace ShadeLife; use PDO; require 'trait/trait_player.php'; require 'bdd.php'; class Players { use TPlayers; //public $pid; public function __construct() { $this->pid = $this->regexPid(); } /** * regexPid * - Vérifie que le pid soit conforme a la numerotation de steam pour preparer le fonctionement de la class player * * @return int * @param regex 7656 */ public function regexPid() { if(isset($_GET["pid"])) { $_GET['pid'] = htmlspecialchars(trim($_GET['pid'])); if (preg_match("#^[7][6][5][6]#", $_GET['pid'])) { return $this->pid = $_GET['pid']; } else { ?> <div class="alert alert-danger" role="alert"> Un problème est survenue sur le PID </div> <?php } } } public function getpid() { echo $this->pid; } public function getInfo() { global $bdd; $q = $bdd->prepare("SELECT * FROM players WHERE pid = :pid"); $q->execute(array('pid'=> $this->pid)); while ($r = $q->fetch()) { $infosArray = array( $this->uid = $r['uid'], $this->name = $r['name'], $this->cash = $r['cash'], $this->bankacc = $r['bankacc'], $this->coplevel = $r['coplevel'], $this->cop_licenses = $r['cop_licenses'], $this->civ_licenses = $r['civ_licenses'], $this->med_licenses = $r['med_licenses'], $this->cop_gear = $r['cop_gear'], $this->med_gear = $r['med_gear'], $this->mediclevel = $r['mediclevel'], $this->arrested = $r['arrested'], $this->aliases = $r['aliases'], $this->adminlevel = $r['adminlevel'], //$this->donatorlvl = $r['donatorlvl'], $this->civ_gear = $r['civ_gear'], $this->blacklist = $r['blacklist'], //$this->sponsor = $r['sponsor'], //$this->credit = $r['credit'], $this->lastseen = $r['last_seen'], $this->pointsPermis = $r['pointsPermis'], $this->num = $r['num'], ); } $q->closeCursor(); } public function countPlayers(){ global $bdd; $sql = $bdd->query('SELECT COUNT(uid) FROM players'); $fetch = $sql->fetch(); return $fetch['COUNT(uid)']; } public function advance_identity() { global $bdd; $q = $bdd->prepare("SELECT * FROM advanced_identity WHERE pid = :pid"); $q->execute(array('pid'=> $this->pid)); while ($r = $q->fetch()) { $infosArray = array( $this->datenaissance = $r['naissance'], $this->lieudenaissance = $r['lieu_naissance'], $this->taille = $r["taille"], $this->sexe = $r["sexe"], ); } $q->closeCursor(); } public function getPlayersLieuNaiss() { $a = $this->lieudenaissance; echo str_replace('"', '', $a); } public function getPlayersNaiss() { $a = $this->datenaissance; $a = str_replace('"', '', $a); $a = str_replace(']', '', $a); $a = str_replace('[', '', $a); echo str_replace(',', '-', $a); } public function getPlayerstaille() { return $this->taille; } public function getplayersHouse() { global $bdd; $q = $bdd->query("SELECT COUNT(*) AS pid FROM houses WHERE pid = ".$this->pid."")->fetchColumn(); return $q; } public function getplayersContanier() { global $bdd; $q = $bdd->query("SELECT COUNT(*) AS pid FROM containers WHERE pid = ".$this->pid."")->fetchColumn(); return $q; } public function GetPlayersFromFacture() { global $bdd; $q = $bdd->query("SELECT COUNT(*) AS from_pid FROM factures WHERE from_pid = ".$this->pid."")->fetchColumn(); return $q; } }
true
7d180394741117a481a8146e188f4cca031309c7
PHP
utopszkij/uklogin
/models/pdfparser.php
UTF-8
16,090
2.578125
3
[]
no_license
<?php /** * OpenId szolgáltatás magyarorszag.hu ügyfélkapu használatával * @package uklogin * @author Fogler Tibor */ include_once 'vendor/autoload.php'; /** PdfData rekord */ class PdfData { /** hibaüzenet */ public $error = ''; /** PDF tartalomban a név */ public $txt_name = ''; /** PDF tartalomban az anyja neve */ public $txt_mothersname = ''; /** PDF tartalomban a születési dátum */ public $txt_birth_date = ''; /** PDF tartalomban az állandó lakcím */ public $txt_address = ''; /** PDF tartalomban a tartozkodási hely */ public $txt_tartozkodas = ''; // PDF info /** PDF információ létrehozó sw */ public $info_creator = ''; /** PDF információ létrehozó sw2 */ public $info_producer = ''; /** PDF információ verzió */ public $info_pdfVersion = ''; // aláírás meghatalmazó /** aláírásban a név */ public $xml_nev = ''; /** aláírásban az email */ public $xml_ukemail = ''; /** aláírásban a születési név */ public $xml_szuletesiNev = ''; /** aláírásban az anyja neve */ public $xml_anyjaNeve = ''; /** aláírásban a születési dátum */ public $xml_szuletesiDatum = ''; /** aláírás kelte */ public $xml_alairasKelte = ''; } /** PDF parser model */ class PdfparserModel { /** * PDF text tartalmának kinyerése * @param string $filePath PDF file elérési utvonala * @param array $lines (IO) * @return bool */ protected function pdf_getText(string $filePath, array &$lines): bool { $outPath = str_replace(".pdf",".txt", $filePath); shell_exec('pdftotext ' . $filePath." ".$outPath); if (file_exists($outPath)) { $lines = file($outPath); $result = true; } else { $result = false; } return $result; } /** * PDF információk kinyerése * @param string $filePath PDF file teljes utvonal * @param array $lines (IO) * return bool */ protected function pdf_getInfo(string $filePath, array &$lines): bool { $outPath = str_replace(".pdf",".inf", $filePath); shell_exec('pdfinfo ' . $filePath." > ".$outPath); if (file_exists($outPath)) { $lines = file($outPath); $result = true; } else { $result = false; } return $result; } /** * PDF aláírás infok kinyerése * @param string $filePath PDF file teljes elérési utvonal * @param array signatureArray * @return bool */ protected function pdf_getSignature(string $filePath, array &$signatureArray) { $signatureArray = explode(PHP_EOL, shell_exec('pdfsig ' . escapeshellarg($filePath).' 2>&1')); } /** * meghatalmazó információk kinyerése a PDF -ből * @param string $filePath PDF file teljes elérési út * @param array $lines (IO) * @return bool */ protected function pdf_getMeghatalmazo(string $filePath, array &$lines): bool { $outPath = str_replace(".pdf","_igazolas.pdf",$filePath); shell_exec('pdfdetach -save 1 -o '.$outPath." ".escapeshellarg($filePath)); if (is_file($outPath)) { $outPath2 = str_replace(".pdf","_meghatalmazo.xml", $filePath); shell_exec("pdfdetach -save 1 -o ".$outPath2." ".$outPath); if (is_file($outPath2)) { $lines = file($outPath2); $result = true; } else { $result = false; } } else { $result = false; } return $result; } /** * pdf text tartalmának elemzése * @param string $filePath PDF file teljes utvpnal * @param PdfData $res */ protected function parseTxt(string $filePath, PdfData &$res) { $res->txt_tartozkodas = ''; // ez nem mindig szerepel a pdf -ben $lines = array(); if ($this->pdf_getText($filePath, $lines)) { $i = 0; while ($i < count($lines)) { $s = trim(str_replace("\n",'', str_replace("\r",'',$lines[$i]))); if ($s == 'Név (névviselés szerint)') { $res->txt_name = mb_strtoupper(trim($lines[$i + 2])); } if ($s == 'Születési dátum') { $res->txt_birth_date = str_replace('.','-',trim($lines[$i + 2])); $res->txt_birth_date = substr($res->txt_birth_date,0,10); } if ($s == 'Anyja neve és utóneve') { $res->txt_mothersname = mb_strtoupper(trim($lines[$i + 2])); } if ($s == 'Lakóhely adatok') { $i++; $s = trim(str_replace("\n",'', str_replace("\r",'',$lines[$i]))); if ($s == 'Cím') { $res->txt_address = mb_strtoupper(trim($lines[$i + 2])); } } if ($s == 'Tartózkodási hely adatok') { $i++; $s = trim(str_replace("\n",'', str_replace("\r",'',$lines[$i]))); if ($s == 'Cím') { $res->txt_tartozkodas = mb_strtoupper(trim($lines[$i + 2])); } } $i++; } } else { $res->error .= 'Nem lehet értelmezni a PDF szöveggét, '; } } /** * pdf információk kezelése ellenörzése * Creator: Apache FOP Version 1.0 * Producer: Apache FOP Version 1.0; modified using iText 5.0.2 (c) 1T3XT BVBA * PDF version: 1.4 * @param string $filePath * @param PdfData $res { ...info_creator, info_producer, info_PDFversion....} */ protected function parseInfo(string $filePath, PdfData &$res) { $lines = array(); if ($this->pdf_getInfo($filePath, $lines)) { $i = 0; while ($i < count($lines)) { $s = str_replace("\r",'',$lines[$i]); $s = trim(str_replace("\n",'',$s)); if (substr($s,0,8) == 'Creator:') { $res->info_creator = trim(substr($s,8,100)); } if (substr($s,0,9) == 'Producer:') { $res->info_producer = trim(substr($s,9,100)); } if (substr($s,0,12) == 'PDF version:') { $res->info_pdfVersion = trim(substr($s,12,100)); } $i++; } } else { $res->error .= 'Nem lehet értelmezni a PDF file infokat, '; } } /** * pdf aláírás elenörzés karakteres kereséssel * @param string $filePath pdf file * @param PdfData $res */ protected function checkPdfSignStr(string $filePath, Pdfdata &$res) { // karakteres keresés a pdf tartalomban $check1 = false; $check2 = false; $buffer = ''; $handle = fopen($filePath, 'r'); while (($buffer = fgets($handle)) !== false) { if (strpos($buffer, 'adbe.pkcs7.detached') !== false) { $check1 = true; } if (strpos($buffer, 'NISZ Nemzeti Infokommun') !== false) { $check2 = true; } } if ($check1 && $check2) { $res->error = ''; } else { $res->error .= 'Nem megfelelő aláírás(1), '; } } /** * check pdf signature, ha a pdfsig hivás sikertelen, de * tartalmazza az aláírásra utaló stringeket akkor a teljes pdf tartalmonból * sha256 has-t képez és beteszi a $res->pdfHash -be. * @param string $filePath * @param PdfData $res {error:"xxxxxx" | error:"", signHash:"" } */ protected function checkPdfSign(string $filePath, PdfData &$res) { $signatureArray = []; $this->pdf_getSignature($filePath, $signatureArray); if (count($signatureArray) == 0) { $this->checkPdfSignStr($filePath, $res); } else if ((strpos($signatureArray[1],'Segmentation fault') >= 0) || ($signatureArray[0] == 'sh: pdfsig: command not found')) { $this->checkPdfSignStr($filePath, $res); } else { if (in_array('File \'' . $filePath . '\' does not contain any signatures' , $signatureArray)) { $res->error .= 'Nincs aláírva, '; } if (!in_array(' - Signature Validation: Signature is Valid.' , $signatureArray)) { $res->error .= 'Aláírás nem érvényes, '; } if (!in_array(' - Signer Certificate Common Name: AVDH Bélyegző' , $signatureArray)) { $res->error .= 'nem AVDH aláírás, '; } } } /** * meghatalmazo.xml kinyerése és elemzése * @param string $filePath pdf file name * @param PdfData $res {.....xml_name....} */ protected function parseMeghatalmazo(string $filePath, PdfData &$res) { $res->xml_viseltNev = ''; $res->xml_ukemail = ''; $res->xml_szuletesiNev = ''; $res->xml_anyjaNeve = ''; $res->xml_szuletesiDatum = ''; $res->xml_alairasKelte = ''; $lines = array(); if ($this->pdf_getMeghatalmazo($filePath, $lines)) { $i = 0; while ($i < count($lines)) { $s = trim($lines[$i]); if ((strpos($s,'fogalmak/Nev') > 0) & (isset($lines[$i+1]))) { $s = trim($lines[$i+1]); $w = explode('>',$s); if (count($w) > 1) { $w2 = explode('<',$w[1]); $res->xml_name = $w2[0]; } } if (strpos($s,'emailAddress') > 0) { $emails = []; preg_match('/emailAddress\"\>.*\</', $s , $emails); if (count($emails) > 0) { $w = explode('>',$emails[0]); $w2 = explode('<',$w[1]); $res->xml_ukemail = $w2[0]; } } // Új aláíró rendszerhez: if ((strpos($s,'viseltNev') > 0) & (isset($lines[$i+1]))) { $s = trim($lines[$i+1]); $w = explode('>',$s); if (count($w) > 1) { $w2 = explode('<',$w[1]); $res->xml_viseltNev = $w2[0]; } } if ((strpos($s,'szuletesiNev') > 0) & (isset($lines[$i+1]))) { $s = trim($lines[$i+1]); $w = explode('>',$s); if (count($w) > 1) { $w2 = explode('<',$w[1]); $res->xml_szuletesiNev = mb_strtoupper($w2[0]); } } if ((strpos($s,'anyjaNeve') > 0) & (isset($lines[$i+1]))) { $s = trim($lines[$i+1]); $w = explode('>',$s); if (count($w) > 1) { $w2 = explode('<',$w[1]); $res->xml_anyjaNeve = mb_strtoupper($w2[0]); } } if ((strpos($s,'szuletesiDatum') > 0) & (isset($lines[$i+1]))) { $s = trim($lines[$i+1]); $w = explode('>',$s); if (count($w) > 1) { $w2 = explode('<',$w[1]); $res->xml_szuletesiDatum = substr(str_replace('.','-',$w2[0]),0,10); } } if (strpos($s,'IssueInstant="') > 0) { $s = trim($lines[$i]); $w = explode('IssueInstant="',$s); $res->xml_alairasKelte = substr($w[1],0,10); } $i++; } } else { $res->error .= 'Nem lehetett az aláíró info XML-t kibontani, '; } } /** * könyvtár teljes tartalmának törlése * @param string $tmpDir */ public function clearFolder(string $tmpDir) { if (is_dir($tmpDir)) { $files = glob($tmpDir.'/*'); // get all file names foreach ($files as $file) { // iterate files if (is_file($file)) { unlink($file); // delete file } } rmdir($tmpDir); } } protected function getDataFromTxt($text, $prefix, $postfix) { $i = strpos($text,$prefix); $j = strpos($text,$postfix); if (($i > 0) & ($j > $i)) { $result = substr($text, $i+strlen($prefix), $j-$i-strlen($prefix) ); } return $result; } protected function isStringInFile($file,$string = 'adbe.pkcs7.detached'){ $handle = fopen($file, 'r'); $valid = false; // init as false while (($buffer = fgets($handle)) !== false) { if (strpos($buffer, $string) !== false) { $valid = TRUE; break; // Once you find the string, you should break out the loop. } } fclose($handle); return $valid; } /** * munkakönyvtár létrehozása session ID -t használva */ public function createWorkDir(): string { $sessionId = session_id(); $tmpDir = './work/tmp'.$sessionId; if (!is_dir($tmpDir)) { mkdir($tmpDir, 0777); } return $tmpDir; } /** * PDF fájl elemzése * @param string $filePath PDF file teljes utvonal * @return PdfData */ public function parser(string $filePath): PdfData { global $pdfParserResult; if (isset($pdfParserResult)) { // UNIT testhez return $pdfParserResult; } $res = new PdfData(); if (!file_exists($filePath)) { $res->error = 'PDF_Nem_található. ('.$filePath.'), '; } else { $filePath = str_replace("'",'',escapeshellarg($filePath)); //+ ha a parancssori pdf eszközök nem elérhetőek /* if (!$this->isStringInFile($filePath)) { $res->error="nincs aláírva"; } $parser = new \Smalot\PdfParser\Parser(); $pdf = $parser->parseFile($filePath); $text = $pdf->getText(); $details = $pdf->getDetails(); unlink($filePath); $res->txt_name = $this->getDataFromTxt($text,'Név (névviselés szerint)','Személyi azonosító'); $res->txt_birth_date = $this->getDataFromTxt($text,'Születési dátum','Neme'); $res->txt_mothersname = $this->getDataFromTxt($text,'Anyja neve és utóneve','Állampolgársága'); $res->txt_address = $this->getDataFromTxt($text,'Cím','Bejelentés'); $res->txt_tartozkodas = ''; $res->xml_viseltNev = $res->txt_name; $res->xml_ukemail = ''; $res->xml_szuletesiNev = $this->getDataFromTxt($text,'Születési név és utónév','Anyja neve és utóneve'); $res->xml_anyjaNeve = $res->txt_mothersname; $res->xml_szuletesiDatum = $res->txt_birth_date; $res->xml_alairasKelte = ''; */ //- ha a parancssori eszközök nem elérhetőek //+ ha a parancssori pdf eszközök elérhetőek $this->checkPdfSign($filePath, $res); if ($res->error == '') { $this->parseTxt($filePath, $res); $this->parseInfo($filePath, $res); $this->parseMeghatalmazo($filePath, $res); // meghatalmazó és pdf tartalom azonos? if ((mb_strtoupper($res->txt_mothersname) != mb_strtoupper($res->xml_anyjaNeve)) | (mb_strtoupper($res->txt_name) != mb_strtoupper($res->xml_viseltNev)) | ($res->txt_birth_date != $res->xml_szuletesiDatum)) { $res->error .= 'PDF tartalom és aláírás ren egyezik, <br>'. $res->txt_mothersname.' / '.$res->xml_anyjaNeve.'<br>'. $res->txt_name.' / '.$res->xml_viseltNev.'<br />'. $res->txt_birth_date.' / '.$res->xml_szuletesiDatum.'<br />'; } } //- ha a parancssori eszközök elérhetőek } return $res; } } // PdfparserModel ?>
true
9787fcb45ca744b41c82d2871e3d99ad3b91b64f
PHP
adamkenway007/PHP-Awal
/pertemuan4/mktime/index.php
UTF-8
275
2.671875
3
[]
no_license
<?php // mktime // membuat sendiri detik sendiri dari detik yang sudah berlalu sejak 1 Januari 1970 // mktime(0,0,0,0,0,0) //jam-menit-detik-bulan-tanggal-tahun echo "<br>"; echo mktime(0,0,0,1,10,1998); echo "<br>"; echo date("l, d-M-Y", mktime(0,0,0,1,10,1998)); ?>
true
56112c8c6950843e3c217f26d70ca96b40167bf9
PHP
maukoese/lulu
/src/Lulu.php
UTF-8
2,613
2.671875
3
[]
no_license
ssword on www.lulusms.com function __construct($AccountNo, $UserName, $Password) { $this->$AccountNo = $AccountNo; $this->$UserName = $UserName; $this->$Password = $Password; } function sms($To , $SMS, $From = 'lulusms.com') { // Creates our data array that we want to post to the endpoint $data_to_post = [ 'AccountNo' => $this->AccountNo, 'UserName' => $this->UserName, 'Password' => $this->Password , 'To' => $To , 'SMS' => $SMS, 'From' => $From , ]; // Sets our options array so we can assign them all at once $options = [ CURLOPT_URL => 'https://www.lulusms.com/api/sendsmsapiv3', CURLOPT_POST => true, CURLOPT_SSL_VERIFYHOST => 0, CURLOPT_SSL_VERIFYPEER => 0, CURLOPT_POSTFIELDS => $data_to_post, CURLOPT_RETURNTRANSFER => 1, // Return the transfer as a string ]; // Initiates the cURL object $curl = curl_init(); // Assigns our options curl_setopt_array($curl, $options); // Executes the cURL POST $results = curl_exec($curl); // Turn the results into an associative array $returned_text = json_decode($results, true); // Get the status of message $Status = trim($returned_text['Status']); // Get the message status $StatusMessage = $returned_text['StatusMessage']; // If status is OK proceed if (strcasecmp($Status, "OK")== 0) { $SMSRefNumber = $returned_text['SMSRefNumber']; $SMSUnitsBalance = $returned_text['SMSUnitsBalance']; /* echo "Text sent successfully to remote server '<br>'";// comment out when live echo "The Units balance is $SMSUnitsBalance '<br>'";// comment out when live echo "The status message returned by the server is - $StatusMessage ";// comment out when live echo "<br>";// comment out when live */ if ($SMSUnitsBalance < 10) { /* echo '<br>'; // comment out when live echo "YOU NEED TO TOP UP. The balance is " . $SMSUnitsBalance . "<br>";// comment out when live */ } ///////////// Your code processing logic here including updating your database } else { /* echo '<br>'; // comment out when live echo "ERROR *******************Not successful. The following error has been generated " . $StatusMessage . '<br>'; ///////////// Your code error processing logic here including updating your database */ } // Be kind, tidy up! curl_close($curl); } } ?>
true
d970e9daa3371053bdd79a3d356aa4ded6624a42
PHP
ctx2002/Tools
/partial_generator.php
UTF-8
734
3.15625
3
[]
no_license
<?php function partial($func, ...$args): Closure { return static function() use($func, $args) { return call_user_func_array($func, array_merge($args, func_get_args())); }; } function identity ($value) { return $value; }; function compose(...$funcs) { return array_reduce($funcs, static function($init, $func){ return static function ($input) use ($init, $func) { return $func($init($input) ); }; }, 'identity'); } function add3($a, $b, $c) { return $a + $b + $c; } function square($a) { return $a * $a; } function double($a) { return $a * 2; } $sum = compose('double','square'); //$sum = partial('add3', 1); var_dump($sum(1));
true
2d5ab8305eed45c1d6209f61b4ce2336bee271ad
PHP
JohnWick1975/klases-projektas-CARMOTO
/app/models/Random.php
UTF-8
463
2.828125
3
[]
no_license
<?php class Random { private $db; public function __construct() { $this->db = new Database(); } public function randomInfoUrl() { $this->db->query("SELECT `img_url` FROM `random` ORDER BY RAND() LIMIT 1"); return $this->db->single(); } public function randomInfoText() { $this->db->query("SELECT `text` FROM `random` ORDER BY RAND() LIMIT 1"); return $this->db->single(); } }
true
fe5a8704842d30f46d76ed98edc25f17f4bcfe36
PHP
bugrov/yandex-tracker
/src/Api/Requests/Queue/QueueGetAllRequest.php
UTF-8
1,275
2.6875
3
[]
no_license
<?php namespace BugrovWeb\YandexTracker\Api\Requests\Queue; use BugrovWeb\YandexTracker\Api\Client; /** * Класс-конструктор для запроса к GET /v2/queues/ * * @see https://cloud.yandex.ru/docs/tracker/concepts/queues/get-queues * * @method QueueGetAllRequest expand(string $field) Дополнительные поля, которые будут включены в ответ * @method QueueGetAllRequest perPage(int $count) Количество очередей на странице ответа * @method QueueGetAllRequest page(int $pageNumber) Номер страницы ответа */ class QueueGetAllRequest extends QueueRequest { const ACTION = 'queues'; const METHOD = Client::METHOD_GET; /** * @var array|string[] Данные для отправки в запросе */ protected array $data = [ 'queryParams' => [], 'bodyParams' => [], ]; /** * @var array|string[] get-параметры, доступные для запроса */ protected array $queryParams = [ 'expand', 'perPage', 'page', ]; public function __construct() { $this->url = self::ACTION.'/'; } }
true
f7587d302496057d289755f1cf9731ae611c5893
PHP
rishirajshekhawat/wordpress
/olomo/include/reviews/ratings.php
UTF-8
5,915
2.703125
3
[]
no_license
<?php /** * Listing Ratings * */ /* ============== Ratings Stars ============ */if(!function_exists('olomo_ratings_stars')){ function olomo_ratings_stars($metaboxID, $postID) { $rating = listing_get_metabox_by_ID($metaboxID ,$postID); if( !empty($rating)){ $blankstars = 5; while( $rating > 0){ if($rating < 1){ echo '<i class="fa fa-star star-worst"></i>'; $rating--; $blankstars--; } else if($rating >=1 && $rating < 2){ echo '<i class="fa fa-star star-bad"></i>'; $rating--; $blankstars--; } else if($rating >=2 && $rating < 3.5){ echo '<i class="fa fa-star star-satisfactory"></i>'; $rating--; $blankstars--; } else if($rating >=3.5 && $rating <= 5){ echo '<i class="fa fa-star star-good"></i>'; $rating--; $blankstars--; } } while( $blankstars > 0 ){ echo '<i class="fa fa-star-o"></i>'; $blankstars--; } } else{ $blankstars = 5; while( $blankstars > 0 ){ echo '<i class="fa fa-star-o"></i>'; $blankstars--; } } } } /* ============== Ratings Figure ============ */ if (!function_exists('olomo_ratings_figure')) { function olomo_ratings_figure($postID) { $print = ''; $total = ''; $comment= get_comments( array( 'post_id' => $postID, 'meta_key' => 'rate' ) ); $count= 0; foreach($comment as $com){ $rating = get_comment_meta($com->comment_ID, 'rate', true); if(!empty($rating)){ $count++; } $total+= $rating; } if($count > 0){ $sub = $total/$count; $afterRound = round($sub); for($i=1;$i<=$afterRound;$i++){ $print .=' <i class="fa fa-star"></i>'; } $emptyStars = 5 - $afterRound; for($i=1;$i<=$emptyStars;$i++){ $print .=' <i class="fa fa-star-o"></i>'; } }else{ for($i=1;$i<=5;$i++){ $print .='<i class="fa fa-star-o"></i>'; } } return $print; } } /* ============== Set_listing_ratings ============ */ if (!function_exists('olomo_set_listing_ratings')) { function olomo_set_listing_ratings($review_id, $listing_id =null, $new_rating = null, $action) { if ($action=="add" || $action=="update"){ $reviews_ids = listing_get_metabox_by_ID('reviews_ids', $listing_id); if (!empty($reviews_ids)){ $reviews_ids = $reviews_ids.','.$review_id; } else{ $reviews_ids = $review_id; } $reviews = array(); listing_set_metabox('reviews_ids', $reviews_ids, $listing_id); $reviews_ids = listing_get_metabox_by_ID('reviews_ids', $listing_id); if (strpos($reviews_ids, ',') !== false) { $reviews = explode(',', $reviews_ids); } else{ $reviews[] = $reviews_ids; } $reviews = array_unique($reviews); $totalRating = 0; $totalReviews = 0; if(!empty($reviews) && !empty($reviews[0])){ foreach($reviews as $review){ if(get_post_status($review)=="publish"){ if($review==$review_id){ $rateOfReview = $new_rating; } else{ $rateOfReview = listing_get_metabox_by_ID('rating', $review); } if (!empty($rateOfReview)) { $totalRating = $totalRating + $rateOfReview; $totalReviews++; } } } } if($totalRating != 0 && $totalReviews != 0){ $sub = $totalRating/$totalReviews; $afterRound = $sub; $afterRound = number_format($sub, 1); update_post_meta( $listing_id, 'listing_rate', $afterRound ); } } else if($action=="delete"){ $reviews_ids = listing_get_metabox_by_ID('reviews_ids', $listing_id); $reviews = array(); if (strpos($reviews_ids, ',') !== false) { $reviews = explode(',', $reviews_ids); } else{ $reviews[] = $reviews_ids; } foreach($reviews as $key=>$review){ if($review==$review_id){ unset($reviews[$key]); } } $reviews_ids = implode(",",$reviews); listing_set_metabox('reviews_ids', $reviews_ids, $listing_id); $totalRating = 0; $totalReviews = 0; foreach($reviews as $review){ if(get_post_status($review)=="publish"){ $rateOfReview = listing_get_metabox_by_ID('rating', $review); if (is_numeric($rateOfReview)) { $totalRating = $totalRating + $rateOfReview; $totalReviews++; } else{ $totalRating = $totalRating + 0; $totalReviews++; } } } $sub = $totalRating/$totalReviews; $afterRound = $sub; $afterRound = number_format($sub, 1); update_post_meta( $listing_id, 'listing_rate', $afterRound ); } } } /* ============== Get rating number =================== */ if(!function_exists('olomo_ratings_numbers')){ function olomo_ratings_numbers($listing_id){ $rating = 0; $reviews_ids = listing_get_metabox_by_ID('reviews_ids', $listing_id); $reviews = array(); $reviews_ids = listing_get_metabox_by_ID('reviews_ids', $listing_id); if (strpos($reviews_ids, ',') !== false) { $reviews = explode(',', $reviews_ids); } else{ $reviews[] = $reviews_ids; } $reviews = array_unique($reviews); if(!empty($reviews) && !empty($reviews[0])){ foreach($reviews as $review){ if(get_post_status($review)=="publish"){ $rating++; } } } return $rating; } } /* ============== Highest avaerage rating ============ */ if (!function_exists('olomo_highest_average_rating')) { function olomo_highest_average_rating($listing_id, $new_rate) { $listing_rate = get_post_meta( $listing_id, 'listing_reviewed', true ); if( !empty($listing_rate) ){ return $listing_rate; } else{ return '0'; } } } /* ============== Total reviewes rating ============ */ if (!function_exists('olomo_total_reviews_add')) { function olomo_total_reviews_add($listing_id){ $total_reviewed = get_post_meta( $listing_id, 'listing_reviewed', true ); if ( ! empty( $total_reviewed ) ) { $total_reviewed++; update_post_meta( $listing_id, 'listing_reviewed', $total_reviewed ); } else{ update_post_meta( $listing_id, 'listing_reviewed', '1' ); } } }
true
071cc7c4f56bb75f6efc4a3cf39555d7b49beb00
PHP
one45/evaluation-data-grabber
/one45api.php
UTF-8
5,974
2.953125
3
[]
no_license
<?php class one45API { private $base_url; private $public_api_url; public $regular_api_url; private $client_key; private $client_secret; private $curl_http_headers = array(); private $session_id = null; private $authorization = null; private $access_token = null; private $curl_headers = array(); private $default_limit = null; public function __construct($key_master) { $this->base_url = $key_master->getBaseUrl(); $this->public_api_url = $key_master->getPublicAPIUrl(); $this->regular_api_url = $key_master->getRegularAPIUrl(); $this->client_key = $key_master->getClientKey(); $this->client_secret = $key_master->getClientSecret(); $this->default_limit = 50; $this->session_id = md5('hello world' . time()); } /** * Gets you the authorization header value for your CURL request */ public function setAuthorization() { // @TODO We don't deal with a case where during your session the token expires if (is_null($this->access_token)) { $response = $this->getToken(); $this->access_token = $response->access_token; $this->authorization = "Bearer " . $this->access_token; } } /** * Set HTTP Headers we're going to need */ private function setCurlHeaders($nontoken_request = true) { // we'll always use a session id $this->curl_headers = array ( "Cookie: PHPSESSID=" . $this->session_id ); // for requests that don't involve grabbing a token, we need to provide some extra data if ($nontoken_request) { $this->curl_headers[] = "Authorization: " . $this->authorization; $this->curl_headers[] = "Content-Type: multipart/form-data; charset=utf-8;"; } else { $this->curl_headers[] = "Content-Type: application/json; charset=utf-8"; } } /** * Check to see if our string is json - used to help process responses from curl requests */ private function isJSONString($string) { json_decode($string); return (json_last_error() == JSON_ERROR_NONE); } /** * Convenience method for generating long, array-like get variable strings */ public static function generateArrayGetVariable($array_name, $variables) { $get_string = ""; $cur_variable_num = 0; foreach ($variables as $variable) { if ($cur_variable_num) { $get_string .= "&"; } // %5B is [ and %5D is ] $get_string .= $array_name . "%5B" . $cur_variable_num . "%5D=" . $variable; $cur_variable_num++; } return $get_string; } /** * Process curl responses into objects, or throw errors if there are problems */ private function processResponse($response, $curl_obj, $write_to_file = false) { if (!$response) { die ('Curl Error: "' . curl_error($curl_obj) . '" - Code: ' . curl_errno($curl_obj)); } else if (!$this->isJSONString($response)) { die ('<div>Bad response error:</div><div>' . $response . "</div>"); } curl_close($curl_obj); if ($write_to_file) { file_put_contents($write_to_file, $response . "\n", FILE_APPEND); $decoded = json_decode($response, true); $big_array = array_fill(0, count($decoded), "0"); return $big_array; } else { return json_decode($response); } } /** * Make a curl request */ private function makeCurlRequest($url, $write_to_file = false, $request_type = "GET", $request_params = null) { // Get cURL resource $ch = curl_init(); // Set url curl_setopt($ch, CURLOPT_URL, $url); // Set method curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request_type); // Set options curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Set headers curl_setopt ( $ch, CURLOPT_HTTPHEADER, $this->curl_headers ); if ($request_params) { $body = json_encode($request_params); // Set body curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $body); } // Send the request & save response to $resp $resp = curl_exec($ch); return $this->processResponse($resp, $ch, $write_to_file); } /** * This is a generic method for sending a request. * The method handles setting authorization, and curl headers so you don't have to worry about it elsewhere. * It also handles any looping/need for multiple requests to get all the data you have asked for. * * @TODO: What happens if you make a request that finds no results? */ public function makeGenericRequest($request_url, $args, &$all_responses = null, &$offset = 0) { //limit 50 // write_to_file false $this->setAuthorization(); $this->setCurlHeaders(); // this limit, write_to_file and args stuff is to let the user optionally pass an associative array of limit/write_to_file $limit = $this->default_limit; $write_to_file = false; extract($args); $responses = $this->makeCurlRequest($request_url . "&limit=" . $limit . "&offset=" . $offset, $write_to_file); file_put_contents("log.txt", "Generic request\n", FILE_APPEND); // if we have gotten all the possible responses if (count($responses) < $limit) { // if this is our first time through the loop if (is_null($all_responses)) { return $responses; } else { $all_responses = array_merge($all_responses, $responses); return $all_responses; } } else // remember the responses we've gotten so far, and go back for some more { $offset += $limit; // if this is our first time through the loop if (is_null($all_responses)) { $all_responses = $responses; } else { $all_responses = array_merge($all_responses, $responses); } return $this->makeGenericRequest($request_url, $args, $all_responses, $offset); } } /** * Get an authorization token */ public function getToken() { $this->setCurlHeaders(false); $request_params = array ( 'client_key' => $this->client_key, 'client_secret' => $this->client_secret ); return $this->makeCurlRequest($this->public_api_url . "v1/token/generate", false, "POST", $request_params); } } ?>
true
c5f1742476911c4d4f75f2cf598a8245b44a9cbe
PHP
wasiseal/iLearn_iSearch_API
/refreshDepartPage.php
UTF-8
7,471
2.65625
3
[]
no_license
<?php //////////////////////////////////////// //refreshDepartPage.php // //1.return string of the department page // //#001 Phantom+Odie, 20130430, // For those departments come from computer list, cannot be edited or deleted. // flag=1 means manually // flag=2 means added by computer list // flag=3(1+2) means manually first, then added by computer list //////////////////////////////////////// define(DELAY_SEC, 3); define(GUID_LENGTH, 36); define(PARAMETER_ERROR, -2); function refreshDepartPage($link, $GUID) { if(!$link || strlen($GUID) != GUID_LENGTH) return PARAMETER_ERROR; define(PAGE_SIZE, 100); //page size //return value define(DB_ERROR, -1); //query $str_query; $result; //query result $row; //1 data array //depart $depID; $dep_name; //return page $return_string; //link if (!$link) //connect to server failure { sleep(DELAY_SEC); echo DB_ERROR; return; } //----- query ----- $str_query = " select * from department where GUID = '$GUID' order by flag"; if ($result = mysqli_query($link, $str_query)) { $depNumber = mysqli_num_rows($result); while ($row = mysqli_fetch_assoc($result)) { $depID[] = $row["depID"]; $dep_name[] =$row["dep_name"]; $dep_flag[] = $row["flag"]; //#001 add } mysqli_free_result($result); unset($row); } else //query failed { if ($link) { mysqli_close($link); $link = 0; } echo DB_ERROR; return; } //----- Print Department Pages ----- $return_string = ""; $return_string = $return_string . "<div class=\"toolMenu\">" . "<span class=\"paging\">"; $depart_page_default_no = 1; $depart_page_size = PAGE_SIZE; $depart_page_num = (int)(($depNumber - 1) / $depart_page_size + 1); $return_string = $return_string . "<input type=\"hidden\" id=depart_no value=$depNumber>" . "<input type=\"hidden\" name=depart_page_no value=1>" . "<input type=\"hidden\" name=depart_page_size value=" . $depart_page_size . ">"; if ($depart_page_num > 1) { for ($i = 0; $i < $depart_page_num; $i++) { $return_string = $return_string . "<span class=\"depart_page"; if ($i + 1 == $depart_page_default_no) $return_string = $return_string . " active"; $return_string = $return_string . "\" id=depart_page_begin_no_" . ($i + 1) . " OnClick=clickDepartPage(this," . ($i + 1) . ");>" . ($i + 1) . "</span>"; } } $return_string = $return_string . "</span>" . "<span id=\"createDepart\" class=\"btn new\" OnClick=\"newDepartFunc();\">新增部門</span>" . "</div>"; //----- Print Department Tables ----- if($depNumber == 0) { $return_string = $return_string . "<div id=\"departTableHead\">" . "<table class=\"report\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">" . "<colgroup>" . "<col class=\"rNameW\"/>" . "<col class=\"actW\"/>" . "</colgroup>" . "<tr>" . "<th>部門名稱</th>" . "<th>動作</th>" . "</tr>" . "<tr>" . "<td colspan=\"2\" class=\"empty\">目前沒有任何部門,請點選&quot;<a>新增部門</a>&quot;</td>" . "</tr>" . "</table>" . "</div>"; } else { $i = 0; $page_no = 1; $page_count = 0; while ($i < $depNumber) { //----- If No Data ----- if ($page_count == 0) { $return_string = $return_string . "<div id=\"depart_page" . $page_no . "\" "; if ($page_no == 1) $return_string = $return_string . "style=\"display:block;\""; else $return_string = $return_string . "style=\"display:none;\""; $return_string = $return_string . ">" . "<table class=\"report\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">" . "<colgroup>" . "<col class=\"rNameW\"/>" . "<col class=\"actW\"/>" . "</colgroup>" . "<tr>" . "<th>部門名稱</th>" . "<th>動作</th>" . "</tr>"; } if ($page_count < $depart_page_size) { $return_string = $return_string . "<tr>" . "<td id=\"" . $depID[$i] . "_dep\" class=\"rNameW\"><span class=\"rName fixWidth\">" . $dep_name[$i] . "</span></td>"; if ($dep_flag[$i] > 1) //#001, flag=2 and flag=3 ===> should not be edited or deleted $return_string = $return_string . "<td class=\"actW\">上傳自用戶端電腦清單,無法編輯</td>"; else $return_string = $return_string . "<td class=\"actW\"><a id=\"editDepart\" class=\"edit\" onClick=\"editDepartFunc($depID[$i], '$dep_name[$i]');\">編輯</a><a class=\"del\" onClick=\"deleteDepart(this, $depID[$i], '$dep_name[$i]');\">刪除</a></td>"; $return_string = $return_string . "</tr>"; $i++; $page_count++; if ($page_count == $depart_page_size) { $return_string = $return_string . "</table>" . "</div>\n"; $page_no++; $page_count = 0; } } } if ($page_count > 0) { $return_string = $return_string . "</table>" . "</div>\n"; } } //----- Print Department Pages ----- $return_string = $return_string . "<div class=\"toolMenu\">" . "<span class=\"paging\">"; if ($depart_page_num > 1) { for ($i = 0; $i < $depart_page_num; $i++) { $return_string = $return_string . "<span class=\"depart_page"; if ($i + 1 == $depart_page_default_no) $return_string = $return_string . " active"; $return_string = $return_string . "\" id=depart_page_end_no_" . ($i + 1) . " OnClick=clickDepartPage(this," . ($i + 1) . ");>" . ($i + 1) . "</span>"; } } $return_string = $return_string . "</span>" . "<span id=\"createDepart\" class=\"btn new\" OnClick=\"newDepartFunc();\">新增部門</span>" . "</div>"; echo $return_string; return; } ?>
true
1aa8accec2759ec09276e848776d9b4b976db7b1
PHP
mele1/music
/includes/classes/LineItem.php
UTF-8
471
3.515625
4
[]
no_license
<?php class LineItem { private $item; private $quantity; public function __construct($item, $quantity) { $this->item = $item; $this->quantity = $quantity; } public function __toString() { return "Item = ".$this->item.": Quantity = ".$this->quantity; } public function getQuantity() { return $this->quantity; } public function changeQuantity($value) { $this->quantity += $value; } public function getItem() { return $this->item; } } ?>
true
5711ef4901c54b972e968f1837492f297ee416c8
PHP
JsTimur/pingip
/src/Services/ViewService.php
UTF-8
348
2.671875
3
[]
no_license
<?php namespace App\Services; class ViewService { private $path; public function __construct() { $this->path = dirname(__DIR__, 2).'/views/'; } public function show($template = "index", $data = []) { if (count($data)>0) { extract($data); } return require_once($this->path.$template.'.php'); } }
true
d63a0510e811adacfea7417f51efc1c950322a17
PHP
edg2s/PHPDOM
/src/Element/HTML/HTMLMetaElement.php
UTF-8
1,597
3
3
[ "MIT" ]
permissive
<?php namespace Rowbot\DOM\Element\HTML; /** * Represents the HTML <meta> element. * * @see https://html.spec.whatwg.org/#the-meta-element * * @property string $content Reflects the value of the HTML content attribute. * Contains the value part of a name => value pair when the name attribute * is present. * * @property string $httpEquiv Reflects the value of the HTML http-equiv * attribute. * * @property string $name Reflects the value of the HTML name attribute. */ class HTMLMetaElement extends HTMLElement { protected function __construct() { parent::__construct(); } public function __get(string $name) { switch ($name) { case 'content': return $this->reflectStringAttributeValue($name); case 'httpEquiv': return $this->reflectStringAttributeValue('http-equiv'); case 'name': return $this->reflectStringAttributeValue($name); default: return parent::__get($name); } } public function __set(string $name, $value) { switch ($name) { case 'content': $this->attributeList->setAttrValue($name, $value); break; case 'httpEquiv': $this->attributeList->setAttrValue('http-equiv', $value); break; case 'name': $this->attributeList->setAttrValue($name, $value); break; default: parent::__set($name, $value); } } }
true
2430186a2e16f3b110d1d42471646d01d239cf85
PHP
hirdeshvishwdewa/eexam
/editProfile.php
UTF-8
1,758
2.53125
3
[]
no_license
<?php if (session_start() && !(isset ($_SESSION['pass']) && isset ($_SESSION['username']))) { header("Location: login.php"); } else { require "connection.php"; $username=$_GET["username"]; $sql="SELECT username,name,result,semester,enrollment,email,branch,mobno FROM users WHERE username='$username'"; $result=mysql_query($sql) or die(mysql_error()); $found=mysql_fetch_assoc($result); $foundUserName=$found['username']; $result=$found['result']; $name=$found['name']; $semester=$found['semester']; $enroll=$found['enrollment']; $email=$found['email']; $branch=$found['branch']; $mobno=$found['mobno']; echo "<form method=\"POST\" action=\"saveProfile.php\"> <input type=\"hidden\" value=\"".$username."\" name=\"username\"/> <input type=\"submit\" style=\"height:40px; background-color:green; color:white; width:80px; text-shadow:1px 1px 1px white; box-shadow:5px 5px 30px grey; -moz-box-shadow:5px 5px 30px grey; border-radius:10px;\" value=\"Done\"> <table cellspacing=\"5px\" cellpadding=\"5px\"> <tr><td><b style=\"color:green;\">Name</b></td><td><input name=\"txtName\" type=\"text\" value=\"".$name."\" /></td></tr> <tr><td><b style=\"color:green;\">Branch</b></td><td><input type=\"text\" name=\"txtBranch\" value=\"".$branch."\"</td></tr> <tr><td><b style=\"color:green;\">Semester</b></td><td><input type=\"text\" name=\"txtSem\" value=\"".$semester."\"</td></tr> <tr><td><b style=\"color:green;\">Email Id</b></td><td><input type=\"text\" name=\"txtEmail\" value=\"".$email."\"</td></tr> <tr><td><b style=\"color:green;\">Mobile Number</b></td><td><input type=\"text\" name=\"txtMobNo\" value=\"".$mobno."\"</td></tr> </table> </form>"; } mysql_close($dbc); ?>
true
1eb22de6a75690e8164519812732ed76b5c2fa91
PHP
aminemouloud/projet_s6_symfony
/src/DataFixtures/UserFixture.php
UTF-8
7,296
2.578125
3
[]
no_license
<?php namespace App\DataFixtures; use App\Entity\Etudiant; use App\Entity\Fichepedago; use App\Entity\UE; use App\Entity\Parcours; use App\Entity\Semestre; use App\Entity\User; use Doctrine\Bundle\FixturesBundle\Fixture; use Doctrine\Persistence\ObjectManager; use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface; class UserFixture extends Fixture { private $encoder ; public function __construct(UserPasswordEncoderInterface $encoder){ $this->encoder=$encoder; } public function load(ObjectManager $manager) { /* $user= new User(); $user->setIdUtilisateur('admin1'); $user->setPassword($this->encoder->encodePassword($user,'0000')); $user->setRoles( ['ROLE_USER']); $manager->persist($user); $manager->flush();*/ //instance de user responsable $user3= new User(); $user3->setIdUtilisateur('responsable1'); $user3->setPassword($this->encoder->encodePassword($user3,'2222')); $user3->setRoles( ['ROLE_RESPONSABLE']); //instance de user secretaire $user4= new User(); $user4->setIdUtilisateur('secretaire1'); $user4->setPassword($this->encoder->encodePassword($user4,'3333')); $user4->setRoles( ['ROLE_SECRETAIRE']); //instance de user etudiant $user2= new User(); $user2->setIdUtilisateur('etudiant1'); $user2->setPassword($this->encoder->encodePassword($user2,'1111')); $user2->setRoles( ['ROLE_ETUDIANT']); //instance de semestre $debut= new \DateTime('2020-09-01'); $fin= new \DateTime('2021-01-01'); $semestre= new Semestre(); $semestre->setNumSemestre('1'); $semestre->setDebut($debut); $semestre->setFin($fin); //instance de semestre 2 $debut= new \DateTime('2021-01-01'); $fin= new \DateTime('2021-06-01'); $semestre2= new Semestre(); $semestre2->setNumSemestre('2'); $semestre2->setDebut($debut); $semestre2->setFin($fin); //instance de etudiant $etudiant=new Etudiant(); $etudiant->setAdresse("rueoorleans"); $etudiant->setAjac(false); $etudiant->setDNN(new \DateTime('1999-01-01')); $etudiant->setEmail("amine@hotmail.Fr"); $etudiant->setNom("mouloud"); $etudiant->setNumEtudiant("2185765"); $etudiant->setPrenom("amine"); $etudiant->setRedoublant(false); $etudiant->setRSE(false); $etudiant->setSemestreObtenu("1 2 3 4 5 "); $etudiant->setTiersTemps(false); $etudiant->setUtilisateur($user2->getIdUtilisateur()); //instance de parcours miage SEM1 $parcours1S1= new Parcours(); $parcours1S1->setSemestre($semestre->getNumSemestre()); $parcours1S1->setNomParcours('MIAGE'); //PARCOURS MIAGE SEMESTRE 2 $parcours1S2= new Parcours(); $parcours1S2->setSemestre($semestre2->getNumSemestre()); $parcours1S2->setNomParcours('MIAGE'); //PARCOURS INGE SEMESTRE 1 $parcours2S1= new Parcours(); $parcours2S1->setSemestre($semestre->getNumSemestre()); $parcours2S1->setNomParcours('INGE'); //PARCOURS INGE SEMESTRE 2 $parcours2S2= new Parcours(); $parcours2S2->setSemestre($semestre2->getNumSemestre()); $parcours2S2->setNomParcours('INGE'); //instance de fiche Pedago $fichePedago= new Fichepedago(); $fichePedago->setSemestre($semestre->getNumSemestre()); $fichePedago->setEtudiant($etudiant->getNumEtudiant()); $fichePedago->setParcours($parcours1S1->getNomParcours()); $fichePedago->setAnnee('2020'); $fichePedago->setRempli(true); $fichePedago->setTransmise(false); $fichePedago->setValide(false); //instance de UE parcours miage //ue miage s1 $ue= new UE(); $ue->setParcours($parcours1S1->getNomParcours()); $ue->setSemestre($semestre->getNumSemestre()); $ue->setCodeUe('javaS5'); $ue->setNomUe('prog avancee java'); $ue->setEcts('4'); //ue1 miage s1 $ue1= new UE(); $ue1->setParcours($parcours1S1->getNomParcours()); $ue1->setSemestre($semestre->getNumSemestre()); $ue1->setCodeUe('COMPT_GEST'); $ue1->setNomUe('comptabilite et gestion'); $ue1->setEcts('3'); //ue3 miage s1 $ue3= new UE(); $ue3->setParcours($parcours1S1->getNomParcours()); $ue3->setSemestre($semestre->getNumSemestre()); $ue3->setCodeUe('SI S5'); $ue3->setNomUe('systeme d_information'); $ue3->setEcts('5'); // UE4 MIAGE S2 $ue4= new UE(); $ue4->setParcours($parcours1S2->getNomParcours()); $ue4->setSemestre($semestre2->getNumSemestre()); $ue4->setCodeUe('ProgNT'); $ue4->setNomUe('programmation n_tiers'); $ue4->setEcts('6'); // UE5 MIAGE S2 $ue5= new UE(); $ue5->setParcours($parcours1S2->getNomParcours()); $ue5->setSemestre($semestre2->getNumSemestre()); $ue5->setCodeUe('FMWEB_s5'); $ue5->setNomUe('FRAMEWORK WEB '); $ue5->setEcts('3'); // UE6 inge S1 $ue6= new UE(); $ue6->setParcours($parcours2S1->getNomParcours()); $ue6->setSemestre($semestre->getNumSemestre()); $ue6->setCodeUe('PROG C/C++'); $ue6->setNomUe('programmation c et c++ '); $ue6->setEcts('5'); // UE7 inge S1 $ue7= new UE(); $ue7->setParcours($parcours2S1->getNomParcours()); $ue7->setSemestre($semestre->getNumSemestre()); $ue7->setCodeUe('lang alg'); $ue7->setNomUe('langage algebriques'); $ue7->setEcts('4'); // UE8 inge S2 $ue8= new UE(); $ue8->setParcours($parcours2S2->getNomParcours()); $ue8->setSemestre($semestre2->getNumSemestre()); $ue8->setCodeUe('PROG logique'); $ue8->setNomUe('programmation logique '); $ue8->setEcts('5'); // UE9 inge S2 $ue9= new UE(); $ue9->setParcours($parcours2S2->getNomParcours()); $ue9->setSemestre($semestre2->getNumSemestre()); $ue9->setCodeUe('Proj_ING_s6'); $ue9->setNomUe('projet informatique INGE s6 '); $ue9->setEcts('5'); //$ue->setInscription(true); //$ue->setNote(13); //$ue2->setInscription(true); //$ue->setNote(12); $manager->persist($semestre); $manager->persist($user2); $manager->persist($user3); $manager->persist($user4); $manager->persist($etudiant); $manager->persist($fichePedago); $manager->persist($parcours1S1); $manager->persist($parcours1S2); $manager->persist($parcours2S1); $manager->persist($parcours2S2); $manager->persist($ue); $manager->persist($ue1); $manager->persist($ue3); $manager->persist($ue4); $manager->persist($ue5); $manager->persist($ue6); $manager->persist($ue7); $manager->persist($ue8); $manager->persist($ue9); $manager->persist($semestre2); $manager->flush(); } }
true
9ed268cd0d748a5fcd0fbe1a9528b397b4d02fba
PHP
Vieraw/TranslateApi
/TranslateApi/GoogleTranslate.php
UTF-8
3,009
2.59375
3
[]
no_license
<?php /** * Created by PhpStorm. * User: Vieraw * Date: 25.04.2018 * Time: 13:33 */ namespace TranslateApi; /** * Class GoogleTranslate * @package TranslateApi */ class GoogleTranslate extends AbstractTranslate { /** * GoogleTranslate constructor. * @param array $config * @throws TranslateException */ public function __construct (array $config = array ()) { if (!array_key_exists('url', $config)) { $config['url'] = 'https://translate.google.com/translate_a/single?client=at&dt=t&dt=ld&dt=qca&dt=rm&dt=bd&dj=1&hl=es-ES&ie=UTF-8&oe=UTF-8&inputm=2&otf=2&iid=1dd3b944-fa62-4b55-b330-74909a99969e'; } parent::__construct($config); } /** * @param string $subject * @param string $to * @param string $from * @return string * @throws TranslateException */ public function translate (string $subject, string $to, string $from = 'auto') : string { $request = $this->sendRequest($from, $to, $subject); return $this->getSentences('trans', $request); } /** * @param string $subject * @param string $to * @param string $from * @return string * @throws TranslateException */ public function translit (string $subject, string $to, string $from = 'auto') : string { $request = $this->sendRequest($from, $to, $subject); return $this->getSentences('src_translit', $request); } /** * @param string $from * @param string $to * @param string $subject * @return string * @throws TranslateException */ public function prepare (string $from, string $to, string $subject) : string { $params = array ( 'sl' => urlencode($from), 'tl' => urlencode($to), 'q' => urlencode($subject) ); if (\strlen($params['q']) >= 5000) { throw new TranslateException('GoogleTranslate: Maximum number of characters exceeded: 5000'); } $result = ''; foreach ($params as $key => $value) { $result .= $key . '=' . $value . '&'; } return $result; } /** * @param string $name * @param string $data * @return string */ protected function getSentences (string $name, string $data) : string { $sentences = ''; $array = json_decode($data, true); foreach ($array['sentences'] as $key => $value) { $sentences .= $value[$name] ?? ''; } return $sentences; } }
true
42c119b39a274ffb2fb012314ad9ad7793e66a10
PHP
mobasherfasihi/target-rule-system
/app/Traits/TargetRuleTrait.php
UTF-8
1,694
2.828125
3
[ "MIT" ]
permissive
<?php namespace App\Traits; use App\Models\PageTarget; use App\Models\TargetRule; use App\User; trait TargetRuleTrait { /** * Create Target Rules * * @param array $ruleData * @param \App\Models\PageTarget $pageTarget * @return void */ public function createTargetRule(array $ruleData, PageTarget $pageTarget) :void { $data = []; foreach($ruleData as $row) { $targetRule = new TargetRule(); $targetRule->instruction = $row['instruction']; $targetRule->rule = $row['rule']; $targetRule->pattern = $row['pattern']; $targetRule->regex_pattern = $this->regexPattern($row); array_push($data, $targetRule); } $pageTarget->targetRules()->delete(); $pageTarget->targetRules()->saveMany($data); } /** * Prepare regex pattern based on instruction, rule and pattern string * * @return string $regexStr */ private function regexPattern($data) { $instruction = match ($data['instruction']) { 'show' => '=', 'not_show' => '!' }; $data['pattern'] = str_replace('/', '\/', $data['pattern']); $regStr = match ($data['rule']) { 'contains' => '(?'.$instruction.'.*'.$data['pattern'].'.*)', 'specific_page' => match($instruction) { '!' => '^(?!'.$data['pattern'].')', '=' => '(?='.$data['pattern'].')' }, 'starting_with' => '^(?'.$instruction.$data['pattern'].')', 'ending_with' => '(?'.$instruction.$data['pattern'].'$)' }; return $regStr; } }
true
7b2b0b033a03e4b6459431b434d675286fa0bced
PHP
saad197/PHP-Art-Store
/includes/process-review.php
UTF-8
1,159
2.703125
3
[]
no_license
<?php require_once ('config.inc.php'); $comment = $_POST['message']; $star = $_POST['rat']; $paintingid = $_POST['paintingid']; echo "$comment"; echo '<br>'; echo "$star"; try { $conn = new PDO(DBCONNSTRING,DBUSER,DBPASS); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully"; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } try { $insertReviewSQL = "INSERT INTO `Reviews` (`PaintingID`, `ReviewDate`, `Rating`, `Comment`) VALUES ( $paintingid, NOW(), $star, '$comment')"; $insertReview = $conn->prepare($insertReviewSQL); $conn->exec($insertReviewSQL); //increment $insertReviewCountSQL = "UPDATE `Paintings` SET ReviewCount = ReviewCount + 1 WHERE PaintingID = $paintingid;"; $insertReviewCount = $conn->prepare($insertReviewSQL); $conn->exec($insertReviewCountSQL); echo "New records created successfully"; header("Location: ../works.php?PaintingID=" . $paintingid); } catch(PDOException $e) { echo $insertReviewSQL . "<br>" . $e->getMessage(); } ?>
true
994980b0b419c77da8b3b81ed06968df2942ad2c
PHP
chege-maina/php-erp
/includes/load_purchase_branch_filter.php
UTF-8
610
2.515625
3
[]
no_license
<?php include_once '../includes/dbconnect.php'; session_start(); if ($_SERVER["REQUEST_METHOD"] == "POST") { $branch = $_POST["branch"]; $query = "SELECT count(branch), branch FROM tbl_requisition WHERE status='approved' and branch= '$branch'"; $result = mysqli_query($conn, $query); $response = array(); while ($row = mysqli_fetch_assoc($result)) { array_push( $response, array( 'branch' => $row['branch'], 'count' => $row['count(branch)'] ) ); } echo json_encode($response); mysqli_close($conn); } else { $message = "Fields have no data..."; echo json_encode($message); }
true
99f9b2aac449a651f492d9c0a64ead2a5014770c
PHP
romulocriston/php7
/cursoemvideo/PHP/_aula10 referencia/exerc11referencia.php
UTF-8
2,128
3.09375
3
[ "MIT" ]
permissive
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="../_css/estilo.css"> <title>Function com referencia</title> </head> <body> <div id="cabecalho"> <p class="cab"> Curso de PHP - Rômulo Criston </p> </div> <div> <a class=voltar href="exerc11referencia.php" title="Iniciar"> <img src="../_css/_imagens/back2.png" width="80px" alt="Voltar"> </a> <br/><hr class="linha1"><br/> <form method="GET" action="exerc11referencia.php"> <fieldset><legend>Function SOMA</legend> <p><label for="num1">Número 1:</label> <input type="number" name="pNum1" id="num1" min="0" required autofocus></p> <p><label for="num2">Número 2:</label> <input type="number" name="pNum2" id="num2" min="0" required autofocus></p> </fieldset> <input type="submit" value="Calcular" class="btnvoltar"> </form> <?php $n1 = isset($_GET["pNum1"])?$_GET["pNum1"]:0; $n2 = isset($_GET["pNum2"])?$_GET["pNum2"]:0; echo "<br/>"; # 1 - FUNÇÃO QUE RETORNA VALOR function soma (&$num1,&$num2){ return $num1 + $num2; } echo "<p>A soma vale: "."<span class='foco'>".$res=soma($n1,$n2)."</span></p><br/>"; echo "FUNÇÃO COM PASSAGEM POR VALOR <br/>"; function teste ($x){ $x += 2; echo "X vale: $x <br/>"; } $a=20; teste($a); echo "A vale: $a <br/><br/>"; echo "FUNÇÃO COM PASSAGEM POR REFERENCIA <br/>"; # qualquer alteração em "x" vai alterar "a" function teste2 (&$x){ $x += 2; echo "X vale: $x <br/>"; } $a=20; teste2($a); echo "A vale: $a <br/><br/>"; ?> </div> </body> </html>
true
9a85c98b34b14fc7729546f5b2869121cffc0d11
PHP
jeffreywang1988/thinkphp-swoole-process
/application/Http/Middleware/ApiRequest.php
UTF-8
414
2.53125
3
[ "PHP-3.0", "Apache-2.0" ]
permissive
<?php namespace app\Http\Middleware; use think\facade\Env; use think\facade\Log; class ApiRequest { public $debug; public function __construct() { $this->debug = Env::get('api.HTTP_DEBUG_SWITCH'); } public function handle($request, \Closure $next) { $this->debug && Log::record('request:'); $this->debug && Log::record($request->param(),'info'); return $next($request); } }
true
66128be27cca802eb45cb3e9a037793c33232250
PHP
swissup/module-core
/Console/Command/ThemeCreate.php
UTF-8
4,843
2.578125
3
[]
no_license
<?php namespace Swissup\Core\Console\Command; use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Framework\Exception\FileSystemException; use Magento\Framework\Filesystem; use Swissup\Core\Console\Command\ThemeCreateCommand; class ThemeCreate { const THEME_COMPOSER_TEMPLATE = <<<EOT { "name": "{{THEME_PACKAGE_NAME}}", "type": "magento2-theme", "version": "1.0.0", "require": { "{{PARENT_THEME_PACKAGE_NAME}}": "*" }, "autoload": { "files": [ "registration.php" ] } } EOT; const THEME_REGISTRATION_TEMPLATE = <<<EOT <?php use \Magento\Framework\Component\ComponentRegistrar; ComponentRegistrar::register( ComponentRegistrar::THEME, '{{THEME_NAME}}', __DIR__ ); EOT; const THEME_XML = <<<EOT <?xml version="1.0"?> <theme xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Config/etc/theme.xsd"> <title>{{THEME_NAME}}</title> <parent>{{PARENT_THEME_NAME}}</parent> </theme> EOT; /** * @var Filesystem\Directory\ReadInterface */ private $appRead; /** * @var Filesystem\Directory\WriteInterface */ private $appWrite; /** * constructor. * * @param Filesystem $fs * @throws FileSystemException */ public function __construct(Filesystem $fs) { $this->appRead = $fs->getDirectoryRead(DirectoryList::APP); $this->appWrite = $fs->getDirectoryWrite(DirectoryList::APP); } /** * @param string $themeName * @return int * @throws FileSystemException */ public function generateRegistration(string $themeName): int { $destinationPath = $this->getThemePath($themeName); $content = self::THEME_REGISTRATION_TEMPLATE; $content = str_replace( '{{THEME_NAME}}', ThemeCreateCommand::SECTION . \Magento\Framework\Config\Theme::THEME_PATH_SEPARATOR . $themeName, $content ); return $this->appWrite->writeFile( $destinationPath . DIRECTORY_SEPARATOR . 'registration.php', $content ); } /** * * @param string $themeName * @return boolean */ public function isExist(string $themeName) { $path = $this->getThemePath($themeName); return $this->appWrite->isExist($path); } /** * @param string $themeName * @param string $parentThemeName * @return int * @throws FileSystemException */ public function generateThemeXml(string $themeName, string $parentThemeName): int { $content = self::THEME_XML; $content = str_replace( '{{THEME_NAME}}', str_replace('/', ' ', $themeName . ' theme'), $content ); $content = str_replace( '{{PARENT_THEME_NAME}}', $parentThemeName, $content ); $destinationPath = $this->getThemePath($themeName); return $this->appWrite->writeFile( $destinationPath . DIRECTORY_SEPARATOR . 'theme.xml', $content ); } /** * @param string $themeName * @param string $parentThemePackageName * @return int * @throws FileSystemException */ public function generateComposerJson(string $themeName, string $parentThemePackageName): int { // local/argento-stripes-custom // swissup/theme-frontend-argento-stripe $content = self::THEME_COMPOSER_TEMPLATE; $content = str_replace( '{{THEME_PACKAGE_NAME}}', strtolower($themeName), // strtolower($themeName) . '-custom', $content ); $content = str_replace( '{{PARENT_THEME_PACKAGE_NAME}}', $parentThemePackageName, $content ); $destinationPath = $this->getThemePath($themeName); return $this->appWrite->writeFile( $destinationPath . DIRECTORY_SEPARATOR . 'composer.json', $content ); } /** * @param string $themeName * @return int * @throws FileSystemException */ public function generateCustomCss(string $themeName): int { $content = '/* Autogenerated */'; $destinationPath = $this->getThemePath($themeName); return $this->appWrite->writeFile( $destinationPath . DIRECTORY_SEPARATOR . 'web/css/source/_argento_custom.less', $content ); } /** * @param $themeName * @return string */ protected function getThemePath($themeName): string { return $destinationPath = $this->appRead->getAbsolutePath( ThemeCreateCommand::THEME_DIR . DIRECTORY_SEPARATOR . $themeName ); } }
true
7f3b7df614b09d81e931cfc054249be8f1a042b6
PHP
melai-melai/php-console-games
/src/Engine.php
UTF-8
1,930
3.328125
3
[]
no_license
<?php namespace PhpConsoleGames\Engine; use function cli\line; use function cli\prompt; use function cli\choose; use function PhpConsoleGames\Games\HappyTicketGame\runTicketGame; use function PhpConsoleGames\Games\ParityGame\runParityGame; /** * Main scenario */ function run() { line("Hello, my friend! \n"); $answer = choose("Let's play? \n", $choices = 'yn', $default = 'n'); if ($answer === "n") { line("See you, my friend! \n"); exit; } line("I'm glad! \n"); $name = prompt("What is your name? \n", false, "Your name: "); line("Hello, my friend %s! \n", $name); line("I have two games for you, %s! \n", $name); line("[1] - Happy ticket game \n"); line("[2] - Parity \n"); $game = choose("What game do you want to play? \n", $choices = '12', $default = '1'); handleGame($game); $answer = choose("Do you want to repeat? \n", $choices = 'yn', $default = 'n'); if ($answer === "n") { line("See you, my friend! \n"); exit; } run(); } /** * Game handler * * @param string $gameNumber Game number (from list og games) */ function handleGame(string $gameNumber) { $gamesMapping = [ "1" => function () { return runTicketGame(); }, "2" => function () { return runParityGame(); } ]; if (array_key_exists($gameNumber, $gamesMapping)) { for ($i = 0; $i < 3; $i += 1) { [$question, $answer, $messages] = $gamesMapping[$gameNumber](); $userAnswer = choose($question, $choices = 'yn', $default = 'n'); if (($answer && ($userAnswer === "y")) || (!$answer && ($userAnswer === "n"))) { line($messages["correctly"]); } else { line($messages["wrong"]); } } } else { line("No, I don't have the game with number %s. \n", $gameNumber); } }
true
2ca244a15a2537d7e3cda84e365ea14b1ce0f185
PHP
bluegrass/blues
/src/Bluegrass/Blues/Component/Widget/Builder/WidgetBuilderInterface.php
UTF-8
410
2.59375
3
[]
no_license
<?php namespace Bluegrass\Blues\Component\Widget\Builder; use Bluegrass\Blues\Component\Widget\WidgetInterface; /** * Interfaz que deben implementar las clases encargadas de construir un modelo * para una vista a partir de un widget. * * @author gcaseres */ interface WidgetBuilderInterface { /** * Construye un widget * * @return WidgetInterface */ function build(); }
true
a35d9c529594acba9068e6ad78d47adb085c8960
PHP
gaua/design-patterns
/Impl/Structural/Composite/Printer.php
UTF-8
1,018
3.265625
3
[]
no_license
<?php declare(strict_types = 1); namespace Impl\Structural\Composite; class Printer { const TAB = "&nbsp&nbsp&nbsp&nbsp"; public function print(ToDo $item) : void { $this->printWithSpace($item); } private function printWithSpace(ToDo $item, string $space = "", int $level = 0) : void { if ($item->getComposite()) { if ($level > 0) { $this->printRow($item, $space); $space .= static::TAB; } /** @var ListItem $item */ foreach ($item->getItems() as $loopItem) { $this->printWithSpace($loopItem, $space, $level + 1); } } else { $this->printRow($item, $space); } } private function printRow(ToDo $item, string $space) : void { $row = $space . $item->getDescription(); if ($item->getDueDate()) { $row .= " due to " . $item->getDueDate()->format('Y-m-d'); } echo printbr($row); } }
true
9988de301a093285b59cdb93dd559fb070171825
PHP
zeroisstart/firetech
/backend/models/ResetPasswordForm.php
UTF-8
1,800
2.90625
3
[]
no_license
<?php /** * @Author: Wang chunsheng email:2192138785@qq.com * @Date: 2020-06-03 11:36:59 * @Last Modified by: Wang chunsheng email:2192138785@qq.com * @Last Modified time: 2020-06-03 11:40:21 */ namespace backend\models; use yii\base\InvalidArgumentException; use yii\base\Model; use common\models\User; /** * Password reset form */ class ResetPasswordForm extends Model { public $password; /** * @var \common\models\User */ private $_user; /** * Creates a form model given a token. * * @param string $token * @param array $config name-value pairs that will be used to initialize the object properties * @throws InvalidArgumentException if token is empty or not valid */ public function __construct($token, $config = []) { if (empty($token) || !is_string($token)) { throw new InvalidArgumentException('密码重置令牌不能为空。'); } $this->_user = User::findByPasswordResetToken($token); if (!$this->_user) { throw new InvalidArgumentException('密码重置令牌错误或者已过期'); } parent::__construct($config); } /** * {@inheritdoc} */ public function rules() { return [ ['password', 'required'], ['password', 'string', 'min' => 6], ]; } /** * Resets password. * * @return bool if password was reset. */ public function resetPassword() { $user = $this->_user; $user->setPassword($this->password); $user->generatePasswordResetToken(); return $user->save(false); } /** * {@inheritdoc} */ public function attributeLabels() { return [ 'password' => '新的密码', ]; } }
true
8f2e6187195bb5e6e908596d38e14d3afe6164bc
PHP
sslab-gatech/autofz
/docker/benchmark/seeds/fuzzer-test-suite/php-fuzz-parser/error_reporting10.phpt
UTF-8
350
2.765625
3
[ "MIT" ]
permissive
<?php error_reporting(E_ALL); function make_exception() { @$blah; error_reporting(0); throw new Exception(); } try { @make_exception(); } catch (Exception $e) {} var_dump(error_reporting()); error_reporting(E_ALL&~E_NOTICE); try { @make_exception(); } catch (Exception $e) {} var_dump(error_reporting()); echo "Done\n"; ?>
true
96b20e4d9be24c15f5758f1996f2162d9c0a2f98
PHP
kurnikarz/Biskupiec
/src/Entity/PsEmployeeSession.php
UTF-8
1,320
2.640625
3
[]
no_license
<?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * PsEmployeeSession * * @ORM\Table(name="ps_employee_session") * @ORM\Entity */ class PsEmployeeSession { /** * @var int * * @ORM\Column(name="id_employee_session", type="integer", nullable=false, options={"unsigned"=true}) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $idEmployeeSession; /** * @var int|null * * @ORM\Column(name="id_employee", type="integer", nullable=true, options={"default"="NULL","unsigned"=true}) */ private $idEmployee = NULL; /** * @var string|null * * @ORM\Column(name="token", type="string", length=40, nullable=true, options={"default"="NULL"}) */ private $token = 'NULL'; public function getIdEmployeeSession(): ?int { return $this->idEmployeeSession; } public function getIdEmployee(): ?int { return $this->idEmployee; } public function setIdEmployee(?int $idEmployee): self { $this->idEmployee = $idEmployee; return $this; } public function getToken(): ?string { return $this->token; } public function setToken(?string $token): self { $this->token = $token; return $this; } }
true
15a27d78b7f9978606ea16f7a08118c813c9f5bb
PHP
buttjer/Hopkins
/lib.php
UTF-8
3,225
2.609375
3
[]
no_license
<?php class Lib { public $options; protected $routes; function __construct($options = array()) { $this->options = array( 'root' => dirname(__FILE__) ); foreach ($options as $key => $value) { $this->options[$key] = $value; } $path = scandir(realpath($this->options['root'] . '/controller/')); foreach ($path as $dir) { if ($dir != '.' && $dir != '..') { $dir = substr($dir, 0, strpos($dir, '.')); $this->register($dir); } } set_error_handler(array($this, 'handle_error')); } function handle_error($errno, $errstr, $errfile, $errline) { if (!(error_reporting() & $errno)) { return; } print "Unknown error type: [$errno] $errstr in file $errfile on line $errline<br />\n"; return true; } function show_404() { header("HTTP/1.0 404 Not Found"); $this->render('404'); die(); } function register($route) { $this->routes[$route] = $route; } function run() { global $global; header("Content-type: text/html; charset={utf-8}"); if (!$global['path']) { include(realpath($this->options['root'] . '/controller/'. $global['index'] . '.php')); $reflection = new ReflectionClass($global['index']); return $reflection->newInstance($this->options, NULL); } else { $path = explode('/', $global['path']); foreach ($this->routes as $route => $class) { if ($route == $path[0]) { $args = array_slice($path, 1); include(realpath($this->options['root'] . '/controller/'. $class . '.php')); $reflection = new ReflectionClass($class); return $reflection->newInstance($this->options, $args); } } } return $this->show_404(); } } class Contr { public $options; function __construct($opt, $args = array()) { $this->options = $opt; if ($this->load()) { if (!empty($args)) { if (method_exists($this, $args[0])) { $ref = new ReflectionMethod(get_class($this), $args[0]); unset($args[0]); return $ref->invokeArgs($this, $args); } } else { return $this->index(); } } else { $this->show_403(); } $this->show_404(); } function helper($name) { include(realpath($this->options['root'] . '/helper/'. $name . '.php')); } function load() { return true; } function index() { $this->show_404(); } function show_404() { $this->render('404'); die(); } function show_403() { $this->render('403'); die(); } function render() { $args = func_get_args(); if (count($args) <= 1) { $files[] = $args[0]; } else { $data = $args[0]; extract($data); unset($args[0]); $files = $args; } foreach ($files as $file) { $view[] = realpath($this->options['root'] . '/views/' . $file . '.php'); } ob_start(); include($view[0]); print ob_get_clean(); } function location($path = '') { global $global; header('Location: '. $global["basepath"] . $path); return true; } }
true