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
74435590f7a1aaf71069e68527c15048c70965c2
PHP
masilio/felix90-eng.github.io
/src/Entity/Position.php
UTF-8
3,980
2.71875
3
[]
no_license
<?php namespace App\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass="App\Repository\PositionRepository") * @ORM\Table(name="positions") */ class Position { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=200) */ private $position; /** * @ORM\ManyToOne(targetEntity="App\Entity\Level", inversedBy="position") */ private $level; /** * @ORM\OneToMany(targetEntity="App\Entity\Staff", mappedBy="designation") */ private $staff; /** * @ORM\OneToMany(targetEntity="App\Entity\Vehicle", mappedBy="position") */ private $vehicles; /** * @ORM\OneToMany(targetEntity="App\Entity\Mission", mappedBy="position") */ private $missions; public function __construct() { $this->staff = new ArrayCollection(); $this->vehicles = new ArrayCollection(); $this->missions = new ArrayCollection(); } public function getId(): ?int { return $this->id; } public function getPosition(): ?string { return $this->position; } public function setPosition(string $position): self { $this->position = $position; return $this; } public function getLevel(): ?Level { return $this->level; } public function setLevel(?Level $level): self { $this->level = $level; return $this; } /** * @return Collection|Staff[] */ public function getStaff(): Collection { return $this->staff; } public function addStaff(Staff $staff): self { if (!$this->staff->contains($staff)) { $this->staff[] = $staff; $staff->setDesignation($this); } return $this; } public function removeStaff(Staff $staff): self { if ($this->staff->contains($staff)) { $this->staff->removeElement($staff); // set the owning side to null (unless already changed) if ($staff->getDesignation() === $this) { $staff->setDesignation(null); } } return $this; } public function __toString(){ return (String)$this->position; } /** * @return Collection|Vehicle[] */ public function getVehicles(): Collection { return $this->vehicles; } public function addVehicle(Vehicle $vehicle): self { if (!$this->vehicles->contains($vehicle)) { $this->vehicles[] = $vehicle; $vehicle->setPosition($this); } return $this; } public function removeVehicle(Vehicle $vehicle): self { if ($this->vehicles->contains($vehicle)) { $this->vehicles->removeElement($vehicle); // set the owning side to null (unless already changed) if ($vehicle->getPosition() === $this) { $vehicle->setPosition(null); } } return $this; } /** * @return Collection|Mission[] */ public function getMissions(): Collection { return $this->missions; } public function addMission(Mission $mission): self { if (!$this->missions->contains($mission)) { $this->missions[] = $mission; $mission->setPosition($this); } return $this; } public function removeMission(Mission $mission): self { if ($this->missions->contains($mission)) { $this->missions->removeElement($mission); // set the owning side to null (unless already changed) if ($mission->getPosition() === $this) { $mission->setPosition(null); } } return $this; } }
true
ffe20c973ed2cec6cc05e1e0cc1d1c00c5d857a2
PHP
gapoorva/apoorvagupta.com
/edit.php
UTF-8
2,894
2.640625
3
[]
no_license
<?php include 'section.php'; $note = null; $is_admin_mode = admin($conn, $note); $page = $_REQUEST['page']; if(!$is_admin_mode || (is_null($page) && $_SERVER['REQUEST_METHOD'] != 'POST')) { header("Location: index.php"); die(); } if($_SERVER['REQUEST_METHOD'] == 'POST') { $handle = fopen($_REQUEST['filename'], 'w') or die("unable to update: error opening file"); if(fwrite($handle, $_REQUEST['new_content']) === FALSE) { echo $_REQUEST['filename']; die("unable to update: did not write to file. SSH to server and resolve issue"); } fclose($handle); } ?> <!DOCTYPE html> <html> <!-- ALL HEAD CONTENT HERE --> <?php head_section($is_admin_mode);?> <body> <!-- FULL SCREEN CONTAINER --> <div class="container-fluid"> <!-- PAGE TITLE --> <?php page_title("Edit", ucwords(str_replace("_", " ", $page)), $is_admin_mode);?> <!-- PAGE CONTENT --> <div class="row"> <!-- MAIN CONTENT --> <div class="col-xs-offset-1 col-xs-10 "> <form id="edit" method="POST" action="edit.php"> <?php if($_SERVER['REQUEST_METHOD'] == 'POST') { echo '<p class="lead text-success">Successfully Updated Content!</p>'; } ?> <p class="lead"> Content from <?php echo $page." ("; echo "<a href='". $page . ".php'>Return to page view</a>)"; ?>:</p> <?php $filename = ""; if($_SERVER['REQUEST_METHOD'] != 'POST') { $stmt = $conn->prepare("SELECT filename FROM content WHERE pagename=?"); $stmt->bind_param("s", $page); $stmt->execute(); $stmt->bind_result($filename); if(!$stmt->fetch()) { die("FILENAME ". $filename . " NOT FOUND"); } } else { $filename = $_REQUEST['filename']; } ?> <code><textarea class="form-control" rows="20" name="new_content"><?php include $filename;?></textarea></code> <?php echo "<input type='hidden' name='filename' value='{$filename}'/>"; echo "<input type='hidden' name='page' value='{$page}'/>"; ?> <div class="form-group"> <button type="submit" class="btn btn-primary form-control">Save Changes</button> </div> <div class="form-group"> <a class="form-control btn btn-default" href="index.php">Cancel</a> </div> </form> <hr style="border-color: black"> <p class="lead">Preview:</p> <hr style="border-color: black"> <?php if($is_admin_mode) {$note->render();}?> </div> </div> <div class="row"> <div class="col-md-7 col-xs-offset-1 col-xs-11 "> <div id="preview"> <?php include $filename; ?> </div> </div> </div> <!-- FOOTER --> <?php $this_page = strlen($_SERVER['QUERY_STRING']) ? basename($_SERVER['PHP_SELF'])."?".$_SERVER['QUERY_STRING'] : basename($_SERVER['PHP_SELF']); footer_section($this_page); ?> </div> </body> </html>
true
28ce0d663bd8240997071288c128e12a0284d21c
PHP
Cowscript/CowScriptPHP
/Reference/ReferenceHandler.php
UTF-8
483
3
3
[]
no_license
<?php namespace Script\Reference; use Script\Exception\ScriptRuntimeException; use Script\TypeHandler; class ReferenceHandler{ public static function toReference($value){ if(!($value instanceof IReference)) throw new ScriptRuntimeException("Cant convert ".TypeHandler::type($value)." is not a reference"); return $value; } public static function getValue($value){ if($value instanceof IReference) return $value->getValue(); return $value; } }
true
5be0e83a72fb4c9d3d3742526e48b722846acadb
PHP
benoitdavidfr/geovect
/coordsys/json.php
UTF-8
3,668
2.71875
3
[]
no_license
<?php /*PhpDoc: name: json.php title: json.php - API JSON d'export du registre des CRS et de calcul de chgt de coords includes: [ full.inc.php ] doc: | Sans paramètre: exporte le registre /schema - exporte le schéma JSON du registre /EPSG - exporte le sous-registre EPSG /EPSG:xxx - exporte la définition d'un code EPSG /EPSG:xxx/ddd,ddd/geo - calcule les coords. géo. des coord. projetées fournies /EPSG:xxx/ddd,ddd/proj - calcule les coords. projetées des coord. géo. fournies /EPSG:xxx/ddd,ddd/chg/EPSG:yyyy - calcule les coords dans le CRS yyyy journal: | 24/3/2019: - création */ require_once __DIR__.'/full.inc.php'; header('Content-type: application/json'); //echo json_encode($_SERVER); if (!isset($_SERVER['PATH_INFO'])) die(json_encode(CRS::registre(), JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE)."\n"); if ($_SERVER['PATH_INFO'] == '/schema') die(json_encode(CRS::schema(), JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE)."\n"); function datum(string $id): array { return array_merge(['id'=> $id], CRS::registre('DATUM', $id)); } function spheroid(string $id): array { return array_merge(['id'=> $id], CRS::registre('ELLIPSOID', $id)); } // sous-registre EPSG if ($_SERVER['PATH_INFO'] == '/EPSG') { $result = [ 'title'=> "Sous-registre EPSG du registre des CRS", 'epsg'=> [], ]; foreach (CRS::registre('EPSG') as $epsg => $crsId) { $crsId2 = is_array($crsId) ? $crsId['latLon'] : $crsId; $crsRec = CRS::registre('CRS', $crsId2); if (isset($crsRec['BASEGEODCRS'])) { $crsRec['BASEGEODCRS'] = CRS::registre('CRS', $crsRec['BASEGEODCRS']); $crsRec['BASEGEODCRS']['DATUM'] = datum($crsRec['BASEGEODCRS']['DATUM']); $crsRec['BASEGEODCRS']['DATUM']['ELLIPSOID'] = spheroid($crsRec['BASEGEODCRS']['DATUM']['ELLIPSOID']); } else { $crsRec['DATUM'] = datum($crsRec['DATUM']); $crsRec['DATUM']['ELLIPSOID'] = spheroid($crsRec['DATUM']['ELLIPSOID']); } $result['epsg'][$epsg] = is_array($crsId) ? ['latLon'=> $crsRec] : $crsRec; } die(json_encode($result, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE)."\n"); } // un code EPSG if (preg_match('!^/EPSG:(\d+)$!', $_SERVER['PATH_INFO'], $matches)) { $epsg = (int)$matches[1]; $crs = CRS::registre('EPSG', $epsg); $crs = CRS::registre('CRS', $crs); if (isset($crs['BASEGEODCRS'])) { $crs['BASEGEODCRS'] = CRS::registre('CRS', $crs['BASEGEODCRS']); $crs['BASEGEODCRS']['DATUM'] = datum($crs['BASEGEODCRS']['DATUM']); $crs['BASEGEODCRS']['DATUM']['ELLIPSOID'] = spheroid($crs['BASEGEODCRS']['DATUM']['ELLIPSOID']); } else { $crs['DATUM'] = datum($crs['DATUM']); $crs['DATUM']['ELLIPSOID'] = spheroid($crs['DATUM']['ELLIPSOID']); } die(json_encode($crs, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE)."\n"); } // proj() ou geo() if (preg_match('!^/EPSG:(\d+)/([\d.,]+)/(proj|geo)$!', $_SERVER['PATH_INFO'], $matches)) { $epsg = (int)$matches[1]; $pos = explode(',', $matches[2]); $op = $matches[3]; $crs = CRS::EPSG($epsg); die(json_encode($crs->$op($pos), JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE)."\n"); } // chg() if (preg_match('!^/EPSG:(\d+)/([\d.,]+)/chg/EPSG:([^/]+)$!', $_SERVER['PATH_INFO'], $matches)) { $crs1 = CRS::EPSG($matches[1]); $pos = explode(',', $matches[2]); $crs2 = CRS::EPSG($matches[3]); die(json_encode($crs1->chg($pos, $crs2), JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE)."\n"); } die(json_encode('ERREUR, paramètres non reconnus', JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE)."\n");
true
d0378cb49f836ff5a303b11a0725188e28960a6f
PHP
koksztul/culinary_website
/recipe.php
UTF-8
5,822
2.546875
3
[]
no_license
<!DOCTYPE html> <html lang="pl-PL"> <head> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="./css/style1.css"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.9.0/css/all.css" integrity="sha384-i1LQnF23gykqWXg6jxC2ZbCbUMxyw5gLZY6UiUS98LYV5unm8GWmfkIS6jqJfb4E" crossorigin="anonymous"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=PT+Sans"> </head> <body> <?php session_start(); if ((isset($_SESSION['zalogowany'])) && ($_SESSION['zalogowany']==true)) { ?> <div id="menu"> <ul> <li> <a href="index.php">logo</a> </li> <li> <a href="recipe.php">Przepisy</a> </li> <li> <a href="quiz.php">Quiz</a> </li> <li> <a href="panel.php"><?php echo $_SESSION['user'] ?></a> </li> <li> <a href="logout.php">Wyloguj się!</a> </li> </ul> </div> <?php } else { ?> <div id="menu"> <ul> <li> <a href="index.php">logo</a> </li> <li> <a href="recipe.php">Przepisy</a> </li> <li> <a href="quiz.php">Quiz</a> </li> <li> <a href="register.php">Register</a> </li> <li> <a href="login.php">Login</a> </li> </ul> </div> <?php } ?> <div id="examform"> <?php require_once "connect.php"; // Create connection $conn = new mysqli($host, $db_user, $db_password, $db_name); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } if(isset($_SESSION['user'])) { $login = $_SESSION['user']; $rezultat = $conn->query("SELECT id_user FROM users WHERE user='$login'"); $row1 = $rezultat->fetch_assoc(); } $result = $conn->query("SET NAMES utf8"); $sql = "SELECT * FROM przepisy"; $sql2 = "SELECT * FROM pyt"; $zapytanie=mysqli_query($conn,$sql2); $rowcount=mysqli_num_rows($zapytanie); $result = $conn->query($sql); $licz=1; if(isset($_POST['id_przep'], $_POST['id_user'], $_POST['submit'])){ $polaczenie = @new mysqli($host, $db_user, $db_password, $db_name); $id_user = $_POST['id_user']; $id_przep = $_POST['id_przep']; $rezultat2 = $polaczenie->query("SELECT * FROM przep_users WHERE (id_przep='$id_przep' AND id_user='$id_user')"); $czyzapisany = $rezultat2->num_rows; if($czyzapisany > 0) { $msg = "Zapisaleś już ten przepis"; } else{ $rezultat = $polaczenie->query("INSERT INTO przep_users VALUES (NULL, '$id_user', '$id_przep')"); $msg = "Zapisano przepis na twoim koncie"; } } if(isset($msg)) { echo '<br><h3>'.$msg.'</h3>'; } if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { // echo "id: " . $row["id"]. " - Pytanie: " . $row["pytanie"]. " " . $row["odpa"]. "<br>"; $skladniki = $row["skladniki"]; $pieces = explode(",", $skladniki); $ile = count($pieces); $opis = $row["przygotowanie"]; $opis2 = explode(";", $opis); $ile2 = count($opis2); ?> <form action="" method="post"> <div class="row"> <h3><?php echo $licz.'. '.$row["nazwa"]; ?></h3> <div class="column"> <br><img src="img/<?php echo $row["img"]; ?>.jpg" width="300" height="300" alt="zdjecie"> <input type="hidden" name="id_przep" value="<?php echo $row["id_przep"]; ?>"> <input type="hidden" name="id_user" value="<?php echo $row1['id_user']; ?>"> </div> <div class="column"> <p>Składniki</p> <ul> <?php for ($i = 0; $i < $ile; $i++) { echo "<li>".$pieces[$i]."</li>"; } ?> </ul> </div> <div class="column"> <p>Opis przygotwania</p> <ul> <?php for ($i = 0; $i < $ile2; $i++) { echo "<li>".$opis2[$i]."</li>"; } ?> </ul> </div> <?php if ((isset($_SESSION['zalogowany'])) && ($_SESSION['zalogowany']==true)){ ?> <br><button class="button" name="submit" value="Sprawdź">Zapisz Przepis</button> <?php } ?> </div> </div> </form> <?php $licz++; } ?> <?php } else { echo "0 results"; } $conn->close(); ?> </div> </form> </div> <div class="big-foot"> <div class="footer-social-icons"> <ul> <li><a href="#" target="blank"><i class="fab fa-facebook"></i></a></li> <li><a href="#" target="blank"><i class="fab fa-twitter"></i></a></li> <li><a href="#" target="blank"><i class="fab fa-google-plus"></i></a></li> <li><a href="#" target="blank"><i class="fab fa-youtube"></i></a></li> </ul> </div> <div class="footer-menu"> <ul> <li><a href="#">Home</a></li> <li><a href="#">About us</a></li> <li><a href="#">Services</a></li> <li><a href="#">Products</a></li> <li><a href="#">Contact us</a></li> </ul> </div> </div> </body> </html>
true
ab5f32ba17e863b4481b4e746ca4377b825622ae
PHP
yugeta/framework
/system/common/php/cookie.php
UTF-8
659
2.796875
3
[]
no_license
<? //---------- //Cookie処理 //---------- class COOKIE{ //Cookie(保持時間) public $id = 'fw'; /* public $d = 30; public $h = 0; public $m = 0; public $s = 0; */ //書き込み※[time:保持時間は秒で指定] function write($id='',$data ,$sec){ if(!$id){$id = $this->id;} $time = (time() + ($sec*1) ); setcookie($id , $data , $time , "/"); } //読み込み function read($id=''){ if(!$id){$id = $this->id;} return $_COOKIE[$id]; } //削除 function clear($id=''){ if(!$id){$id = $this->id;} setcookie($id,'',-1,'/'); } }
true
d1ae17bb973f52d453d7d6230e8a00e491f27f73
PHP
Cassini17/laralog
/app/Http/Controllers/SessionsController.php
UTF-8
823
2.640625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class SessionsController extends Controller { // avoid login twice public function __construct() { // $this->middleware('guest',['except'=>'destroy']); } // Sign-in page public function create() { auth()->logout(); return view('sessions.create'); } // deal with sign-in request public function store() { // attempt to authenticate the user // dd(request(['email','password'])); if(! auth()->attempt(request(['email','password']))) { return back(); } session()->flash('message','Sign in successfully!'); return redirect()->home(); } // deal with sign-out request public function destroy() { auth()->logout(); session()->flash('message','Sign out successfully!'); return redirect()->home(); } }
true
d9bdbd478f98e53ac7799fcf6711ae4dac4a2d49
PHP
DaveWishesHe/adventofcode-solutions
/DaveWishesHe/06/6-1.php
UTF-8
964
2.875
3
[]
no_license
<?php $contents = str_replace("turn ", "", file_get_contents("6.input")); $instructions = array_filter(explode("\n",$contents)); $row = ""; while (strlen($row) < 1000) { $row .= "0"; } $grid = array_pad(array(), 1000, $row); foreach ($instructions as $instruction) { list($state, $from, $through, $to) = explode(" ", $instruction); list($from_x, $from_y) = explode(",", $from); list($to_x, $to_y) = explode(",", $to); foreach ($grid as $y => $row) { if ($y < $from_y) { continue; } $i = $from_x; while ($i <= $to_x) { if ($state == "on" || $state == "off") { $row[$i] = ($state == "on" ? "1" : "0"); } else { $row[$i] = ($row[$i] == "0") ? "1" : "0"; } $i++; } $grid[$y] = $row; if ($y >= $to_y) { break; } } } echo substr_count(implode("\n", $grid), "1") . "\n";
true
4818e68d4d57c4d21aec1d41899a81a3d1123b58
PHP
fiboknacky/googleads-php-lib
/src/Google/AdsApi/AdWords/v201809/cm/PolicySummaryInfo.php
UTF-8
4,378
2.546875
3
[ "Apache-2.0" ]
permissive
<?php namespace Google\AdsApi\AdWords\v201809\cm; /** * This file was generated from WSDL. DO NOT EDIT. */ abstract class PolicySummaryInfo { /** * @var \Google\AdsApi\AdWords\v201809\cm\PolicyTopicEntry[] $policyTopicEntries */ protected $policyTopicEntries = null; /** * @var string $reviewState */ protected $reviewState = null; /** * @var string $denormalizedStatus */ protected $denormalizedStatus = null; /** * @var string $combinedApprovalStatus */ protected $combinedApprovalStatus = null; /** * @var string $PolicySummaryInfoType */ protected $PolicySummaryInfoType = null; /** * @var array $parameterMap */ private $parameterMap = ['PolicySummaryInfo.Type' => 'PolicySummaryInfoType']; /** * @param \Google\AdsApi\AdWords\v201809\cm\PolicyTopicEntry[] $policyTopicEntries * @param string $reviewState * @param string $denormalizedStatus * @param string $combinedApprovalStatus * @param string $PolicySummaryInfoType */ public function __construct(array $policyTopicEntries = null, $reviewState = null, $denormalizedStatus = null, $combinedApprovalStatus = null, $PolicySummaryInfoType = null) { $this->policyTopicEntries = $policyTopicEntries; $this->reviewState = $reviewState; $this->denormalizedStatus = $denormalizedStatus; $this->combinedApprovalStatus = $combinedApprovalStatus; $this->PolicySummaryInfoType = $PolicySummaryInfoType; } /** * @return \Google\AdsApi\AdWords\v201809\cm\PolicyTopicEntry[] */ public function getPolicyTopicEntries() { return $this->policyTopicEntries; } /** * @param \Google\AdsApi\AdWords\v201809\cm\PolicyTopicEntry[] $policyTopicEntries * @return \Google\AdsApi\AdWords\v201809\cm\PolicySummaryInfo */ public function setPolicyTopicEntries(array $policyTopicEntries) { $this->policyTopicEntries = $policyTopicEntries; return $this; } /** * @return string */ public function getReviewState() { return $this->reviewState; } /** * @param string $reviewState * @return \Google\AdsApi\AdWords\v201809\cm\PolicySummaryInfo */ public function setReviewState($reviewState) { $this->reviewState = $reviewState; return $this; } /** * @return string */ public function getDenormalizedStatus() { return $this->denormalizedStatus; } /** * @param string $denormalizedStatus * @return \Google\AdsApi\AdWords\v201809\cm\PolicySummaryInfo */ public function setDenormalizedStatus($denormalizedStatus) { $this->denormalizedStatus = $denormalizedStatus; return $this; } /** * @return string */ public function getCombinedApprovalStatus() { return $this->combinedApprovalStatus; } /** * @param string $combinedApprovalStatus * @return \Google\AdsApi\AdWords\v201809\cm\PolicySummaryInfo */ public function setCombinedApprovalStatus($combinedApprovalStatus) { $this->combinedApprovalStatus = $combinedApprovalStatus; return $this; } /** * @return string */ public function getPolicySummaryInfoType() { return $this->PolicySummaryInfoType; } /** * @param string $PolicySummaryInfoType * @return \Google\AdsApi\AdWords\v201809\cm\PolicySummaryInfo */ public function setPolicySummaryInfoType($PolicySummaryInfoType) { $this->PolicySummaryInfoType = $PolicySummaryInfoType; return $this; } /** * Getter for a non PHP standard named variables. * * @param string $var variable name to get * @return string variable value */ public function __get($var) { if (!array_key_exists($var, $this->parameterMap)) { return null; } return $this->{$this->parameterMap[$var]}; } /** * Setter for a non PHP standard named variables. * * @param string $var variable name * @param mixed $value variable value to set * @return \Google\AdsApi\AdWords\v201809\cm\PolicySummaryInfo */ public function __set($var, $value) { $this->{$this->parameterMap[$var]} = $value; } }
true
a435baa0761068e5cd48089e5cf527cf4bf7ee9c
PHP
RomanRabirokh/ImageRandSearch
/src/app/classes/ImageTextCsv.php
UTF-8
1,723
3.34375
3
[]
no_license
<?php namespace classes; use interfaces\ImageText; /** * Class ImageTextCsv * @package classes */ class ImageTextCsv implements ImageText { /** * @var array|false|string */ protected $fileNames; /** * @var array|false|string */ protected $fileNameSigns; /** * ImageTextCsv constructor. */ public function __construct() { $this->fileNames = getenv('FILE_NAMES'); $this->fileNameSigns = getenv('FILE_SIGNS'); } /** * @return string */ public function getText(): string { $names = $this->getNamesFromCsv($this->fileNames); $signs = $this->getNamesFromCsv($this->fileNameSigns); return $this->getRandName($names, $signs); } /** * @param $filename * @return array */ protected function getNamesFromCsv($filename) { try { $lines = file_get_contents(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'files' . DIRECTORY_SEPARATOR . $filename); if (!$lines) { throw new \Exception('Not found file ' . $filename); } $data = explode(PHP_EOL, $lines); } catch (\Exception $exception) { Application::getLogErrors()->saveLog($exception->getMessage()); } return $data; } /** * @param $names * @param $signs * @return string */ protected function getRandName($names, $signs) { $randName = trim($names[rand(0, count($names) - 1)]); $randSign = trim($signs[rand(0, count($signs) - 1)]); $text = "{$randName} {$randSign}"; Application::getLog()->saveLog($text, true); return $text; } }
true
dae753205d5a7861da2094888658271f80158b22
PHP
AlexeyMinsk/tasks
/db_array/34.php
UTF-8
2,093
3.140625
3
[]
no_license
<?php function getMaxLineIndex(array $arr){ $arrCounter = array(); for($i = 0; $i < count($arr); $i++){ $arrCounter[$i] = 0; for($s = 0; $s < count($arr[$i]); $s++) $arrCounter[$i] += $arr[$i][$s]; if(!isset($max) || $max < $arrCounter[$i]){ $max = $arrCounter[$i]; $indexMax = $i; } } return $indexMax; } function getPosition(array $arr){ $arrCounter = array(); for($i = 0; $i < count($arr); $i++) $arrCounter[$i] = $arr[$i][0]; return getPriority($arrCounter); } function sortArr(array &$arr, $sort = true){ for($i = 0; $i < count($arr); $i++){ $value = $arr[$i]; $index = $i; for($n = $i+1; $n < count($arr); $n++){ if($value > $arr[$n] && $sort){ $value = $arr[$n]; $index = $n; }elseif($value < $arr[$n] && !$sort){ $value = $arr[$n]; $index = $n; } } switchElem($arr, $i, $index); } } function getPriority(array $arr){ $arrPriority = array(); $tempArr = $arr; sortArr($tempArr); for($i = 0; $i < count($tempArr); $i++){ for($s = 0; $s < count($arr); $s++){ if($tempArr[$i] == $arr[$s]) { $arrPriority[] = $s; break; } } } return $arrPriority; } function switchElem(array &$arr, $elem1, $elem2){ if($elem1 == $elem2) return; $temp = $arr[$elem1]; $arr[$elem1] = $arr[$elem2]; $arr[$elem2] = $temp; } $db_array = array( array(13, 22, 1, 3, 2), array(0, 1, -2, 3, 4), array(2, 8, -9, -3, 12), array(32, 81, -91, 30, 32), array(24 ,18 , 49, -23, -22) ); $temp_arr = array(); $firstLineIndex = getMaxLineIndex($db_array); $arrPriority = getPosition($db_array); for($i = 0; $i < count($db_array); $i++){ if(!$i) $temp_arr[] = $db_array[$firstLineIndex ]; if($arrPriority[$i] != $firstLineIndex) $temp_arr[] = $db_array[$arrPriority[$i] ]; } print_r($temp_arr);
true
c9be3b0cd7d20756b2d8af4eea9de455943648fa
PHP
besthird/rbac-api
/app/Service/Dao/UserDao.php
UTF-8
4,007
2.671875
3
[]
no_license
<?php declare(strict_types=1); /** * This file is part of Besthird. * * @document https://besthird.github.io/rbac-doc/ * @license https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE */ namespace App\Service\Dao; use App\Constants\ErrorCode; use App\Exception\BusinessException; use App\Kernel\Helper\ModelHelper; use App\Model\User; class UserDao extends Dao { /** * @param $id * @param bool $throw * @return User */ public function first($id, $throw = true) { $model = User::query()->find($id); if ($throw && empty($model)) { throw new BusinessException(ErrorCode::USRE_NOT_EXIST); } return $model; } /** * @param $key * @param bool $throw * @return User */ public function firstByKey($key, $throw = true) { $model = User::query()->where('key', $key)->first(); if ($throw && empty($model)) { throw new BusinessException(ErrorCode::USRE_NOT_EXIST); } return $model; } /** * @param $mobile * @return null|\Hyperf\Database\Model\Builder|\Hyperf\Database\Model\Model|object */ public function firstMobile($mobile) { $model = User::query()->where(['mobile' => $mobile])->first(); if (! $model) { throw new BusinessException(ErrorCode::USRE_NOT_EXIST); } return $model; } public function delete($id) { return User::query()->where('id', $id)->delete(); } /** * @param $input * @param $offset * @param $limit * @return array */ public function find($input, $offset, $limit): array { $query = User::query(); if (isset($input['id']) && ! empty($input['id'])) { $query->where('id', $input['id']); } if (isset($input['name']) && ! empty($input['name'])) { $query->where('name', $input['name']); } if (isset($input['mobile']) && ! empty($input['mobile'])) { $query->where('mobile', $input['mobile']); } if (isset($input['status'])) { $query->where('status', $input['status']); } return ModelHelper::pagination($query, $offset, $limit); } /** * @param $input * @param int|string $id * @return object */ public function save($input, $id = 0): object { if ($id === null) { $model = $this->firstByKey($input['key']); } elseif ($id > 0) { $model = $this->first($id); } else { $model = new User(); $model->key = $input['key']; } if (! empty($input['name'])) { $exist = $this->exist($input['name'], $id); if ($exist) { throw new BusinessException(ErrorCode::USRE_EXIST); } $model->name = $input['name']; } if (! empty($input['mobile'])) { $model->mobile = $input['mobile']; } if (! empty($input['key'])) { $model->key = $input['key']; } if (! empty($input['password'])) { $cost = 12; $option = ['cost' => $cost]; $model->password = password_hash($input['password'], PASSWORD_BCRYPT, $option); } if (! empty($input['status'])) { $model->status = $input['status']; } $model->save(); return $model; } public function status($id) { $model = $this->first($id); $model->status = $model->status == 0 ? 1 : 0; return $model->save(); } /** * 当前登录名是否已经存在. * @param string $name * @param int $id * @return bool */ public function exist(string $name, $id = 0): bool { $query = User::query()->where('name', $name); if ($id > 0) { $query->where('id', '<>', $id); } return $query->exists(); } }
true
60eeb80e2d4a0f8f13d56c2f89b703a6bf614365
PHP
johnalula/noradVMS
/apps/frontend/modules/employee/actions/actions.class.php
UTF-8
3,863
2.5625
3
[]
no_license
<?php /** * employee actions. * * @package noradVMS * @subpackage employee * @author Your name here * @version SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $ */ class employeeActions extends sfActions { public function executeIndex(sfWebRequest $request) { $offset = 0; $limit = 10; $this->employees = EmployeeTable::processSelection($status, $keyword, $exclusion, $emp_type, $type, $offset, $limit ); $this->parents = EmployeeTable::processUmbrellaSelection($status, $keyword, $exclusion, $type, $offset, $limit ); $this->totalData = EmployeeTable::processUmbrellaSelection($status, $keyword, $exclusion, $type, $offset, 1000 ); //$this->parents = CollegeTable::processSelection($status, $keyword, $exclusion, $type, $offset, $limit ) ; } public function executeCreateEmployee(sfWebRequest $request) { $name = $request->getParameter('name'); $father_name = $request->getParameter('father_name'); $g_father_name = $request->getParameter('g_father_name'); $birth_date = $request->getParameter('birth_date'); $gender = $request->getParameter('gender'); $dept_id = $request->getParameter('department_id'); $id_no = $request->getParameter('id_no'); $project_no = $request->getParameter('project_no'); $vat_no = $request->getParameter('vat_no'); $status = $request->getParameter('status'); $job_title = $request->getParameter('job_title'); $emp_type = $request->getParameter('employment_type'); $phone_no = $request->getParameter('phone_no'); $mobile_no = $request->getParameter('mobile_no'); $pobox = $request->getParameter('pobox'); $fax_no = $request->getParameter('fax_no'); $email = $request->getParameter('email'); $website = $request->getParameter('website'); $description = $request->getParameter('description'); $flag = EmployeeTable::processCreate($dept_id, $emp_type, $title, $name, $father_name, $g_father_name, $id_no, $job_title, $birth_date, $status, $vat_no, $project_no, $description, $pobox, $mobile_no, $phone_no, $fax_no, $email, $website); return $flag; } public function executePagination(sfWebRequest $request) { $offset = $request->getParameter('offset'); $limit = intval($request->getParameter('limit')); //$status = $request->getParameter('status_id'); $type = intval($request->getParameter('type_id')); $keyword = $request->getParameter('keyword'); //$keyword = '%'.$keyword.'%'; if(!$offset || $offset=='') $offset = 0; if(!$limit || $limit=='' ) $limit = 10; if(!$type || $type=='' ) $type = null; if(!$status || $status=='' ) $status = null; if(!$keyword || $keyword=='' ) $keyword = null; if(!$exclusion || $exclusion=='' ) $exclusion = null; if(!$emp_type || $emp_type=='' ) $emp_type = null; $this->employees = EmployeeTable::processSelection($status, $keyword, $exclusion, $emp_type, $type, $offset, $limit ); return $this->renderPartial('list', array('employees' => $this->employees)); } public function executeParentPagination(sfWebRequest $request) { $offset = $request->getParameter('offset'); $limit = intval($request->getParameter('limit')); //$status = $request->getParameter('status_id'); $type = intval($request->getParameter('type_id')); $keyword = $request->getParameter('keyword'); //$keyword = '%'.$keyword.'%'; if(!$offset || $offset=='') $offset = 0; if(!$limit || $limit=='' ) $limit = 10; if(!$type || $type=='' ) $type = null; if(!$status || $status=='' ) $status = null; if(!$keyword || $keyword=='' ) $keyword = null; if(!$exclusion || $exclusion=='' ) $exclusion = null; $this->parents = EmployeeTable::processUmbrellaSelection($status, $keyword, $exclusion, $type, $offset, $limit ); return $this->renderPartial('departmentList', array('parents' => $this->parents)); } }
true
83514567b3546650829dd32066f79cfe24c92c4f
PHP
eirikref/Loom
/tests/unit/Breadcrumbs/SetAndGetTest.php
UTF-8
1,668
2.890625
3
[]
no_license
<?php /** * Loom: Unit tests * Copyright (c) 2017 Eirik Refsdal <eirikref@gmail.com> */ namespace Loom\Tests\Unit\Breadcrumbs; use PHPUnit\Framework\TestCase; /** * Loom: Unit tests for Breadcrumbs::set() and get() * * @package Loom * @subpackage Tests * @version 2017-04-13 * @author Eirik Refsdal <eirikref@gmail.com> */ class SetAndGetTest extends TestCase { /** * Test simple set() and get() * * @test * @covers \Loom\Breadcrumbs::set * @covers \Loom\Breadcrumbs::get * @author Eirik Refsdal <eirikref@gmail.com> * @since 2017-04-13 * @access public * @return void */ public function testBasicSetAndGet() { $data = array(array("title" => "Test", "url" => "/test")); $bc = new \Loom\Breadcrumbs(); $this->assertEmpty($bc->get()); $bc->set($data); $this->assertCount(1, $bc->get()); } /** * Test set() and get() with multiple items * * @test * @covers \Loom\Breadcrumbs::set * @covers \Loom\Breadcrumbs::get * @author Eirik Refsdal <eirikref@gmail.com> * @since 2017-04-14 * @access public * @return void */ public function testMultipleSetAndGet() { $data = array(array("title" => "A", "url" => "/a"), array("title" => "B", "url" => "/a/b"), array("title" => "C", "url" => "/a/b/c") ); $bc = new \Loom\Breadcrumbs(); $this->assertEmpty($bc->get()); $bc->set($data); $this->assertCount(3, $bc->get()); } }
true
d6bcada2162f71cb1af3af091cb7b859a5b67a81
PHP
alexisljn/collab-media
/models/forms/ForgottenPasswordForm.php
UTF-8
334
2.640625
3
[ "WTFPL" ]
permissive
<?php namespace app\models\forms; use yii\base\Model; class ForgottenPasswordForm extends Model { public $email; public function rules() { return [ // email is required [['email'], 'required'], // email must be a valid email ['email', 'email'], ]; } }
true
8d8e71a40419a56819be57ceb5aa55d2d7f982b2
PHP
ltg-uic/phenomena-website
/lib/php/PageController.php
UTF-8
4,997
2.8125
3
[ "MIT" ]
permissive
<?php namespace PhenLib; abstract class PageController { private static $session = NULL; private static $initDone = FALSE; private static $URIQueue = NULL; private static $URIRaw = NULL; private static $URIRawDepth = NULL; private static $baseURL = NULL; private static $baseRelativePath = NULL; private static $resourceQueue = NULL; private static $rootResource = NULL; private static $rootResourceName = NULL; public static function init( $uri = NULL, $default = NULL ) { //init only performs on first call if( self::$initDone === FALSE ) { Session::start(); //link static vars to session storage if( ! isset( $_SESSION[__CLASS__] ) ) $_SESSION[__CLASS__] = array( 'lastPage' => "/" ); self::$session =& $_SESSION[__CLASS__]; //validity checks if( $default === NULL ) throw new \Exception( "PageController must be initialized before use" ); //build queue of uri self::$URIRaw = $uri; self::$URIRawDepth = 0; if( $uri === NULL || $uri === "" ) { $uri = $default; self::$URIRawDepth--; } $uri = explode( "/", $uri ); self::$URIQueue = new \SPLQueue(); for( $x=0; $x<sizeof($uri); $x++ ) if( $uri[$x] !== "" ) self::$URIQueue->enqueue( $uri[$x] ); self::$URIRawDepth += self::$URIQueue->count(); //determine paths self::calculatePaths(); self::$initDone = TRUE; self::loadResources(); } } private static function calculatePaths() { //DO NOT INIT(), IS SUB-CALL OF INIT() //get the raw URI path depth and create relative path to root self::$baseRelativePath = ""; for( $x=0; $x<self::$URIRawDepth; $x++ ) self::$baseRelativePath .= "../"; //create base URL //TODO - need to validate HTTP_HOST, can be spoofed by client //TODO - need to correctly handle $_SERVER['SERVER_PORT'] VARIANTS http !== 80 || https !== 443, put port //TODO - check for multiple consecutive slashes in path (should be fixed for end of path)?? $protocol = ( isset( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] !== 'off' ) ? "https" : "http"; $path = parse_url( $_SERVER['SCRIPT_NAME'], PHP_URL_PATH ); $path = substr( $path, 0, strrpos( $path, "/" )+1 ); self::$baseURL = "{$protocol}://{$_SERVER['HTTP_HOST']}{$path}"; } private static function loadResources() { //TODO THIS LOGIC WILL CHANGE SUBSTANTIALLY DUE TO NEW GET/POST PARADIGM // - DISPLAY ONLY HAPPENS ON GET // - ACTION ONLY HAPPENS ON POST //DO NOT INIT(), IS SUB-CALL OF INIT() self::$resourceQueue = new \SPLQueue(); if( $_SERVER['REQUEST_METHOD'] === "GET" ) self::$session['lastPage'] = ""; while( ! self::$URIQueue->isEmpty() ) { //determine class name from url //url name format is "word-word-word-word" //converts to class name format of "WordWordWordWord" $rawName = self::$URIQueue->dequeue(); $name = str_replace( " ", "", ucwords( str_replace( "-", " ", $rawName ) ) ); //404 error if invalid class if( ! is_readable( "res/{$name}.php" ) ) { header( "HTTP/1.1 404 Not Found" ); $message = "<h1>HTTP/1.1 404 Not Found</h1>\n"; $message .= "URI: /". self::$URIRaw . "<br />\n"; $message .= "Resource Name: {$name}"; exit( $message ); } //for actions (POSTS), skip to last resource if( $_SERVER['REQUEST_METHOD'] === "POST" && ! self::$URIQueue->isEmpty() ) continue; //instantiate resource //send clone of URIQueue enforce read only $class = "\\Phen\\{$name}"; $res = new $class( clone self::$URIQueue ); //TODO - evaluate if lastpage is in proper place, functionality //keep this / last page history if( $_SERVER['REQUEST_METHOD'] === "GET" && $res instanceof Page ) self::$session['lastPage'] .= "{$rawName}/"; //will only hit for last res if( $_SERVER['REQUEST_METHOD'] === "POST" && $res instanceof Action ) { //restore ID (will probably always be NULL) if( $res->getID() === NULL ) { if( isset( $_POST['id'] ) ) $res->setID( $_POST['id'] ); else throw new \Exception( "Uninitialized \$this->id in Action: {$class}" ); } $res->execute(); if( ( $dest = $res->getRedirect() ) !== NULL ) { header( "Location: {$dest}" ); exit(); } continue; } self::$resourceQueue->enqueue( $res ); //save the root resource if( self::$rootResource === NULL ) { self::$rootResource = $res; self::$rootResourceName = $name; } } } public static function getLastPage() { self::init(); return self::$session['lastPage']; } public static function getBaseURL() { self::init(); return self::$baseURL; } public static function getBaseRelativePath() { self::init(); return self::$baseRelativePath; } public static function getResourceQueue() { self::init(); return self::$resourceQueue; } public static function getRootResource() { self::init(); return self::$rootResource; } public static function getRootResourceName() { self::init(); return self::$rootResourceName; } } ?>
true
c60850dbb96fb9d077f0a99db5f446daa4bc9f1c
PHP
Athirajs/video_manager
/app/Http/Controllers/UploadController.php
UTF-8
946
2.640625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use App\Models\Upload; use Illuminate\Http\Request; class UploadController extends Controller { public function index() { return Upload::all(); } public function store(Request $request) { $request->validate([ 'title' => ['required'], 'description' => ['required'], 'url' => ['required'] ]); if (preg_match("/youtube\.com\/watch\?v=([^\&\?\/]+)/", $request->url)) { $url = explode('v=', $request->url); $video_id = explode("&", $url[1]); // dd( $video_id); $video = "https://www.youtube.com/embed/" . $video_id[0]; // dd($video); } Upload::create([ 'title' => $request->title, 'description' => $request->description, 'url' => $video, ]); return response()->json(null, 200); } }
true
ddcb443686a88c216124d7a6e64ed65417ffe651
PHP
MARMones/facebook
/inbox.php
UTF-8
863
2.6875
3
[]
no_license
<?php session_start(); $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = ''; $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql'); $dbname = 'dbs'; mysql_select_db($dbname); $query = "SELECT * FROM tbl_msg"; $result = mysql_query($query) or die(mysql_error()); ?> <html> <head> </head> <body> <center> <fieldset style="width: 500px; border-color: #9900FF"><legend style="font-size: 30px">Inbox</legend> <center> <?php print "<table>"; while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { print "<tr>"; print "<td>" . $row['subject'] . " | " . $row['msg'] . "</td>"; print "</tr>"; } print "</table>"; ?> </center> </center> </fieldset> </body> </html>
true
0d53680ec2b586fe5e515dbaaa7299b468ef3a49
PHP
msh123456/mongogram
/login.php
UTF-8
1,656
2.59375
3
[]
no_license
<?php include_once 'header.php'; ?> <?php if (isLogin()) { header("Location: ?a=home"); } $validator = new validator(); if (isset($_POST['username']) && isset($_POST['password'])) { global $db; $username = protect($_POST['username']); $password = protect($_POST['password']); $count = $db->users->count(array("username" => $username, "password" => $password)); if ($count == 1) { $doc = $db->users->findOne(array("username" => $username, "password" => $password)); $_SESSION['username'] = $doc['username']; $_SESSION['userdata'] = $doc; header("Location: ?a=home"); } else { $validator->error("Username or password is incorrect!"); } } ?> <body> <div class="container"> <div class="col-sm-3 col-xs-12"></div> <div class="col-sm-6 col-xs-12"> <?= $validator->getErrorHtml(); ?> <h2>Login</h2> <hr> <form action="" method="post"> <div class="form-group"> <label for="email">Username:</label> <input type="text" class="form-control" id="email" placeholder="Enter username" name="username"> </div> <div class="form-group"> <label for="pwd">Password:</label> <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="password"> </div> <button type="submit" class="btn btn-success">Login</button> <a href="signup.php" class="btn btn-warning">SignUp</a> </form> </div> <div class="col-sm-3 col-xs-12"></div> </div> </body> <?php include_once 'footer.php'; ?>
true
7fefe376b308ab9bc8e25aae92c9f4c9b8c5e37a
PHP
OliverCaiJia/jtadmin
/app/Helpers/Logger/SLogger.php
UTF-8
2,254
2.546875
3
[]
no_license
<?php namespace App\Helpers\Logger; use MongoDB\Client; use Monolog\Handler\MongoDBHandler; use Monolog\Logger as MonologLogger; use Monolog\Handler\StreamHandler; use Monolog\Processor\WebProcessor; class SLogger { private static $logger; public static function i() { return self::getStream(); } /** * 文件日志 * * @return \Monolog\Logger * @throws \Exception */ public static function getStream() { if (!(self::$logger instanceof MonologLogger)) { $extraFields = [ 'url' => 'REQUEST_URI', 'ip' => 'REMOTE_ADDR', 'http_method' => 'REQUEST_METHOD', 'server' => 'SERVER_NAME', 'referrer' => 'HTTP_REFERER', 'ua' => 'HTTP_USER_AGENT', 'query' => 'QUERY_STRING', 'ser_ip' => 'SERVER_ADDR' ]; self::$logger = new MonologLogger('sdzj-stream'); self::$logger->pushHandler(self::getStreamHandler()); self::$logger->pushProcessor(new WebProcessor(null, $extraFields)); self::$logger->setTimezone(new \DateTimeZone('PRC')); } return self::$logger; } /** * MongoDB 日志 * * @return \Monolog\Logger */ public static function getMongo() { if (!(self::$logger instanceof MonologLogger)) { self::$logger = new MonologLogger('sdzj-mongo'); self::$logger->pushHandler(self::getMongoHandler()); } return self::$logger; } /** * 处理器 * * @return \Monolog\Handler\StreamHandler * @throws \Exception */ private static function getStreamHandler() { $logpath = storage_path() . '/logs/admin.jietiaozhijia-' . date('Y-m-d') . '.log'; $handler = new StreamHandler($logpath, MonologLogger::INFO, true, 0777); return $handler; } /** * 处理器 * * @return \Monolog\Handler\MongoDBHandler */ private static function getMongoHandler() { $client = new Client('mongodb://localhost:27017'); $handler = new MongoDBHandler($client, 'logs', 'prod'); return $handler; } }
true
19cf57236939a6ecef8896903525b4d7df23e5c6
PHP
JonathanDLR/simmyadmin
/backend/UpdateTable.php
UTF-8
380
2.734375
3
[]
no_license
<?php require_once('Manager.php'); class UpdateTable extends Manager { public function update($table, $newNom) { try { $req = $this->_connexion->getDb()->prepare("ALTER TABLE $table RENAME TO $newNom"); $req->execute(); echo "la table ".$table." a été renommée!"; } catch(Exception $e) { echo $e; } $req->closeCursor(); } } ?>
true
c4a780cd2549e3848aa39a9667c6d9f2d6bf3c4d
PHP
alifahfathonah/AbsensiOnlineQRCode
/mahasiswa/prosestdkhdr.php
UTF-8
4,984
2.546875
3
[ "MIT" ]
permissive
<?php session_start(); $nim = $_SESSION['username']; include "../koneksi.php"; if(isset($_POST['submit'])){ $id_matkul = $_POST['idmatkul']; $id_matkul_enc = base64_encode($id_matkul); $ket = htmlentities(strip_tags(trim($_POST['keterangan']))); $i = 1; $querymhs = mysqli_query($konek,"SELECT * FROM Mahasiswa WHERE nim='$nim'"); $datamhs = mysqli_fetch_array($querymhs); $nama = $datamhs['nama']; $query = mysqli_query($konek,"SELECT * FROM Kehadiran WHERE nim='$nim' AND id_matkul='$id_matkul'"); $kolom = mysqli_fetch_array($query); while ($i<14) { if ($kolom[$i]=="-") { break; }else{ $i=$i+1; } } $error = $_FILES['bukti']['error']; // Menyimpan jumlah error ke variabel $error // Validasi error if($error == 0){ $ukuran_file = $_FILES['bukti']['size']; // Menyimpan ukuran file ke variabel $ukuran_file // Validasi ukuran file if($ukuran_file <= 2000000){ $nama_file = $_FILES['bukti']['name']; // Menyimpan nama file ke variabel $nama_file $format = pathinfo($nama_file, PATHINFO_EXTENSION); // Mendapatkan format file // Validasi format if( ($format == "jpg") or ($format == "pdf") or ($format == "jpeg") ){ $file_asal = $_FILES['bukti']['tmp_name']; $file_tujuan = "../bukti/".$_FILES['bukti']['name']; $upload = move_uploaded_file($file_asal, $file_tujuan); // Proses upload. Menghasilkan nilai true jika upload berhasil // Validasi upload (hasil true jika upload berhasil) if($upload == true){ $queryupdate = mysqli_query($konek,"INSERT INTO `TidakHadir` (`nim`, `nama`, `id_matkul`, `pertemuan`, `keterangan`, `bukti`) VALUES ('$nim', '$nama', '$id_matkul', '$i', '$ket', '$nama_file');"); $query = mysqli_query($konek,"UPDATE `Kehadiran` SET `$i` = 'T', kondisi = 'false' WHERE `Kehadiran`.`nim` = '$nim' AND `Kehadiran`.`id_matkul` = '$id_matkul'"); $pesan = "Entry data berhasil!!"; echo " <!DOCTYPE html> <html> <head> <title>Dialog Alert</title> <meta http-equiv='refresh' content='0;url=../'> </head> <body> <script> alert('$pesan'); </script> </body> </html>"; }else{ // else upload gagal $pesan = "Entry data gagal!!"; echo " <!DOCTYPE html> <html> <head> <title>Dialog Alert</title> <meta http-equiv='refresh' content='0;url=tidakhadir.php?id_matkul=$id_matkul_enc'> </head> <body> <script> alert('$pesan'); </script> </body> </html>"; } }else{ // else validasi format $pesan = "Format harus jpg atau pdf."; echo " <!DOCTYPE html> <html> <head> <title>Dialog Alert</title> <meta http-equiv='refresh' content='0;url=tidakhadir.php?id_matkul=$id_matkul_enc'> </head> <body> <script> alert('$pesan'); </script> </body> </html>"; } }else{ // else validasi ukuran file $pesan = "Ukuran file kamu ".$ukuran_file.", file tidak boleh lebih dari (2MB)"; echo " <!DOCTYPE html> <html> <head> <title>Dialog Alert</title> <meta http-equiv='refresh' content='0;url=tidakhadir.php?id_matkul=$id_matkul_enc'> </head> <body> <script> alert('$pesan'); </script> </body> </html>"; } }else{ // else validasi error $pesan = 'Ada '.$error.' error. Gagal upload.'; echo " <!DOCTYPE html> <html> <head> <title>Dialog Alert</title> <meta http-equiv='refresh' content='0;url=tidakhadir.php?id_matkul=$id_matkul_enc'> </head> <body> <script> alert('$pesan'); </script> </body> </html>"; } } ?>
true
1dee589619a8f6c60879b84dacb93222c4c39b26
PHP
justyork/mod
/Libs/Lng.php
UTF-8
1,813
2.6875
3
[]
no_license
<?php /** * Created by PhpStorm. * User: York * Date: 05.04.14 * Time: 20:28 */ class Lng { private $types; private $categories; private $langs; public function __construct(){ $this->types = JL::ListData(MSQL::Results('lang_type'), 'name'); $this->categories = JL::ListData(MSQL::Results('lang_category'), 'name'); $this->langs = JL::ListData(MSQL::Results('langs'), 'code'); require(ROOT_PATH.'/langs/lang.'.strtolower($this->GetLng()).'.php'); $GLOBALS['texts'] = $texts; } public function GetLng(){ $lang = false; if(isset($_COOKIE['lang'])) $lang = $_COOKIE['lang']; elseif(isset($_SESSION['lang'])) $lang = $_SESSION['lang']; if(!$lang){ setcookie('lang', 'en', 3600*24*365); $lang = 'en'; } return $lang; } public function GetLngId(){ $lang = $this->langs[$this->GetLng()]; return $lang['id']; } public function T($id, $type, $category, $lang = null){ if($lang == null) $lang = $this->GetLngId(); if((int)$type == 0) $type = $this->types[$type]['id']; if((int)$category == 0) $category = $this->categories[$category]['id']; $where = array( array('item_id', $id), array('type_id', $type), array('category_id', $category), array('lang_id', $lang), ); //var_dump($where); $data = MSQL::Row('lang_data', $where); if(!$data['value']){ if($type == 1) $id = array('propid', $id); elseif($type == 5) $id = array('news_id', $id); $typeRow = ''; foreach($this->types as $t){ if($t['id'] == $type){ $typeRow = $t['name']; break; } } $categoryRow = ''; foreach($this->categories as $c){ if($c['id'] == $category){ $categoryRow = $c['name']; break; } } $item = MSQL::Row($typeRow, $id); return $item[$categoryRow]; } return $data['value']; } }
true
f358b1773eca9b5e3f4b4045d84a33a3ec9beca7
PHP
juan2ramos/credito
/app/database/migrations/2015_03_10_175601_create_excelDaily_table.php
UTF-8
500
2.53125
3
[]
no_license
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateExcelDailyTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('excelDaily',function($table) { $table->increments('id'); $table->integer('cedula'); $table->float('pago_minimo'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('excelDayly'); } }
true
88004f2d5bb75b6dcf9257020ab029911974c4f6
PHP
Djoulzy/Toolbox
/Daemon/Signal.class.php
UTF-8
299
3.078125
3
[]
no_license
<?php final class Signal { public static $signo = 0; public static function set($signo) { self::$signo = $signo; } public static function get() { return(self::$signo); } public static function reset() { self::$signo = 0; } }
true
8dc4126e9bf21e4d5ed3323ce3aa6ce355fb8a89
PHP
PigWeb/miMuro
/paginas/register.php
UTF-8
2,364
2.515625
3
[]
no_license
<?php header('Content-Type:text/html; charset=UTF-8'); session_start(); error_reporting(0); $errores = array(); $nombre=$_POST['nombre']; $apellido=$_POST['apellido']; $mail=$_POST['mail']; $p1 = $_POST['pass1']; $p2 = $_POST['pass2']; if (!empty($_POST)) { if(isset($nombre) && isset($apellido)) { if(empty($nombre)){ $errores[] = "Debe escribir un nombre"; } else{ if(!preg_match('/^[a-zA-Z]+$/', $nombre){ $errores[] = "El nombre solo puede contener letras" } } if (empty($apellido)){ $errores[] = "Debe escribir un apellido" } else{ if(!preg_match('/^[a-zA-Z]+$/', $nombre){ $errores[] = "El nombre solo puede contener letras" } } } if (isset($mail) && isset ($p1)) { if(empty($mail)){ $errores[] = "Debe escribir un mail"; else{ if(!preg_match('/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/', $mail){ $errores[] = "Debe escribir un mail correcto"; } } } if (empty($p1)){ $errores[] = "Debe escribir una contraseña"; else{ if(strlen($p1) < 10){ $errores[] = "La contraseña debe tener mas de 10 caracteres" } } } if($p1 != $p2){ $errores [] = "La contraseñas deben ser iguales" } } } $pelicula = $_POST['pelicula']; $passhash = password_hash($p1, PASSWORD_BCRYPT); $pelicula_hash = password_hash($pelicula, PASSWORD_BCRYPT); $con="CALL usuario_alta('$nombre','$apellido','$mail','$passhash','$pelicula_hash')"; require ("mysql.php"); if($consulta!='0'){ echo "<script language='JavaScript'>"; echo "alert('Usuario registrado. Pendiente de alta.');"; echo "document.location =('../index.php');"; echo "</script>"; } else{ echo "error en el envio"; echo "<script language='JavaScript'>"; echo "alert('El usuario no se pudo registrar. Intente de nuevo mas tarde');"; echo "document.location =('../index.php');"; echo "</script>"; } ?>
true
7497d38a2d12261efb45b143de2c0b791351db16
PHP
zzhxlyc/zhifu
/app/model/Apply.php
UTF-8
1,621
2.671875
3
[]
no_license
<?php class Apply extends AppModel{ public $table = 'applys'; public function check(&$data, array $ignore = array()){ $check_arrays = array( 'need' => array('title', 'name'), 'length' => array('description'=>3000), 'int' => array('num', 'identity', 'education', 'year', 'age'), 'email' => array('email'), 'mobile' => array('mobile'), 'word'=> array('title', 'name', 'description', 'address', 'area', 'evaluate'), ); $errors = &parent::check($data, $check_arrays, $ignore); $array = array(); $a = get_value($data, 'available'); $ret = explode(' ', $a); if(count($ret) == 7){ for($i = 0;$i < 7;$i++){ $r = $ret[$i]; $rr = explode('-', $r); if(count($rr) == 3){ array_map('intval', $rr); $array[] = implode('-', $rr); } else{ $errors['available'] = '选择日期有误'; break; } } if(!isset($errors['available'])){ set_value($data, 'available', implode(' ', $array)); } } return $errors; } public function escape(&$data, array $ignore = array()){ $escape_array = array( 'string'=>array('title', 'name', 'description', 'address', 'area', 'evaluatere'), 'url'=>array(), 'html'=>array() ); return parent::escape($data, $escape_array, $ignore); } public function get_status(){ if($this->status == 1){ return '有效'; } else{ return '已关闭'; } } public function do_available(){ $available = $this->available; $this->days = array(); $days = explode(' ', $available); foreach($days as $day){ $day = trim($day); $this->days[] = explode('-', $day); } } }
true
2d67742474aa2447fee62c3bb7ca036d70b7a036
PHP
jkapuscik2/design-patterns-php
/src/Behavioral/Strategy/OutputFormatter.php
UTF-8
122
2.515625
3
[ "MIT" ]
permissive
<?php namespace App\Behavioral\Strategy; interface OutputFormatter { public function format(array $data): string; }
true
b942ea67165e766188855156f24c84153dbe7b46
PHP
scieloorg/Web
/htdocs/applications/scielo-org/classes/NewsDAO.php
WINDOWS-1250
4,321
2.984375
3
[]
no_license
<?php /** *@package Scielo.org *@version 1.0 *@author Andr Otero(andre.otero@bireme.org) *@copyright BIREME */ /** *Noticias do Usario * *Encapsula as funces CRUD em uma classe, assim temos "independencia" do Banco de dados a ser utilizado. *@package Scielo.org *@version 1.0 *@author Andr Otero(andre.otero@bireme.org) *@copyright BIREME */ require_once(dirname(__FILE__)."/../users/DBClass.php"); require_once(dirname(__FILE__)."/News.php"); class NewsDAO { function NewsDAO(){ $this->_db = new DBClass(); } function addNews($news){ $strsql = "INSERT INTO user_news (user_id, rss_url, in_home) VALUES ( '".$news->getUserID()."', '".$news->getRSSURL()."', '".$news->getInHome()."')"; $result = $this->_db->databaseExecInsert($strsql); return $result; } function updateNews($news){ $strsql = "UPDATE user_news SET "; if($news->getUserID() != '') $strsql .= "user_id = '".$news->getUserID()."',"; if($news->getRSSURL() != '') $strsql .= "rss_url = '".$news->getRSSURL()."',"; if($news->getInHome() != '') $strsql .= "in_home = '".$news->getInHome()."',"; $strsql = substr($strsql,0,strlen($strsql)-1); $strsql .= " WHERE news_id = '".$news->getID()."' "; return $this->_db->databaseExecUpdate($strsql); } function removeNews($news){ $strsql = "DELETE FROM user_news WHERE user_id = '".$news->getUserID()."' AND news_id = '".$news->getID()."'"; $result = $this->_db->databaseExecUpdate($strsql); return $result; } /** *Retorna um array de objetos News * *L a base de dados, e retorna um array de objetos News *@param News news objeto news que contm o ID do usurio que se quer as news carregadas *@param integer from *@param integer count * *@returns mixed Array de objetos news */ function getNewsList($news, $from=0, $count=-1){ /* $directory_id = $news->getDirectory(); if ( isset($directory_id) ){ if ($directory_id == 0){ $filter = " and user_news.directory_id=".$directory_id; }else{ $filterTb = ", directories"; $filter = " and user_news.directory_id=directories.directory_id and user_news.directory_id=".$directory_id; } } */ if($news->getID() != ''){ $where = " and user_news.news_id = " .$news->getID(); } $strsql = "SELECT * FROM user_news ".$filterTb." WHERE user_news.user_id = '".$news->getUserID()."' ".$filter.$where; if($count > 0){ $strsql .= " LIMIT $from,$count"; } $result = $this->_db->databaseQuery($strsql); $newsList = array(); for($i = 0; $i < count($result); $i++) { $news = new News(); $news->setID($result[$i]['news_id']); $news->setRSSURL($result[$i]['rss_url']); $news->setInHome($result[$i]['in_home']); $news->setUserID($result[$i]['user_id']); array_push($newsList, $news); } return $newsList; } function getRssInHome($news){ $strsql = "SELECT * FROM user_news WHERE user_news.user_id = '".$news->getUserID()."' and user_news.in_home = 1"; $result = $this->_db->databaseQuery($strsql); $news = new News(); $news->setID($result[0]['news_id']); $news->setRSSURL($result[0]['rss_url']); $news->setInHome($result[0]['in_home']); $news->setUserID($result[0]['user_id']); return $news; } function getTotalItens($news){ $filter = ""; /* $directory_id = $news->getDirectory(); if ( isset($directory_id) ) $filter = " and directory_id=".$directory_id; */ $strsql = "SELECT count(*) as total FROM user_news WHERE user_id = ".$news->getUserID().$filter ; $result = $this->_db->databaseQuery($strsql); return $result[0]['total']; } function updateNewsDirectory($news){ $strsql = "Update user_news SET directory_id=".$news->getDirectory()." WHERE news_id=".$news->getnews_id(); $result = $this->_db->databaseExecUpdate($strsql); } function showInHome($news){ $strsql = "Update user_news SET in_home = 0 where user_id = ".$news->getUserID(); $this->_db->databaseExecUpdate($strsql); $strsql = "Update user_news SET in_home = 1 where news_id = ".$news->getID(); $this->_db->databaseExecUpdate($strsql); } } ?>
true
5ebb4edb0e2232508eb5f7db359665339b56dc64
PHP
adamramadhan/red
/libraries/core.views.php
UTF-8
5,967
2.6875
3
[]
no_license
<?php if (! defined ( 'SECURE' )) exit ( 'Hello, security@networks.co.id' ); /** * DONOTEDIT, extend olny at /application/views * @version 100.20/3/2011 * @package ENGINE/CORE * @author rama@networks.co.id * @tutorial wiki/missing.txt */ class Views { final function __construct() { # cant change construct } /** * place a string for class css in views * @author rama@networks.co.id * @tutorial wiki/missing.txt */ public function ActiveCSS() { $url = $_SERVER ["REQUEST_URI"]; $url = htmlspecialchars ( $url ); $class = str_replace ( '/', '-', $url ); $class = substr ( $class, 1 ); $vowels = array ("@", "?" ); $pieces['request'] = str_replace ( $vowels, "", $class ); if (empty($pieces['request'])) { $pieces['request'] = 'home'; } $pieces['version'] = 'v1'; $activecss = implode (' ', $pieces ); echo $activecss; } /** * echos a <img> from www-static/assets/images * @param string $img * @param array $options * @author rama@networks.co.id * @tutorial wiki/missing.txt */ public function getIMG($img, $options = NULL) { if (! file_exists ( "www-static" . DS . "assets" . DS . "images" . DS . $img )) { throw new Exception ( "No such img as $img" ); } // epic fix / kalo dihapus jadinya ya cacat $img = "/www-static" . DS . "assets" . DS . "images" . DS . $img; echo '<img ' . $options . ' src="' . $img . '" />'; } /** * echos a <img> from www-static/storage/$uid/$img * @param int $uid * @param string $img * @author rama@networks.co.id * @tutorial wiki/missing.txt */ public function getStorage($uid, $img) { #var_dump("www-static". DS ."storage". DS . $uid . DS . $img); if (! file_exists ( "www-static" . DS . "storage" . DS . $uid . DS . $img )) { throw new Exception ( "No such img as $img" ); } # tambahan masih @ujicoba $options = getimagesize("www-static" . DS . "storage" . DS . $uid . DS . $img); // epic fix / kalo dihapus jadinya ya cacat $img = "/www-static" . DS . "storage" . DS . $uid . DS . $img; echo '<img '.$options[3].' src="' . $img . '" />'; } /** * echos a inline css style * @param args $views->css('css1','css2','etc'); * @author rama@networks.co.id * @tutorial wiki/missing.txt */ public function CSS( $files, $type = NULL ) { #sementara if (!is_array($files)) { $files = func_get_args (); } # Is it External or Inline ? switch ($type) { case 'external': foreach ($files as $css) { if (config ( 'development' )) { if (! file_exists ( "www-static" . DS . "assets" . DS . "css" . DS . $css . ".css" )) { throw new Exception ( "No such file as $css.css" ); } } $fullpath = "/www-static" . DS . "assets" . DS . "css" . DS . $css . ".css"; echo '<link type="text/css" rel="stylesheet" href="'.$fullpath.'"/>'."\n\t\t"; } break; default: if (config ( 'features/compress/css' )) { // See @ref #1 ob_start ( array ($this, 'compressorCSS' ) ); } echo "<style type='text/css'>"; foreach ( $files as $css ) { if (config ( 'development' )) { if (! file_exists ( "www-static" . DS . "assets" . DS . "css" . DS . $css . ".css" )) { throw new Exception ( "No such file as $css.css" ); } } require_once "www-static" . DS . "assets" . DS . "css" . DS . $css . ".css"; } echo "</style>"; if (config ( 'features/compress/css' )) { ob_end_flush (); } break; } } /** * echos a inline css style * @param args $views->css('css1,css2,etc','external or empty'); * @author rama@networks.co.id * @tutorial wiki/missing.txt */ public function JS( $files, $type = NULL ) { if (!is_array($files)) { # Get the files from the string $files = explode(",", $files); } # Is it External or Inline ? switch ($type) { # External = CACHE case 'external': foreach ($files as $js) { if (config ( 'development' )) { if (! file_exists ( "www-static" . DS . "assets" . DS . "js" . DS . $js . ".js" )) { throw new Exception ( "No such file as $js.js" ); } } $fullpath = "/www-static" . DS . "assets" . DS . "js" . DS . $js . ".js"; echo '<script type="text/javascript" src="'.$fullpath.'"></script>'; } break; # Inline = COMPRESS default: if (config ( 'features/compress/js' )) { // See @ref #1 ob_start ( array ($this, 'compressorJS' ) ); } echo "<script type='text/javascript'>"; foreach ( $files as $js ) { if (config ( 'development' )) { if (! file_exists ( "www-static" . DS . "assets" . DS . "js" . DS . $js . ".js" )) { throw new Exception ( "No such file as $js.js" ); } } require_once "www-static" . DS . "assets" . DS . "js" . DS . $js . ".js"; } echo "</script>"; if (config ( 'features/compress/js' )) { ob_end_flush (); } break; } } /** * main compressor for CSS buffer * @param string $buffer * @author rama@networks.co.id * @tutorial wiki/missing.txt */ public function compressorCSS($buffer) { $buffer = preg_replace ( '!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer ); $buffer = str_replace ( array ("\r\n", "\r", "\n", "\t", ' ', ' ', ' ' ), '', $buffer ); return $buffer; } /** * main compressor for JS buffer * @param string $buffer * @author rama@networks.co.id * @tutorial wiki/missing.txt */ public function compressorJS($buffer) { $buffer = str_replace ( array ("\r\n", "\r", "\n", "\t", ' ', ' ', ' ' ), '', $buffer ); return $buffer; } /** * echos a <a> for href or linking * @param string $link * @param string $language * @author rama@networks.co.id * @tutorial wiki/missing.txt */ public function href($link, $language) { echo "<a title='$language' href='$link'>$language</a>"; } } ?>
true
fdc02a61c9286782489543d9ed7b0a391d7cc884
PHP
shilpabharamanaik/shilpazend3Fisdap
/vendor/fisdap/members-api/app/Entity/MoodleCourseOverride.php
UTF-8
895
2.578125
3
[ "MIT" ]
permissive
<?php namespace Fisdap\Entity; use Doctrine\ORM\Mapping\Column; use Doctrine\ORM\Mapping\Entity; use Doctrine\ORM\Mapping\GeneratedValue; use Doctrine\ORM\Mapping\Id; use Doctrine\ORM\Mapping\JoinColumn; use Doctrine\ORM\Mapping\ManyToOne; use Doctrine\ORM\Mapping\Table; /** * Entity class for mapping Programs and Products to a particular moodle group (specifically for the Transistion Course) * * @Entity * @Table(name="fisdap2_moodle_course_overrides") */ class MoodleCourseOverride extends EntityBaseClass { /** * @Id * @Column(type="integer") * @GeneratedValue */ protected $id; /** * @ManyToOne(targetEntity="Product") */ protected $product; /** * @ManyToOne(targetEntity="ProgramLegacy") * @JoinColumn(name="program_id", referencedColumnName="Program_id") */ protected $program; /** * @Column(type="integer") */ protected $moodle_course_id; }
true
7ba0de7ac8c03d202af3d9714d9dd2435f827e18
PHP
Morebec/OrkestraSymfonyBundle
/Module/SymfonyOrkestraModuleContainerConfigurator.php
UTF-8
4,211
2.609375
3
[ "MIT" ]
permissive
<?php namespace Morebec\OrkestraSymfonyBundle\Module; use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; use Symfony\Component\DependencyInjection\Loader\Configurator\ServiceConfigurator; use Symfony\Component\DependencyInjection\Loader\Configurator\ServicesConfigurator; /** * Helper class containing methods to easily configure services that are orkestra flavored. */ class SymfonyOrkestraModuleContainerConfigurator { /** @var string */ public const UPCASTER_TAG = 'upcaster'; /** @var string */ public const PROJECTOR_TAG = 'projector'; /** * @var ContainerConfigurator */ private $container; /** * @var ServicesConfigurator */ private $services; public function __construct(ContainerConfigurator $container) { $this->container = $container; $this->services = $container->services(); } public function services(): ServicesConfigurator { return $this->services; } /** * Adds a command handler service definition. * Configured as autowired, autoconfigured, public and lazy. * @param string $serviceId * @param string|null $className * @return DomainMessageHandlerConfigurator */ public function commandHandler(string $serviceId, string $className = null): DomainMessageHandlerConfigurator { return $this->messageHandler($serviceId, $className); } /** * Adds an event handler definition. * Configured as autowired, autoconfigured, public and lazy. * @param string $serviceId * @param string|null $serviceClass * @return DomainMessageHandlerConfigurator */ public function eventHandler(string $serviceId, ?string $serviceClass = null): DomainMessageHandlerConfigurator { return $this->messageHandler($serviceId, $serviceClass); } /** * Adds an query handler definition. * Configured as autowired, autoconfigured, public and lazy. * @param string $serviceId * @param string|null $serviceClass * @return DomainMessageHandlerConfigurator */ public function queryHandler(string $serviceId, ?string $serviceClass = null): DomainMessageHandlerConfigurator { return $this->messageHandler($serviceId, $serviceClass); } /** * Configures a Domain Message Handler * @param string $serviceId * @param string|null $serviceClass * @return DomainMessageHandlerConfigurator */ protected function messageHandler(string $serviceId, ?string $serviceClass = null): DomainMessageHandlerConfigurator { $conf = new DomainMessageHandlerConfigurator( $this->container, $this->services->set($serviceId, $serviceClass), $serviceId ); $conf->public()->lazy()->autoconfigure()->autowire(); return $conf; } /** * Configures a console command. * @param string $className */ public function consoleCommand(string $className): ServiceConfigurator { return $this->services ->set($className) ->tag('console.command') ; } /** * Registers a service * @param string $serviceId * @param string|null $serviceClass * @return ServiceConfigurator */ public function service(string $serviceId, ?string $serviceClass = null): ServiceConfigurator { return $this->services->set($serviceId, $serviceClass); } /** * Registers an upcaster * @param string $serviceId * @param string|null $serviceClass * @return ServiceConfigurator */ public function upcaster(string $serviceId, ?string $serviceClass = null): ServiceConfigurator { return $this->services->set($serviceId, $serviceClass)->tag(self::UPCASTER_TAG); } /** * Registers a projector * @param string $serviceId * @param string|null $serviceClass * @return ServiceConfigurator */ public function projector(string $serviceId, ?string $serviceClass = null): ServiceConfigurator { return $this->services->set($serviceId, $serviceClass)->tag(self::PROJECTOR_TAG); } }
true
ac729e2b7d0c4fa8ab0f236d276f30966aa93644
PHP
liexusong/open-source-reading-comments
/php-4.0.6/tests/basic/011.phpt
UTF-8
200
2.796875
3
[ "LicenseRef-scancode-unknown-license-reference", "PHP-3.0" ]
permissive
--TEST-- Testing $argc and $argv handling --POST-- --GET-- ab+cd+ef+123+test --FILE-- <?php for($i=0;$i<$argc;$i++) { echo "$i: ".$argv[$i]."\n"; } ?> --EXPECT-- 0: ab 1: cd 2: ef 3: 123 4: test
true
5e04bc878205dbdbaf44250c47120924f552c550
PHP
foxyframework/foxy
/classes/user.php
UTF-8
3,006
2.765625
3
[]
no_license
<?php /** * @version 1.0.0 Foxy Framework $ * @package Foxy Framework * @copyright Copyright © 2014 - All rights reserved. * @license GNU/GPL * @author Foy Team * @website https://foxyframework.github.io/foxysite/ * */ defined('_Foxy') or die ('restricted access'); class User { public static $id = 0; public static $username = ""; public static $registerDate = ""; public static $email = ""; public static $lastvisitDate = "0000-00-00 00:00:00"; public static $level = 0; public static $language = ""; public static $token = ""; public static $block = 0; public static $image = 'assets/img/nouser.png'; public static $cargo = ''; public static $address = ''; public static $bio = ''; public static $template = 'green'; public static $apikey = ''; /** * Method to generate auth token * @param str $str * @return str */ public static function genToken($str) { return bin2hex($str); } /** * Method to know if user exist * @param int $id * @return boolean true if owner false if not */ public static function isUser($id) { database::query('SELECT * FROM `#_users` WHERE id = '.(int)$id); if(database::num_rows() > 0) { return true; } return false; } /** * Method to get the user authentication * @return boolean true if authenticate false if not */ public static function getAuth() { if( !isset($_SESSION['FOXY_userid']) ) { return false; } return true; } /** * Method to set authentication values * @param id int the user id * @return void */ public static function setAuth($id) { $_SESSION['FOXY_userid'] = $id; $row = self::getUserObject($id); session::setVar('id', $row->id); session::setVar('username', $row->username); session::setVar('registerDate', $row->registerDate); session::setVar('email', $row->email); session::setVar('lastvisitDate', $row->lastvisitDate); session::setVar('level', $row->level); session::setVar('language', $row->language); session::setVar('block', $row->block); session::setVar('image', $row->image); session::setVar('cargo', $row->cargo); session::setVar('address', $row->address); session::setVar('bio', $row->bio); session::setVar('token', $row->token); session::setVar('apikey', $row->apikey); } /** * Method to get the user object * @param id int the user id * @return object */ public static function getUserObject($id) { database::query('SELECT * FROM `#_users` WHERE id = '.$id); $row = database::fetchObject(); return $row; } } ?>
true
a0d3083d9ee9dee238c1a3f2047f1e96965ddb0b
PHP
apalette/tchouk-tchouk
/core/components/data/InSql.php
UTF-8
2,940
2.9375
3
[]
no_license
<?php /** * Ingo Sql * * PHP 5 * * @package data * @author apalette * @version 1.0 * @since 24/09/2015 * */ class InSql { protected static $_config; protected $_connexion; protected $_exception; protected $_query; protected $_data; protected $_type; public function __construct(){ if (! self::$_config) { if (! defined('IN_DATABASE')) { $this->_exception = new Exception('Database Config not found'); } else { self::$_config = unserialize(IN_DATABASE); } } } public function select($columns = '*'){ $this->_data = array(); $this->_type = 1; $this->_query = 'SELECT '.(is_array($columns) ? implode(',', $columns) : $columns); return $this; } public function from($table){ $this->_query .= ' FROM '.$table; return $this; } public function where($conditions) { if (is_array($conditions)) { $this->_query .= ' WHERE'; $i = 0; foreach ($conditions as $k => $v) { $op = '='; if (is_array($v)) { $op = $v[0]; $v = $v[1]; } $this->_query .= (($i > 0) ? ' AND ' : ' '); if ($v === null && ($op === '=' || $op === '!')) { $this->_query .= $k.(($op === '=') ? ' IS NULL' : ' IS NOT NULL'); } else { $d_key = ':w_'.$k; $this->_data[$d_key] = $v; $this->_query .= ($k.' '.$op.' '.$d_key); } $i++; } } return $this; } public function order($orders) { if (is_array($orders)) { $this->_query .= ' ORDER BY'; $i=0; $last = count($orders) - 1; foreach ($orders as $k => $v) { $dir = 'ASC'; if (is_array($v)) { $dir = $v[1]; $v = $v[0]; } $this->_query .= (' '.$v.' '.$dir); if ($i != $last) { $this->_query .=','; $i++; } } } return $this; } public function execute(){ $c = $this->_connect(); if ($c) { $sql = $c->prepare($this->_query); try { if ($sql->execute($this->_data)) { $r = $this->_result($sql); $c = $sql = null; return $r; } } catch(PDOException $e) { $this->_exception = $e; } } return false; } public function getQuery() { return $this->_query; } public function getException() { return $this->_exception; } protected function _connect() { if (self::$_config) { try { $connexion = new PDO('mysql:host='.self::$_config['host'].';port='.self::$_config['port'].';dbname='.self::$_config['database'].';charset='.self::$_config['charset'], self::$_config['user'], self::$_config['password']); $connexion->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $connexion; } catch(PDOException $e) { $this->_exception = $e; } } return false; } protected function _result($sql) { switch($this->_type) { case 1 : $rows = $sql->fetchAll(PDO::FETCH_ASSOC); return ($rows && is_array($rows)) ? $rows : array(); default : return null; } } } ?>
true
5404cb87b7175118638ffdd928b7b0a3f2d5f93d
PHP
etki/allure-runner
/src/IO/Controller/DummyController.php
UTF-8
1,821
2.859375
3
[ "MIT" ]
permissive
<?php namespace Etki\Testing\AllureFramework\Runner\IO\Controller; use Etki\Testing\AllureFramework\Runner\Configuration\Verbosity; use Etki\Testing\AllureFramework\Runner\IO\IOControllerInterface; /** * Dummy I/O controller implementation. Acts like a black hole. * * @SuppressWarnings(PHPMD.UnusedFormalParameter) * * @codeCoverageIgnore * * @version 0.1.0 * @since 0.1.0 * @package Etki\Testing\AllureFramework\Runner\IO\Controller * @author Etki <etki@etki.name> */ class DummyController implements IOControllerInterface { /** * Dummy implementation. * * @param string $message Message to output (that won't happen). * @param string $verbosity Message verbosity level (who cares). * * @return void * @since 0.1.0 */ public function write($message, $verbosity = Verbosity::LEVEL_INFO) { // pass } /** * Dummy implementation. * * @param string $message Message to output (that won't happen). * @param string $verbosity Message verbosity level (who cares). * * @return void * @since 0.1.0 */ public function writeLine($message = '', $verbosity = Verbosity::LEVEL_INFO) { // pass } /** * Dummy implementation. * * @param string[] $messages Messages to output (that won't happen). * @param string $verbosity Messages verbosity level (who cares). * * @return void * @since 0.1.0 */ public function writeLines( array $messages, $verbosity = Verbosity::LEVEL_INFO ) { // pass } /** * Dummy implementation * * @param int $verbosity Verbosity level. * * @return void * @since 0.1.0 */ public function setVerbosity($verbosity) { // pass } }
true
636474eebe52f03e88054947edbb40829b8fe4fd
PHP
lucques/mycms
/library/models/mappers/UpdateSettingsMapper.php
UTF-8
254
2.671875
3
[ "Apache-2.0", "MIT" ]
permissive
<?php /** * This is the interface for updating the settings from a data source. */ interface UpdateSettingsMapper { /** * @param Map $settings */ public function setSettings(Map $settings); /** * */ public function map(); }
true
d1672ed2d8971a877548fa561a3ff2fb86d625a8
PHP
M1naret/lumen-graphql
/src/M1naret/GraphQL/Error/Error.php
UTF-8
410
2.6875
3
[ "MIT" ]
permissive
<?php namespace M1naret\GraphQL\Error; use GraphQL\Error\Error as GraphQLError; class Error extends GraphQLError { protected $headers = []; /** * @param array $headers */ public function setHeaders(array $headers) { $this->headers = $headers; } /** * @return array */ public function getHeaders() : array { return $this->headers; } }
true
9c290288592519dc5550f3158d7a4cb40cc7786e
PHP
curator-wik/curator
/tests/Shared/Traits/Persistence/PersistenceTestsTrait.php
UTF-8
2,203
2.59375
3
[ "MIT" ]
permissive
<?php namespace Curator\Tests\Shared\Traits\Persistence; use Curator\Persistence\PersistenceInterface; trait PersistenceTestsTrait { /** * @return PersistenceInterface */ protected abstract function sutFactory(); public function testBasicStoreAndRetrieve() { $sut = $this->sutFactory(); $sut->beginReadWrite(); $sut->set('test', 'hello world'); $this->assertEquals('hello world', $sut->get('test'), 'Basic store/retrieve failed.'); $sut->end(); $sut->beginReadOnly(); $this->assertEquals('hello world', $sut->get('test'), 'Basic store/retrieve after end()ing writes failed.'); $sut->end(); } public function testGetDefaultValue() { $sut = $this->sutFactory(); $sut->beginReadOnly(); $this->assertEquals('the default', $sut->get('testGetDefaultValue', 'the default'), 'Default value was not returned when retrieving an unset key.'); } public function testUnsetValue() { $sut = $this->sutFactory(); $sut->beginReadWrite(); $sut->set('testUnsetValue', 'set'); $this->assertEquals('set', $sut->get('testUnsetValue')); $sut->set('testUnsetValue', NULL); $this->assertNull($sut->get('testUnsetValue')); $sut->set('testUnsetValue', 'set'); $sut->end(); $sut->beginReadWrite(); $sut->set('testUnsetValue', NULL); $sut->end(); $sut->beginReadOnly(); $this->assertEquals('unset', $sut->get('testUnsetValue', 'unset')); $sut->end(); } /** * @expectedException \LogicException */ public function testGetWithoutLock_throws() { $sut = $this->sutFactory(); $sut->get('foo'); } /** * @expectedException \LogicException */ public function testGetWithoutLock_throws_2() { $sut = $this->sutFactory(); $sut->beginReadOnly(); $sut->end(); $sut->get('foo'); } /** * @expectedException \LogicException */ public function testSetWithoutLock_throws() { $sut = $this->sutFactory(); $sut->set('foo', 'bar'); } /** * @expectedException \LogicException */ public function testSetWithoutLock_throws2() { $sut = $this->sutFactory(); $sut->beginReadWrite(); $sut->end(); $sut->set('foo', 'bar'); } }
true
24947d372eae09b93a2510bc512479721532b004
PHP
disono/archie
/src/Database/DSDB.php
UTF-8
1,031
2.875
3
[ "Apache-2.0" ]
permissive
<?php namespace Archie\Database; class DSDB { private $connection = null; private $table = null; private $selects = []; private $where = []; public function __construct() { $this->connection = new \MeekroDB($host, $user, $pass, $dbName, $port, $encoding); } public function table($name) { $this->table = $name; return $this; } public function select($columns) { $this->selects = $columns; } public function where() { $args = func_get_args(); if (count($args) === 2) { $this->where[] = ['left' => $args[0], 'right' => $args[1], 'middle' => '=']; } else if (count($args) === 3) { $this->where[] = ['left' => $args[0], 'right' => $args[1], 'middle' => $args[2]]; } return $this; } public function orWhere() { } public function query() { return $this->connection->query("SELECT * FROM " . $this->name . " WHERE id = %s", $type); } }
true
d592768bad1676e40f9d7d4f0375745a4dd25cc5
PHP
makarova/skeleton
/application/models/Roles/Crud.php
UTF-8
1,839
2.859375
3
[ "MIT" ]
permissive
<?php /** * @copyright Bluz PHP Team * @link https://github.com/bluzphp/skeleton */ /** * @namespace */ namespace Application\Roles; /** * Crud * * @package Application\Test * * @method Table getTable() * * @author Anton Shevchuk * @created 03.09.12 13:11 */ class Crud extends \Bluz\Crud\Table { /** * validate Name * * @param string $name * @return void */ public function checkName($name) { if (empty($name)) { $this->addError(__('Role name can\'t be empty'), 'name'); } if (!preg_match('/^[a-zA-Z0-9-_ ]+$/', $name)) { $this->addError(__('Name should contains only Latin characters'), 'name'); } } /** * {@inheritdoc} */ public function validateCreate($data) { // role name validator $name = isset($data['name'])?$data['name']:null; $this->checkName($name); if (Table::getInstance()->findRowWhere(['name'=>$name])) { $this->addError(__('Role name "%s" already exists', $name), 'name'); } } /** * {@inheritdoc} */ public function validateUpdate($id, $data) { // role name validator $name = isset($data['name'])?$data['name']:null; $this->checkName($name); if (in_array(strtolower($name), Table::getInstance()->getBasicRoles())) { $this->addError(__('Role name "%s" is basic and can\'t be editable', $name), 'name'); }; $originalRow = $this->readOne($id); if ($originalRow->name == $name) { $this->addError(__('Role name "%s" the same as original', $name), 'name'); } elseif (Table::getInstance()->findRowWhere(['name'=>$name])) { $this->addError(__('Role name "%s" already exists', $name), 'name'); } } }
true
d72017da2cebba7729f919e45937d2b6d0adf046
PHP
hackevil/Torrent-Streamer
/src/Homesoft/Bundle/TorrentStreamerBundle/Utils/CPasBienExtractor.php
UTF-8
3,135
2.703125
3
[]
no_license
<?php namespace Homesoft\Bundle\TorrentStreamerBundle\Utils; use Cocur\Slugify\Slugify; use Sunra\PhpSimple\HtmlDomParser; class CPasBienExtractor { const CPASBIEN_BASE_URL = 'http://www.cpasbien.io'; /** * @var Slugify $slugifier */ private $slugifier; /** * @var string $tmpFolder */ private $tmpFolder; public function __construct(Slugify $slugifier, $tmpFolder) { $this->slugifier = $slugifier; $this->tmpFolder = $tmpFolder; } public function search($tags) { $searchUrl = self::CPASBIEN_BASE_URL . '/recherche/' . $this->slugifier->slugify($tags) . '.html'; $dom = HtmlDomParser::file_get_html($searchUrl); $lignes0 = $dom->find('div[class=ligne0]'); $lignes1 = $dom->find('div[class=ligne1]'); $torrentsLigne0 = array(); foreach($lignes0 as $torrentLigne0) array_push($torrentsLigne0, $this->parseHtmlToTorrent($torrentLigne0)); $torrentsLigne1 = array(); foreach($lignes1 as $torrentLigne1) array_push($torrentsLigne1, $this->parseHtmlToTorrent($torrentLigne1)); //merge array to respect website order result $result = array(); $index0 = $index1 = 0; for($i = 0; $i < (count($torrentsLigne0) + count($torrentsLigne1)); $i++) { if($i % 2 == 0){ array_push($result, $torrentsLigne0[$index0]); $index0++; } else{ array_push($result, $torrentsLigne1[$index1]); $index1++; } } return $result; } public function parseHtmlToTorrent($torrentDom) { $result = new \stdClass(); $result->title = $torrentDom->find('a', 0)->innertext; $result->urlCard = $torrentDom->find('a', 0)->href; $size = $torrentDom->find('div[class=poid]', 0)->plaintext; $result->size = substr($size, 0, strlen($size)-6); $result->seeders = $torrentDom->find('span[class=seed_ok]', 0)->plaintext; $result->leechers = $torrentDom->find('div[class=down]', 0)->plaintext; return $result; } public function downloadTorrentFile($torrentUrlCard) { $dom = HtmlDomParser::file_get_html($torrentUrlCard); $urlTorrentFile = $dom->find('a[id=telecharger]', 0)->href; $urlTorrentFile = self::CPASBIEN_BASE_URL . $urlTorrentFile; $curl = curl_init($urlTorrentFile); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_COOKIESESSION, true); $fileContent = curl_exec($curl); curl_close($curl); $filename = $torrentUrlCard; while(strpos($filename, '/') !== false) { $test = strpos($filename, '/'); $filename = substr($filename, strpos($filename, '/')+1); } $test = strpos($filename, '/'); $filename = substr($filename, 0, strlen($filename) - 5) . '.torrent'; $filePath = $this->tmpFolder . '/' . $filename; file_put_contents($filePath, $fileContent); return $filePath; } }
true
f82462a01d80a5dc2f89b2b07d28d10f55220580
PHP
trieunb/resume-builder
/app/Repositories/Device/DeviceEloquent.php
UTF-8
775
2.75
3
[ "MIT" ]
permissive
<?php namespace App\Repositories\Device; use App\Models\Device; use App\Repositories\AbstractRepository; use App\Repositories\Device\DeviceInterface; class DeviceEloquent extends AbstractRepository implements DeviceInterface { protected $model; public function __construct(Device $device) { $this->model = $device; } public function createOrUpdateDevice($user_id, $data) { $this->getFirstDataWhereClause('user_id', '=', $user_id) ? $device = $this->getFirstDataWhereClause('user_id', '=', $user_id) : $device = new Device(); $device->user_id = $user_id; $device->device_id = $data['device_id']; $device->platform = $data['device_platform']; return $device->save(); } }
true
1c9e2b2021b28b3caebefc092171fcd580a1411c
PHP
david-garcia-nete/hackerrank
/tests/Practice/InterviewPreparationKit/WarmUpChallenges/CountingValleysTest.php
UTF-8
667
3.046875
3
[]
no_license
<?php use PHPUnit\Framework\TestCase; include '/home/david/PhpstormProjects/hackerrank/src/Practice/InterviewPreparationKit/WarmUpChallenges/CountingValleys.php'; final class CountingValleysTest extends TestCase { public function testCountingValleys(): void { $countingValleys = new CountingValleys(); $n = 20; $s = "UDDUUUDDUUDDDUUUUUUD"; $this->assertEquals( 2, $countingValleys->countingValleys($n, $s) ); $n = 26; $s = "UDDDUUUUUUDDDUUUUUUDDDUUUUU"; $this->assertEquals( 1, $countingValleys->countingValleys($n, $s) ); } }
true
ffb5b80b3276090fce1ec45e25453222f4c43a22
PHP
aaaleksandra1303/GestorDeTareas
/Bootstrap/Request.php
UTF-8
807
3.0625
3
[]
no_license
<?php namespace DreamWeb\Bootstrap; class Request { private $domain; private $path; private $params; private $method; public function __construct() { $this->domain = $_SERVER['HTTP_HOST']; $this->path = explode('?', $_SERVER['REQUEST_URI'])[0]; $this->method = $_SERVER['REQUEST_METHOD']; $this->params = array_merge($_POST, $_GET); } public function getUrl(): string { return $this->domain . $this->path; } public function getDomain(): string { return $this->domain; } public function getPath(): string { return $this->path; } public function getParams(): array { return $this->params; } public function getParam(string $name) { return $this->params[$name] ?? null; } public function hasParam(string $name): bool { return isset($this->params[$name]); } }
true
7c364b0152987d59b0b1cf64847cffe3f586f775
PHP
pytchoun/eSport
/model/User.php
UTF-8
3,771
3.015625
3
[]
no_license
<?php class User { private $id; private $username; private $email; private $firstName; private $lastName; private $language; private $country; private $birthDate; private $gender; private $creationDate; private $presentation; private $facebook; private $twitter; private $twitch; private $youtube; private $isActive; private $isBanned; public function __construct( int $id, string $username, string $email, string $firstName, string $lastName, string $language, string $country, DateTime $birthDate, string $gender, DateTime $creationDate, string $presentation, string $facebook, string $twitter, string $twitch, string $youtube, int $isActive, int $isBanned ) { $this->id = $id; $this->username = $username; $this->email = $email; $this->firstName = $firstName; $this->lastName = $lastName; $this->language = $language; $this->country = $country; $this->birthDate = $birthDate; $this->gender = $gender; $this->creationDate = $creationDate; $this->presentation = $presentation; $this->facebook = $facebook; $this->twitter = $twitter; $this->twitch = $twitch; $this->youtube = $youtube; $this->isActive = $isActive; $this->isBanned = $isBanned; } public function getId(){ return $this->id; } public function setId($id){ $this->id = $id; } public function getUsername(){ return $this->username; } public function setUsername($username){ $this->username = $username; } public function getEmail(){ return $this->email; } public function setEmail($email){ $this->email = $email; } public function getFirstName(){ return $this->firstName; } public function setFirstName($firstName){ $this->firstName = $firstName; } public function getLastName(){ return $this->lastName; } public function setLastName($lastName){ $this->lastName = $lastName; } public function getLanguage(){ return $this->language; } public function setLanguage($language){ $this->language = $language; } public function getCountry(){ return $this->country; } public function setCountry($country){ $this->country = $country; } public function getBirthDate(){ return $this->birthDate; } public function setBirthDate($birthDate){ $this->birthDate = $birthDate; } public function getGender(){ return $this->gender; } public function setGender($gender){ $this->gender = $gender; } public function getCreationDate(){ return $this->creationDate; } public function setCreationDate($creationDate){ $this->creationDate = $creationDate; } public function getPresentation(){ return $this->presentation; } public function setPresentation($presentation){ $this->presentation = $presentation; } public function getFacebook(){ return $this->facebook; } public function setFacebook($facebook){ $this->facebook = $facebook; } public function getTwitter(){ return $this->twitter; } public function setTwitter($twitter){ $this->twitter = $twitter; } public function getTwitch(){ return $this->twitch; } public function setTwitch($twitch){ $this->twitch = $twitch; } public function getYoutube(){ return $this->youtube; } public function setYoutube($youtube){ $this->youtube = $youtube; } public function getIsActive(){ return $this->isActive; } public function setIsActive($isActive){ $this->isActive = $isActive; } public function getIsBanned(){ return $this->isBanned; } public function setIsBanned($isBanned){ $this->isBanned = $isBanned; } }
true
751c6c4400ff423d150f28e94747dfdea4110812
PHP
droath/hostsfile-manager
/tests/HostsFileTest.php
UTF-8
2,594
2.671875
3
[]
no_license
<?php namespace Droath\HostsFileManager\Tests; use Droath\HostsFileManager\HostsFile; use PHPUnit\Framework\TestCase; use org\bovigo\vfs\vfsStream; /** * Define the hosts file test. */ class HostsFileTest extends TestCase { /** * Mimic the unix /etc directory. * * @var \org\bovigo\vfs\vfsStreamDirectory */ protected $root; /** * Hosts file object. * * @var \Droath\HostsFileManager\HostsFile */ protected $hostsFile; /** * Hosts file permissions. * * @var int */ protected $hostsPerm = 0664; public function setUp() { $this->root = vfsStream::setup('etc'); // Add hosts file to the /etc directory. $this->root->addChild(vfsStream::newFile('hosts', $this->hostsPerm)); $this->hostsFile = new HostsFile($this->getHostsFileUrl()); } public function testIsReadable() { $is_readable = $this->hostsFile->isReadable(); $this->assertTrue($is_readable); } public function testIsWrittable() { $is_writable = $this->hostsFile->isWritable(); $this->assertTrue($is_writable); } public function testSetLine() { $this->hostsFile ->setLine('127.0.0.1', 'local.google.com'); $lines = $this->hostsFile->getLines(); $this->assertArrayHasKey('local.google.com', $lines); $this->assertEquals('127.0.0.1', $lines['local.google.com'][0]); } public function testGetPermission() { $permission = $this->hostsFile->getPermission(); $this->assertSame('0664', $permission); } public function testGetFormattedLines() { $this->hostsFile ->setLine('192.168.1.1', 'local.cnn.com') ->setLine('127.0.0.1', 'local.google.com'); $formatted_lines = $this->hostsFile->getFormattedLines(); $this->assertEquals("192.168.1.1\tlocal.cnn.com", $formatted_lines[0]); $this->assertEquals("127.0.0.1\tlocal.google.com", $formatted_lines[1]); } /** * @expectedException Exception */ public function testRollbackPermission() { $filename = $this->getHostsFileUrl(); chmod($filename, 0555); $this->assertEquals('0555', $this->getFilePermission($filename)); $this->hostsFile->rollbackPermission(); } protected function getFilePermission($filename) { return substr(sprintf('%o', fileperms($filename)), -4); } protected function getHostsFileUrl() { return vfsStream::url('etc/hosts'); } }
true
3891d498e8b89ddbfc1218e9de3392d9f1aba3db
PHP
NEWLIFEVE/Etelix_SINE
/src/web/protected/models/Managers.php
UTF-8
3,485
2.640625
3
[]
no_license
<?php /** * This is the model class for table "managers". * * The followings are the available columns in table 'managers': * @property integer $id * @property string $name * @property string $lastname * @property string $address * @property string $record_date * @property string $position * * The followings are the available model relations: * @property CarrierManagers[] $carrierManagers */ class Managers extends CActiveRecord { public $vendedor; public $operador; public $company; public $termino_pago; public $monetizable; public $dias_disputa; public $limite_credito; public $limite_compra; public $production_unit; public $status; /** * Returns the static model of the specified AR class. * @param string $className active record class name. * @return Managers the static model class */ public static function model($className=__CLASS__) { return parent::model($className); } /** * @return string the associated database table name */ public function tableName() { return 'managers'; } /** * @return array validation rules for model attributes. */ public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. return array( array('name,lastname, record_date','required'), array('name,lastname, position','length','max'=>50), array('address','safe'), // The following rule is used by search(). // Please remove those attributes that should not be searched. array('id, name,lastname, address, record_date, position','safe','on'=>'search'), ); } /** * @return array relational rules. */ public function relations() { // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( 'carrierManagers'=>array(self::HAS_MANY,'CarrierManagers','id_managers'), ); } /** * @return array customized attribute labels (name=>label) */ public function attributeLabels() { return array( 'id'=>'ID', 'name'=>'Name', 'lastname'=>'Last Name', 'address'=>'Address', 'record_date'=>'Record Date', 'position'=>'Position', ); } /** * Retrieves a list of models based on the current search/filter conditions. * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions. */ public function search() { // Warning: Please modify the following code to remove attributes that // should not be searched. $criteria=new CDbCriteria; $criteria->compare('id',$this->id); $criteria->compare('name',$this->name,true); $criteria->compare('lastname',$this->name,true); $criteria->compare('address',$this->address,true); $criteria->compare('record_date',$this->record_date,true); $criteria->compare('position',$this->position,true); return new CActiveDataProvider($this, array( 'criteria'=>$criteria, )); } /** * @access public * @static */ public static function getName($id) { $model=self::model()->find('id=:id',array(':id'=>$id)); if($model->lastname!=null) { return $model->lastname; } else { return FALSE; } } /** * @access public * @static * @return CActiveRecord */ public static function getManagers() { $model=self::model()->findAll(); return $model; } }
true
8e9c4dc57e50c9e95f1221ee6dddf40f235cb6fe
PHP
adventure-star/ci-chinaschoolwebsite
/manage/index.php
UTF-8
1,713
2.609375
3
[]
no_license
<!--增加学校--> <!--增加信息--> <!--还有删除信息--> <!--修改信息--> <?php session_start(); if (isset($_GET['action']) && $_GET['action'] == 'post') { $name = $_POST['name']; $pass = $_POST['password']; $code = $_POST['code']; if ($_SESSION['code'] == $code) { //连接数据库 $db = new pdo('mysql:host=115.159.201.83;dbname=school',"bitzo","bitzo"); $str = "select * from admininfo where AdminName = \"$name\""; $sth = $db->query($str); var_dump($sth); $arrData = $sth->fetch(PDO::FETCH_ASSOC); var_dump($arrData); if ($pass == $arrData['AdminPass']) { echo "hello4"; setcookie('Name',$name,time()+60*30); setcookie('is_log',1,time()+60*30); header("Location:manage.php"); }else header("Location:index.php"); } } if (isset($_GET['action'])&&$_GET['action']=='out') { setcookie('is_log','',time()-1); setcookie('Name','',time()-1); } ?> <!DOCTYPE HTML> <html> <head> <title>请登录!高校云-后台管理系统</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <style type="text/css"> #log{ margin: auto; width: 300px; height: 200px; padding: 20px; border: solid 1px black; } </style> </head> <body> <div id="log"> <form action="index.php?action=post" method="POST"> <p>=== Log in (Administrator) ====</p> UserName:<input type="text" name="name" size="20"><br/ ><br /> Password:<input type="password" name="password" size="20"><br/ ><br /> 验证码: <input type="text" size="8px" name="code"><a href="./"><img src="code.php"></a><br /><br /> <input type="reset" name="Reset"> <input type="submit" name="Ensure"> </form> </div> </body> </html>
true
050ccaa2a26905cc37b90a32ea289a0014acf65f
PHP
cjborkowski/balboaparkcommons
/app/views/pages/.svn/text-base/getimage.ctp.svn-base
UTF-8
386
2.5625
3
[ "MIT" ]
permissive
<strong>GD Check image size</strong><br /><br /> <p> <?PHP $image = 'http://piction.bpoc.org/piction/ump.show_public_image?v_umo=21157880&quality=WEB'; echo 'We are checking : '. $image. '<br />'; //check if image exists if($img = @GETIMAGESIZE($image)){ ECHO "<br />image exists and is :"; print_r($img) ; }else{ ECHO "<br />image does not exist"; } ?> </p>
true
00703c5034a9dd1ac36923dba2673e9ebb34eee6
PHP
AncaorDev/ancaor2017
/model/templateModel.php
UTF-8
1,316
2.78125
3
[]
no_license
<?php /** * extends Model */ class pageModel { private $table; function __construct() { //Instanciamos la BD $this -> con = new gestionBD(); $this -> table = "template"; } public function listaPage() { try { $sql = "SELECT * FROM ".$this -> table; //Ejecución de consulta //$ejePagina = $con -> ejecutar($sql); return $lista = $this -> con -> ejecutararray($sql); } catch (Exception $e) { throw $e; } } public function listaDetallesPage(){ try { $sql = ""; //Ejecución de consulta //$ejePagina = $con -> ejecutar($sql); // return $sql; $lista = $this -> con -> ejecutararray($sql); $statusTable = $this -> statusTable(); $listaAttributePage = $this -> listaAttributePage(); $compilated = array('datos' => $lista, 'status' => $statusTable, 'attributepage' => $listaAttributePage); return $compilated; } catch (Exception $e) { throw $e; } } public function listaAttributePage(){ try { $sql = "SELECT * FROM attributepage"; return $lista = $this -> con -> ejecutararray($sql); } catch (Exception $e) { throw $e; } } public function statusTable(){ try { $sql = "SHOW TABLE STATUS LIKE '".$this -> table."'"; return $lista = $this -> con -> ejecutararray($sql); } catch (Exception $e) { throw $e; } } }
true
eb433b1bdd55903bcf77674dded2f989ec648e42
PHP
glennfriend/wordpress
/content/plugins/onramp-woo-custom-emails-plus/OnrampMini/Core/MainBase.php
UTF-8
766
2.625
3
[]
no_license
<?php namespace OnrampWooCustomEmailsPlus\OnrampMini\Core; /** * Class Base */ class MainBase { /** * @var array */ protected $data = []; /** * @param $key * @param null $defaultValue * @return mixed|null */ public function get($key, $defaultValue=null) { if (isset($this->data[$key])) { return $this->data[$key]; } return $defaultValue; } /** * @param $key * @param $value */ public function set($key, $value) { $this->data[$key] = $value; } // -------------------------------------------------------------------------------- // // -------------------------------------------------------------------------------- }
true
30ae018cd9255a8a32b575a86e721bd8633522a9
PHP
kevinmel2000/Biorhythm.XYZ
/inc/lib/mail_signature.class.php
UTF-8
15,868
2.5625
3
[ "MIT" ]
permissive
<?php /* php-mail-signature v1.0.1 https://github.com/louisameline/php-mail-signature Author: Louis Ameline - 04/2012 This stand-alone DKIM class is based on the work made on PHP-MAILER (see license below). The differences are : - it is a standalone class - it supports Domain Keys header - it supports UTF-8 - it will let you choose the headers you want to base the signature on - it will let you choose between simple and relaxed body canonicalization If the class fails to sign the e-mail, the returned DKIM header will be empty and the mail will still be sent, just unsigned. A php warning is thrown for logging. NOTE: you will NOT be able to use Domain Keys with PHP's mail() function, since it does not allow to prepend the DK header before the To and Subject ones. DKIM is ok with that, but Domain Keys is not. If you still want Domain Keys, you will have to manage to send your mail straight to your MTA without the mail() function. Successfully tested against Gmail, Yahoo Mail, Live.com, appmaildev.com Hope it helps and saves you plenty of time. Let me know if you find issues. For more info, you should read : http://www.ietf.org/rfc/rfc4871.txt http://www.zytrax.com/books/dns/ch9/dkim.html Original PHPMailer CC info : .---------------------------------------------------------------------------. | Software: PHPMailer - PHP email class | | Version: 5.2.1 | | Site: https://code.google.com/a/apache-extras.org/p/phpmailer/ | | ------------------------------------------------------------------------- | | Admin: Jim Jagielski (project admininistrator) | | Authors: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net | | : Marcus Bointon (coolbru) coolbru@users.sourceforge.net | | : Jim Jagielski (jimjag) jimjag@gmail.com | | Founder: Brent R. Matzelle (original founder) | | Copyright (c) 2010-2012, Jim Jagielski. All Rights Reserved. | | Copyright (c) 2004-2009, Andy Prevost. All Rights Reserved. | | Copyright (c) 2001-2003, Brent R. Matzelle | | ------------------------------------------------------------------------- | | License: Distributed under the Lesser General Public License (LGPL) | | http://www.gnu.org/copyleft/lesser.html | | This program is distributed in the hope that it will be useful - WITHOUT | | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or | | FITNESS FOR A PARTICULAR PURPOSE. | '---------------------------------------------------------------------------' */ //You can delete this function if you have PHP >= 5.3.0 if (!function_exists('array_replace_recursive')) { function recurse($array, $array1) { foreach ($array1 as $key => $value) { // create new key in $array, if it is empty or not an array if (!isset($array[$key]) || (isset($array[$key]) && !is_array($array[$key]))) { $array[$key] = array(); } // overwrite the value in the base array if (is_array($value)) { $value = recurse($array[$key], $value); } $array[$key] = $value; } return $array; } function array_replace_recursive($array, $array1) { // handle the arguments, merge one by one $args = func_get_args(); $array = $args[0]; if (!is_array($array)) { return $array; } for ($i = 1; $i < count($args); $i++) { if (is_array($args[$i])) { $array = recurse($array, $args[$i]); } } return $array; } } class mail_signature { private $private_key; private $domain; private $selector; private $options; private $canonicalized_headers_relaxed; public function __construct($private_key, $passphrase, $domain, $selector, $options = array()){ // prepare the resource $this -> private_key = openssl_get_privatekey($private_key, $passphrase); $this -> domain = $domain; $this -> selector = $selector; // this function will not let you ask for the simple header canonicalization because it would require more code, it would not be more secure and mails would yet be more likely to be rejected : no point in that $default_options = array( 'use_dkim' => true, // disabled by default, see why at the top of this file 'use_domainKeys' => false, // Allowed user, defaults is "@<MAIL_DKIM_DOMAIN>", meaning anybody in the MAIL_DKIM_DOMAIN domain. Ex: 'admin@mydomain.tld'. You'll never have to use this unless you do not control the "From" value in the e-mails you send. 'identity' => null, // "relaxed" is recommended over "simple" for better chances of success 'dkim_body_canonicalization' => 'relaxed', // "nofws" is recommended over "simple" for better chances of success 'dk_canonicalization' => 'nofws', // the default list of headers types you want to base the signature on. The types here (in the default options) are to be put in lower case, but the types in $options can have capital letters. If one or more of the headers specified are not found in the $headers given to the function, they will just not be used // if you supply a new list, it will replace the default one 'signed_headers' => array( 'mime-version', 'from', 'to', 'subject', 'reply-to' ) ); if(isset($options['signed_headers'])){ // lower case fields foreach($options['signed_headers'] as $key => $value){ $options['signed_headers']['key'] = strtolower($value); } // delete the default fields if a custom list is provided, not merge $default_options['signed_headers'] = array(); } // PHP >= 5.3.0. if(function_exists('array_replace_recursive')){ $this -> options = array_replace_recursive($default_options, $options); } else { trigger_error(sprintf('Your PHP version is lower than 5.3.0, please get the "array_replace_recursive" function on the following page (it is in the first comment) and declare it before using this class : http://php.net/manual/fr/function.array-replace-recursive.php'), E_USER_WARNING); } } // this function returns an array of relaxed canonicalized headers (lowercases the header type and cleans the new lines/spaces according to the RFC requirements). // only headers required for signature (specified by $options) will be returned // the result is an array of the type : array(headerType => fullHeader [, ...]), e.g. array('mime-version' => 'mime-version:1.0') private function _dkim_canonicalize_headers_relaxed($sHeaders){ $aHeaders = array(); // a header value which is spread over several lines must be 1-lined $sHeaders = preg_replace("/\n\s+/", " ", $sHeaders); $lines = explode("\r\n", $sHeaders); foreach($lines as $key => $line){ // delete multiple WSP $line = preg_replace("/\s+/", ' ', $line); if(!empty($line)){ // header type to lowercase and delete WSP which are not part of the header value $line = explode(':', $line, 2); $header_type = trim(strtolower($line[0])); $header_value = trim($line[1]); if(in_array($header_type, $this -> options['signed_headers']) or $header_type == 'dkim-signature'){ $aHeaders[$header_type] = $header_type.':'.$header_value; } } } return $aHeaders; } // apply RFC 4871 requirements before body signature. Do not modify private function _dkim_canonicalize_body_simple($body){ // unlike other libraries, we do not convert all \n in the body to \r\n here because the RFC does not specify to do it here. However it should be done anyway since MTA may modify them and we recommend you do this on the mail body before calling this DKIM class - or signature could fail. // remove multiple trailing CRLF while(mb_substr($body, mb_strlen($body, 'UTF-8')-4, 4, 'UTF-8') == "\r\n\r\n") $body = mb_substr($body, 0, mb_strlen($body, 'UTF-8')-2, 'UTF-8'); // must end with CRLF anyway if(mb_substr($body, mb_strlen($body, 'UTF-8')-2, 2, 'UTF-8') != "\r\n"){ $body .= "\r\n"; } return $body; } // apply RFC 4871 requirements before body signature. Do not modify private function _dkim_canonicalize_body_relaxed($body){ $lines = explode("\r\n", $body); foreach($lines as $key => $value){ // ignore WSP at the end of lines $value = rtrim($value); // ignore multiple WSP inside the line $lines[$key] = preg_replace('/\s+/', ' ', $value); } $body = implode("\r\n", $lines); // ignore empty lines at the end $body = $this -> _dkim_canonicalize_body_simple($body); return $body; } // apply RFC 4870 requirements before body signature. Do not modify private function _dk_canonicalize_simple($body, $sHeaders){ // Note : the RFC assumes all lines end with CRLF, and we assume you already took care of that before calling the class // keep only headers wich are in the signature headers $aHeaders = explode("\r\n", $sHeaders); foreach($aHeaders as $key => $line){ if(!empty($aHeaders)){ // make sure this line is the line of a new header and not the continuation of another one $c = substr($line, 0, 1); $is_signed_header = true; // new header if(!in_array($c, array("\r", "\n", "\t", ' '))){ $h = explode(':', $line); $header_type = strtolower(trim($h[0])); // keep only signature headers if(in_array($header_type, $this -> options['signed_headers'])){ $is_signed_header = true; } else { unset($aHeaders[$key]); $is_signed_header = false; } } // continuated header else { // do not keep if it belongs to an unwanted header if($is_signed_header == false){ unset($aHeaders[$key]); } } } else { unset($aHeaders[$key]); } } $sHeaders = implode("\r\n", $aHeaders); $mail = $sHeaders."\r\n\r\n".$body."\r\n"; // remove all trailing CRLF while(mb_substr($body, mb_strlen($mail, 'UTF-8')-4, 4, 'UTF-8') == "\r\n\r\n") $mail = mb_substr($mail, 0, mb_strlen($mail, 'UTF-8')-2, 'UTF-8'); return $mail; } // apply RFC 4870 requirements before body signature. Do not modify private function _dk_canonicalize_nofws($body, $sHeaders){ // HEADERS // a header value which is spread over several lines must be 1-lined $sHeaders = preg_replace("/\r\n\s+/", " ", $sHeaders); $aHeaders = explode("\r\n", $sHeaders); foreach($aHeaders as $key => $line){ if(!empty($line)){ $h = explode(':', $line); $header_type = strtolower(trim($h[0])); // keep only signature headers if(in_array($header_type, $this -> options['signed_headers'])){ // delete all WSP in each line $aHeaders[$key] = preg_replace("/\s/", '', $line); } else { unset($aHeaders[$key]); } } else { unset($aHeaders[$key]); } } $sHeaders = implode("\r\n", $aHeaders); // BODY // delete all WSP in each body line $body_lines = explode("\r\n", $body); foreach($body_lines as $key => $line){ $body_lines[$key] = preg_replace("/\s/", '', $line); } $body = rtrim(implode("\r\n", $body_lines))."\r\n"; return $sHeaders."\r\n\r\n".$body; } // the function will return no DKIM header (no signature) if there is a failure, so the mail will still be sent in the default unsigned way // it is highly recommended that all linefeeds in the $body and $headers you submit are in the CRLF (\r\n) format !! Otherwise signature may fail with some MTAs private function _get_dkim_header($body){ $body = ($this -> options['dkim_body_canonicalization'] == 'simple') ? $this -> _dkim_canonicalize_body_simple($body) : $this -> _dkim_canonicalize_body_relaxed($body); // Base64 of packed binary SHA-1 hash of body $bh = rtrim(chunk_split(base64_encode(pack("H*", sha1($body))), 64, "\r\n\t")); $i_part = ($this -> options['identity'] == null) ? '' : ' i='.$this -> options['identity'].';'."\r\n\t"; $dkim_header = 'DKIM-Signature: '. 'v=1;'."\r\n\t". 'a=rsa-sha1;'."\r\n\t". 'q=dns/txt;'."\r\n\t". 's='.$this -> selector.';'."\r\n\t". 't='.time().';'."\r\n\t". 'c=relaxed/'.$this -> options['dkim_body_canonicalization'].';'."\r\n\t". 'h='.implode(':', array_keys($this -> canonicalized_headers_relaxed)).';'."\r\n\t". 'd='.$this -> domain.';'."\r\n\t". $i_part. 'bh='.$bh.';'."\r\n\t". 'b='; // now for the signature we need the canonicalized version of the $dkim_header we've just made $canonicalized_dkim_header = $this -> _dkim_canonicalize_headers_relaxed($dkim_header); // we sign the canonicalized signature headers $to_be_signed = implode("\r\n", $this -> canonicalized_headers_relaxed)."\r\n".$canonicalized_dkim_header['dkim-signature']; // $signature is sent by reference in this function $signature = ''; if(openssl_sign($to_be_signed, $signature, $this -> private_key)){ $dkim_header .= rtrim(chunk_split(base64_encode($signature), 64, "\r\n\t"))."\r\n"; } else { trigger_error(sprintf('Could not sign e-mail with DKIM : %s', $to_be_signed), E_USER_WARNING); $dkim_header = ''; } return $dkim_header; } private function _get_dk_header($body, $sHeaders){ // Creating DomainKey-Signature $domainkeys_header = 'DomainKey-Signature: '. 'a=rsa-sha1; '."\r\n\t". 'c='.$this -> options['dk_canonicalization'].'; '."\r\n\t". 'd='.$this -> domain.'; '."\r\n\t". 's='.$this -> selector.'; '."\r\n\t". 'h='.implode(':', array_keys($this -> canonicalized_headers_relaxed)).'; '."\r\n\t". 'b='; // we signed the canonicalized signature headers + the canonicalized body $to_be_signed = ($this-> options['dk_canonicalization'] == 'simple') ? $this -> _dk_canonicalize_simple($body, $sHeaders) : $this -> _dk_canonicalize_nofws($body, $sHeaders); $signature = ''; if(openssl_sign($to_be_signed, $signature, $this -> private_key, OPENSSL_ALGO_SHA1)){ $domainkeys_header .= rtrim(chunk_split(base64_encode($signature), 64, "\r\n\t"))."\r\n"; } else { $domainkeys_header = ''; } return $domainkeys_header; } // you may leave $to and $subject empty if the corresponding headers are already in $headers public function get_signed_headers($to, $subject, $body, $headers){ $signed_headers = ''; // prevent header injection if(strpos($to, "\n") !== false or strpos($subject, "\n") !== false){ trigger_error(sprintf('Aborted mail signature because of potential header injection : %s', $to), E_USER_WARNING); } else { if(!empty($to) or !empty($subject)){ // To and Subject are not supposed to be present in $headers if you use the php mail() function, because it takes care of that itself in parameters for security reasons, so we reconstruct them here for the signature only $headers .= (mb_substr($headers, mb_strlen($headers, 'UTF-8')-2, 2, 'UTF-8') == "\r\n") ? '' : "\r\n"; if(!empty($to)) $headers .= 'To: '.$to."\r\n"; if(!empty($subject)) $headers .= 'Subject: '.$subject."\r\n"; } // get the clean version of headers used for signature $this -> canonicalized_headers_relaxed = $this -> _dkim_canonicalize_headers_relaxed($headers); if(!empty($this -> canonicalized_headers_relaxed)){ // Domain Keys must be the first header, it is an RFC (stupid) requirement if($this -> options['use_domainKeys'] == true){ $signed_headers .= $this -> _get_dk_header($body, $headers); } if($this -> options['use_dkim'] == true){ $signed_headers .= $this -> _get_dkim_header($body); } } else { trigger_error(sprintf('No headers found to sign the e-mail with ! %s', $to_be_signed), E_USER_WARNING); } } return $signed_headers; } } ?>
true
6861ad3a848c567a9cf6b2bfffb8ab4b76a072f3
PHP
renekoch/framework
/tests/Console/ConsoleParserTest.php
UTF-8
4,930
2.515625
3
[ "MIT" ]
permissive
<?php use Illuminate\Console\Parser; class ConsoleParserTest extends PHPUnit_Framework_TestCase { public function testBasicParameterParsing() { $results = Parser::parse('command:name'); $this->assertEquals('command:name', $results[0]); $results = Parser::parse('command:name {argument} {--option}'); $this->assertEquals('command:name', $results[0]); $this->assertEquals('argument', $results[1][0]->getName()); $this->assertEquals('option', $results[2][0]->getName()); $this->assertFalse($results[2][0]->acceptValue()); $results = Parser::parse('command:name {argument*} {--option=}'); $this->assertEquals('command:name', $results[0]); $this->assertEquals('argument', $results[1][0]->getName()); $this->assertTrue($results[1][0]->isArray()); $this->assertTrue($results[1][0]->isRequired()); $this->assertEquals('option', $results[2][0]->getName()); $this->assertTrue($results[2][0]->acceptValue()); $results = Parser::parse('command:name {argument?*} {--option=*}'); $this->assertEquals('command:name', $results[0]); $this->assertEquals('argument', $results[1][0]->getName()); $this->assertTrue($results[1][0]->isArray()); $this->assertFalse($results[1][0]->isRequired()); $this->assertEquals('option', $results[2][0]->getName()); $this->assertTrue($results[2][0]->acceptValue()); $this->assertTrue($results[2][0]->isArray()); $results = Parser::parse('command:name {argument?* : The argument description.} {--option=* : The option description.}'); $this->assertEquals('command:name', $results[0]); $this->assertEquals('argument', $results[1][0]->getName()); $this->assertEquals('The argument description.', $results[1][0]->getDescription()); $this->assertTrue($results[1][0]->isArray()); $this->assertFalse($results[1][0]->isRequired()); $this->assertEquals('option', $results[2][0]->getName()); $this->assertEquals('The option description.', $results[2][0]->getDescription()); $this->assertTrue($results[2][0]->acceptValue()); $this->assertTrue($results[2][0]->isArray()); $results = Parser::parse('command:name {argument?* : The argument description.} {--option=* : The option description.}'); $this->assertEquals('command:name', $results[0]); $this->assertEquals('argument', $results[1][0]->getName()); $this->assertEquals('The argument description.', $results[1][0]->getDescription()); $this->assertTrue($results[1][0]->isArray()); $this->assertFalse($results[1][0]->isRequired()); $this->assertEquals('option', $results[2][0]->getName()); $this->assertEquals('The option description.', $results[2][0]->getDescription()); $this->assertTrue($results[2][0]->acceptValue()); $this->assertTrue($results[2][0]->isArray()); } public function testShortcutNameParsing() { $results = Parser::parse('command:name {--o|option}'); $this->assertEquals('o', $results[2][0]->getShortcut()); $this->assertEquals('option', $results[2][0]->getName()); $this->assertFalse($results[2][0]->acceptValue()); $results = Parser::parse('command:name {--o|option=}'); $this->assertEquals('o', $results[2][0]->getShortcut()); $this->assertEquals('option', $results[2][0]->getName()); $this->assertTrue($results[2][0]->acceptValue()); $results = Parser::parse('command:name {--o|option=*}'); $this->assertEquals('command:name', $results[0]); $this->assertEquals('o', $results[2][0]->getShortcut()); $this->assertEquals('option', $results[2][0]->getName()); $this->assertTrue($results[2][0]->acceptValue()); $this->assertTrue($results[2][0]->isArray()); $results = Parser::parse('command:name {--o|option=* : The option description.}'); $this->assertEquals('command:name', $results[0]); $this->assertEquals('o', $results[2][0]->getShortcut()); $this->assertEquals('option', $results[2][0]->getName()); $this->assertEquals('The option description.', $results[2][0]->getDescription()); $this->assertTrue($results[2][0]->acceptValue()); $this->assertTrue($results[2][0]->isArray()); $results = Parser::parse('command:name {--o|option=* : The option description.}'); $this->assertEquals('command:name', $results[0]); $this->assertEquals('o', $results[2][0]->getShortcut()); $this->assertEquals('option', $results[2][0]->getName()); $this->assertEquals('The option description.', $results[2][0]->getDescription()); $this->assertTrue($results[2][0]->acceptValue()); $this->assertTrue($results[2][0]->isArray()); } }
true
368aac002056a86be5d4cafda981ef3ceab0087d
PHP
mrmiagi/acme2
/examples/example.php
UTF-8
1,894
2.59375
3
[ "MIT" ]
permissive
<?php /** * example php file * * @author Zhang Jinlong <466028373@qq.com> * @link https://github.com/stonemax/acme2 * @copyright Copyright &copy; 2018 Zhang Jinlong * @license https://opensource.org/licenses/mit-license.php MIT License */ include('../vendor/autoload.php'); use stonemax\acme2\Client; use stonemax\acme2\constants\CommonConstant; $domainInfo = [ CommonConstant::CHALLENGE_TYPE_HTTP => [ 'abc.example.com' ], CommonConstant::CHALLENGE_TYPE_DNS => [ '*.www.example.com', 'www.example.com', ], ]; $client = new Client(['alert@example.com'], '../data/', TRUE); $order = $client->getOrder($domainInfo, CommonConstant::KEY_PAIR_TYPE_RSA); // $order = $client->getOrder($domainInfo, CommonConstant::KEY_PAIR_TYPE_RSA, TRUE); // Renew certificates $challengeList = $order->getPendingChallengeList(); /* Verify authorizations */ foreach ($challengeList as $challenge) { $challengeType = $challenge->getType(); // http-01 or dns-01 $credential = $challenge->getCredential(); // echo $challengeType."\n"; // print_r($credential); /* http-01 */ if ($challengeType == CommonConstant::CHALLENGE_TYPE_HTTP) { /* example purpose, create or update the ACME challenge file for this domain */ setChallengeFile( $credential['identifier'], $credential['fileName'], $credential['fileContent'] ); } /* dns-01 */ else if ($challengeType == CommonConstant::CHALLENGE_TYPE_DNS) { /* example purpose, create or update the ACME challenge DNS record for this domain */ setDNSRecore( $credential['identifier'], $credential['dnsContent'] ); } /* Infinite loop until the authorization status becomes valid */ $challenge->verify(); } $certificateInfo = $order->getCertificateFile(); // print_r($certificateInfo);
true
930170ba3b7e3112cabb953bd157ca6d6316a759
PHP
jnider/carving
/export.php
UTF-8
1,076
2.78125
3
[]
no_license
<?php include_once('login.php'); function cleanData(&$str) { $str = preg_replace("/\t/", "\\t", $str); $str = preg_replace("/\r?\n/", "\\n", $str); $str = preg_replace("/,/", "\,", $str); } /****************************************/ // make sure the user is logged in if (!is_logged_in() && is_admin()) header('Location: index.php'); if (isset($_GET['action'])) { $page_action = $_GET['action']; } if (isset($page_action)) { // read the entire art table $res = pg_query($db, "select * from art order by book_id asc"); if (!$res) { $err = pg_last_error($db); return FALSE; } $items = pg_fetch_all($res); // clean the data for CSV format array_walk($row, __NAMESPACE__ . '\cleanData'); header("Content-type: text/csv"); header("Content-disposition: attachment; filename=carvings.csv"); //$num_items = count($items); echo "book_id,tag,artist,material,description\n"; // print a row at a time foreach ($items as &$item) { echo "${item['book_id']},${item['reg_tag']},${item['artist']},\"${item['material']}\",\"${item['description']}\"\n"; } }
true
a219fd1d1d8841675b69a2222f1453dce79dd302
PHP
travtex/codeup.dev
/public/address_book.php
UTF-8
6,717
3.046875
3
[]
no_license
<?php $new_entry = []; $errors = []; $filename = "data/address_book.csv"; $ex_error = ''; // Address book handler class included require_once('classes/address_data_store.php'); $address_book = new AddressDataStore($filename); class InvalidEntryException extends Exception {} // Loads address .csv file, or empty array if absent if (file_exists($filename)) { $address_array = $address_book->read(); } else { $address_array = []; } // Validate $_POST data, push new entry to array, save to .csv try { if(!empty($_POST)) { $new_entry = $address_book->set_entry($_POST); if(empty($new_entry[0]) || empty($new_entry[1]) || empty($new_entry[2]) || empty($new_entry[3]) || empty($new_entry[4])) { empty($new_entry[0]) ? $errors[] = "Name" : false; empty($new_entry[1]) ? $errors[] = "Address" : false; empty($new_entry[2]) ? $errors[] = "City" : false; empty($new_entry[3]) ? $errors[] = "State" : false; empty($new_entry[4]) ? $errors[] = "Zip" : false; } elseif ((strlen($new_entry[0]) > 125) || (strlen($new_entry[1]) > 125) || (strlen($new_entry[2]) > 125) || (strlen($new_entry[3]) > 125) || (strlen($new_entry[4]) > 125) || (strlen($new_entry[5]) > 125)) { throw new InvalidEntryException("Entries must be less than 125 characters."); } else { $address_array[] = $new_entry; $address_book->write($address_array); $new_entry = []; } } } catch (InvalidEntryException $e) { $ex_error = $e->getMessage(); } // Delete entries and save to .csv if(isset($_GET['remove'])) { unset($address_array[$_GET['remove']]); $address_book->write($address_array); header("Location: address_book.php"); exit(0); } if (count($_FILES) > 0 && $_FILES['file001']['error'] == 0) { if($_FILES['file001']['type'] == 'text/csv') { // Set the destination directory for uploads $upload_dir = '/vagrant/sites/codeup.dev/public/uploads/'; // Grab the filename from the uploaded file by using basename $filename = basename($_FILES['file001']['name']); // Create the saved filename using the file's original name and our upload directory $saved_filename = $upload_dir . $filename; // Move the file from the temp location to our uploads directory move_uploaded_file($_FILES['file001']['tmp_name'], $saved_filename); $new_addresses = new AddressDataStore("uploads/" . $filename); $address_array = array_merge($address_array, $new_addresses->read()); $address_book->write($address_array); } } ?> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Address Book</title> <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css"> <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" /> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script> <link rel="stylesheet" href="css/default.css"> <style> .snip { -webkit-transition: all .3s ease-in-out !important; } .snip:hover { display: inline-block; text-decoration: none; -webkit-transform: rotate(180deg) scale(1.4); position: relative; } </style> </head> <body> <div id="main"> <h2>Address Book</h2> <table class="table"> <tr> <td>Name</td> <td>Address</td> <td>City</td> <td>State</td> <td>Zip</td> <td>Phone</td> <td>Delete?</td> </tr> <? if(!empty($address_array)): ?> <? foreach($address_array as $key => $address): ?> <tr> <? foreach($address as $value): ?> <td><?= $value; ?></td> <? endforeach; ?> <td><a class="snip" href="?remove=<?= $key ?>">&#9988;</a></td> </tr> <? endforeach; ?> <? else: ?> <tr> <td style="text-align:center;"><strong>No Addresses Available</strong></td> </tr> <? endif; ?> <? if (!empty($ex_error)) : ?> <p><mark><?= $ex_error; ?></mark></p> <? endif; ?> </table> <hr /> <form method="POST" enctype="multipart/form-data" action="" name="form1"> <div class="form-group"> <label for="name">Name: <input type="text" class="form-control" name="name" id="name" placeholder="Name." <? if(!empty($new_entry[0])): ?> value="<?= $new_entry[0]; endif;?>" /> </label><br /> <label for="address">Address: <input type="text" class="form-control" name="address" id="address" placeholder="Address." <? if(!empty($new_entry[1])): ?> value="<?= $new_entry[1]; endif; ?>"/> </label><br /> <label for="city">City: <input type="text" class="form-control" name="city" id="city" placeholder="City." <? if(!empty($new_entry[2])): ?> value="<?= $new_entry[2]; endif; ?>"/> </label><br /> <label for="state">State: <input type="text" class="form-control" name="state" id="state" placeholder="State." <? if(!empty($new_entry[3])): ?> value="<?= $new_entry[3]; endif; ?>"/> </label><br /> <label for="zip">Zip: <input type="text" class="form-control" name="zip" id="zip" placeholder="Zip." <? if(!empty($new_entry[4])): ?> value="<?= $new_entry[4]; endif; ?>" /> </label><br /> <label for="phone">Phone: <input type="text" class="form-control" name="phone" id="phone" placeholder="Phone." <? if(!empty($new_entry[5])): ?> value="<?= $new_entry[5]; endif; ?>"/> </label><br /><br /> <? if(!empty($errors)) : ?> <p>Missing Fields: <mark> <? foreach($errors as $error) : ?> <?= $error ?> <? endforeach; ?></mark></p> <? endif; ?> <button type="submit" class="btn btn-primary">Add New Address</button> </div> </form> <hr /> <form method="POST" enctype="multipart/form-data" action="" name="form2"> <div class="form-group"> <p> <? if(count($_FILES) > 0 && $_FILES['file001']['name'] != "" && $_FILES['file001']['type'] !== 'text/csv') : echo "<p><mark>Uploaded files must be in .csv format.</mark></p>"; endif; ?> <label for="file001">Add a .csv file of Addresses: </label> <input type="file" id="file001" name="file001" /> </p> <button type="submit" class="btn btn-warning">Add From File</button> </div> </form> </div> </body> </html>
true
b09726031b383f9eacc9ea280930b5d36e7177a3
PHP
imzonnet/memorials
/app/Components/Memorials/Models/Video.php
UTF-8
993
2.546875
3
[]
no_license
<?php namespace App\Components\Memorials\Models; use App\Components\Memorials\Presenters\VideoPresenter; use App\User; use Illuminate\Database\Eloquent\Model; use Laracasts\Presenter\PresentableTrait; class Video extends Model { use PresentableTrait; protected $presenter = VideoPresenter::class; /** * The database table used by the model. * * @var string */ protected $table = 'granit_videos'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = ['mem_id', 'title', 'url', 'image', 'times', 'created_by']; /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function user() { return $this->belongsTo(User::class, 'created_by', 'id'); } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function memorial() { return $this->belongsTo(Memorial::class, 'mem_id', 'id'); } }
true
70b2cbb07d2c7391608959b1261c00e2dada1631
PHP
jingmian/SuperCooperationAPI
/app/Utils/UnderLineToHump.php
UTF-8
2,353
3.109375
3
[ "Apache-2.0" ]
permissive
<?php namespace App\Utils; class UnderLineToHump { /** * 下划线转驼峰 字符串转化函数 _make_by_id_ => makeById * * @param $str * * @return string $str string 输出转化后的字符串 */ public static function underLineToHump($str) { $str = trim($str, '_');//去除前后下划线_ $len = strlen($str); $out = strtolower($str[0]); for ($i = 1; $i < $len; $i++) { if (ord($str[$i]) == ord('_')) {//如果当前是下划线,去除,并且下一位大写 $out .= isset($str[$i + 1]) ? strtoupper($str[$i + 1]) : ''; $i++; } else { $out .= $str[$i]; } } return $out; } /** * 驼峰转下划线 字符串函数 MakeById => make_by_id * @param $str * * @return string */ public static function humpToUnderLine($str) { $len = strlen($str); $out = strtolower($str[0]); for ($i=1; $i<$len; $i++) { if(ord($str[$i]) >= ord('A') && (ord($str[$i]) <= ord('Z'))) { $out .= '_'.strtolower($str[$i]); }else{ $out .= $str[$i]; } } return $out; } /** * 驼峰式 与 下划线式 转化 * @param string $str 字符串 * @param string $mode 转化方法 hump驼峰|line下划线 * * @return mixed|null|string|string[] */ static public function pregConvertString($str,$mode='hump'){ if(empty($str)){ return ''; } switch ($mode){ case 'hump'://下划线转驼峰 $str = preg_replace_callback('/[-_]+([a-z]{1})/',function($matches){ return strtoupper($matches[1]); },$str); $str = ucfirst($str);//首字母大写 break; case 'line'://驼峰转下划线 $str = str_replace("_", "", $str); $str = preg_replace_callback('/([A-Z]{1})/',function($matches){ return '_'.strtolower($matches[0]); },$str); $str = trim($str,'_'); break; default: echo 'mode is error!'; } return $str; } }
true
1f0be450a78855d687645aecae03f1a1e57bd296
PHP
Zebedeu/repository-examples
/tests/Infrastructure/Persistence/PostRepositoryTest.php
UTF-8
2,887
2.65625
3
[ "MIT" ]
permissive
<?php use Domain\Model\Body; use Domain\Model\Post; use Domain\Model\PostId; abstract class PostRepositoryTest extends \PHPUnit_Framework_TestCase { /** * @var \Domain\Model\PostRepository */ protected $postRepository; public function setUp() { $this->postRepository = $this->createPostRepository(); } abstract protected function createPostRepository(); /** * @test */ public function itShouldRemovePost() { $post = $this->persistPost(); $this->postRepository->remove($post); $this->assertPostExist($post->id()); } protected function persistPost($body = 'irrelevant body', \DateTime $createdAt = null, PostId $id = null) { $this->persist( $post = new Post( $id ?: $this->postRepository->nextIdentity(), new Body($body), $createdAt ) ); return $post; } abstract protected function persist(Post $post); private function assertPostExist($id) { $result = $this->postRepository->postOfId($id); $this->assertNull($result); } /** * @test */ public function itShouldFetchLatestPostsByMethod() { $this->assertPostsAreFetchedWith(function() { return $this->postRepository->latestPosts(new \DateTime('-24 hours')); }); } private function assertPostsAreFetchedWith(callable $fetchPostsFn) { $this->persistPost('a year ago', new \DateTime('-1 year')); $this->persistPost('a month ago', new \DateTime('-1 month')); $this->persistPost('few hours ago', new \DateTime('-3 hours')); $this->persistPost('few minutes ago', new \DateTime('-2 minutes')); $this->assertPostContentsEquals(['few hours ago', 'few minutes ago'], $fetchPostsFn()); } private function assertPostContentsEquals($expectedContents, array $posts) { $postContents = array_map(function(Post $post) { return $post->body()->content(); }, $posts); $this->assertEquals( array_diff($expectedContents, $postContents), array_diff($postContents, $expectedContents) ); } /** * @test */ public function sizeShouldMatchNumberOfStoredPosts() { $this->persistPost(); $this->persistPost(); $size = $this->postRepository->size(); $this->assertEquals(2, $size); } /** * @test */ public function itShouldFetchLatestPostsBySpecification() { $this->assertPostsAreFetchedWith(function() { return $this->postRepository->query( $this->createLatestPostSpecification(new \DateTime('-24 hours')) ); }); } abstract protected function createLatestPostSpecification(\DateTime $since); }
true
5466e721225be156948a76495f45b8093d3c8a89
PHP
Adms1/php
/flinnt/database/migrations/2018_10_23_062112_create_str_book_table.php
UTF-8
1,269
2.578125
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateStrBookTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('book', function(Blueprint $table) { $table->bigInteger('book_id', true)->unsigned(); $table->integer('publisher_id')->unsigned()->index('FK_book_publisher_publisher_id'); $table->integer('covertype_id')->unsigned()->nullable(); $table->integer('language_id')->unsigned()->nullable()->index('FK_book_language_language_id'); $table->string('book_name', 100); $table->string('isbn', 40)->nullable(); $table->string('series', 100)->nullable(); $table->string('book_guid', 100); $table->string('hs_code', 40)->nullable(); $table->boolean('is_active')->default(1)->comment('1 = Active, 0 = Inactive'); $table->boolean('is_academic')->default(1)->comment('1 = Active, 0 = Inactive'); $table->decimal('book_width', 10, 0)->nullable(); $table->decimal('book_length', 10, 0)->nullable(); $table->decimal('book_height', 10, 0)->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('str_book'); } }
true
b0df1437f26afff6a21ba64f33a22701e90c633c
PHP
Uncle-Yakult/UP
/php-hxbc4/10-__call()、__callstatic().php
UTF-8
628
3.484375
3
[]
no_license
<?php header('content-type:text/html;charset=utf-8'); class Student { /* * 当调用一个不存在的普通方法时自动调用 * @param $fn_name string 方法名 * @param $fn_args array 参数数组 */ public function __call($fn_name,$fn_args) { echo "学生类中没有{$fn_name}方法<br>"; print_r($fn_args); } /* * 当调用一个不存在的静态的时候自动调用 */ public static function __callstatic($fn_name,$fn_args){ echo "<br>{$fn_name}静态方法<br>"; } } $stu = new Student; $stu -> show(10,20,30); Student::display(); ?>
true
5bf9391e6e2927ebb793a21ba7d7c0304c31ba26
PHP
sukei/bsod-bundle
/autoload.php
UTF-8
1,799
2.84375
3
[ "MIT" ]
permissive
<?php if (!file_exists('../vendor/composer/autoload_psr4.php')) { return; } $map = require '../vendor/composer/autoload_psr4.php'; $autoload = function ($class) use ($map) { if (strpos($class, 'Symfony\\') !== 0 && strpos($class, 'App\\') !== 0) { return null; } if (random_int(0, 100) !== 0) { return null; } foreach ($map as $prefix => $basePaths) { if (strpos($class, $prefix) !== 0) { continue; } foreach ($basePaths as $basePath) { $path = $basePath.DIRECTORY_SEPARATOR.substr(str_replace('\\', DIRECTORY_SEPARATOR, $class), strlen($prefix)).'.php'; if (file_exists($path)) { $parts = explode('\\', $class); $namespace = implode('\\', array_slice($parts, 0, -1)); $clazz = array_pop($parts); $content = <<<PHP namespace $namespace; /** * The class is way lighter this way. It'll for sure improve the performances of your app! */ class $clazz { /** * Faster than ever! */ public function __call(\$name, \$args) { } /** * You probably don't need that. */ public function __get(\$name) { return null; } /** * Nor this one. */ public function __set(\$name, \$value) { } /** * Yep! It has been set. */ public function __isset(\$name) { return true; } /** * Who cares? */ public function __unset(\$name) { } /** * I'm my own father. */ public function __clone() { return \$this; } } PHP; eval($content); } } } return null; }; spl_autoload_register($autoload, false, true);
true
e64a6d9252ca8b741fb201cee814b8b07765c1eb
PHP
goksagun/postalcode-api
/app/Repositories/TokenRepository.php
UTF-8
1,204
2.625
3
[]
no_license
<?php namespace App\Repositories; use App\Consumer; use App\Token; use Carbon\Carbon; class TokenRepository extends AbstractRepository { /** * @var Token */ protected $model; /** * TokenRepository constructor. * * @param Token $model */ public function __construct(Token $model) { parent::__construct($model); $this->model = $model; } /** * @param Consumer $consumer * @param $data * * @return Token */ public function insert(Consumer $consumer, array $data) { $token = new Token($data); $consumer->token()->save($token); return $token; } /** * @param $accessKey * @param $accessSecret * * @return bool */ public function verifyTokenAccessKeyAndAccessSecret($accessKey, $accessSecret) { return Token::where('access_key', $accessKey) ->where('access_secret', $accessSecret) ->where('expired_at', '>=', Carbon::now()) ->exists(); } /** * @return mixed */ public function generateTokenAttributes() { return $this->model->generateTokens(); } }
true
7c1bde34ea3dda2ed4b28fe51925b60c35a8f1e1
PHP
priskz/sorad-module-core
/src/Priskz/SORAD/Auth/API/Laravel/Login/Action.php
UTF-8
1,296
2.78125
3
[ "MIT" ]
permissive
<?php namespace Priskz\SORAD\Auth\API\Laravel\Login; use Auth; use Priskz\Payload\Payload; use Priskz\SORAD\Action\LaravelAction; class Action extends LaravelAction { /** * @var array Data configuration. */ protected $config = [ 'email' => 'required', 'password' => 'required', ]; /** * Logic */ public function execute($data) { // Process Domain Data Keys $payload = $this->processor->process($data, $this->config); // Verify that the data has been sanitized and validated. if( ! $payload->isStatus(Payload::STATUS_VALID)) { return $payload; } // Set the execute data. $executeData = $payload->getData(); // Init $returnData = [ 'status' => 'log_in_failed', 'data' => false ]; if(filter_var($data['email'], FILTER_VALIDATE_EMAIL)) { // Attempt the log in by email. $attempt = Auth::attempt(['email' => $data['email'], 'password' => $data['password']], true); } else { // Attempt the log in by username. $attempt = Auth::attempt(['username' => $data['email'], 'password' => $data['password']], true); } if($attempt) { // Set return data. $returnData['data'] = Auth::user(); $returnData['status'] = 'logged_in'; } return new Payload($returnData['data'], $returnData['status']); } }
true
069bd50c6622ada3c0520313364c186a495fae26
PHP
peachpiecompiler/peachpie
/tests/operators/equality_001.php
UTF-8
214
2.90625
3
[ "Apache-2.0" ]
permissive
<?php namespace operators\equality_001; function b($value) { echo ($value == null) ? 0 : 1; } function test() { b(null); b(true); b(false); b([]); b(new \stdClass); b("hello"); b("0"); b([0]); } test();
true
1855b51810a8fe0b3e0f419b28da74af50edc4e7
PHP
NuhashHaque/HR-Managment-KUET-
/resources/views/project.php
UTF-8
786
2.796875
3
[]
no_license
<?php if(isset($_GET['submit'])) { $servername = "localhost"; $username = "root"; $password = ""; $dbname = "hrkuet"; // Create connection $conn = new mysqli($servername, $username, $password,$dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully"; $name = $_GET['name']; $supervisor_id = $_GET['supervisor_id']; $duration = $_GET['duration']; $fund = $_GET['fund']; // Attempt insert query execution $sql = "INSERT INTO project (name,supervisor_id,duration,fund) VALUES ('$name','$supervisor_id','$duration','$fund')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; }$conn->close(); unset($_GET['submit']); } ?>
true
140dd3ebfd3027296860e132290222bfa3e61586
PHP
trxo/PHPTools
/DB/DB.php
UTF-8
6,300
3.109375
3
[]
no_license
<?php /** * Created by PhpStorm. * User: zxt778@gmail.com * Date: 2017/7/28 * Time: 下午2:07 */ class DB { //pdo对象 private $_pdo = null; //存放实例对象 static private $_instance = null; /** * 获取db实例 * @return DB|null */ static public function getInstance() { if (!(self::$_instance instanceof self)) { self::$_instance = new self(); } return self::$_instance; } /** * 防止克隆 */ private function __clone() { } /** * 私有构造 * DB constructor. */ private function __construct() { try { $this->_pdo = new PDO(DB_DNS, DB_USER, DB_PASS); $this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { $this->log($e->getMessage()); } } /** * 新增 * @param $_table * @param array $_addData * @return int */ public function add($_table, Array $_addData) { $_addFields = array(); $_addValues = array(); foreach ($_addData as $_key => $_value) { $_addFields[] = $_key; $_addValues[] = $_value; } $_addFields = implode(',', $_addFields); $_addValues = implode("','", $_addValues); $_sql = "INSERT INTO $_table ($_addFields) VALUES ('$_addValues')"; return $this->execute($_sql)->rowCount(); } /** * 修改 * @param $_table * @param array $_param * @param array $_updateData * @return int */ public function update($_table, Array $_param, Array $_updateData) { $_where = $_setData = ''; foreach ($_param as $_key => $_value) { $_where .= $_value . ' AND '; } $_where = 'WHERE ' . substr($_where, 0, -4); foreach ($_updateData as $_key => $_value) { if (is_array($_value)) { $_setData .= "$_key=$_value[0],"; } else { $_setData .= "$_key='$_value',"; } } $_setData = substr($_setData, 0, -1); $_sql = "UPDATE $_table SET $_setData $_where"; return $this->execute($_sql)->rowCount(); } /** * 删除 * @param $_table * @param array $_param * @return int */ public function delete($_table, Array $_param) { $_where = ''; foreach ($_param as $_key => $_value) { $_where .= $_value . ' AND '; } $_where = 'WHERE ' . substr($_where, 0, -4); $_sql = "DELETE FROM $_table $_where"; return $this->execute($_sql)->rowCount(); } /** * 查询 * @param $_table * @param array $_fileld * @param array $_param * @return mixed */ public function select($_table, Array $_fileld, Array $_param = array()) { $_limit = $_order = $_where = $_like = ''; if (is_array($_param) && !empty($_param)) { $_limit = isset($_param['limit']) ? 'LIMIT ' . $_param['limit'] : ''; $_order = isset($_param['order']) ? 'ORDER BY ' . $_param['order'] : ''; if (isset($_param['where'])) { foreach ($_param['where'] as $_key => $_value) { $_where .= $_value . ' AND '; } $_where = 'WHERE ' . substr($_where, 0, -4); } if (isset($_param['like'])) { foreach ($_param['like'] as $_key => $_value) { $_like = "WHERE $_key LIKE '%$_value%'"; } } } $_selectFields = implode(',', $_fileld); $_sql = "SELECT $_selectFields FROM $_table $_where $_like $_order $_limit"; $_stmt = $this->execute($_sql); $_result = array(); while (!!$_objs = $_stmt->fetch()) { $_result[] = $_objs; } return $_result; } /** * sql语句查询 * @param $_sql * @return array */ public function query($_sql) { $_stmt = $this->execute($_sql); $_result = array(); while (!!$_objs = $_stmt->fetch()) { $_result[] = $_objs; } return $_result; } /** * 总记录数 * @param $_table * @param array $_param * @return mixed */ public function total($_table, Array $_param = array()) { $_where = ''; if (isset($_param['where'])) { foreach ($_param['where'] as $_key => $_value) { $_where .= $_value . ' AND '; } $_where = 'WHERE ' . substr($_where, 0, -4); } $_sql = "SELECT COUNT(*) as count FROM $_table $_where"; $_stmt = $this->execute($_sql); return $_stmt->fetchObject()->count; } /** * 执行SQL * @param $_sql * @return PDOStatement */ public function execute($_sql) { try { $_stmt = $this->_pdo->prepare($_sql); $_stmt->execute(); } catch (PDOException $e) { $this->log('SQL语句:' . $_sql . ' 错误信息:' . $e->getMessage()); } return $_stmt; } /** * 开启事务 */ public function startTransaction() { $this->_pdo->beginTransaction(); } /** * 事务回滚 */ public function rollBack() { $this->_pdo->rollBack(); } /** * 提交事务 */ public function commit() { $this->_pdo->commit(); } /** * log * @param $_msg */ private function log($_msg) { exit($_msg); } } // //define("DB_DNS", $dsn = "pgsql:host=192.168.1.26;port=5432;dbname=fusionpbx;"); //define("DB_USER", "postgres"); //define("DB_PASS", ""); //define("DB_CHARSET", ""); // //$_obj = DB::getInstance(); //$total = $_obj->total('v_ivr_menus'); //$arrs = $_obj->select('v_ivr_menus', ['*']); // //$_obj->add("v_ivr_menus",['ivr_menu_uuid'=>'38a28ff0-71b3-11e7-a05e-155593030c3e']); //$_obj->update("v_ivr_menus",["ivr_menu_uuid='38a28ff0-71b3-11e7-a05e-155593030c3e'"],['ivr_menu_name'=>'obj']); //$_obj->delete("v_ivr_menus",["ivr_menu_uuid='38a28ff0-71b3-11e7-a05e-155593030c3e'"]);
true
6b1022574dd187e8a04812863ac8866ad3e67bcb
PHP
AlexaRuth/IDM-6630-SP-18-FORMS-Kusick-Alex
/checkIn5_2/code/stage.php
UTF-8
1,610
3.046875
3
[]
no_license
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <title>Week 5 Assignment</title> </head> <body> <header> <?php echo "<h1>Favorite Superhero</h1>";?> <nav><?php include "inc/nav.php" ?></nav> </header> <?php require 'inc/conn.php'; $query = "DELETE FROM hero WHERE id = " .$_REQUEST['id']; $hero_to_update = $conn->query ($query)->fetch('name'); //echo $hero_to_update['id']; //echo $query; ?> <form action="update.php" method="post"> <input type="text" name="name" value="<?php $hero_to_update['name'];?>"> <input type="submit" value="Add Hero"> </form> <?php $query = "SELECT * FROM hero ORDER BY id DESC"; //$query = "SELECT * FROM hero WHERE name = 'Sailormoon' "; //to find a specific piece of information foreach ($conn->query($query) as $hero) { //echo $hero['id'] . ", " . $hero['name']; //do not show ID echo "<ul>"; echo "<li>" . $hero['id'] . "</li>"; echo "<li>" . $hero['name'] . "</li>"; echo "<li> <form action='stage.php' method='post'> <input type='text' name='name' value='". $hero['id'] . "'/> <input type='submit' value='Edit'></submit> </form> </li>"; echo "<li> <form action='delete.php' method='post'> <input type='text' name='name' value='". $hero['id'] . "'/> <input type='submit' value='Delete'></submit> </form> </li>"; echo "</ul>"; } //} catch(PDOException $e) { // echo "Select Failed: " . $e->getMessage(); // exit(); //} ?> </body> </html>
true
03f7740faf96b5edb085250b82d153c45908aa16
PHP
jimdelois/raml-generator
/src/Raml/Generator/Model/Uri/BaseUri.php
UTF-8
733
2.828125
3
[]
no_license
<?php namespace DeLois\Raml\Generator\Model\Uri; use DeLois\Raml\Generator\Model\AbstractUri; class BaseUri extends AbstractUri { protected function _validate( $uri ) { // TODO: Validate for https://www.ietf.org/rfc/rfc2396.txt - URI Format // TODO: Validate for https://tools.ietf.org/html/rfc6570 - URI Template Format // Stupid validation for now: return strpos( $uri, 'http' ) === 0; // TODO: Might make sense to throw an exception if there is no {version} set // in the API, yet the $base_uri template provides one } protected function _getFormatDescripton() { return 'Uri must be absolute (http, https, etc) conforming to RFC2396 or templated in conjunction with RFC6570.'; } }
true
b145f44454fef76afdb3bda33bd3be46b502498f
PHP
ANDREW-LVIV/TextAnalyzer
/tests/CalculateHashTest.php
UTF-8
854
2.65625
3
[ "MIT" ]
permissive
<?php use PHPUnit\Framework\TestCase; class CalculateHashTest extends TestCase { /** * @dataProvider textDataProvider * * @param $input * @param $expected */ public function testFunction($input, $expected) { $analyze = new TextAnalyzer\Analyzer(); $this->assertEquals($expected, $analyze->calculateHash($input)); $this->assertIsString($analyze->calculateHash($input)); } public function textDataProvider() { return [ ['текст', 'e481113f85a89878a87d52b22c7f917d6e7280e6'], ['lviv.travel - Плануй подорож до Львова! Корисні поради та цікава інформація про те, куди піти в місті. Події, заклади, музеї та маршрути.', 'c868d5fc53046e7a32b2600da89b377ea09c42f2'], ]; } }
true
f12f313be4ec78ec753067434e7d0553c8df66c7
PHP
ktvincent/tp_phpsql
/films.php
UTF-8
2,435
2.78125
3
[]
no_license
<!DOCTYPE html> <html> <!-- Il faut que tu commit à chaque fois que tu reussi une partie --> <!-- exo1: clarté: 2/4 fonctionnement: 4/4 --> <!-- exo2: clarté: 2.5/4 fonctionnement: 1.5/4 artistique: 1/1 --> <!-- exo3: 0/4 --> <body> <?php $debug = FALSE; if (isset($_GET['nom'])){ $x = $_GET['nom']; echo "$x"; } ?> <h1>FILMS</h1> <form method="get" action="films.php"> <fieldset> <SELECT name='nom' size="1"> <?php $conn = mysqli_connect("dwarves.iut-fbleau.fr","kwan-tea","CUDDZA1662","kwan-tea") or die("Impossible"); $liste = mysqli_query($conn,"SELECT DISTINCT nom FROM Artiste"); echo "<OPTION>".$x; while($artiste=mysqli_fetch_assoc($liste)){ echo "<OPTION>".$artiste['nom']; // manque </option> } ?> </SELECT> <input type="submit" name="Chercher" value="Chercher" /> </fieldset> </form> <table border=1> <tr> <th> Titre </th> <th> Annee </th> <th> Genre </th> <th> Realisateur </th> </tr> <?php $link = mysqli_connect("dwarves.iut-fbleau.fr","kwan-tea","CUDDZA1662","kwan-tea") // pas besoin de se connecter 2 fois or die("Impossible"); $queryId = "SELECT * FROM Artiste WHERE nom = '".$x."'"; if ($debug) echo $queryId."<br>"; $resultQueryID = mysqli_query($link,$queryId); $artistId; if($resultQueryID){ $firstLine= mysqli_fetch_assoc($resultQueryID); $artistId = $firstLine['idArtiste']; } $query = "SELECT titre,annee,genre,nom FROM Film F JOIN Artiste A ON F.idMes = A.idArtiste WHERE F.idMes = $artistId"; if ($debug) echo $query."<br>"; $resultat= mysqli_query($link,$query); if($resultat){ while($ligne= mysqli_fetch_assoc($resultat)){ //manque une condition pour prendre seulement le realisateur en question pour l'exo 2 echo "<tr>"; echo "<td>".$ligne['titre']."</td>"; echo "<td>".$ligne['annee']."</td>"; echo "<td>".$ligne['genre']."</td>"; echo "<td>".$ligne['nom']."</td>"; echo "</tr>"; } } //manque la deconnexion ?> </table> </body> </html>
true
ecf5dab9a4990c7977c12797f547d90d921f7fd3
PHP
xavierws/backend_hmtiapp
/database/seeders/UserSeeder.php
UTF-8
5,181
2.59375
3
[ "MIT" ]
permissive
<?php namespace Database\Seeders; use App\Models\AdministratorProfile; use App\Models\CollegerProfile; use App\Models\User; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Str; class UserSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // CollegerProfile::factory()->count(300)->create()->each(function ($profile) { // User::factory()->state([ // 'userable_id' => $profile->id // ])->create(); // }); // // AdministratorProfile::factory()->count(1)->create(); // DB::table('users')->insert([ // 'id' => 301, // 'email' => env('MAIL_USER_ADMIN'), // 'email_verified_at' => now(), // 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password // 'remember_token' => Str::random(10), // 'userable_id' => 1, // 'userable_type' => 'App\Models\AdministratorProfile' // ]); $this->generateColleger(); $this->generateAdmin(); DB::table('colleger_profiles')->insert([ 'name' => 'test_name', 'nrp'=> '05211840000001', 'birthday' => '1970-01-01', 'address' => 'test_address', 'role_id' => 1, 'created_at' => now(), 'updated_at' => now(), ]); $colleger = CollegerProfile::orderBy('id', 'desc')->first(); DB::table('users')->insert([ 'email' => 'rakaabadisusilo@gmail.com', 'email_verified_at' => now(), 'password' => Hash::make('password'), 'remember_token' => Str::random(10), 'userable_id' => $colleger->id, 'userable_type' => 'App\Models\CollegerProfile', 'created_at' => now(), 'updated_at' => now(), ]); } private function generateColleger() { $path = 'database/seeders/dataset/data-hmti.csv'; $array = $fields = array(); $i = 0; $handle = @fopen($path, "r"); if ($handle) { while (($row = fgetcsv($handle, 4096)) !== false) { if (empty($fields)) { $fields = $row; continue; } foreach ($row as $k=>$value) { $array[$i][$fields[$k]] = $value; } $i++; } if (!feof($handle)) { echo "Error: unexpected fgets() fail\n"; } fclose($handle); } foreach ($array as $row) { $nrp = (int)$row['nrp']; $birthday = date('Y-m-d', strtotime($row['birthday'])); DB::table('colleger_profiles')->insert([ 'name' => $row['name'], 'nrp'=> $nrp, 'birthday' => $birthday=='1970-01-01'? null:$birthday, 'address' => $row['address']===''? null:$row['address'], 'role_id' => 1, 'created_at' => now(), 'updated_at' => now(), ]); $colleger = CollegerProfile::orderBy('id', 'desc')->first(); DB::table('users')->insert([ 'email' => $row['email'], 'email_verified_at' => now(), 'password' => Hash::make($nrp), 'remember_token' => Str::random(10), 'userable_id' => $colleger->id, 'userable_type' => 'App\Models\CollegerProfile', 'created_at' => now(), 'updated_at' => now(), ]); } } private function generateAdmin() { DB::table('administrator_profiles')->insert([ [ 'name' => 'HMTI-ITS 1', 'role_id' => 2, 'created_at' => now(), 'updated_at' => now(), ], [ 'name' => 'HMTI-ITS 2', 'role_id' => 2, 'created_at' => now(), 'updated_at' => now(), ], [ 'name' => 'HMTI-ITS 3', 'role_id' => 2, 'created_at' => now(), 'updated_at' => now(), ] ]); DB::table('users')->insert([ [ 'email' => 'hosthmtiits@gmail.com', 'email_verified_at' => now(), 'password' => Hash::make('hmti_admin'), 'remember_token' => Str::random(10), 'userable_id' => 1, 'userable_type' => 'App\Models\AdministratorProfile', 'created_at' => now(), 'updated_at' => now(), ], [ 'email' => 'hmtiits1920@gmail.com', 'email_verified_at' => now(), 'password' => Hash::make('hmti_admin'), 'remember_token' => Str::random(10), 'userable_id' => 2, 'userable_type' => 'App\Models\AdministratorProfile', 'created_at' => now(), 'updated_at' => now(), ], ]); } }
true
88a0a8a36f5f029b8ec0bae8efb4bc6fe0598a2a
PHP
abir-taheer/urban-doodle
/requests/submit_vote.php
UTF-8
1,141
2.78125
3
[ "MIT" ]
permissive
<?php // If they got to this stage, that means their form and all other relevant information was already verified. // Even in the case of a duplicate vote, mysql will throw an exception because of the unique index on the verification_hash column // Just insert their choices into the database now try { $vote_data = $user->getConfirmationData($form["extra"]); $e = new Election($vote_data["db_code"]); if( $e->electionState() === 0 && ! $user->hasVoted($vote_data["db_code"]) ){ $verification = hash("sha256", $vote_data["db_code"].$user->u_id); Database::secureQuery("INSERT INTO `votes` (`db_code`, `content`, `verification_hash`, `grade`) VALUES (:d, :c, :v, :g)", array(":d"=>$vote_data["db_code"], ":c"=>$vote_data["content"], ":v"=>$verification, ":g"=>$user->grade), null ); $response["status"] = "success"; } else { $response["status"] = "error"; $response["message"][] = "Error: You have already voted"; } } catch (Exception $e){ $response["status"] = "error"; $response["message"][] = "Unexpected Error Please Send This To Developer: ".$e; }
true
0be4fc3c6696b0d1d0caf5f141b394e475c0dcf2
PHP
lrpatricio/warlock
/src/Warlock/Utils/Math.php
UTF-8
2,030
3.390625
3
[]
no_license
<?php /** * Created by PhpStorm. * User: leona * Date: 07/04/2017 * Time: 18:16 */ namespace Warlock\Utils; use Warlock\Exception\MathException; use Warlock\Exception\MessageErrors; class Math { /** * @param float $base * @param float $exp * @return float */ public static function pow($base, $exp) { return pow($base, $exp); } /** * @param number $number * @param int $precision * @param int $mode * @return float */ public static function round($number, $precision = 0, $mode = PHP_ROUND_HALF_UP) { return round($number, $precision, $mode); } /** * @param float $number * @param int $precision * @return float */ public static function ceil($number, $precision = 0) { if($precision > 0) { $pow = self::pow(10, $precision); $result = ceil($number * $pow) / $pow; return $result; } else { return ceil($number); } } /** * @param float $number * @param int $precision * @return float */ public static function floor($number, $precision = 0) { if($precision > 0) { $pow = self::pow(10, $precision); $result = floor($number * $pow) / $pow; return $result; } else { return floor($number); } } /** * Soma os valores dos itens do array * @param array $values * @return float * @throws MathException */ public static function sum($values) { if(!is_array($values)) { throw MessageErrors::get_exception_by_code(5001); } $response = 0; foreach ($values as $item) { if (!is_numeric($item)) { throw MessageErrors::get_exception_by_code(5002); } $response += $item; } return $response; } }
true
9fa21624f57b84c64d66906824f314e82beef2e5
PHP
efuentesp/ento_cdn_theme
/template.php
UTF-8
7,715
2.625
3
[]
no_license
<?php /** * @file * The primary PHP file for this theme. */ /** * Bootstrap theme wrapper function for the primary menu links. */ function ento_cdn_menu_tree__primary(&$variables) { return $variables['tree']; } /** * Returns HTML for a menu link and submenu. * * @param array $variables * An associative array containing: * - element: Structured array data for a menu link. * * @return string * The constructed HTML. * * @see theme_menu_link() * * @ingroup theme_functions */ function ento_cdn_menu_link(array $variables) { $element = $variables['element']; $sub_menu = ''; if ($element['#below']) { // Prevent dropdown functions from being added to management menu so it // does not affect the navbar module. if (($element['#original_link']['menu_name'] == 'management') && (module_exists('navbar'))) { $sub_menu = drupal_render($element['#below']); } elseif ((!empty($element['#original_link']['depth'])) && ($element['#original_link']['depth'] == 1)) { // Add our own wrapper. unset($element['#below']['#theme_wrappers']); $sub_menu = '<ul class="dropdown-menu">' . drupal_render($element['#below']) . '</ul>'; // Generate as standard dropdown. $element['#title'] .= ' <span class="caret"></span>'; $element['#attributes']['class'][] = 'dropdown'; $element['#localized_options']['html'] = TRUE; // Set dropdown trigger element to # to prevent inadvertant page loading // when a submenu link is clicked. $element['#localized_options']['attributes']['data-target'] = '#'; $element['#localized_options']['attributes']['class'][] = 'dropdown-toggle'; $element['#localized_options']['attributes']['data-toggle'] = 'dropdown'; } } // On primary navigation menu, class 'active' is not set on active menu item. // @see https://drupal.org/node/1896674 if (($element['#href'] == $_GET['q'] || ($element['#href'] == '<front>' && drupal_is_front_page())) && (empty($element['#localized_options']['language']))) { $element['#attributes']['class'][] = 'active'; } $output = l($element['#title'], $element['#href'], $element['#localized_options']); return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n"; } /** * Returns HTML for a breadcrumb trail. * * @param array $variables * An associative array containing: * - breadcrumb: An array containing the breadcrumb links. * * @return string * The constructed HTML. * * @see theme_breadcrumb() * * @ingroup theme_functions */ function ento_cdn_breadcrumb($variables) { // Use the Path Breadcrumbs theme function if it should be used instead. //if (_bootstrap_use_path_breadcrumbs()) { // return path_breadcrumbs_breadcrumb($variables); //} $output = ''; $breadcrumb = $variables['breadcrumb']; if (!empty($breadcrumb)) { // Provide a navigational heading to give context for breadcrumb links to // screen-reader users. Make the heading invisible with .element-invisible. $output = '<h2 class="element-invisible">' . t('You are here') . '</h2>'; $crumbs = '<ol class="breadcrumb">'; $array_size = count($breadcrumb); $i = 0; while ( $i < $array_size) { $crumbs .= '<li'; if ($i+1 == $array_size) { $crumbs .= ' class="active"'; } $crumbs .= '>'; if ($i+1 == $array_size) { $crumbs .= ' <strong>' . $breadcrumb[$i] . '</strong>' . '</li>'; } else { $crumbs .= $breadcrumb[$i] . '</li>'; } $i++; } $crumbs .= '</ol>'; return $crumbs; } // Determine if we are to display the breadcrumb. /* $bootstrap_breadcrumb = bootstrap_setting('breadcrumb'); if (($bootstrap_breadcrumb == 1 || ($bootstrap_breadcrumb == 2 && arg(0) == 'admin')) && !empty($breadcrumb)) { $output = theme('item_list', array( 'attributes' => array( 'class' => array('breadcrumb'), ), 'items' => $breadcrumb, 'type' => 'ol', )); } return $output;*/ } function ento_cdn_preprocess_page (&$variables) { if ($variables['logged_in']) { $user = user_load($variables['user']->uid); if (isset($user->picture->uri)) { $path = $user->picture->uri; } else { $path = variable_get('user_picture_default', ''); } $variables['user_avatar'] = theme_image_style( array( 'style_name' => 'user_picture_side_bar', 'path' => $path, 'attributes' => array( 'class' => 'img-circle' ), 'width' => NULL, 'height' => NULL, ) ); $variables['user_name'] = $user->name; $variables['user_roles'] = implode(', ', array_slice($user->roles, 1)); } else { echo ''; } } function ento_cdn_form_alter(&$form, $form_state, $form_id) { if ($form_id == 'user_register') { drupal_set_title(t('Create new account')); } elseif ($form_id == 'user_pass') { drupal_set_title(t('Solicitar nueva contraseña')); } elseif ($form_id == 'user_login') { drupal_set_title(t('Log in')); } } function ento_cdn_form_user_login_block_alter(&$form, &$form_state, $form_id) { //dpm($form); $form['name']['#title'] = Null; $form['name']['#attributes'] = array('placeholder' => t('Usuario')); $form['pass']['#title'] = Null; $form['pass']['#attributes'] = array('placeholder' => t('Contraseña')); unset($form['actions']['submit']['#attributes']); //$form['actions']['submit']['#attributes']['class'][] = 'btn btn-primary block full-width m-b'; $form['actions']['submit']['#attributes'] = array('class' => array('block full-width m-b')); $form['links']['#weight'] = 10000; $markup = l(t('¿Olvidaste tu contraseña?'), 'user/password', array('attributes' => array('title' => t('Solicitar contraseña por correo electrónico.')))); if (variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL)) { $markup .= ' ' . l(t('Sign up'), 'user/register', array('attributes' => array('title' => t('Create a new user account.'), 'class' => 'register-link'))); } $markup = '<div class="clearfix">' . $markup . '</div>'; $form['links']['#markup'] = $markup; } function ento_cdn_form_user_login_alter(&$form, &$form_state) { $form['name']['#title'] = Null; $form['name']['#attributes'] = array('placeholder' => t('Usuario')); $form['pass']['#title'] = Null; $form['pass']['#attributes'] = array('placeholder' => t('Contraseña')); #$form['actions']['submit']['#value'] = t('Enviar Contraseña'); $form['actions']['submit']['#attributes'] = array('class' => array('block full-width m-b')); } function ento_cdn_form_user_pass_alter(&$form, &$form_state) { $form['name']['#title'] = Null; $form['name']['#attributes'] = array('placeholder' => t('Usuario')); $form['actions']['submit']['#value'] = t('Enviar Contraseña'); $form['actions']['submit']['#attributes'] = array('class' => array('block full-width m-b')); } function ento_cdn_bootstrap_colorize_text_alter(&$texts) { // This matches the exact string: "Log in". $texts['matches'][t('Log in')] = 'primary'; $texts['matches'][t('Enviar Contraseña')] = 'primary'; // This would also match the string above, however the class returned would // also be the one above; "matches" takes precedence over "contains". $texts['contains'][t('Unique')] = 'notice'; // Remove matching for strings that contain "apply": unset($texts['contains'][t('Apply')]); // Change the class that matches "Rebuild" (originally "warning"): $texts['contains'][t('Rebuild')] = 'success'; }
true
32fd56a25629859443511854a0593f7d12f8da96
PHP
AdamMarton/Stub
/src/Tokenizer.php
UTF-8
12,033
2.65625
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace Stub; use Stub\Exception\LambdaException; use Stub\Token\TokenFilter; use Stub\Token\TokenIterator; use Stub\Token\Traverse\Criteria; final class Tokenizer { /** * @var string */ const BRACKET_OPEN = '{'; /** * @var string */ const BRACKET_CLOSE = '}'; /** * @var string */ const LINE_BREAK = "\n"; /** * @var string */ const PARENTHESIS_OPEN = '('; /** * @var string */ const PARENTHESIS_CLOSE = ')'; /** * @var string */ const SCOPE_RESOLUTION = '::'; /** * @var string */ const SEMICOLON = ';'; /** * @var string */ protected $source = ''; /** * @var TokenIterator $tokenIterator; */ protected $tokenIterator; /** * @var mixed */ protected $currentToken; /** * @var Storage */ private $storage; /** * @var bool */ private $openTag = false; /** * @var callable */ private $logger; /** * @param string $source * @return void */ public function __construct(string $source, callable $logger) { $this->source = $source; $this->logger = $logger; $this->storage = new Storage(); $this->initIterator(); } /** * @return string */ public function parse() : string { while ($this->getIterator()->valid()) { switch ($this->getIterator()->type()) { case T_OPEN_TAG: $this->handleOpen(); break; case T_USE: $this->handleUse(); break; case T_NAMESPACE: $this->addEntity($this->initEntity(Storage::S_NAMESPACE)); break; case T_DOC_COMMENT: $this->handleDocComment(); break; case T_STRING: $this->handleString(); break; default: $this->handle($this->getIterator()->type()); break; } $this->getIterator()->next(); } return $this->getStorage()->format(); } /** * @return void */ private function initIterator() { $tokenFilter = new TokenFilter(token_get_all($this->source, TOKEN_PARSE)); $this->tokenIterator = new TokenIterator($tokenFilter->filter()); } /** * @return TokenIterator */ private function getIterator() : TokenIterator { return $this->tokenIterator; } /** * @return Storage */ private function getStorage() : Storage { return $this->storage; } /** * @return int */ private function getStorageSize() : int { return $this->getStorage()->length(); } /** * @param string $type * @return EntityInterface */ private function initEntity(string $type) : EntityInterface { $class = __NAMESPACE__ . '\\Entity\\' . ucfirst($type) . 'Entity'; $class = new $class; if ($class instanceof EntityInterface) { $class->add($this->getIterator()); return $class; } $class = new Entity\StringEntity(); $class->add($this->getIterator()); return $class; } /** * @param EntityInterface $entity * @return void */ private function addEntity(EntityInterface $entity) { $this->getStorage()->add($entity); } /** * @param string $type * @return null|EntityInterface */ private function getLastEntity(string $type) { return $this->getStorage()->getLast($type); } /** * @param mixed $token * @return mixed */ private function handle($token) { if (in_array($token, [T_ABSTRACT, T_FINAL])) { $this->handleAbstractFinal(); return; } if (in_array($token, [T_CLASS, T_INTERFACE, T_TRAIT])) { $this->handleObjects(); return; } if (in_array($token, [T_PUBLIC, T_PRIVATE, T_PROTECTED, T_STATIC, T_FUNCTION])) { $this->handleMethodProperty(); return; } if (in_array($token, [T_CONST, T_VAR])) { $this->handleConstVar(); } } /** * @return void */ private function handleOpen() { if (!$this->openTag) { $this->addEntity($this->initEntity(Storage::S_STRING)); $this->openTag = true; } } /** * @return mixed */ private function handleUse() { $useEntity = $this->initEntity(Storage::S_USE); $objectEntity = $this->getLastEntity(Storage::S_OBJECT); if ($objectEntity instanceof Entity\ObjectEntity) { $objectEntity->addUse($useEntity); return; } $this->addEntity($useEntity); } /** * @return mixed */ private function handleAbstractFinal() { if ($this->isAbstractClass() && !$this->isAnonymousClass()) { $this->addEntity($this->initEntity(Storage::S_OBJECT)); return; } $functionEntity = $this->initEntity(Storage::S_FUNCTION); $objectEntity = $this->getLastEntity(Storage::S_OBJECT); if ($objectEntity instanceof Entity\ObjectEntity) { $objectEntity->addMethod($functionEntity); } } /** * @return void */ private function handleObjects() { if ($this->isObject() && !$this->isAnonymousClass()) { $this->addEntity($this->initEntity(Storage::S_OBJECT)); } } /** * @return void */ private function handleConstVar() { $objectEntity = $this->getLastEntity(Storage::S_OBJECT); if ($objectEntity instanceof Entity\ObjectEntity) { $objectEntity->addProperty($this->initEntity(Storage::S_VARIABLE)); } } /** * @return void */ private function handleDocComment() { $objectEntity = $this->getLastEntity(Storage::S_OBJECT); $docblockEntity = $this->initEntity(Storage::S_DOCBLOCK); if ($objectEntity instanceof Entity\ObjectEntity) { $objectEntity->addDocblock($docblockEntity); } elseif ($this->getStorageSize() === 1) { $this->addEntity($docblockEntity); } } /** * @return mixed */ private function handleMethodProperty() { try { $objectEntity = $this->getLastEntity(Storage::S_OBJECT); if ($this->isFunction()) { $functionEntity = $this->initEntity(Storage::S_FUNCTION); if ($objectEntity instanceof Entity\ObjectEntity) { $objectEntity->addMethod($functionEntity); return; } $this->addEntity($functionEntity); return; } if ($objectEntity instanceof Entity\ObjectEntity) { $objectEntity->addProperty($this->initEntity(Storage::S_VARIABLE)); } } catch (LambdaException $e) { return; } } /** * @return void */ private function handleString() { $objectEntity = $this->getLastEntity(Storage::S_OBJECT); if (!$objectEntity instanceof Entity\ObjectEntity) { $this->addEntity($this->initEntity(Storage::S_STRING)); } } /** * @return bool */ private function isAbstractClass() : bool { $startKey = $this->getIterator()->key(); $tempTokens = $this->getIterator()->seekUntil(new Criteria(self::SEMICOLON)); if (in_array('class', $tempTokens)) { $this->getIterator()->reset($startKey); return true; } $this->getIterator()->reset($startKey); return false; } /** * @return bool */ private function isAnonymousClass() : bool { $startKey = $this->getIterator()->key(); $tempTokens = $this->getIterator()->seekUntil(new Criteria(self::BRACKET_OPEN)); if (in_array(self::PARENTHESIS_OPEN, $tempTokens)) { $open = 0; $close = 0; while ($this->getIterator()->valid()) { if ($this->getIterator()->current() === self::BRACKET_OPEN) { $open++; } elseif ($this->getIterator()->current() === self::BRACKET_CLOSE) { $close++; } if ($close > $open) { call_user_func_array($this->logger, ['LAMBDA OBJECT (1): ' . implode(' ', $tempTokens)]); return true; } $this->getIterator()->next(); } call_user_func_array($this->logger, ['LAMBDA OBJECT (2): ' . implode(' ', $tempTokens)]); return true; } call_user_func_array($this->logger, ['NORMAL CLASS: ' . implode(' ', $tempTokens)]); $this->getIterator()->reset($startKey); return false; } /** * @return bool */ private function isObject() : bool { $objects = ['class', 'interface', 'trait']; $startKey = $this->getIterator()->key(); $tempTokens = $this->getIterator()->seekUntil(new Criteria(self::BRACKET_OPEN)); foreach ($objects as $type) { if (in_array($type, $tempTokens)) { call_user_func_array($this->logger, ['NATIVE OBJECT: ' . implode(' ', $tempTokens)]); $this->getIterator()->reset($startKey); return true; } } return false; } /** * @return bool * @throws LambdaException */ private function isFunction() : bool { $startKey = $this->getIterator()->key(); $tempTokens = $this->getIterator()->seekUntil(new Criteria([self::SEMICOLON, self::BRACKET_OPEN])); $lastToken = (string) $tempTokens[sizeof($tempTokens)-1]; if ($lastToken === self::SEMICOLON && in_array('function', $tempTokens)) { call_user_func_array($this->logger, ['ABSTRACT FUNCTION: ' . implode(' ', $tempTokens)]); $this->getIterator()->reset($startKey); return true; } if (in_array('use', $tempTokens) || in_array(self::SCOPE_RESOLUTION, $tempTokens) || $tempTokens[1] === self::PARENTHESIS_OPEN ) { call_user_func_array($this->logger, ['LAMBDA FUNCTION: ' . implode(' ', $tempTokens)]); $open = 0; $close = 0; while ($this->getIterator()->valid()) { if ($this->getIterator()->current() === self::BRACKET_OPEN) { $open++; } elseif ($this->getIterator()->current() === self::BRACKET_CLOSE) { $close++; } if ($close > $open) { call_user_func_array($this->logger, ['LAMBDA OBJECT: ' . implode(' ', $tempTokens)]); throw new LambdaException(); } $this->getIterator()->next(); } call_user_func_array($this->logger, ['LAMBDA OBJECT (2): ' . implode(' ', $tempTokens)]); throw new LambdaException(); } if (in_array(Storage::S_FUNCTION, $tempTokens)) { call_user_func_array($this->logger, ['NATIVE FUNCTION: ' . implode(' ', $tempTokens)]); $this->getIterator()->reset($startKey); return true; } call_user_func_array($this->logger, ['PROPERTY: ' . implode(' ', $tempTokens)]); $this->getIterator()->reset($startKey); return false; } }
true
7b051326b81c6c2b69e2e8816f232d17a3e4e583
PHP
ElvenSpellmaker/AdventOfCode2020
/s-d18p2.php
UTF-8
533
2.765625
3
[]
no_license
<?php if (! defined('JACK_ADD_MULT_PRECEDENCE_ADD_HIGHER')) { echo <<< EOF Note: This script uses a specially crafted PHP version which treats + as a higher precedence order than *. Please use the `d18p2.Dockerfile` image to run this script! EOF; exit(1); } $sums = rtrim(file_get_contents('d18.txt')); $sums = explode("\n", $sums); function weirdAddition(string $sum) : int { $answer = 0; eval('$answer += ' . $sum . ';'); return $answer; } $sums = array_map('weirdAddition', $sums); echo array_sum($sums), "\n";
true
b779631b25ac3c962fe662352e1d6d14371d6d1f
PHP
jmc18/senasii
/modules/calendarios/models/LineamientosCalibracion.php
UTF-8
1,867
2.578125
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\modules\calendarios\models; use Yii; /** * This is the model class for table "lineamientos_calibracion". * * @property integer $idlineamiento * @property integer $idarea * @property integer $idreferencia * @property string $file_linea * @property string $hash_linea * @property string $fecinilinea * @property string $fecfinlinea * * @property CalendarioCalibracion $idarea0 */ class LineamientosCalibracion extends \yii\db\ActiveRecord { public $image; /** * @inheritdoc */ public static function tableName() { return 'lineamientos_calibracion'; } /** * @inheritdoc */ public function rules() { return [ [['image'], 'safe'], [['image'], 'file', 'extensions'=>'pdf'], [['idarea', 'idreferencia'], 'integer'], [['fecinilinea', 'fecfinlinea'], 'safe'], [['file_linea', 'hash_linea'], 'string', 'max' => 100], [['idarea', 'idreferencia'], 'exist', 'skipOnError' => true, 'targetClass' => CalendarioCalibracion::className(), 'targetAttribute' => ['idarea' => 'idarea', 'idreferencia' => 'idreferencia']], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'image' => 'Archivo', 'idlineamiento' => 'Idlineamiento', 'idarea' => 'Idarea', 'idreferencia' => 'Idreferencia', 'file_linea' => 'File Linea', 'hash_linea' => 'Hash Linea', 'fecinilinea' => 'Fecha Inicial', 'fecfinlinea' => 'Fecha Final', ]; } /** * @return \yii\db\ActiveQuery */ public function getIdarea0() { return $this->hasOne(CalendarioCalibracion::className(), ['idarea' => 'idarea', 'idreferencia' => 'idreferencia']); } }
true
098239241ee733b7ff37a5c05b5646af14a23118
PHP
PolakMartinCopy/crm_pharmacorp
/app/controllers/education_types_controller.php
UTF-8
2,495
2.578125
3
[]
no_license
<?php class EducationTypesController extends AppController { var $name = 'EducationTypes'; var $left_menu_list = array('settings', 'education_types'); function beforeRender(){ parent::beforeRender(); $this->set('active_tab', 'settings'); $this->set('left_menu_list', $this->left_menu_list); } function user_index() { $this->paginate = array( 'show' => 'all', 'conditions' => array('EducationType.active' => true), 'contain' => array(), 'order' => array('EducationType.name' => 'asc') ); $education_types = $this->paginate(); $this->set('education_types', $education_types); } function user_add() { if (isset($this->data)) { if ($this->EducationType->save($this->data)) { $this->Session->setFlash('Typ edukace byl uložen.'); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash('Typ edukace se nepodařilo uložit. Opravte chyby ve formuláři a opakujte prosím akci.'); } } } function user_edit($id = null) { if (!$id) { $this->Session->setFlash('Není zadán typ edukace, který chcete upravit'); $this->redirect(array('action' => 'index')); } $education_type = $this->EducationType->find('first', array( 'conditions' => array('EducationType.id' => $id), 'contain' => array() )); if (empty($education_type)) { $this->Session->setFlash('Typ edukace, který chcete upravit, neexistuje'); $this->redirect(array('action' => 'index')); } if (isset($this->data)) { if ($this->EducationType->save($this->data)) { $this->Session->setFlash('Typ edukace byl upraven'); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash('Typ edukace se nepodařilo upravit, opravte chyby ve formuláři a opakujte akci'); } } else { $this->data = $education_type; } } function user_delete($id = null) { if (!$id) { $this->Session->setFlash('Není zadán typ edukace, který chcete smazat'); $this->redirect(array('action' => 'index')); } if (!$this->EducationType->hasAny(array('EducationType.id' => $id))) { $this->Session->setFlash('Typ edukace, který chcete upravit, neexistuje'); $this->redirect(array('action' => 'index')); } if ($this->EducationType->delete($id)) { $this->Session->setFlash('Typ edukace byl odstraněn'); } else { $this->Session->setFlash('Typ edukace se nepodařilo odstranit, opakujte prosím akci'); } $this->redirect(array('action' => 'index')); } } ?>
true
13c4c7f48e4208c3ed41cb5ca37439ccfd8acc67
PHP
Zichis/booky
/app/Http/Controllers/Api/v1/BooksController.php
UTF-8
4,631
2.578125
3
[]
no_license
<?php namespace App\Http\Controllers\Api\v1; use App\Http\Controllers\Controller; use App\Http\Requests\BookPostRequest; use App\Models\Book; use Error; use Exception; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; class BooksController extends Controller { protected $statusCode; protected $statusText; protected $message; public function __construct() { $this->statusCode = 500; $this->statusText = 'failed'; $this->message = 'Something went wrong'; } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $this->statusText = 'success'; $this->statusCode = 200; return response()->json([ 'status_code' => $this->statusCode, 'status' => $this->statusText, 'data' => Book::all() ])->setStatusCode($this->statusCode, $this->statusText); } /** * Store a newly created resource in storage. * * @param BookPostRequest $request * @return \Illuminate\Http\Response */ public function store(BookPostRequest $request) { try { $book = Book::create( $request->only([ 'name','isbn','authors','country','number_of_pages','publisher','release_date' ]) ); $this->statusCode = 201; $this->statusText = 'success'; } catch(Exception $exception) { Log::alert("Something went wrong. Book not created. " . $exception->getMessage()); } return response()->json([ 'status_code' => $this->statusCode, 'status' => $this->statusText, 'data' => ["book" => $book] ])->setStatusCode(201, 'success'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { try { $book = Book::find($id); $this->statusCode = 200; $this->statusText = 'success'; } catch (Exception $e) { Log::alert("Something went wrong. " . $e->getMessage()); } return response()->json([ 'status_code' => $this->statusCode, 'status' => $this->statusText, 'data' => $book == null ?[]:$book // If book is null return empty array ]); } /** * Update the specified resource in storage. * * @param BookPostRequest $request * @param int $id * @return \Illuminate\Http\Response */ public function update(BookPostRequest $request, $id) { try { $book = Book::find($id); $book->update( $request->only([ 'name','isbn','authors','country','number_of_pages','publisher','release_date' ]) ); $this->statusCode = 200; $this->statusText = 'success'; $this->message = 'The book My First Book was updated successfully'; } catch (Exception $exception) { Log::alert("Something went wrong. " . $exception->getMessage()); } catch (Error $error) { Log::alert("An error occured. " . $error->getMessage()); } return response()->json([ 'status_code' => $this->statusCode, 'status' => $this->statusText, 'message' => $this->message, 'data' => $book == null ?[]:$book // If book is null return empty array ])->setStatusCode($this->statusCode, $this->statusText); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $book = Book::find($id); try { $book->delete(); $this->statusCode = 200; $this->statusText = 'success'; $this->message = 'The book My First Book was deleted successfully'; $book = null; } catch (Exception $exception) { Log::alert("Something went wrong. " . $exception->getMessage()); } catch (Error $error) { Log::alert("An error occured. " . $error->getMessage()); } return response()->json([ 'status_code' => $this->statusCode, 'status' => $this->statusText, 'message' => $this->message, 'data' => is_null($book) ? []:$book ])->setStatusCode($this->statusCode, $this->statusText); } }
true
fb051ce7c7804db4136a27177d037aed8dad29b2
PHP
shubhransh-gupta/online-e-learning-website-
/login.php
UTF-8
1,966
2.671875
3
[]
no_license
<?php include 'header.php'; if (isset($_COOKIE['email'])) { # code... ?> <script> alert("already Logged in. Redirecting you to Dashboard."); window.location.assign("dashboard.php"); </script> <?php } if ($_SERVER['REQUEST_METHOD'] == "POST") { # code... include 'connect.php'; if (isset($_POST['email']) && isset($_POST['pass'])) { # code... $email = test_input($_POST['email']); $pass = test_input($_POST['pass']); $sql = "select * from user where email='$email' and password='$pass'"; $sql1 = "select * from teacher where temail= '$email' and password ='$pass'"; $result = $conn->query($sql); $res = $conn->query($sql1); if ($result->num_rows > 0) { ?> <script> window.location.assign("log.php?in=<?php echo $email; ?>"); </script> <?php }elseif ($res->num_rows>0) { ?> <script> window.location.assign("log.php?te=<?php echo $email; ?>") </script> } <?php }else { ?> <script> alert("wrong Details. Please check type your Details carefully."); </script> <?php } }else { ?> <script> alert("Fields cannot be left blank please fill your Details"); </script> <?php } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <div class="login-form"> <center> <h2> Login to your Account </h2> <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>"> <input type="email" placeholder="E-Mail" name="email" autocomplete="off" required="yes" /> <input type="password" placeholder="Password" name="pass" autocomplete="off" required="yes" /> <button type="submit">LOGIN</button> </form> <h3>Forgot Password?</h3> <a href="register.php"><button>Not Registered? Register Here</button></a> </center> </div> <?php include 'footer.php'; ?>
true
e6ccd026a4630c771938b253bc8f38a0b972b620
PHP
BlasonB/moyennestudent
/moyenne.php
UTF-8
350
3.21875
3
[]
no_license
<?php /** * Created by PhpStorm. * User: wilder1 * Date: 27/02/17 * Time: 17:24 */ $students = [ "Emmanuel" => 42, "Thierry" => 51, "Pascal" => 45, "Eric" => 48, "Nicolas" => 19 ]; foreach ($students as $name => $age){ echo $name . ' a ' . $age . '</br>'; } echo array_sum($students) / count ($students); ?>
true
8fd73ac67125c183f63ca579235301289bac458f
PHP
jacobappia/insurance-app
/app/Aforance/Business/FuneralBusiness.php
UTF-8
711
2.8125
3
[]
no_license
<?php namespace Aforance\Aforance\Business; use Aforance\Aforance\Validation\ValidationException; class FuneralBusiness extends Business{ public function __construct(FuneralPolicyValidator $validator, FuneralPolicyRepository $repository){ parent::__construct($validator, $repository); $this->type = 'funeral'; } /** * Handles the issuing of a funeral policy * * @param array $data * * @return null * * @throws ValidationException */ public function issue(array $data){ // validate policy data parent::validate($data); // get first premium $data['premium'] = $this->premiumService->getFirstPremium('funeral', $data); // complete the policy issue parent::issue($data); } }
true
ae1619272097792deeca16aa3f22f87963d44391
PHP
esauvage1978/oc_projet5
/Core/Form/WebControls/WebControlsSelect.php
UTF-8
2,748
2.828125
3
[]
no_license
<?php namespace ES\Core\Form\WebControls; /** * WebControlsTextaera short summary. * * WebControlsTextaera description. * * @version 1.0 * @author ragus */ class WebControlsSelect extends WebControlsParamText { use ParamValid; use ParamRequire; /** * Liste des valeurs de la liste déroulante * @var array */ public $liste; protected static $buildParamsListe='liste'; public function render() { $this->addCssClass ('form-control'); $input = '<select '. $this->buildParams([ self::$buildParamsCSS, self::$buildParamsName, self::$buildParamsId, self::$buildParamsRequire, self::$buildParamsDisabled]) . '>'. $this->buildParams([self::$buildParamsListe]) . '</select>'; return $this->buildParams([self::$buildParamsLabel]) . $input . $this->buildParams([self::$buildParamsHelBlock]); } protected function buildParams($keys=[]):string { $params=''; $param=''; foreach($keys as $key) { switch ($key) { case self::$buildParamsListe: if(isset($this->liste)) { foreach ($this->liste as $listekey => $listevalue) { $listekey == $this->getText()? $attributes = ' selected': $attributes = ''; $param .= '<option value="' . $listekey . '"' . $attributes . '>' . $listevalue . '</option>'; } } break; case self::$buildParamsRequire: $param=$this->paramBuildsRequire(); break; case self::$buildParamsValid: $param=$this->paramBuildsValid(); break; case self::$buildParamsLabel: $param=$this->label?: '<label for="' . $this->getName() . '">'. $this->label .'</label>'; break; default: $param=parent::buildParams([$key]); break; } if($param!=MSG_FORM_PARAMS_NOT_FOUND && !empty($param)) { $param .=' '; } $params .= $param; } return $params; } public function check():bool { $retour=true; $value=$this->getText(); if( empty($value)) { $this->setIsInvalid(MSG_FORM_NOT_GOOD); $retour=false; } return $retour; } }
true
1f27163fee2fec3fde9bd32066a3a87de3a3725a
PHP
Artiso/datoriki
/library/JP/View/Helper/DateIntervalElement.php
UTF-8
3,205
2.546875
3
[]
no_license
<?php class JP_View_Helper_DateIntervalElement extends Zend_View_Helper_FormElement { protected $html = ''; protected $date_format="dateFormat: 'dd MM yy'"; public function dateIntervalElement($name, $value = null, $attribs = null) { if (is_array($attribs)) { $format = (isset($attribs['format'])) ? "dateFormat: '".$value['areanum']."'" : $this->date_format; $geonum = (isset($value['geonum'])) ? $value['geonum'] : ''; // $localnum = (isset($value['localnum'])) ? $value['localnum'] : ''; } $areanum = $geonum = $localnum = ''; $script='$(function () { $("#txtStartDate, #txtEndDate").datepicker( { showOn: "both", beforeShow: customRange, dateFormat: "dd M yy", firstDay: 1, changeFirstDay: false }); }); function customRange(input) { var min = null; var dateMin = min; var dateMax = null; var dayRange = 6; // Set this to the range of days you want to restrict to if (input.id == "txtStartDate") { if ($("#txtEndDate").datepicker("getDate") != null) { dateMax = $("#txtEndDate").datepicker("getDate"); dateMin = $("#txtEndDate").datepicker("getDate"); dateMin.setDate(dateMin.getDate() - dayRange); if (dateMin < min) { dateMin = min; } } else { //dateMax = new Date(); //Set this to your absolute maximum date } } else if (input.id == "txtEndDate") { dateMax = new Date(); //Set this to your absolute maximum date if ($("#txtStartDate").datepicker("getDate") != null) { dateMin = $("#txtStartDate").datepicker("getDate"); var rangeMax = new Date(dateMin.getFullYear(), dateMin.getMonth(), dateMin.getDate() + dayRange); if(rangeMax < dateMax) { dateMax = rangeMax; } } } return { minDate: dateMin, maxDate: dateMax, }; }'; $this->view->headScript()->appendScript($script, $type = 'text/javascript', $attrs = array()); //$this->view->headScript()->appendFile($this->view->baseUrl() . "/js/jquery-ui-1.7.2.custom.min.js"); $helper = new Zend_View_Helper_FormText(); // $helper = new ZendX_Jquery_View_Help(); $helper->setView($this->view); if (is_array($value)) { $areanum = (isset($value['areanum'])) ? $value['areanum'] : ''; $geonum = (isset($value['geonum'])) ? $value['geonum'] : ''; // $localnum = (isset($value['localnum'])) ? $value['localnum'] : ''; } $this->html .= $helper->formText('txtStartDate',$areanum,array('class'=>'calendar')); $this->html .= $helper->formText('txtEndDate',$geonum,array('class'=>'calendar')); return $this->html; } }
true
61ed7d97bd68833b350044e950a7cca5dd08c2d3
PHP
paulbunyannet/bandolier
/tests/Type/String/ContainsTest.php
UTF-8
2,786
3.1875
3
[ "MIT" ]
permissive
<?php /** * StartWithTest * * Created 5/30/17 9:36 AM * Tests for the startsWith method in Strings * * @author Nate Nolting <naten@paulbunyan.net> * @package Pbc\Bandolier\Type * @subpackage Subpackage */ namespace Tests\Type\String; use Pbc\Bandolier\Type\Strings; use Tests\BandolierTestCase; /** * Class StartWithTest * @package Pbc\Bandolier\Type */ class ContainsTest extends BandolierTestCase { /** * Check that a string can be found in string if case sensitive */ public function testStringIsFoundIfCaseSensitive() { $needle = "Foo"; $haystack = $needle . " Bar"; $this->assertTrue(Strings::contains($haystack, $needle, true)); } /** * Check that a string can not be found in string if case sensitive */ public function testStringIsNotFoundIfCaseSensitive() { $needle = "Foo"; $haystack = "Bar Baz"; $this->assertFalse(Strings::contains($haystack, $needle, true)); } /** * Check that a string can be found in string if case insensitive */ public function testStringIsFoundIfCaseInsensitive() { $needle = "foo"; $haystack = ucfirst($needle) . " Bar"; $this->assertTrue(Strings::contains($haystack, $needle, false)); } /** * Check that a string can not be found in string if case insensitive */ public function testStringIsNotFoundIfCaseInsensitive() { $needle = "foo"; $haystack = "Bar Baz"; $this->assertFalse(Strings::contains($haystack, $needle, false)); } /** * Check if string in array is inside the haystack case sensitive */ public function testAnArrayValueIsInTheHaystackCaseSensitive() { $needle = ["Foo"]; $haystack = "Foo Bar Baz"; $this->assertTrue(Strings::contains($haystack, $needle)); } /** * Check if string in array is not inside the haystack case sensitive */ public function testAnArrayValueIsNotInTheHaystackCaseSensitive() { $needle = ["foo"]; $haystack = "Foo Bar Baz"; $this->assertFalse(Strings::contains($haystack, $needle)); } /** * Check if string in array is inside the haystack case insensitive */ public function testAnArrayValueIsInTheHaystackCaseInsensitive() { $needle = ["foo"]; $haystack = "Foo Bar Baz"; $this->assertTrue(Strings::contains($haystack, $needle, false)); } /** * Check if string in array is not inside the haystack case insensitive */ public function testAnArrayValueIsNotInTheHaystackCaseInsensitive() { $needle = ["Bin"]; $haystack = "foo bar baz"; $this->assertFalse(Strings::contains($haystack, $needle, false)); } }
true
e982369b76e5fa3445e077f2b4666a22288101fe
PHP
iguoji/minimal-pool
/tests/HttpServer.php
UTF-8
3,320
2.515625
3
[]
no_license
<?php use Swoole\Http\Server; use Swoole\Coroutine; class HttpServer { public function __construct(string $ip, int $port, callable $callback) { $server = new Server($ip, $port); $server->set([ 'worker_num' => 2, 'task_worker_num' => 2, // 'hook_flags' => SWOOLE_HOOK_TCP, ]); $server->on('start', function($server){ echo 'onStart', PHP_EOL; }); $server->on('ManagerStart', function($server){ echo 'onManagerStart', PHP_EOL; cli_set_process_title('php swoole manager'); }); $server->on('workerStart', function($server, $workerId){ echo 'onWorkerStart', PHP_EOL; echo 'workerId: '. $workerId, PHP_EOL; cli_set_process_title(sprintf('php swoole http server worker #%s', $workerId)); }); $server->on('workerStop', function($server, $workerId){ echo 'onWorkerStop', PHP_EOL; echo 'workerId: '. $workerId, PHP_EOL; }); $server->on('workerExit', function($server, $workerId){ echo 'onWorkerExit', PHP_EOL; echo 'workerId: '. $workerId, PHP_EOL; }); $server->on('connect', function($server, $fd, $reactorId){ // echo 'onConnect', PHP_EOL; }); $server->on('request', function($req, $res) use($server, $callback){ // echo 'onRequest', PHP_EOL; Coroutine::create(function() use($server, $req, $res, $callback){ try { // 回调函数 $callback($server, $req, $res); } catch (\Throwable $th) { echo $th->getMessage(), PHP_EOL; echo $th->getFile(), PHP_EOL; echo $th->getLine(), PHP_EOL; } }); }); $server->on('Receive', function($server, $fd, $reactorId, $data){ echo 'onReceive', PHP_EOL; }); $server->on('Packet', function($server, $data, $clientInfo){ echo 'onPacket', PHP_EOL; }); $server->on('Close', function($server, $fd, $reactorId){ // echo 'onClose', PHP_EOL; }); $server->on('task', function($server, $task){ echo 'onTask', PHP_EOL; $task->finish(time()); }); $server->on('finish', function($server, $task_id, $data){ echo 'onFinish', PHP_EOL; }); $server->on('PipeMessage', function($server, $src_worker_id, $message){ echo 'onPipeMessage', PHP_EOL; }); $server->on('WorkerError', function($server, $workerId, $worker_pid, $exit_code, $signal){ echo 'onWorkerError', PHP_EOL; echo 'workerId: '. $workerId, PHP_EOL; }); $server->on('ManagerStop', function($server){ echo 'onManagerStop', PHP_EOL; }); $server->on('BeforeReload', function($server){ echo 'onBeforeReload', PHP_EOL; }); $server->on('AfterReload', function($server){ echo 'onAfterReload', PHP_EOL; }); $server->on('shutdown', function($server){ echo 'onShutdown', PHP_EOL; }); $server->start(); } }
true
2bfdb8aa7755f5d6b40e2a0e1caaf619984f414e
PHP
tkwalker-git/genesis
/webservice/getuserresponce.php
UTF-8
3,114
2.734375
3
[]
no_license
<?php session_start(); function login($user,$pass) { $client = new SoapClient("https://pangeaifa.com/novisurvey/ws/AdminWebService.asmx?WSDL", array( "trace" => 1, // enable trace to view what is happening "exceptions" => 0, // disable exceptions "cache_wsdl" => 0) // disable any caching on the wsdl, encase you alter the wsdl server ); $check = $client->Authenticate(array("userName"=>$user,"passwordOrHash"=>$pass))->AuthenticateResult; if($check==1) { $tmp = $client->_cookies; $_SESSION['NoviSurveySessionCookie'] = $tmp['NoviSurveySessionCookie'][0]; session_write_close(); } else { unset($_SESSION['NoviSurveySessionCookie']); session_write_close(); } } function getrespondent($post) { $client = new SoapClient("https://pangeaifa.com/novisurvey/ws/SurveyWebService.asmx?WSDL", array( "trace" => 1, // enable trace to view what is happening "exceptions" => 0, // disable exceptions "cache_wsdl" => 0) // disable any caching on the wsdl, encase you alter the wsdl server ); $client->__setCookie("NoviSurveySessionCookie",$_SESSION['NoviSurveySessionCookie']); $tmp = $client->GetSurveyResponsesByIds(array("surveyResponseIds" => array($post['id']),"separator" => "Comma","headerSeparator" => "|","condenseValues" => True,"encodedHeaderFormat" => True,"tagForOptionsSelected" => "1","tagForOptionsNotSelected" => "0","tagForNas" => "NA","includePersonData" => True,"includeParameterData"=>True,"includeScoreData"=>True,"includeResponseData"=>True,"includePartialPageData"=>True)); /* print "<pre>\n"; print "Request: \n".htmlspecialchars($client->__getLastRequest()) ."\n"; print "Response: \n".htmlspecialchars($client->__getLastResponse())."\n"; print "</pre>"; */ //print_r($tmp); session_destroy(); //exit; echo '<pre>'; if($tmp->GetSurveyResponsesByIdsResult->Success==1) { $resstr=$tmp->GetSurveyResponsesByIdsResult->Data->string; echo $resstr; echo "\n"; $data = explode("\n",$resstr); print_r($data); } else { //return null; } exit; } if(isset($_POST['username']) && isset($_POST['password'])) { login($_POST['username'],$_POST['password']); } if(isset($_POST['id'])) { $data = getrespondent($_POST); if($data !=null) { session_destroy(); exit; } } ?> <?php if(isset($_SESSION['NoviSurveySessionCookie']) && $_SESSION['NoviSurveySessionCookie'] !="") { ?> Get Responce By Id <br/> <Form action="" method="POST" name="getresponce"> <table> <tr> <td>Responce Id : </td> <td><input type="text" name="id" value="1"/></td> </tr> <tr> <td></td> <td><input type="submit"/></td> </tr> </table> </form> <?php } else { ?> Login Wih Webservice User (admin) <br/> <Form action="" method="POST" name="loginfrm"> <table> <tr> <td>User Name : </td> <td><input type="text" name="username" value="admin"/></td> </tr> <tr> <td>Password : </td> <td><input type="password" name="password" value="Meghal123"/></td> </tr> <tr> <td></td> <td><input type="submit"/></td> </tr> </table> </form> <?php } ?>
true
ff011c97a0fdecc19c12a401323390006c561232
PHP
mdavison/vegetablefree
/app/Http/Middleware/MustBeOwner.php
UTF-8
1,491
2.8125
3
[ "MIT" ]
permissive
<?php namespace App\Http\Middleware; use App\Recipe; use Closure; use Illuminate\Support\Facades\Auth; class MustBeOwner { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $user = Auth::user(); // Not logged in if ( ! $user) { return redirect()->guest('auth/login'); } // User is admin - send them on if ($user->is_admin) { return $next($request); } $routeParameters = $request->route()->parameters(); // $key = route, $value = id foreach ($routeParameters as $key => $value) { if ($key == 'users') { // If these are the same, user is accessing their own record if ( (int) $value === (int) $user->id) { return $next($request); } // Otherwise, send them back to their own record return redirect('users/' . $user->id); } if ($key == 'recipes') { $recipe = Recipe::findOrFail($value); // If these are the same, user is accessing a recipe they created if ($recipe->user_id === $user->id) { return $next($request); } return redirect('recipes'); } } return redirect('/'); } }
true
2619b316503daf7ca950689f4c15524a76bbb3fb
PHP
Magoo624/Submitty
/Docs/student_auto_feed/accounts.php
UTF-8
6,361
2.515625
3
[ "BSD-3-Clause", "MIT" ]
permissive
#!/usr/bin/env php <?php /* HEADING --------------------------------------------------------------------- * * accounts.php * By Peter Bailie, Systems Programmer (RPI dept of computer science) * * This script is intended to be run from the CLI as a scheduled cron job, and * should not be executed as part of a website. * * This script will read all user IDs of all active Submitty courses and create * auth and svn access accounts on the Submitty server. * * -------------------------------------------------------------------------- */ error_reporting(0); ini_set('display_errors', 0); //list of courses that also need SVN accounts as serialized array. //NOTE: Serializing the array allows the list to be defined as a constant. define('SVN_LIST', serialize( array ( 'cs1000', 'cs2000', 'cs3000', 'cs4000', ))); //Database access define('DB_LOGIN', 'hsdbu'); define('DB_PASSWD', 'hsdbu_pa55w0rd'); define('DB_HOST', '192.168.56.101'); //Location of accounts creation error log file define('ERROR_LOG_FILE', '/var/local/submitty/bin/accounts_errors.log'); //Where to email error messages so they can get more immediate attention. define('ERROR_E_MAIL', 'sysadmins@lists.myuniversity.edu'); /* SUGGESTED SETTINGS FOR TIMEZONES IN USA ------------------------------------- * * Eastern ........... America/New_York * Central ........... America/Chicago * Mountain .......... America/Denver * Mountain no DST ... America/Phoenix * Pacific ........... America/Los_Angeles * Alaska ............ America/Anchorage * Hawaii ............ America/Adak * Hawaii no DST ..... Pacific/Honolulu * * For complete list of timezones, view http://php.net/manual/en/timezones.php * * -------------------------------------------------------------------------- */ //Univeristy campus's timezone. date_default_timezone_set('America/New_York'); /* EXAMPLE CRONTAB ------------------------------------------------------------- * * This will run the script every hour at the half-hour (e.g. 8:30, 9:30, etc). 30 * * * * /var/local/submitty/bin/accounts.php * -------------------------------------------------------------------------- */ /* MAIN ===================================================================== */ //IMPORTANT: This script needs to be run as root! if (posix_getuid() !== 0) { exit("This script must be run as root." . PHP_EOL); } //if ($month <= 5) {...} else if ($month >= 8) {...} else {...} $semester = ($month <= 5) ? "s{$year}" : (($month >= 8) ? "f{$year}" : "m{$year}"); $courses = determine_courses($semester); foreach($courses as $course) { if (array_search($course, unserialize(SVN_LIST)) !== false) { //Create both auth account and SVN account //First make sure SVN repo exists if (!file_exists("/var/lib/svn/{$course}")) { mkdir("/var/lib/svn/{$course}"); } $user_list = get_user_list_from_course_db($semester, $course); foreach($user_list as $user) { //Let's make sure SVN account doesn't already exist before making it. if (!file_exists("/var/lib/svn/{$course}/{$user}")) { system ("/usr/sbin/adduser --quiet --home /tmp --gecos 'RCS auth account' --no-create-home --disabled-password --shell /usr/sbin/nologin {$user} > /dev/null 2>&1"); system ("svnadmin create /var/lib/svn/{$course}/{$user}"); system ("touch /var/lib/svn/{$course}/{$user}/db/rep-cache.db"); system ("chmod g+w /var/lib/svn/{$course}/{$user}/db/rep-cache.db"); system ("chmod 2770 /var/lib/svn/{$course}/{$user}"); system ("chown -R www-data:svn-{$course} /var/lib/svn/{$course}/{$user}"); system ("ln -s /var/lib/svn/hooks/pre-commit /var/lib/svn/{$course}/{$user}/hooks/pre-commit"); } } //Restart Apache system ("/root/bin/regen.apache > /dev/null 2>&1"); system ("/usr/sbin/apache2ctl -t > /dev/null 2>&1"); } else { //Only create auth account $user_list = get_user_list_from_course_db($semester, $course); foreach($user_list as $user) { //We don't care if user already exists as adduser will skip over any account that already exists. system ("/usr/sbin/adduser --quiet --home /tmp --gecos 'RCS auth account' --no-create-home --disabled-password --shell /usr/sbin/nologin {$user} > /dev/null 2>&1"); } } } exit(0); /* END MAIN ================================================================= */ function determine_courses($semester) { //IN: Parameter has the current semester code (e.g. "f16" for Fall 2016) //OUT: Array of courses used in Submitty. Determined from data file structure. //PURPOSE: A list of active courses is needed so that user lists can be read // from current class databases. $path = "/var/local/submitty/courses/{$semester}/"; $courses = scandir($path); if ($courses === false) { log_it("Submitty Auto Account Creation: Cannot parse {$path}, CANNOT MAKE ACCOUNTS"); exit(1); } //remove "." and ".." entries foreach ($courses as $index => $course) { if ($course[0] === '.') { unset($courses[$index]); } } return $courses; } function get_user_list_from_course_db($semester, $course) { //IN: The current course code with semester code (needed to access course DB) //OUT: An array containing the user list read from the course's database //PURPOSE: Read all user_ids from the user list to create auth/svn accounts. $db_user = DB_LOGIN; $db_pass = DB_PASSWD; $db_host = DB_HOST; $db_name = "submitty_{$semester}_{$course}"; $user_list = array(); $db_conn = pg_connect("host={$db_host} dbname={$db_name} user={$db_user} password={$db_pass}"); if ($db_conn === false) { log_it("Submitty Auto Account Creation: Cannot connect to DB {$db_name}, skipping..."); return array(); } $db_query = pg_query($db_conn, "SELECT user_id FROM users;"); if ($db_query === false) { log_it("Submitty Auto Account Creation: Cannot read user list for {$course}, skipping..."); return array(); } $row = pg_fetch_row($db_query); while($row !== false) { $user_list[] = $row[0]; $row = pg_fetch_row($db_query); } return $user_list; } function log_it($msg) { //IN: Message to write to log file //OUT: No return, although log file is updated //PURPOSE: Log messages to email and text files. $msg = date('m/d/y H:i:s : ', time()) . $msg . PHP_EOL; error_log(msg, 1, ERROR_E_MAIL); error_log(msg, 3, ERROR_LOG_FILE); } /* EOF ====================================================================== */ ?>
true
e05f1d8bb7593f4e948f7193e7f582dfe88b14d1
PHP
305806761/babyfs
/models/LoginForm.php
UTF-8
1,207
2.96875
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\models; use Yii; use yii\base\Model; /** * LoginForm is the model behind the login form. * * @property User|null $user This property is read-only. * */ class LoginForm extends Model { public $phone; public $password; public $rememberMe = true; private $_user = false; /** * @return array the validation rules. */ public function rules() { return [ // username and password are both required [['phone', 'password'], 'required'], // rememberMe must be a boolean value ['rememberMe', 'boolean'], ]; } /** * 生成form的表单获取的值,然后传递到member模板 进行数据处理 * @return boolean whether the user is logged in successfully */ public function login() { if ($this->validate()) { $member = new User(); $user = array('phone'=>$this->phone,'password' => $this->password,'rememberMe' => $this->rememberMe); if(!$member->login($user)){ $this->addError( '用户名或密码输入有误'); }else{ return true; } } } }
true
da91055e5c30e13d8ddea59b22ff34cf8b314319
PHP
Hamjeth68/Safee_Enviro_Academy
/database/migrations/2021_07_09_043746_create_products_table.php
UTF-8
1,046
2.5625
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateProductsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('products', function (Blueprint $table) { $table->bigIncrements('id'); // $table->unsignedInteger('student_id')->index(); $table->string('p_title'); $table->string('p_name'); $table->string('slug'); $table->string('p_description')->nullable(); $table->unsignedInteger('p_quantity'); $table->decimal('p_ammount', 8, 2)->nullable(); // $table->foreign('student_id')->references('id')->on('students')->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('products'); } }
true
957a7f081f91f6723c869897464d377c9ff7ab92
PHP
vens8/Apocalypse
/login.php
UTF-8
1,128
2.796875
3
[]
no_license
<?php $con = mysqli_connect('localhost', 'root','root','login'); //check if username exist if(mysqli_connect_error()) { echo "1: Connection Failed.";//error #1 = connection failed. exit(); } $username = $_POST["username"]; $password = $_POST["password"]; //check if username exists $namecheckquery = "SELECT Username, Hash, Salt, Medic, Infected FROM Players WHERE Username='".$username."';"; $namecheck = mysqli_query($con, $namecheckquery) or die("2: Name Check Query Failed");//Error code #2 = name check query failed. if(mysqli_num_rows($namecheck) != 1) { echo "5: Either no user with this name, or more than one"; //Error code #5 = number of names matching is not 1 } //get login info from query $existinginfo = mysqli_fetch_assoc($namecheck); $Salt=$existinginfo["Salt"]; $Hash=$existinginfo["Hash"]; $loginhash = crypt($password, $Salt); if($Hash!=$loginhash) { echo "6: Incorrect Password.";//Error code #6 = password doesn't hash to match table. exit(); } echo ("0\t" . $existinginfo["Medic"] . "\t" . $existinginfo["Infected"]); ?>
true
a49c9546c0f48712530e8f6987f1c37f59c6e09b
PHP
ingerable/Projet_Web-L3
/views/recipe/addStageIngredients.php
UTF-8
1,375
2.5625
3
[]
no_license
<?php $allIngredients = Ingredient::get_all_names(); if (user_connected()) { for ($i=1; $i <= $_GET["nbrStages"]; $i++) { echo '<h3> Stage '.$i.'</h3> <div class="formline"> <label>Time (minutes)</label> <input type="number" name="temps'.$i.'"> </div> <div class="formline"> <label>Link for an illustration</label> <input type="text" placeholder="link" name="illustration'.$i.'"> </div> <div class="formline"> <label>Description</label> <textarea name="description_etape'.$i.'" rows="10" cols="30"> </textarea> </div>'; } for ($i=1; $i <= $_GET["nbrIngredients"] ; $i++) { echo '<h3> Ingrédient '.$i.'</h3> <div class="formline"> <label>Quantity</label> <input type="number" name="nbrIngredients" min="1"> </div> <div class="formline"> <label>grammes</label> <input type="number" name="nbrIngredients" min="1"> </div>'; echo ' <div class="formline"> <label>ingredient </label> <select name="Ingredient">'; foreach ($allIngredients as $key => $ing) { echo '<option value='.$allIngredients[$key]['nomIngredient'].'>'.$allIngredients[$key]['nomIngredient'].'</option>'; } echo '</select> </div>'; } } else { message('error', 'Please sign in or sign up'); header('Location: '.BASEURL.'/index.php/user/signin'); }
true
f9df9bf31ca533246e1d4a4bffb9b6e0a4c34249
PHP
diegonella/multicrm
/Modules/Platform/CodeGenerator/Lib/StubGenerator.php
UTF-8
1,483
2.953125
3
[]
no_license
<?php namespace Modules\Platform\CodeGenerator\Lib; /** * Stub generator * * Class StubGenerator * @package Modules\Platform\CodeGenerator\Lib */ class StubGenerator { /** * @var string */ protected $source; /** * @var string */ protected $target; public function setSource($source) { $this->source = $source; } public function setTarget($target) { $this->target = $target; } /** * @param array $replacements */ public function save(array $replacements) { $contents = file_get_contents($this->source); // Standard replacements collect($replacements)->each(function (string $replacement, string $tag) use (&$contents) { $contents = str_replace($tag, $replacement, $contents); }); $path = pathinfo($this->target, PATHINFO_DIRNAME); if (!file_exists($path)) { mkdir($path, 0776, true); } return file_put_contents($this->target, $contents); } /** * @param array $replacements * @return string */ public function render(array $replacements): string { $contents = file_get_contents($this->source); // Standard replacements collect($replacements)->each(function (string $replacement, string $tag) use (&$contents) { $contents = str_replace($tag, $replacement, $contents); }); return $contents; } }
true
3cceb62247991ccbf0d1d040daa6e8a19c794585
PHP
trilbymedia/grav-plugin-tntsearch
/classes/GravConnector.php
UTF-8
2,287
2.546875
3
[ "MIT" ]
permissive
<?php namespace Grav\Plugin\TNTSearch; use Grav\Common\Config\Config; use Grav\Common\Grav; use Grav\Common\Yaml; use Grav\Common\Page\Page; use Grav\Plugin\TNTSearchPlugin; use PDO; class GravConnector extends PDO { public function __construct() { } /** * @param int $attribute * @return bool */ public function getAttribute($attribute): bool { return false; } /*** * @param string $statement * @param int|null $fetch_style * @param mixed ...$extra * @return GravResultObject */ public function query(string $statement, ?int $fetch_style = null, ...$extra): GravResultObject { $counter = 0; $results = []; /** @var Config $config */ $config = Grav::instance()['config']; $filter = $config->get('plugins.tntsearch.filter'); $default_process = $config->get('plugins.tntsearch.index_page_by_default'); $gtnt = TNTSearchPlugin::getSearchObjectType(); if ($filter && array_key_exists('items', $filter)) { if (is_string($filter['items'])) { $filter['items'] = Yaml::parse($filter['items']); } $page = new Page; $collection = $page->collection($filter, false); } else { $collection = Grav::instance()['pages']->all(); $collection->published()->routable(); } foreach ($collection as $page) { $counter++; $process = $default_process; $header = $page->header(); $url = $page->url(); if (isset($header->tntsearch['process'])) { $process = $header->tntsearch['process']; } // Only process what's configured if (!$process) { echo("Skipped {$counter} {$url}\n"); continue; } try { $fields = $gtnt->indexPageData($page); $results[] = (array) $fields; echo("Added {$counter} {$url}\n"); } catch (\Exception $e) { echo("Skipped {$counter} {$url} - {$e->getMessage()}\n"); continue; } } return new GravResultObject($results); } }
true
0b039585d3dad84eab46ff371c207d9d13e9c93e
PHP
kazmij/demo
/Symfony2/Controller/AnalyticsApiController.php
UTF-8
17,990
2.5625
3
[]
no_license
<?php namespace Bally\AdminBundle\Controller; use Bally\AdminBundle\Controller\MainController, Symfony\Component\HttpFoundation\Request, Sensio\Bundle\FrameworkExtraBundle\Configuration\Security, Symfony\Component\DependencyInjection\ContainerBuilder, Symfony\Component\HttpFoundation\JsonResponse, Bally\EntityBundle\Entity\App, Bally\EntityBundle\Entity\Statistics, Bally\EntityBundle\Entity\StatisticsAssets, Bally\EntityBundle\Entity\StatisticsDownloads, Bally\EntityBundle\Entity\StatisticsLocations, Bally\EntityBundle\Entity\StatisticsShares, Bally\EntityBundle\Entity\StatisticsTime, Bally\EntityBundle\Entity\Country, Bally\EntityBundle\Entity\City; /** * @author Arcyro <arek@arcyro.pl> * @version v1 */ class AnalyticsApiController extends MainController { /** * Json data from request as array * @var array */ private $data = array(); /** * Current app object * @var App */ private $app; /** * Action type * @var integer */ private $type; /** * Unique session id * @var string */ private $sessionId; /** * Statistics object * @var Statistics */ private $statistics; /** * Api version * @var string */ private $version; /** * Allowed actions array * @var array */ private $actions = array( 1 => 'downloadAppAction', 2 => 'downloadAssetsAction', 3 => 'shareAction', 4 => 'chooseAssetsAction', 5 => 'startSessionAction', 6 => 'endSessionAction' ); /** * Method is used before any other actions in this controller */ public function _init() { parent::_init(); # Set access to mobile app for this if (isset($_SERVER['HTTP_ORIGIN'])) { header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}"); header('Access-Control-Allow-Credentials: true'); header('Access-Control-Max-Age: 86400'); // cache for 1 day } try { if ($this->request->isMethod('POST')) { $this->version = $this->request->get('version', 1); $this->sessionId = $this->request->get('unique', null); $this->type = $this->request->get('type', null); $appId = $this->request->get('app_id', null); $data = $this->request->get('data', null); # If required arg no exist return json with error if (!($this->sessionId && $this->type && $appId)) { $response = new JsonResponse(array('success' => false, 'msg' => 'Once of required arguments is null, valid structure is (String unique, String type, String app_id, Object data = null)')); $response->send(); exit; } # if data json is not null then create array from this if ($data) { $this->data = json_decode($data, true); } # App object $this->app = $this->em->getRepository('BallyEntityBundle:App')->find($appId); # If can't find app by id, we must break because it's required value if (!$this->app) { $response = new JsonResponse(array('success' => false, 'msg' => 'App with code: ' . $appId . ' no exist!!!')); $response->send(); exit; } $this->statistics = $this->em->getRepository('BallyEntityBundle:Statistics')->findOneBy(array('sessionId' => $this->sessionId, 'app' => $this->app->getId())); # if all ok, can save statistics if no exist } else { # return error if it's no post method $response = new JsonResponse(array('success' => false, 'msg' => 'Only post method allowed for api !!')); $response->send(); exit; } } catch (\Exception $e) { $response = new JsonResponse(array('success' => false, 'msg' => 'An error occured', 'error' => $e->getMessage())); $response->send(); exit; } } /** * Main action wchich redirect to other actions idetified by type id * @param \Symfony\Component\HttpFoundation\Request $request * @param type $type * @return \Symfony\Component\HttpFoundation\JsonResponse */ public function indexAction(Request $request) { if (method_exists($this, $this->actions[$this->type])) { return call_user_func_array(array($this, $this->actions[$this->type]), array($this->data)); } else { return new JsonResponse(array('success' => false, 'msg' => 'Action with id"' . $this->type . '" no exist, maybe wrong name is it ?')); } } /** * Action used if app was downloaded, requried params in data array is: language, country, city and ios_version * @param array $data * @return \Symfony\Component\HttpFoundation\JsonResponse * @throws \Exception */ public function downloadAppAction($data) { try { if ($this->statistics) { $language = @$data['language']; $country = @$data['country']; $city = @$data['city']; $ios_version = @$data['ios_version']; if ($city && $language && $country) { # Get language object by id $language = $this->em->getRepository('BallyEntityBundle:Language')->find($language); $qb = $this->em->createQueryBuilder(); # Set country object if no exist or user existing if ($country) { if (is_numeric($country)) { $countryObj = $this->em->getRepository('BallyEntityBundle:Country')->find($country); } else { $country = trim($country); $countryObj = $this->em ->getRepository('BallyEntityBundle:Country') ->createQueryBuilder('c') ->where($qb->expr()->like($qb->expr()->upper('c.name'), $qb->expr()->literal(strtoupper($country)))) ->getQuery() ->getOneOrNullResult(); if ($countryObj) { $country = $countryObj; } else { $countryObj = new Country(); $countryObj->setName(strtoupper($country)); $countryObj->setLanguage($language); $this->em->persist($countryObj); $this->em->flush(); } } } # Set city object if no exist or user existing if ($city) { if (is_numeric($city)) { $cityObj = $this->em->getRepository('BallyEntityBundle:City')->find($city); } else { $city = trim($city); $cityObj = $this->em ->getRepository('BallyEntityBundle:City') ->createQueryBuilder('c') ->where($qb->expr()->like($qb->expr()->upper('c.name'), $qb->expr()->literal(strtoupper($city)))) ->getQuery() ->getOneOrNullResult(); if ($cityObj) { $city = $cityObj; } else { $cityObj = new City(); $cityObj->setName(strtoupper($city)); if ($countryObj) { $cityObj->setCountry($countryObj); } $this->em->persist($cityObj); $this->em->flush(); } } } # Create new statistics of download $this->statistics->setCountry($countryObj); $statisticsDownloads = new StatisticsDownloads(); $statisticsDownloads ->setStatistics($this->statistics) ->setAction($this->type) ->setVersion($ios_version) ->setMySessionId($this->sessionId) ->setLanguage($language) ->setCountry($countryObj) ->setCity($cityObj) ->setAppDownload(1) ->setIp(@$_SERVER['REMOTE_ADDR']); $this->em->persist($statisticsDownloads); $this->em->flush(); return new JsonResponse(array('success' => true, 'msg' => 'App download stats added successufly')); } else { throw new \Exception('Once or more of parameters from data json(country, city, language, ios_version) is empty!'); } } else { throw new \Exception('Cant find statistics for this session id and app id!'); } } catch (\Exception $e) { return new JsonResponse(array('success' => false, 'msg' => 'An error occured', 'error' => $e->getMessage())); } } /** * If any asset was downloaded, it must be saved to statistics * @return \Symfony\Component\HttpFoundation\JsonResponse * @throws \Exception */ public function downloadAssetsAction() { try { if ($this->statistics) { $statisticsAssets = new StatisticsDownloads(); $statisticsAssets ->setStatistics($this->statistics) ->setAction($this->type) ->setMySessionId($this->sessionId) ->setIp(@$_SERVER['REMOTE_ADDR']) ->setAssetDownloads(1); $this->em->persist($statisticsAssets); $this->em->flush(); return new JsonResponse(array('success' => true, 'msg' => 'Assets download stats successufly added')); } else { throw new \Exception('Cant find statistics for this session id and app id!'); } } catch (\Exception $e) { return new JsonResponse(array('success' => false, 'msg' => 'An error occured', 'error' => $e->getMessage())); } } /** * Share facebook, twitter statistics, in $data array required "social" param * @param type $data * @return \Symfony\Component\HttpFoundation\JsonResponse * @throws \Exception */ public function shareAction($data) { try { $social = @$data['social']; if (!$social) { throw new \Exception('Social param no exist in data json!'); } if ($this->statistics) { $statisticsShare = new StatisticsShares(); $statisticsShare ->setStatistics($this->statistics) ->setAction($this->type) ->setShareType($social) ->setMySessionId($this->sessionId) ->setIp(@$_SERVER['REMOTE_ADDR']) ->setShareCount(1); $this->em->persist($statisticsShare); $this->em->flush(); return new JsonResponse(array('success' => true, 'msg' => 'Share actions successufly added')); } else { throw new \Exception('Cant find statistics for this session id and app id!'); } } catch (\Exception $e) { return new JsonResponse(array('success' => false, 'msg' => 'An error occured', 'error' => $e->getMessage())); } } /** * Save count of specific asset view, required asset_id as asset variable in data array * @param type $data * @return \Symfony\Component\HttpFoundation\JsonResponse * @throws \Exception */ public function chooseAssetsAction($data) { try { $styleId = @$data['styleId']; $materialId = @$data['materialId']; $colorId = @$data['colorId']; $type = @$data['type']; if (!($styleId && $materialId && $colorId && $type)) { throw new \Exception('Error. One of the parameters (styleId, materialId, colorId, type) is empty, it must be numeric values and type as string( shoes, belts)!'); } $asset = $this->em ->getRepository('BallyEntityBundle:Asset') ->createQueryBuilder('a') ->leftJoin('a.product_type', 't') ->where('a.product_style = :style') ->andWhere('a.leather = :material') ->andWhere('a.color = :color') ->andWhere('t.app = :app') ->andWhere('t.name = :type') ->setParameters(array( 'style' => (int) $styleId, 'material' => (int) $materialId, 'color' => (int) $colorId, 'app' => $this->app->getId(), 'type' => $type )) ->setMaxResults(1) ->getQuery() ->getOneOrNullResult(); if (!$asset) { throw new \Exception('Asset with this parameters no exist!'); } if ($this->statistics) { $statisticsShare = new StatisticsAssets(); $statisticsShare ->setStatistics($this->statistics) ->setAction($this->type) ->setMySessionId($this->sessionId) ->setIp(@$_SERVER['REMOTE_ADDR']) ->setViews(1) ->setAsset($asset); $this->em->persist($statisticsShare); $this->em->flush(); return new JsonResponse(array('success' => true, 'msg' => 'Choose assets actions successufly added')); } else { throw new \Exception('Cant find statistics for this session id and app id!'); } } catch (\PDOException $e) { return new JsonResponse(array('success' => false, 'msg' => 'An error occured', 'error' => $e->getMessage())); } } /** * Start session action, start was saved early in _init function, bu in this point is returned status * @return \Symfony\Component\HttpFoundation\JsonResponse * @throws \Exception */ public function startSessionAction() { try { $isset = false; if ($this->statistics) { $isset = true; $this->statistics->setUpdateOnly(!$this->statistics->getUpdateOnly()); } else { $this->statistics = new Statistics(); $this->statistics ->setSessionId($this->sessionId) ->setMySessionId($this->sessionId) ->setAction($this->type) ->setApp($this->app) ->setIp(@$_SERVER['REMOTE_ADDR']); $this->em->persist($this->statistics); } $statisticsTime = new StatisticsTime(); $statisticsTime ->setStatistics($this->statistics) ->setAction($this->type) ->setTimeType('start') ->setMySessionId($this->sessionId) ->setIp(@$_SERVER['REMOTE_ADDR']); $this->statistics->addTime($statisticsTime); $this->em->persist($statisticsTime); $this->em->flush(); return new JsonResponse(array('success' => true, 'msg' => $isset ? 'Restart session action successuflly did' : 'Start session action successuflly did')); } catch (\Exception $e) { return new JsonResponse(array('success' => false, 'msg' => 'An error occured', 'error' => $e->getMessage())); } } /** * Action save to time of session in stats if request was sent * @return \Symfony\Component\HttpFoundation\JsonResponse * @throws \Exception */ public function endSessionAction() { try { if ($this->statistics) { $statisticsTime = new StatisticsTime(); $statisticsTime ->setStatistics($this->statistics) ->setAction($this->type) ->setMySessionId($this->sessionId) ->setIp(@$_SERVER['REMOTE_ADDR']) ->setTimeType('end') ->setTimeLength(time() - $this->statistics->getCreatedAt()->getTimestamp()); $this->em->persist($statisticsTime); $this->em->flush(); return new JsonResponse(array('success' => true, 'msg' => 'End session action successuflly did')); } else { throw new \Exception('Cant find statistics for this session id and app id!'); } } catch (\Exception $e) { return new JsonResponse(array('success' => false, 'msg' => 'An error occured', 'error' => $e->getMessage())); } } }
true
c07bff5c232f103f81736818d59f3450fee190d0
PHP
combolek/gallery2
/eval/gx/benchmark/tests/hooks_without_inheritance_procedural.php
UTF-8
376
2.546875
3
[]
no_license
<?php function module1_hook() { return 1; } function expected() { return 1; } function prepare() { $GLOBALS['callbacks'] = array( 'module1_hook', 'module2_hook', 'module3_hook'); } function go() { $answer = 0; foreach ($GLOBALS['callbacks'] as $callback) { if (function_exists($callback)) { $answer += $callback(); } } return $answer; } ?>
true
37d397fc0ad2adf935bdf55cb8cd790334ac71fc
PHP
Royar13/Library-QA-Demo
/server/classes/User/UserValidator.php
UTF-8
2,327
2.6875
3
[]
no_license
<?php class UserValidator extends InputValidator implements IDatabaseAccess { private $db; public function __construct() { parent::__construct(); $this->setValidation("username", "username"); $this->setValidation("name", "hebrew"); $this->setValidation("password", "password"); } public function setDatabase($db) { $this->db = $db; } public function validateDelete($user, $loggedUserHierarchy) { if (!$this->validateIdExist($user->id)) $this->addGeneralError("לא נמצא המשתמש"); if (!$this->validateType($user->type, $loggedUserHierarchy)) $this->addGeneralError("לא ניתן למחוק משתמש עם סוג משתמש בכיר ממך"); return $this->isValid(); } public function validateUsernameFree($username) { $query = "select id from users where username=:username"; $bind[":username"] = $username; $result = $this->db->preparedQuery($query, $bind); $rows = $result->fetchAll(PDO::FETCH_ASSOC); return (count($rows) == 0); } public function validateIdExist($id) { $query = "select id from users where id=:id"; $bind[":id"] = $id; $result = $this->db->preparedQuery($query, $bind); $rows = $result->fetchAll(PDO::FETCH_ASSOC); return (count($rows) == 1); } public function validatePasswordRepeat($password, $passwordRepeat) { return ($password == $passwordRepeat); } public function validateCurrentPassword($id, $password) { $query = "select id from users where id=:id AND password=:password"; $bind[":id"] = $id; $bind[":password"] = $password; $result = $this->db->preparedQuery($query, $bind); $rows = $result->fetchAll(PDO::FETCH_ASSOC); return (count($rows) == 1); } public function validateType($type, $loggedUserHierarchy) { $query = "select hierarchy from user_types where id=:type"; $bind[":type"] = $type; $result = $this->db->preparedQuery($query, $bind); $rows = $result->fetchAll(PDO::FETCH_ASSOC); if (count($rows) != 1) return false; $hierarchy = $rows[0]["hierarchy"]; return ($loggedUserHierarchy <= $hierarchy); } }
true